GNU Linux-libre 4.14.328-gnu1
[releases.git] / fs / nilfs2 / the_nilfs.c
1 /*
2  * the_nilfs.c - the_nilfs shared structure.
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  * Written by Ryusuke Konishi.
17  *
18  */
19
20 #include <linux/buffer_head.h>
21 #include <linux/slab.h>
22 #include <linux/blkdev.h>
23 #include <linux/backing-dev.h>
24 #include <linux/random.h>
25 #include <linux/log2.h>
26 #include <linux/crc32.h>
27 #include "nilfs.h"
28 #include "segment.h"
29 #include "alloc.h"
30 #include "cpfile.h"
31 #include "sufile.h"
32 #include "dat.h"
33 #include "segbuf.h"
34
35
36 static int nilfs_valid_sb(struct nilfs_super_block *sbp);
37
38 void nilfs_set_last_segment(struct the_nilfs *nilfs,
39                             sector_t start_blocknr, u64 seq, __u64 cno)
40 {
41         spin_lock(&nilfs->ns_last_segment_lock);
42         nilfs->ns_last_pseg = start_blocknr;
43         nilfs->ns_last_seq = seq;
44         nilfs->ns_last_cno = cno;
45
46         if (!nilfs_sb_dirty(nilfs)) {
47                 if (nilfs->ns_prev_seq == nilfs->ns_last_seq)
48                         goto stay_cursor;
49
50                 set_nilfs_sb_dirty(nilfs);
51         }
52         nilfs->ns_prev_seq = nilfs->ns_last_seq;
53
54  stay_cursor:
55         spin_unlock(&nilfs->ns_last_segment_lock);
56 }
57
58 /**
59  * alloc_nilfs - allocate a nilfs object
60  * @sb: super block instance
61  *
62  * Return Value: On success, pointer to the_nilfs is returned.
63  * On error, NULL is returned.
64  */
65 struct the_nilfs *alloc_nilfs(struct super_block *sb)
66 {
67         struct the_nilfs *nilfs;
68
69         nilfs = kzalloc(sizeof(*nilfs), GFP_KERNEL);
70         if (!nilfs)
71                 return NULL;
72
73         nilfs->ns_sb = sb;
74         nilfs->ns_bdev = sb->s_bdev;
75         atomic_set(&nilfs->ns_ndirtyblks, 0);
76         init_rwsem(&nilfs->ns_sem);
77         mutex_init(&nilfs->ns_snapshot_mount_mutex);
78         INIT_LIST_HEAD(&nilfs->ns_dirty_files);
79         INIT_LIST_HEAD(&nilfs->ns_gc_inodes);
80         spin_lock_init(&nilfs->ns_inode_lock);
81         spin_lock_init(&nilfs->ns_next_gen_lock);
82         spin_lock_init(&nilfs->ns_last_segment_lock);
83         nilfs->ns_cptree = RB_ROOT;
84         spin_lock_init(&nilfs->ns_cptree_lock);
85         init_rwsem(&nilfs->ns_segctor_sem);
86         nilfs->ns_sb_update_freq = NILFS_SB_FREQ;
87
88         return nilfs;
89 }
90
91 /**
92  * destroy_nilfs - destroy nilfs object
93  * @nilfs: nilfs object to be released
94  */
95 void destroy_nilfs(struct the_nilfs *nilfs)
96 {
97         might_sleep();
98         if (nilfs_init(nilfs)) {
99                 brelse(nilfs->ns_sbh[0]);
100                 brelse(nilfs->ns_sbh[1]);
101         }
102         kfree(nilfs);
103 }
104
105 static int nilfs_load_super_root(struct the_nilfs *nilfs,
106                                  struct super_block *sb, sector_t sr_block)
107 {
108         struct buffer_head *bh_sr;
109         struct nilfs_super_root *raw_sr;
110         struct nilfs_super_block **sbp = nilfs->ns_sbp;
111         struct nilfs_inode *rawi;
112         unsigned int dat_entry_size, segment_usage_size, checkpoint_size;
113         unsigned int inode_size;
114         int err;
115
116         err = nilfs_read_super_root_block(nilfs, sr_block, &bh_sr, 1);
117         if (unlikely(err))
118                 return err;
119
120         down_read(&nilfs->ns_sem);
121         dat_entry_size = le16_to_cpu(sbp[0]->s_dat_entry_size);
122         checkpoint_size = le16_to_cpu(sbp[0]->s_checkpoint_size);
123         segment_usage_size = le16_to_cpu(sbp[0]->s_segment_usage_size);
124         up_read(&nilfs->ns_sem);
125
126         inode_size = nilfs->ns_inode_size;
127
128         rawi = (void *)bh_sr->b_data + NILFS_SR_DAT_OFFSET(inode_size);
129         err = nilfs_dat_read(sb, dat_entry_size, rawi, &nilfs->ns_dat);
130         if (err)
131                 goto failed;
132
133         rawi = (void *)bh_sr->b_data + NILFS_SR_CPFILE_OFFSET(inode_size);
134         err = nilfs_cpfile_read(sb, checkpoint_size, rawi, &nilfs->ns_cpfile);
135         if (err)
136                 goto failed_dat;
137
138         rawi = (void *)bh_sr->b_data + NILFS_SR_SUFILE_OFFSET(inode_size);
139         err = nilfs_sufile_read(sb, segment_usage_size, rawi,
140                                 &nilfs->ns_sufile);
141         if (err)
142                 goto failed_cpfile;
143
144         raw_sr = (struct nilfs_super_root *)bh_sr->b_data;
145         nilfs->ns_nongc_ctime = le64_to_cpu(raw_sr->sr_nongc_ctime);
146
147  failed:
148         brelse(bh_sr);
149         return err;
150
151  failed_cpfile:
152         iput(nilfs->ns_cpfile);
153
154  failed_dat:
155         iput(nilfs->ns_dat);
156         goto failed;
157 }
158
159 static void nilfs_init_recovery_info(struct nilfs_recovery_info *ri)
160 {
161         memset(ri, 0, sizeof(*ri));
162         INIT_LIST_HEAD(&ri->ri_used_segments);
163 }
164
165 static void nilfs_clear_recovery_info(struct nilfs_recovery_info *ri)
166 {
167         nilfs_dispose_segment_list(&ri->ri_used_segments);
168 }
169
170 /**
171  * nilfs_store_log_cursor - load log cursor from a super block
172  * @nilfs: nilfs object
173  * @sbp: buffer storing super block to be read
174  *
175  * nilfs_store_log_cursor() reads the last position of the log
176  * containing a super root from a given super block, and initializes
177  * relevant information on the nilfs object preparatory for log
178  * scanning and recovery.
179  */
180 static int nilfs_store_log_cursor(struct the_nilfs *nilfs,
181                                   struct nilfs_super_block *sbp)
182 {
183         int ret = 0;
184
185         nilfs->ns_last_pseg = le64_to_cpu(sbp->s_last_pseg);
186         nilfs->ns_last_cno = le64_to_cpu(sbp->s_last_cno);
187         nilfs->ns_last_seq = le64_to_cpu(sbp->s_last_seq);
188
189         nilfs->ns_prev_seq = nilfs->ns_last_seq;
190         nilfs->ns_seg_seq = nilfs->ns_last_seq;
191         nilfs->ns_segnum =
192                 nilfs_get_segnum_of_block(nilfs, nilfs->ns_last_pseg);
193         nilfs->ns_cno = nilfs->ns_last_cno + 1;
194         if (nilfs->ns_segnum >= nilfs->ns_nsegments) {
195                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
196                           "pointed segment number is out of range: segnum=%llu, nsegments=%lu",
197                           (unsigned long long)nilfs->ns_segnum,
198                           nilfs->ns_nsegments);
199                 ret = -EINVAL;
200         }
201         return ret;
202 }
203
204 /**
205  * load_nilfs - load and recover the nilfs
206  * @nilfs: the_nilfs structure to be released
207  * @sb: super block isntance used to recover past segment
208  *
209  * load_nilfs() searches and load the latest super root,
210  * attaches the last segment, and does recovery if needed.
211  * The caller must call this exclusively for simultaneous mounts.
212  */
213 int load_nilfs(struct the_nilfs *nilfs, struct super_block *sb)
214 {
215         struct nilfs_recovery_info ri;
216         unsigned int s_flags = sb->s_flags;
217         int really_read_only = bdev_read_only(nilfs->ns_bdev);
218         int valid_fs = nilfs_valid_fs(nilfs);
219         int err;
220
221         if (!valid_fs) {
222                 nilfs_msg(sb, KERN_WARNING, "mounting unchecked fs");
223                 if (s_flags & MS_RDONLY) {
224                         nilfs_msg(sb, KERN_INFO,
225                                   "recovery required for readonly filesystem");
226                         nilfs_msg(sb, KERN_INFO,
227                                   "write access will be enabled during recovery");
228                 }
229         }
230
231         nilfs_init_recovery_info(&ri);
232
233         err = nilfs_search_super_root(nilfs, &ri);
234         if (unlikely(err)) {
235                 struct nilfs_super_block **sbp = nilfs->ns_sbp;
236                 int blocksize;
237
238                 if (err != -EINVAL)
239                         goto scan_error;
240
241                 if (!nilfs_valid_sb(sbp[1])) {
242                         nilfs_msg(sb, KERN_WARNING,
243                                   "unable to fall back to spare super block");
244                         goto scan_error;
245                 }
246                 nilfs_msg(sb, KERN_INFO,
247                           "trying rollback from an earlier position");
248
249                 /*
250                  * restore super block with its spare and reconfigure
251                  * relevant states of the nilfs object.
252                  */
253                 memcpy(sbp[0], sbp[1], nilfs->ns_sbsize);
254                 nilfs->ns_crc_seed = le32_to_cpu(sbp[0]->s_crc_seed);
255                 nilfs->ns_sbwtime = le64_to_cpu(sbp[0]->s_wtime);
256
257                 /* verify consistency between two super blocks */
258                 blocksize = BLOCK_SIZE << le32_to_cpu(sbp[0]->s_log_block_size);
259                 if (blocksize != nilfs->ns_blocksize) {
260                         nilfs_msg(sb, KERN_WARNING,
261                                   "blocksize differs between two super blocks (%d != %d)",
262                                   blocksize, nilfs->ns_blocksize);
263                         goto scan_error;
264                 }
265
266                 err = nilfs_store_log_cursor(nilfs, sbp[0]);
267                 if (err)
268                         goto scan_error;
269
270                 /* drop clean flag to allow roll-forward and recovery */
271                 nilfs->ns_mount_state &= ~NILFS_VALID_FS;
272                 valid_fs = 0;
273
274                 err = nilfs_search_super_root(nilfs, &ri);
275                 if (err)
276                         goto scan_error;
277         }
278
279         err = nilfs_load_super_root(nilfs, sb, ri.ri_super_root);
280         if (unlikely(err)) {
281                 nilfs_msg(sb, KERN_ERR, "error %d while loading super root",
282                           err);
283                 goto failed;
284         }
285
286         err = nilfs_sysfs_create_device_group(sb);
287         if (unlikely(err))
288                 goto sysfs_error;
289
290         if (valid_fs)
291                 goto skip_recovery;
292
293         if (s_flags & MS_RDONLY) {
294                 __u64 features;
295
296                 if (nilfs_test_opt(nilfs, NORECOVERY)) {
297                         nilfs_msg(sb, KERN_INFO,
298                                   "norecovery option specified, skipping roll-forward recovery");
299                         goto skip_recovery;
300                 }
301                 features = le64_to_cpu(nilfs->ns_sbp[0]->s_feature_compat_ro) &
302                         ~NILFS_FEATURE_COMPAT_RO_SUPP;
303                 if (features) {
304                         nilfs_msg(sb, KERN_ERR,
305                                   "couldn't proceed with recovery because of unsupported optional features (%llx)",
306                                   (unsigned long long)features);
307                         err = -EROFS;
308                         goto failed_unload;
309                 }
310                 if (really_read_only) {
311                         nilfs_msg(sb, KERN_ERR,
312                                   "write access unavailable, cannot proceed");
313                         err = -EROFS;
314                         goto failed_unload;
315                 }
316                 sb->s_flags &= ~MS_RDONLY;
317         } else if (nilfs_test_opt(nilfs, NORECOVERY)) {
318                 nilfs_msg(sb, KERN_ERR,
319                           "recovery cancelled because norecovery option was specified for a read/write mount");
320                 err = -EINVAL;
321                 goto failed_unload;
322         }
323
324         err = nilfs_salvage_orphan_logs(nilfs, sb, &ri);
325         if (err)
326                 goto failed_unload;
327
328         down_write(&nilfs->ns_sem);
329         nilfs->ns_mount_state |= NILFS_VALID_FS; /* set "clean" flag */
330         err = nilfs_cleanup_super(sb);
331         up_write(&nilfs->ns_sem);
332
333         if (err) {
334                 nilfs_msg(sb, KERN_ERR,
335                           "error %d updating super block. recovery unfinished.",
336                           err);
337                 goto failed_unload;
338         }
339         nilfs_msg(sb, KERN_INFO, "recovery complete");
340
341  skip_recovery:
342         nilfs_clear_recovery_info(&ri);
343         sb->s_flags = s_flags;
344         return 0;
345
346  scan_error:
347         nilfs_msg(sb, KERN_ERR, "error %d while searching super root", err);
348         goto failed;
349
350  failed_unload:
351         nilfs_sysfs_delete_device_group(nilfs);
352
353  sysfs_error:
354         iput(nilfs->ns_cpfile);
355         iput(nilfs->ns_sufile);
356         iput(nilfs->ns_dat);
357
358  failed:
359         nilfs_clear_recovery_info(&ri);
360         sb->s_flags = s_flags;
361         return err;
362 }
363
364 static unsigned long long nilfs_max_size(unsigned int blkbits)
365 {
366         unsigned int max_bits;
367         unsigned long long res = MAX_LFS_FILESIZE; /* page cache limit */
368
369         max_bits = blkbits + NILFS_BMAP_KEY_BIT; /* bmap size limit */
370         if (max_bits < 64)
371                 res = min_t(unsigned long long, res, (1ULL << max_bits) - 1);
372         return res;
373 }
374
375 /**
376  * nilfs_nrsvsegs - calculate the number of reserved segments
377  * @nilfs: nilfs object
378  * @nsegs: total number of segments
379  */
380 unsigned long nilfs_nrsvsegs(struct the_nilfs *nilfs, unsigned long nsegs)
381 {
382         return max_t(unsigned long, NILFS_MIN_NRSVSEGS,
383                      DIV_ROUND_UP(nsegs * nilfs->ns_r_segments_percentage,
384                                   100));
385 }
386
387 /**
388  * nilfs_max_segment_count - calculate the maximum number of segments
389  * @nilfs: nilfs object
390  */
391 static u64 nilfs_max_segment_count(struct the_nilfs *nilfs)
392 {
393         u64 max_count = U64_MAX;
394
395         do_div(max_count, nilfs->ns_blocks_per_segment);
396         return min_t(u64, max_count, ULONG_MAX);
397 }
398
399 void nilfs_set_nsegments(struct the_nilfs *nilfs, unsigned long nsegs)
400 {
401         nilfs->ns_nsegments = nsegs;
402         nilfs->ns_nrsvsegs = nilfs_nrsvsegs(nilfs, nsegs);
403 }
404
405 static int nilfs_store_disk_layout(struct the_nilfs *nilfs,
406                                    struct nilfs_super_block *sbp)
407 {
408         u64 nsegments, nblocks;
409
410         if (le32_to_cpu(sbp->s_rev_level) < NILFS_MIN_SUPP_REV) {
411                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
412                           "unsupported revision (superblock rev.=%d.%d, current rev.=%d.%d). Please check the version of mkfs.nilfs(2).",
413                           le32_to_cpu(sbp->s_rev_level),
414                           le16_to_cpu(sbp->s_minor_rev_level),
415                           NILFS_CURRENT_REV, NILFS_MINOR_REV);
416                 return -EINVAL;
417         }
418         nilfs->ns_sbsize = le16_to_cpu(sbp->s_bytes);
419         if (nilfs->ns_sbsize > BLOCK_SIZE)
420                 return -EINVAL;
421
422         nilfs->ns_inode_size = le16_to_cpu(sbp->s_inode_size);
423         if (nilfs->ns_inode_size > nilfs->ns_blocksize) {
424                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
425                           "too large inode size: %d bytes",
426                           nilfs->ns_inode_size);
427                 return -EINVAL;
428         } else if (nilfs->ns_inode_size < NILFS_MIN_INODE_SIZE) {
429                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
430                           "too small inode size: %d bytes",
431                           nilfs->ns_inode_size);
432                 return -EINVAL;
433         }
434
435         nilfs->ns_first_ino = le32_to_cpu(sbp->s_first_ino);
436
437         nilfs->ns_blocks_per_segment = le32_to_cpu(sbp->s_blocks_per_segment);
438         if (nilfs->ns_blocks_per_segment < NILFS_SEG_MIN_BLOCKS) {
439                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
440                           "too short segment: %lu blocks",
441                           nilfs->ns_blocks_per_segment);
442                 return -EINVAL;
443         }
444
445         nilfs->ns_first_data_block = le64_to_cpu(sbp->s_first_data_block);
446         nilfs->ns_r_segments_percentage =
447                 le32_to_cpu(sbp->s_r_segments_percentage);
448         if (nilfs->ns_r_segments_percentage < 1 ||
449             nilfs->ns_r_segments_percentage > 99) {
450                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
451                           "invalid reserved segments percentage: %lu",
452                           nilfs->ns_r_segments_percentage);
453                 return -EINVAL;
454         }
455
456         nsegments = le64_to_cpu(sbp->s_nsegments);
457         if (nsegments > nilfs_max_segment_count(nilfs)) {
458                 nilfs_msg(nilfs->ns_sb, KERN_ERR,
459                           "segment count %llu exceeds upper limit (%llu segments)",
460                           (unsigned long long)nsegments,
461                           (unsigned long long)nilfs_max_segment_count(nilfs));
462                 return -EINVAL;
463         }
464
465         nblocks = (u64)i_size_read(nilfs->ns_sb->s_bdev->bd_inode) >>
466                 nilfs->ns_sb->s_blocksize_bits;
467         if (nblocks) {
468                 u64 min_block_count = nsegments * nilfs->ns_blocks_per_segment;
469                 /*
470                  * To avoid failing to mount early device images without a
471                  * second superblock, exclude that block count from the
472                  * "min_block_count" calculation.
473                  */
474
475                 if (nblocks < min_block_count) {
476                         nilfs_msg(nilfs->ns_sb, KERN_ERR,
477                                   "total number of segment blocks %llu exceeds device size (%llu blocks)",
478                                   (unsigned long long)min_block_count,
479                                   (unsigned long long)nblocks);
480                         return -EINVAL;
481                 }
482         }
483
484         nilfs_set_nsegments(nilfs, nsegments);
485         nilfs->ns_crc_seed = le32_to_cpu(sbp->s_crc_seed);
486         return 0;
487 }
488
489 static int nilfs_valid_sb(struct nilfs_super_block *sbp)
490 {
491         static unsigned char sum[4];
492         const int sumoff = offsetof(struct nilfs_super_block, s_sum);
493         size_t bytes;
494         u32 crc;
495
496         if (!sbp || le16_to_cpu(sbp->s_magic) != NILFS_SUPER_MAGIC)
497                 return 0;
498         bytes = le16_to_cpu(sbp->s_bytes);
499         if (bytes < sumoff + 4 || bytes > BLOCK_SIZE)
500                 return 0;
501         crc = crc32_le(le32_to_cpu(sbp->s_crc_seed), (unsigned char *)sbp,
502                        sumoff);
503         crc = crc32_le(crc, sum, 4);
504         crc = crc32_le(crc, (unsigned char *)sbp + sumoff + 4,
505                        bytes - sumoff - 4);
506         return crc == le32_to_cpu(sbp->s_sum);
507 }
508
509 /**
510  * nilfs_sb2_bad_offset - check the location of the second superblock
511  * @sbp: superblock raw data buffer
512  * @offset: byte offset of second superblock calculated from device size
513  *
514  * nilfs_sb2_bad_offset() checks if the position on the second
515  * superblock is valid or not based on the filesystem parameters
516  * stored in @sbp.  If @offset points to a location within the segment
517  * area, or if the parameters themselves are not normal, it is
518  * determined to be invalid.
519  *
520  * Return Value: true if invalid, false if valid.
521  */
522 static bool nilfs_sb2_bad_offset(struct nilfs_super_block *sbp, u64 offset)
523 {
524         unsigned int shift_bits = le32_to_cpu(sbp->s_log_block_size);
525         u32 blocks_per_segment = le32_to_cpu(sbp->s_blocks_per_segment);
526         u64 nsegments = le64_to_cpu(sbp->s_nsegments);
527         u64 index;
528
529         if (blocks_per_segment < NILFS_SEG_MIN_BLOCKS ||
530             shift_bits > ilog2(NILFS_MAX_BLOCK_SIZE) - BLOCK_SIZE_BITS)
531                 return true;
532
533         index = offset >> (shift_bits + BLOCK_SIZE_BITS);
534         do_div(index, blocks_per_segment);
535         return index < nsegments;
536 }
537
538 static void nilfs_release_super_block(struct the_nilfs *nilfs)
539 {
540         int i;
541
542         for (i = 0; i < 2; i++) {
543                 if (nilfs->ns_sbp[i]) {
544                         brelse(nilfs->ns_sbh[i]);
545                         nilfs->ns_sbh[i] = NULL;
546                         nilfs->ns_sbp[i] = NULL;
547                 }
548         }
549 }
550
551 void nilfs_fall_back_super_block(struct the_nilfs *nilfs)
552 {
553         brelse(nilfs->ns_sbh[0]);
554         nilfs->ns_sbh[0] = nilfs->ns_sbh[1];
555         nilfs->ns_sbp[0] = nilfs->ns_sbp[1];
556         nilfs->ns_sbh[1] = NULL;
557         nilfs->ns_sbp[1] = NULL;
558 }
559
560 void nilfs_swap_super_block(struct the_nilfs *nilfs)
561 {
562         struct buffer_head *tsbh = nilfs->ns_sbh[0];
563         struct nilfs_super_block *tsbp = nilfs->ns_sbp[0];
564
565         nilfs->ns_sbh[0] = nilfs->ns_sbh[1];
566         nilfs->ns_sbp[0] = nilfs->ns_sbp[1];
567         nilfs->ns_sbh[1] = tsbh;
568         nilfs->ns_sbp[1] = tsbp;
569 }
570
571 static int nilfs_load_super_block(struct the_nilfs *nilfs,
572                                   struct super_block *sb, int blocksize,
573                                   struct nilfs_super_block **sbpp)
574 {
575         struct nilfs_super_block **sbp = nilfs->ns_sbp;
576         struct buffer_head **sbh = nilfs->ns_sbh;
577         u64 sb2off, devsize = nilfs->ns_bdev->bd_inode->i_size;
578         int valid[2], swp = 0;
579
580         if (devsize < NILFS_SEG_MIN_BLOCKS * NILFS_MIN_BLOCK_SIZE + 4096) {
581                 nilfs_msg(sb, KERN_ERR, "device size too small");
582                 return -EINVAL;
583         }
584         sb2off = NILFS_SB2_OFFSET_BYTES(devsize);
585
586         sbp[0] = nilfs_read_super_block(sb, NILFS_SB_OFFSET_BYTES, blocksize,
587                                         &sbh[0]);
588         sbp[1] = nilfs_read_super_block(sb, sb2off, blocksize, &sbh[1]);
589
590         if (!sbp[0]) {
591                 if (!sbp[1]) {
592                         nilfs_msg(sb, KERN_ERR, "unable to read superblock");
593                         return -EIO;
594                 }
595                 nilfs_msg(sb, KERN_WARNING,
596                           "unable to read primary superblock (blocksize = %d)",
597                           blocksize);
598         } else if (!sbp[1]) {
599                 nilfs_msg(sb, KERN_WARNING,
600                           "unable to read secondary superblock (blocksize = %d)",
601                           blocksize);
602         }
603
604         /*
605          * Compare two super blocks and set 1 in swp if the secondary
606          * super block is valid and newer.  Otherwise, set 0 in swp.
607          */
608         valid[0] = nilfs_valid_sb(sbp[0]);
609         valid[1] = nilfs_valid_sb(sbp[1]);
610         swp = valid[1] && (!valid[0] ||
611                            le64_to_cpu(sbp[1]->s_last_cno) >
612                            le64_to_cpu(sbp[0]->s_last_cno));
613
614         if (valid[swp] && nilfs_sb2_bad_offset(sbp[swp], sb2off)) {
615                 brelse(sbh[1]);
616                 sbh[1] = NULL;
617                 sbp[1] = NULL;
618                 valid[1] = 0;
619                 swp = 0;
620         }
621         if (!valid[swp]) {
622                 nilfs_release_super_block(nilfs);
623                 nilfs_msg(sb, KERN_ERR, "couldn't find nilfs on the device");
624                 return -EINVAL;
625         }
626
627         if (!valid[!swp])
628                 nilfs_msg(sb, KERN_WARNING,
629                           "broken superblock, retrying with spare superblock (blocksize = %d)",
630                           blocksize);
631         if (swp)
632                 nilfs_swap_super_block(nilfs);
633
634         nilfs->ns_sbwcount = 0;
635         nilfs->ns_sbwtime = le64_to_cpu(sbp[0]->s_wtime);
636         nilfs->ns_prot_seq = le64_to_cpu(sbp[valid[1] & !swp]->s_last_seq);
637         *sbpp = sbp[0];
638         return 0;
639 }
640
641 /**
642  * init_nilfs - initialize a NILFS instance.
643  * @nilfs: the_nilfs structure
644  * @sb: super block
645  * @data: mount options
646  *
647  * init_nilfs() performs common initialization per block device (e.g.
648  * reading the super block, getting disk layout information, initializing
649  * shared fields in the_nilfs).
650  *
651  * Return Value: On success, 0 is returned. On error, a negative error
652  * code is returned.
653  */
654 int init_nilfs(struct the_nilfs *nilfs, struct super_block *sb, char *data)
655 {
656         struct nilfs_super_block *sbp;
657         int blocksize;
658         int err;
659
660         down_write(&nilfs->ns_sem);
661
662         blocksize = sb_min_blocksize(sb, NILFS_MIN_BLOCK_SIZE);
663         if (!blocksize) {
664                 nilfs_msg(sb, KERN_ERR, "unable to set blocksize");
665                 err = -EINVAL;
666                 goto out;
667         }
668         err = nilfs_load_super_block(nilfs, sb, blocksize, &sbp);
669         if (err)
670                 goto out;
671
672         err = nilfs_store_magic_and_option(sb, sbp, data);
673         if (err)
674                 goto failed_sbh;
675
676         err = nilfs_check_feature_compatibility(sb, sbp);
677         if (err)
678                 goto failed_sbh;
679
680         blocksize = BLOCK_SIZE << le32_to_cpu(sbp->s_log_block_size);
681         if (blocksize < NILFS_MIN_BLOCK_SIZE ||
682             blocksize > NILFS_MAX_BLOCK_SIZE) {
683                 nilfs_msg(sb, KERN_ERR,
684                           "couldn't mount because of unsupported filesystem blocksize %d",
685                           blocksize);
686                 err = -EINVAL;
687                 goto failed_sbh;
688         }
689         if (sb->s_blocksize != blocksize) {
690                 int hw_blocksize = bdev_logical_block_size(sb->s_bdev);
691
692                 if (blocksize < hw_blocksize) {
693                         nilfs_msg(sb, KERN_ERR,
694                                   "blocksize %d too small for device (sector-size = %d)",
695                                   blocksize, hw_blocksize);
696                         err = -EINVAL;
697                         goto failed_sbh;
698                 }
699                 nilfs_release_super_block(nilfs);
700                 sb_set_blocksize(sb, blocksize);
701
702                 err = nilfs_load_super_block(nilfs, sb, blocksize, &sbp);
703                 if (err)
704                         goto out;
705                         /*
706                          * Not to failed_sbh; sbh is released automatically
707                          * when reloading fails.
708                          */
709         }
710         nilfs->ns_blocksize_bits = sb->s_blocksize_bits;
711         nilfs->ns_blocksize = blocksize;
712
713         get_random_bytes(&nilfs->ns_next_generation,
714                          sizeof(nilfs->ns_next_generation));
715
716         err = nilfs_store_disk_layout(nilfs, sbp);
717         if (err)
718                 goto failed_sbh;
719
720         sb->s_maxbytes = nilfs_max_size(sb->s_blocksize_bits);
721
722         nilfs->ns_mount_state = le16_to_cpu(sbp->s_state);
723
724         err = nilfs_store_log_cursor(nilfs, sbp);
725         if (err)
726                 goto failed_sbh;
727
728         set_nilfs_init(nilfs);
729         err = 0;
730  out:
731         up_write(&nilfs->ns_sem);
732         return err;
733
734  failed_sbh:
735         nilfs_release_super_block(nilfs);
736         goto out;
737 }
738
739 int nilfs_discard_segments(struct the_nilfs *nilfs, __u64 *segnump,
740                             size_t nsegs)
741 {
742         sector_t seg_start, seg_end;
743         sector_t start = 0, nblocks = 0;
744         unsigned int sects_per_block;
745         __u64 *sn;
746         int ret = 0;
747
748         sects_per_block = (1 << nilfs->ns_blocksize_bits) /
749                 bdev_logical_block_size(nilfs->ns_bdev);
750         for (sn = segnump; sn < segnump + nsegs; sn++) {
751                 nilfs_get_segment_range(nilfs, *sn, &seg_start, &seg_end);
752
753                 if (!nblocks) {
754                         start = seg_start;
755                         nblocks = seg_end - seg_start + 1;
756                 } else if (start + nblocks == seg_start) {
757                         nblocks += seg_end - seg_start + 1;
758                 } else {
759                         ret = blkdev_issue_discard(nilfs->ns_bdev,
760                                                    start * sects_per_block,
761                                                    nblocks * sects_per_block,
762                                                    GFP_NOFS, 0);
763                         if (ret < 0)
764                                 return ret;
765                         nblocks = 0;
766                 }
767         }
768         if (nblocks)
769                 ret = blkdev_issue_discard(nilfs->ns_bdev,
770                                            start * sects_per_block,
771                                            nblocks * sects_per_block,
772                                            GFP_NOFS, 0);
773         return ret;
774 }
775
776 int nilfs_count_free_blocks(struct the_nilfs *nilfs, sector_t *nblocks)
777 {
778         unsigned long ncleansegs;
779
780         ncleansegs = nilfs_sufile_get_ncleansegs(nilfs->ns_sufile);
781         *nblocks = (sector_t)ncleansegs * nilfs->ns_blocks_per_segment;
782         return 0;
783 }
784
785 int nilfs_near_disk_full(struct the_nilfs *nilfs)
786 {
787         unsigned long ncleansegs, nincsegs;
788
789         ncleansegs = nilfs_sufile_get_ncleansegs(nilfs->ns_sufile);
790         nincsegs = atomic_read(&nilfs->ns_ndirtyblks) /
791                 nilfs->ns_blocks_per_segment + 1;
792
793         return ncleansegs <= nilfs->ns_nrsvsegs + nincsegs;
794 }
795
796 struct nilfs_root *nilfs_lookup_root(struct the_nilfs *nilfs, __u64 cno)
797 {
798         struct rb_node *n;
799         struct nilfs_root *root;
800
801         spin_lock(&nilfs->ns_cptree_lock);
802         n = nilfs->ns_cptree.rb_node;
803         while (n) {
804                 root = rb_entry(n, struct nilfs_root, rb_node);
805
806                 if (cno < root->cno) {
807                         n = n->rb_left;
808                 } else if (cno > root->cno) {
809                         n = n->rb_right;
810                 } else {
811                         atomic_inc(&root->count);
812                         spin_unlock(&nilfs->ns_cptree_lock);
813                         return root;
814                 }
815         }
816         spin_unlock(&nilfs->ns_cptree_lock);
817
818         return NULL;
819 }
820
821 struct nilfs_root *
822 nilfs_find_or_create_root(struct the_nilfs *nilfs, __u64 cno)
823 {
824         struct rb_node **p, *parent;
825         struct nilfs_root *root, *new;
826         int err;
827
828         root = nilfs_lookup_root(nilfs, cno);
829         if (root)
830                 return root;
831
832         new = kzalloc(sizeof(*root), GFP_KERNEL);
833         if (!new)
834                 return NULL;
835
836         spin_lock(&nilfs->ns_cptree_lock);
837
838         p = &nilfs->ns_cptree.rb_node;
839         parent = NULL;
840
841         while (*p) {
842                 parent = *p;
843                 root = rb_entry(parent, struct nilfs_root, rb_node);
844
845                 if (cno < root->cno) {
846                         p = &(*p)->rb_left;
847                 } else if (cno > root->cno) {
848                         p = &(*p)->rb_right;
849                 } else {
850                         atomic_inc(&root->count);
851                         spin_unlock(&nilfs->ns_cptree_lock);
852                         kfree(new);
853                         return root;
854                 }
855         }
856
857         new->cno = cno;
858         new->ifile = NULL;
859         new->nilfs = nilfs;
860         atomic_set(&new->count, 1);
861         atomic64_set(&new->inodes_count, 0);
862         atomic64_set(&new->blocks_count, 0);
863
864         rb_link_node(&new->rb_node, parent, p);
865         rb_insert_color(&new->rb_node, &nilfs->ns_cptree);
866
867         spin_unlock(&nilfs->ns_cptree_lock);
868
869         err = nilfs_sysfs_create_snapshot_group(new);
870         if (err) {
871                 kfree(new);
872                 new = NULL;
873         }
874
875         return new;
876 }
877
878 void nilfs_put_root(struct nilfs_root *root)
879 {
880         if (atomic_dec_and_test(&root->count)) {
881                 struct the_nilfs *nilfs = root->nilfs;
882
883                 nilfs_sysfs_delete_snapshot_group(root);
884
885                 spin_lock(&nilfs->ns_cptree_lock);
886                 rb_erase(&root->rb_node, &nilfs->ns_cptree);
887                 spin_unlock(&nilfs->ns_cptree_lock);
888                 iput(root->ifile);
889
890                 kfree(root);
891         }
892 }