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