xref: /linux/fs/bcachefs/super-io.c (revision 8244f3209b5b49a6bde9921d7825af9f57161b23)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "btree_update_interior.h"
5 #include "buckets.h"
6 #include "checksum.h"
7 #include "disk_groups.h"
8 #include "ec.h"
9 #include "error.h"
10 #include "io.h"
11 #include "journal.h"
12 #include "journal_io.h"
13 #include "journal_seq_blacklist.h"
14 #include "replicas.h"
15 #include "quota.h"
16 #include "super-io.h"
17 #include "super.h"
18 #include "vstructs.h"
19 
20 #include <linux/backing-dev.h>
21 #include <linux/sort.h>
22 
23 static const struct blk_holder_ops bch2_sb_handle_bdev_ops = {
24 };
25 
26 const char * const bch2_sb_fields[] = {
27 #define x(name, nr)	#name,
28 	BCH_SB_FIELDS()
29 #undef x
30 	NULL
31 };
32 
33 static const char *bch2_sb_field_validate(struct bch_sb *,
34 					  struct bch_sb_field *);
35 
36 struct bch_sb_field *bch2_sb_field_get(struct bch_sb *sb,
37 				      enum bch_sb_field_type type)
38 {
39 	struct bch_sb_field *f;
40 
41 	/* XXX: need locking around superblock to access optional fields */
42 
43 	vstruct_for_each(sb, f)
44 		if (le32_to_cpu(f->type) == type)
45 			return f;
46 	return NULL;
47 }
48 
49 static struct bch_sb_field *__bch2_sb_field_resize(struct bch_sb_handle *sb,
50 						   struct bch_sb_field *f,
51 						   unsigned u64s)
52 {
53 	unsigned old_u64s = f ? le32_to_cpu(f->u64s) : 0;
54 	unsigned sb_u64s = le32_to_cpu(sb->sb->u64s) + u64s - old_u64s;
55 
56 	BUG_ON(__vstruct_bytes(struct bch_sb, sb_u64s) > sb->buffer_size);
57 
58 	if (!f && !u64s) {
59 		/* nothing to do: */
60 	} else if (!f) {
61 		f = vstruct_last(sb->sb);
62 		memset(f, 0, sizeof(u64) * u64s);
63 		f->u64s = cpu_to_le32(u64s);
64 		f->type = 0;
65 	} else {
66 		void *src, *dst;
67 
68 		src = vstruct_end(f);
69 
70 		if (u64s) {
71 			f->u64s = cpu_to_le32(u64s);
72 			dst = vstruct_end(f);
73 		} else {
74 			dst = f;
75 		}
76 
77 		memmove(dst, src, vstruct_end(sb->sb) - src);
78 
79 		if (dst > src)
80 			memset(src, 0, dst - src);
81 	}
82 
83 	sb->sb->u64s = cpu_to_le32(sb_u64s);
84 
85 	return u64s ? f : NULL;
86 }
87 
88 void bch2_sb_field_delete(struct bch_sb_handle *sb,
89 			  enum bch_sb_field_type type)
90 {
91 	struct bch_sb_field *f = bch2_sb_field_get(sb->sb, type);
92 
93 	if (f)
94 		__bch2_sb_field_resize(sb, f, 0);
95 }
96 
97 /* Superblock realloc/free: */
98 
99 void bch2_free_super(struct bch_sb_handle *sb)
100 {
101 	if (sb->bio)
102 		kfree(sb->bio);
103 	if (!IS_ERR_OR_NULL(sb->bdev))
104 		blkdev_put(sb->bdev, sb->holder);
105 	kfree(sb->holder);
106 
107 	kfree(sb->sb);
108 	memset(sb, 0, sizeof(*sb));
109 }
110 
111 int bch2_sb_realloc(struct bch_sb_handle *sb, unsigned u64s)
112 {
113 	size_t new_bytes = __vstruct_bytes(struct bch_sb, u64s);
114 	size_t new_buffer_size;
115 	struct bch_sb *new_sb;
116 	struct bio *bio;
117 
118 	if (sb->bdev)
119 		new_bytes = max_t(size_t, new_bytes, bdev_logical_block_size(sb->bdev));
120 
121 	new_buffer_size = roundup_pow_of_two(new_bytes);
122 
123 	if (sb->sb && sb->buffer_size >= new_buffer_size)
124 		return 0;
125 
126 	if (sb->have_layout) {
127 		u64 max_bytes = 512 << sb->sb->layout.sb_max_size_bits;
128 
129 		if (new_bytes > max_bytes) {
130 			pr_err("%pg: superblock too big: want %zu but have %llu",
131 			       sb->bdev, new_bytes, max_bytes);
132 			return -ENOSPC;
133 		}
134 	}
135 
136 	if (sb->buffer_size >= new_buffer_size && sb->sb)
137 		return 0;
138 
139 	if (dynamic_fault("bcachefs:add:super_realloc"))
140 		return -ENOMEM;
141 
142 	if (sb->have_bio) {
143 		unsigned nr_bvecs = DIV_ROUND_UP(new_buffer_size, PAGE_SIZE);
144 
145 		bio = bio_kmalloc(nr_bvecs, GFP_KERNEL);
146 		if (!bio)
147 			return -ENOMEM;
148 
149 		bio_init(bio, NULL, bio->bi_inline_vecs, nr_bvecs, 0);
150 
151 		if (sb->bio)
152 			kfree(sb->bio);
153 		sb->bio = bio;
154 	}
155 
156 	new_sb = krealloc(sb->sb, new_buffer_size, GFP_NOFS|__GFP_ZERO);
157 	if (!new_sb)
158 		return -ENOMEM;
159 
160 	sb->sb = new_sb;
161 	sb->buffer_size = new_buffer_size;
162 
163 	return 0;
164 }
165 
166 struct bch_sb_field *bch2_sb_field_resize(struct bch_sb_handle *sb,
167 					  enum bch_sb_field_type type,
168 					  unsigned u64s)
169 {
170 	struct bch_sb_field *f = bch2_sb_field_get(sb->sb, type);
171 	ssize_t old_u64s = f ? le32_to_cpu(f->u64s) : 0;
172 	ssize_t d = -old_u64s + u64s;
173 
174 	if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s) + d))
175 		return NULL;
176 
177 	if (sb->fs_sb) {
178 		struct bch_fs *c = container_of(sb, struct bch_fs, disk_sb);
179 		struct bch_dev *ca;
180 		unsigned i;
181 
182 		lockdep_assert_held(&c->sb_lock);
183 
184 		/* XXX: we're not checking that offline device have enough space */
185 
186 		for_each_online_member(ca, c, i) {
187 			struct bch_sb_handle *sb = &ca->disk_sb;
188 
189 			if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s) + d)) {
190 				percpu_ref_put(&ca->ref);
191 				return NULL;
192 			}
193 		}
194 	}
195 
196 	f = bch2_sb_field_get(sb->sb, type);
197 	f = __bch2_sb_field_resize(sb, f, u64s);
198 	if (f)
199 		f->type = cpu_to_le32(type);
200 	return f;
201 }
202 
203 /* Superblock validate: */
204 
205 static inline void __bch2_sb_layout_size_assert(void)
206 {
207 	BUILD_BUG_ON(sizeof(struct bch_sb_layout) != 512);
208 }
209 
210 static const char *validate_sb_layout(struct bch_sb_layout *layout)
211 {
212 	u64 offset, prev_offset, max_sectors;
213 	unsigned i;
214 
215 	if (!uuid_equal(&layout->magic, &BCACHE_MAGIC) &&
216 	    !uuid_equal(&layout->magic, &BCHFS_MAGIC))
217 		return "Not a bcachefs superblock layout";
218 
219 	if (layout->layout_type != 0)
220 		return "Invalid superblock layout type";
221 
222 	if (!layout->nr_superblocks)
223 		return "Invalid superblock layout: no superblocks";
224 
225 	if (layout->nr_superblocks > ARRAY_SIZE(layout->sb_offset))
226 		return "Invalid superblock layout: too many superblocks";
227 
228 	max_sectors = 1 << layout->sb_max_size_bits;
229 
230 	prev_offset = le64_to_cpu(layout->sb_offset[0]);
231 
232 	for (i = 1; i < layout->nr_superblocks; i++) {
233 		offset = le64_to_cpu(layout->sb_offset[i]);
234 
235 		if (offset < prev_offset + max_sectors)
236 			return "Invalid superblock layout: superblocks overlap";
237 		prev_offset = offset;
238 	}
239 
240 	return NULL;
241 }
242 
243 const char *bch2_sb_validate(struct bch_sb_handle *disk_sb)
244 {
245 	struct bch_sb *sb = disk_sb->sb;
246 	struct bch_sb_field *f;
247 	struct bch_sb_field_members *mi;
248 	const char *err;
249 	u32 version, version_min;
250 	u16 block_size;
251 
252 	version		= le16_to_cpu(sb->version);
253 	version_min	= version >= bcachefs_metadata_version_new_versioning
254 		? le16_to_cpu(sb->version_min)
255 		: version;
256 
257 	if (version    >= bcachefs_metadata_version_max ||
258 	    version_min < bcachefs_metadata_version_min)
259 		return "Unsupported superblock version";
260 
261 	if (version_min > version)
262 		return "Bad minimum version";
263 
264 	if (sb->features[1] ||
265 	    (le64_to_cpu(sb->features[0]) & (~0ULL << BCH_FEATURE_NR)))
266 		return "Filesystem has incompatible features";
267 
268 	block_size = le16_to_cpu(sb->block_size);
269 
270 	if (block_size > PAGE_SECTORS)
271 		return "Bad block size";
272 
273 	if (bch2_is_zero(sb->user_uuid.b, sizeof(sb->user_uuid)))
274 		return "Bad user UUID";
275 
276 	if (bch2_is_zero(sb->uuid.b, sizeof(sb->uuid)))
277 		return "Bad internal UUID";
278 
279 	if (!sb->nr_devices ||
280 	    sb->nr_devices <= sb->dev_idx ||
281 	    sb->nr_devices > BCH_SB_MEMBERS_MAX)
282 		return "Bad number of member devices";
283 
284 	if (!BCH_SB_META_REPLICAS_WANT(sb) ||
285 	    BCH_SB_META_REPLICAS_WANT(sb) > BCH_REPLICAS_MAX)
286 		return "Invalid number of metadata replicas";
287 
288 	if (!BCH_SB_META_REPLICAS_REQ(sb) ||
289 	    BCH_SB_META_REPLICAS_REQ(sb) > BCH_REPLICAS_MAX)
290 		return "Invalid number of metadata replicas";
291 
292 	if (!BCH_SB_DATA_REPLICAS_WANT(sb) ||
293 	    BCH_SB_DATA_REPLICAS_WANT(sb) > BCH_REPLICAS_MAX)
294 		return "Invalid number of data replicas";
295 
296 	if (!BCH_SB_DATA_REPLICAS_REQ(sb) ||
297 	    BCH_SB_DATA_REPLICAS_REQ(sb) > BCH_REPLICAS_MAX)
298 		return "Invalid number of data replicas";
299 
300 	if (BCH_SB_META_CSUM_TYPE(sb) >= BCH_CSUM_OPT_NR)
301 		return "Invalid metadata checksum type";
302 
303 	if (BCH_SB_DATA_CSUM_TYPE(sb) >= BCH_CSUM_OPT_NR)
304 		return "Invalid metadata checksum type";
305 
306 	if (BCH_SB_COMPRESSION_TYPE(sb) >= BCH_COMPRESSION_OPT_NR)
307 		return "Invalid compression type";
308 
309 	if (!BCH_SB_BTREE_NODE_SIZE(sb))
310 		return "Btree node size not set";
311 
312 	if (BCH_SB_GC_RESERVE(sb) < 5)
313 		return "gc reserve percentage too small";
314 
315 	if (!sb->time_precision ||
316 	    le32_to_cpu(sb->time_precision) > NSEC_PER_SEC)
317 		return "invalid time precision";
318 
319 	/* validate layout */
320 	err = validate_sb_layout(&sb->layout);
321 	if (err)
322 		return err;
323 
324 	vstruct_for_each(sb, f) {
325 		if (!f->u64s)
326 			return "Invalid superblock: invalid optional field";
327 
328 		if (vstruct_next(f) > vstruct_last(sb))
329 			return "Invalid superblock: invalid optional field";
330 	}
331 
332 	/* members must be validated first: */
333 	mi = bch2_sb_get_members(sb);
334 	if (!mi)
335 		return "Invalid superblock: member info area missing";
336 
337 	err = bch2_sb_field_validate(sb, &mi->field);
338 	if (err)
339 		return err;
340 
341 	vstruct_for_each(sb, f) {
342 		if (le32_to_cpu(f->type) == BCH_SB_FIELD_members)
343 			continue;
344 
345 		err = bch2_sb_field_validate(sb, f);
346 		if (err)
347 			return err;
348 	}
349 
350 	return NULL;
351 }
352 
353 /* device open: */
354 
355 static void bch2_sb_update(struct bch_fs *c)
356 {
357 	struct bch_sb *src = c->disk_sb.sb;
358 	struct bch_sb_field_members *mi = bch2_sb_get_members(src);
359 	struct bch_dev *ca;
360 	unsigned i;
361 
362 	lockdep_assert_held(&c->sb_lock);
363 
364 	c->sb.uuid		= src->uuid;
365 	c->sb.user_uuid		= src->user_uuid;
366 	c->sb.version		= le16_to_cpu(src->version);
367 	c->sb.version_min	= le16_to_cpu(src->version_min);
368 	c->sb.nr_devices	= src->nr_devices;
369 	c->sb.clean		= BCH_SB_CLEAN(src);
370 	c->sb.encryption_type	= BCH_SB_ENCRYPTION_TYPE(src);
371 	c->sb.encoded_extent_max= 1 << BCH_SB_ENCODED_EXTENT_MAX_BITS(src);
372 
373 	c->sb.nsec_per_time_unit = le32_to_cpu(src->time_precision);
374 	c->sb.time_units_per_sec = NSEC_PER_SEC / c->sb.nsec_per_time_unit;
375 
376 	/* XXX this is wrong, we need a 96 or 128 bit integer type */
377 	c->sb.time_base_lo	= div_u64(le64_to_cpu(src->time_base_lo),
378 					  c->sb.nsec_per_time_unit);
379 	c->sb.time_base_hi	= le32_to_cpu(src->time_base_hi);
380 
381 	c->sb.features		= le64_to_cpu(src->features[0]);
382 	c->sb.compat		= le64_to_cpu(src->compat[0]);
383 
384 	for_each_member_device(ca, c, i)
385 		ca->mi = bch2_mi_to_cpu(mi->members + i);
386 }
387 
388 static void __copy_super(struct bch_sb_handle *dst_handle, struct bch_sb *src)
389 {
390 	struct bch_sb_field *src_f, *dst_f;
391 	struct bch_sb *dst = dst_handle->sb;
392 	unsigned i;
393 
394 	dst->version		= src->version;
395 	dst->version_min	= src->version_min;
396 	dst->seq		= src->seq;
397 	dst->uuid		= src->uuid;
398 	dst->user_uuid		= src->user_uuid;
399 	memcpy(dst->label,	src->label, sizeof(dst->label));
400 
401 	dst->block_size		= src->block_size;
402 	dst->nr_devices		= src->nr_devices;
403 
404 	dst->time_base_lo	= src->time_base_lo;
405 	dst->time_base_hi	= src->time_base_hi;
406 	dst->time_precision	= src->time_precision;
407 
408 	memcpy(dst->flags,	src->flags,	sizeof(dst->flags));
409 	memcpy(dst->features,	src->features,	sizeof(dst->features));
410 	memcpy(dst->compat,	src->compat,	sizeof(dst->compat));
411 
412 	for (i = 0; i < BCH_SB_FIELD_NR; i++) {
413 		if (i == BCH_SB_FIELD_journal)
414 			continue;
415 
416 		src_f = bch2_sb_field_get(src, i);
417 		dst_f = bch2_sb_field_get(dst, i);
418 		dst_f = __bch2_sb_field_resize(dst_handle, dst_f,
419 				src_f ? le32_to_cpu(src_f->u64s) : 0);
420 
421 		if (src_f)
422 			memcpy(dst_f, src_f, vstruct_bytes(src_f));
423 	}
424 }
425 
426 int bch2_sb_to_fs(struct bch_fs *c, struct bch_sb *src)
427 {
428 	struct bch_sb_field_journal *journal_buckets =
429 		bch2_sb_get_journal(src);
430 	unsigned journal_u64s = journal_buckets
431 		? le32_to_cpu(journal_buckets->field.u64s)
432 		: 0;
433 	int ret;
434 
435 	lockdep_assert_held(&c->sb_lock);
436 
437 	ret = bch2_sb_realloc(&c->disk_sb,
438 			      le32_to_cpu(src->u64s) - journal_u64s);
439 	if (ret)
440 		return ret;
441 
442 	__copy_super(&c->disk_sb, src);
443 
444 	if (BCH_SB_INITIALIZED(c->disk_sb.sb))
445 		set_bit(BCH_FS_INITIALIZED, &c->flags);
446 
447 	ret = bch2_sb_replicas_to_cpu_replicas(c);
448 	if (ret)
449 		return ret;
450 
451 	ret = bch2_sb_disk_groups_to_cpu(c);
452 	if (ret)
453 		return ret;
454 
455 	bch2_sb_update(c);
456 	return 0;
457 }
458 
459 int bch2_sb_from_fs(struct bch_fs *c, struct bch_dev *ca)
460 {
461 	struct bch_sb *src = c->disk_sb.sb, *dst = ca->disk_sb.sb;
462 	struct bch_sb_field_journal *journal_buckets =
463 		bch2_sb_get_journal(dst);
464 	unsigned journal_u64s = journal_buckets
465 		? le32_to_cpu(journal_buckets->field.u64s)
466 		: 0;
467 	unsigned u64s = le32_to_cpu(src->u64s) + journal_u64s;
468 	int ret;
469 
470 	ret = bch2_sb_realloc(&ca->disk_sb, u64s);
471 	if (ret)
472 		return ret;
473 
474 	__copy_super(&ca->disk_sb, src);
475 	return 0;
476 }
477 
478 /* read superblock: */
479 
480 static const char *read_one_super(struct bch_sb_handle *sb, u64 offset)
481 {
482 	struct bch_csum csum;
483 	size_t bytes;
484 reread:
485 	bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
486 	sb->bio->bi_iter.bi_sector = offset;
487 	bch2_bio_map(sb->bio, sb->sb, sb->buffer_size);
488 
489 	if (submit_bio_wait(sb->bio))
490 		return "IO error";
491 
492 	if (!uuid_equal(&sb->sb->magic, &BCACHE_MAGIC) &&
493 	    !uuid_equal(&sb->sb->magic, &BCHFS_MAGIC))
494 		return "Not a bcachefs superblock";
495 
496 	if (le16_to_cpu(sb->sb->version) <  bcachefs_metadata_version_min ||
497 	    le16_to_cpu(sb->sb->version) >= bcachefs_metadata_version_max)
498 		return "Unsupported superblock version";
499 
500 	bytes = vstruct_bytes(sb->sb);
501 
502 	if (bytes > 512 << sb->sb->layout.sb_max_size_bits)
503 		return "Bad superblock: too big";
504 
505 	if (bytes > sb->buffer_size) {
506 		if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s)))
507 			return "cannot allocate memory";
508 		goto reread;
509 	}
510 
511 	if (BCH_SB_CSUM_TYPE(sb->sb) >= BCH_CSUM_NR)
512 		return "unknown csum type";
513 
514 	/* XXX: verify MACs */
515 	csum = csum_vstruct(NULL, BCH_SB_CSUM_TYPE(sb->sb),
516 			    null_nonce(), sb->sb);
517 
518 	if (bch2_crc_cmp(csum, sb->sb->csum))
519 		return "bad checksum reading superblock";
520 
521 	sb->seq = le64_to_cpu(sb->sb->seq);
522 
523 	return NULL;
524 }
525 
526 int bch2_read_super(const char *path, struct bch_opts *opts,
527 		    struct bch_sb_handle *sb)
528 {
529 	u64 offset = opt_get(*opts, sb);
530 	struct bch_sb_layout layout;
531 	const char *err;
532 	__le64 *i;
533 	int ret;
534 
535 	pr_verbose_init(*opts, "");
536 
537 	memset(sb, 0, sizeof(*sb));
538 	sb->mode	= BLK_OPEN_READ;
539 	sb->have_bio	= true;
540 	sb->holder	= kmalloc(1, GFP_KERNEL);
541 	if (!sb->holder)
542 		return -ENOMEM;
543 
544 	if (!opt_get(*opts, noexcl))
545 		sb->mode |= BLK_OPEN_EXCL;
546 
547 	if (!opt_get(*opts, nochanges))
548 		sb->mode |= BLK_OPEN_WRITE;
549 
550 	sb->bdev = blkdev_get_by_path(path, sb->mode, sb->holder, &bch2_sb_handle_bdev_ops);
551 	if (IS_ERR(sb->bdev) &&
552 	    PTR_ERR(sb->bdev) == -EACCES &&
553 	    opt_get(*opts, read_only)) {
554 		sb->mode &= ~BLK_OPEN_WRITE;
555 
556 		sb->bdev = blkdev_get_by_path(path, sb->mode, sb->holder, &bch2_sb_handle_bdev_ops);
557 		if (!IS_ERR(sb->bdev))
558 			opt_set(*opts, nochanges, true);
559 	}
560 
561 	if (IS_ERR(sb->bdev)) {
562 		ret = PTR_ERR(sb->bdev);
563 		goto out;
564 	}
565 
566 	err = "cannot allocate memory";
567 	ret = bch2_sb_realloc(sb, 0);
568 	if (ret)
569 		goto err;
570 
571 	ret = -EFAULT;
572 	err = "dynamic fault";
573 	if (bch2_fs_init_fault("read_super"))
574 		goto err;
575 
576 	ret = -EINVAL;
577 	err = read_one_super(sb, offset);
578 	if (!err)
579 		goto got_super;
580 
581 	if (opt_defined(*opts, sb))
582 		goto err;
583 
584 	pr_err("error reading default superblock: %s", err);
585 
586 	/*
587 	 * Error reading primary superblock - read location of backup
588 	 * superblocks:
589 	 */
590 	bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
591 	sb->bio->bi_iter.bi_sector = BCH_SB_LAYOUT_SECTOR;
592 	/*
593 	 * use sb buffer to read layout, since sb buffer is page aligned but
594 	 * layout won't be:
595 	 */
596 	bch2_bio_map(sb->bio, sb->sb, sizeof(struct bch_sb_layout));
597 
598 	err = "IO error";
599 	if (submit_bio_wait(sb->bio))
600 		goto err;
601 
602 	memcpy(&layout, sb->sb, sizeof(layout));
603 	err = validate_sb_layout(&layout);
604 	if (err)
605 		goto err;
606 
607 	for (i = layout.sb_offset;
608 	     i < layout.sb_offset + layout.nr_superblocks; i++) {
609 		offset = le64_to_cpu(*i);
610 
611 		if (offset == opt_get(*opts, sb))
612 			continue;
613 
614 		err = read_one_super(sb, offset);
615 		if (!err)
616 			goto got_super;
617 	}
618 
619 	ret = -EINVAL;
620 	goto err;
621 
622 got_super:
623 	err = "Superblock block size smaller than device block size";
624 	ret = -EINVAL;
625 	if (le16_to_cpu(sb->sb->block_size) << 9 <
626 	    bdev_logical_block_size(sb->bdev)) {
627 		pr_err("error reading superblock: Superblock block size (%u) smaller than device block size (%u)",
628 		       le16_to_cpu(sb->sb->block_size) << 9,
629 		       bdev_logical_block_size(sb->bdev));
630 		goto err_no_print;
631 	}
632 
633 	ret = 0;
634 	sb->have_layout = true;
635 out:
636 	pr_verbose_init(*opts, "ret %i", ret);
637 	return ret;
638 err:
639 	pr_err("error reading superblock: %s", err);
640 err_no_print:
641 	bch2_free_super(sb);
642 	goto out;
643 }
644 
645 /* write superblock: */
646 
647 static void write_super_endio(struct bio *bio)
648 {
649 	struct bch_dev *ca = bio->bi_private;
650 
651 	/* XXX: return errors directly */
652 
653 	if (bch2_dev_io_err_on(bio->bi_status, ca, "superblock write error: %s",
654 			       bch2_blk_status_to_str(bio->bi_status)))
655 		ca->sb_write_error = 1;
656 
657 	closure_put(&ca->fs->sb_write);
658 	percpu_ref_put(&ca->io_ref);
659 }
660 
661 static void read_back_super(struct bch_fs *c, struct bch_dev *ca)
662 {
663 	struct bch_sb *sb = ca->disk_sb.sb;
664 	struct bio *bio = ca->disk_sb.bio;
665 
666 	bio_reset(bio, ca->disk_sb.bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
667 	bio->bi_iter.bi_sector	= le64_to_cpu(sb->layout.sb_offset[0]);
668 	bio->bi_end_io		= write_super_endio;
669 	bio->bi_private		= ca;
670 	bch2_bio_map(bio, ca->sb_read_scratch, PAGE_SIZE);
671 
672 	this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_sb],
673 		     bio_sectors(bio));
674 
675 	percpu_ref_get(&ca->io_ref);
676 	closure_bio_submit(bio, &c->sb_write);
677 }
678 
679 static void write_one_super(struct bch_fs *c, struct bch_dev *ca, unsigned idx)
680 {
681 	struct bch_sb *sb = ca->disk_sb.sb;
682 	struct bio *bio = ca->disk_sb.bio;
683 
684 	sb->offset = sb->layout.sb_offset[idx];
685 
686 	SET_BCH_SB_CSUM_TYPE(sb, bch2_csum_opt_to_type(c->opts.metadata_checksum, false));
687 	sb->csum = csum_vstruct(c, BCH_SB_CSUM_TYPE(sb),
688 				null_nonce(), sb);
689 
690 	bio_reset(bio, ca->disk_sb.bdev, REQ_OP_WRITE|REQ_SYNC|REQ_META);
691 	bio->bi_iter.bi_sector	= le64_to_cpu(sb->offset);
692 	bio->bi_end_io		= write_super_endio;
693 	bio->bi_private		= ca;
694 	bch2_bio_map(bio, sb,
695 		     roundup((size_t) vstruct_bytes(sb),
696 			     bdev_logical_block_size(ca->disk_sb.bdev)));
697 
698 	this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_sb],
699 		     bio_sectors(bio));
700 
701 	percpu_ref_get(&ca->io_ref);
702 	closure_bio_submit(bio, &c->sb_write);
703 }
704 
705 int bch2_write_super(struct bch_fs *c)
706 {
707 	struct closure *cl = &c->sb_write;
708 	struct bch_dev *ca;
709 	unsigned i, sb = 0, nr_wrote;
710 	const char *err;
711 	struct bch_devs_mask sb_written;
712 	bool wrote, can_mount_without_written, can_mount_with_written;
713 	unsigned degraded_flags = BCH_FORCE_IF_DEGRADED;
714 	int ret = 0;
715 
716 	if (c->opts.very_degraded)
717 		degraded_flags |= BCH_FORCE_IF_LOST;
718 
719 	lockdep_assert_held(&c->sb_lock);
720 
721 	closure_init_stack(cl);
722 	memset(&sb_written, 0, sizeof(sb_written));
723 
724 	le64_add_cpu(&c->disk_sb.sb->seq, 1);
725 
726 	if (test_bit(BCH_FS_ERROR, &c->flags))
727 		SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 1);
728 	if (test_bit(BCH_FS_TOPOLOGY_ERROR, &c->flags))
729 		SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 1);
730 
731 	SET_BCH_SB_BIG_ENDIAN(c->disk_sb.sb, CPU_BIG_ENDIAN);
732 
733 	for_each_online_member(ca, c, i)
734 		bch2_sb_from_fs(c, ca);
735 
736 	for_each_online_member(ca, c, i) {
737 		err = bch2_sb_validate(&ca->disk_sb);
738 		if (err) {
739 			bch2_fs_inconsistent(c, "sb invalid before write: %s", err);
740 			ret = -1;
741 			goto out;
742 		}
743 	}
744 
745 	if (c->opts.nochanges)
746 		goto out;
747 
748 	for_each_online_member(ca, c, i) {
749 		__set_bit(ca->dev_idx, sb_written.d);
750 		ca->sb_write_error = 0;
751 	}
752 
753 	for_each_online_member(ca, c, i)
754 		read_back_super(c, ca);
755 	closure_sync(cl);
756 
757 	for_each_online_member(ca, c, i) {
758 		if (!ca->sb_write_error &&
759 		    ca->disk_sb.seq !=
760 		    le64_to_cpu(ca->sb_read_scratch->seq)) {
761 			bch2_fs_fatal_error(c,
762 				"Superblock modified by another process");
763 			percpu_ref_put(&ca->io_ref);
764 			ret = -EROFS;
765 			goto out;
766 		}
767 	}
768 
769 	do {
770 		wrote = false;
771 		for_each_online_member(ca, c, i)
772 			if (!ca->sb_write_error &&
773 			    sb < ca->disk_sb.sb->layout.nr_superblocks) {
774 				write_one_super(c, ca, sb);
775 				wrote = true;
776 			}
777 		closure_sync(cl);
778 		sb++;
779 	} while (wrote);
780 
781 	for_each_online_member(ca, c, i) {
782 		if (ca->sb_write_error)
783 			__clear_bit(ca->dev_idx, sb_written.d);
784 		else
785 			ca->disk_sb.seq = le64_to_cpu(ca->disk_sb.sb->seq);
786 	}
787 
788 	nr_wrote = dev_mask_nr(&sb_written);
789 
790 	can_mount_with_written =
791 		bch2_have_enough_devs(c, sb_written, degraded_flags, false);
792 
793 	for (i = 0; i < ARRAY_SIZE(sb_written.d); i++)
794 		sb_written.d[i] = ~sb_written.d[i];
795 
796 	can_mount_without_written =
797 		bch2_have_enough_devs(c, sb_written, degraded_flags, false);
798 
799 	/*
800 	 * If we would be able to mount _without_ the devices we successfully
801 	 * wrote superblocks to, we weren't able to write to enough devices:
802 	 *
803 	 * Exception: if we can mount without the successes because we haven't
804 	 * written anything (new filesystem), we continue if we'd be able to
805 	 * mount with the devices we did successfully write to:
806 	 */
807 	if (bch2_fs_fatal_err_on(!nr_wrote ||
808 				 !can_mount_with_written ||
809 				 (can_mount_without_written &&
810 				  !can_mount_with_written), c,
811 		"Unable to write superblock to sufficient devices (from %ps)",
812 		(void *) _RET_IP_))
813 		ret = -1;
814 out:
815 	/* Make new options visible after they're persistent: */
816 	bch2_sb_update(c);
817 	return ret;
818 }
819 
820 void __bch2_check_set_feature(struct bch_fs *c, unsigned feat)
821 {
822 	mutex_lock(&c->sb_lock);
823 	if (!(c->sb.features & (1ULL << feat))) {
824 		c->disk_sb.sb->features[0] |= cpu_to_le64(1ULL << feat);
825 
826 		bch2_write_super(c);
827 	}
828 	mutex_unlock(&c->sb_lock);
829 }
830 
831 /* BCH_SB_FIELD_journal: */
832 
833 static int u64_cmp(const void *_l, const void *_r)
834 {
835 	u64 l = *((const u64 *) _l), r = *((const u64 *) _r);
836 
837 	return l < r ? -1 : l > r ? 1 : 0;
838 }
839 
840 static const char *bch2_sb_validate_journal(struct bch_sb *sb,
841 					    struct bch_sb_field *f)
842 {
843 	struct bch_sb_field_journal *journal = field_to_type(f, journal);
844 	struct bch_member *m = bch2_sb_get_members(sb)->members + sb->dev_idx;
845 	const char *err;
846 	unsigned nr;
847 	unsigned i;
848 	u64 *b;
849 
850 	journal = bch2_sb_get_journal(sb);
851 	if (!journal)
852 		return NULL;
853 
854 	nr = bch2_nr_journal_buckets(journal);
855 	if (!nr)
856 		return NULL;
857 
858 	b = kmalloc_array(sizeof(u64), nr, GFP_KERNEL);
859 	if (!b)
860 		return "cannot allocate memory";
861 
862 	for (i = 0; i < nr; i++)
863 		b[i] = le64_to_cpu(journal->buckets[i]);
864 
865 	sort(b, nr, sizeof(u64), u64_cmp, NULL);
866 
867 	err = "journal bucket at sector 0";
868 	if (!b[0])
869 		goto err;
870 
871 	err = "journal bucket before first bucket";
872 	if (m && b[0] < le16_to_cpu(m->first_bucket))
873 		goto err;
874 
875 	err = "journal bucket past end of device";
876 	if (m && b[nr - 1] >= le64_to_cpu(m->nbuckets))
877 		goto err;
878 
879 	err = "duplicate journal buckets";
880 	for (i = 0; i + 1 < nr; i++)
881 		if (b[i] == b[i + 1])
882 			goto err;
883 
884 	err = NULL;
885 err:
886 	kfree(b);
887 	return err;
888 }
889 
890 static const struct bch_sb_field_ops bch_sb_field_ops_journal = {
891 	.validate	= bch2_sb_validate_journal,
892 };
893 
894 /* BCH_SB_FIELD_members: */
895 
896 static const char *bch2_sb_validate_members(struct bch_sb *sb,
897 					    struct bch_sb_field *f)
898 {
899 	struct bch_sb_field_members *mi = field_to_type(f, members);
900 	struct bch_member *m;
901 
902 	if ((void *) (mi->members + sb->nr_devices) >
903 	    vstruct_end(&mi->field))
904 		return "Invalid superblock: bad member info";
905 
906 	for (m = mi->members;
907 	     m < mi->members + sb->nr_devices;
908 	     m++) {
909 		if (!bch2_member_exists(m))
910 			continue;
911 
912 		if (le64_to_cpu(m->nbuckets) > LONG_MAX)
913 			return "Too many buckets";
914 
915 		if (le64_to_cpu(m->nbuckets) -
916 		    le16_to_cpu(m->first_bucket) < BCH_MIN_NR_NBUCKETS)
917 			return "Not enough buckets";
918 
919 		if (le16_to_cpu(m->bucket_size) <
920 		    le16_to_cpu(sb->block_size))
921 			return "bucket size smaller than block size";
922 
923 		if (le16_to_cpu(m->bucket_size) <
924 		    BCH_SB_BTREE_NODE_SIZE(sb))
925 			return "bucket size smaller than btree node size";
926 	}
927 
928 	return NULL;
929 }
930 
931 static const struct bch_sb_field_ops bch_sb_field_ops_members = {
932 	.validate	= bch2_sb_validate_members,
933 };
934 
935 /* BCH_SB_FIELD_crypt: */
936 
937 static const char *bch2_sb_validate_crypt(struct bch_sb *sb,
938 					  struct bch_sb_field *f)
939 {
940 	struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
941 
942 	if (vstruct_bytes(&crypt->field) != sizeof(*crypt))
943 		return "invalid field crypt: wrong size";
944 
945 	if (BCH_CRYPT_KDF_TYPE(crypt))
946 		return "invalid field crypt: bad kdf type";
947 
948 	return NULL;
949 }
950 
951 static const struct bch_sb_field_ops bch_sb_field_ops_crypt = {
952 	.validate	= bch2_sb_validate_crypt,
953 };
954 
955 /* BCH_SB_FIELD_clean: */
956 
957 int bch2_sb_clean_validate(struct bch_fs *c, struct bch_sb_field_clean *clean, int write)
958 {
959 	struct jset_entry *entry;
960 	int ret;
961 
962 	for (entry = clean->start;
963 	     entry < (struct jset_entry *) vstruct_end(&clean->field);
964 	     entry = vstruct_next(entry)) {
965 		ret = bch2_journal_entry_validate(c, "superblock", entry,
966 						  le16_to_cpu(c->disk_sb.sb->version),
967 						  BCH_SB_BIG_ENDIAN(c->disk_sb.sb),
968 						  write);
969 		if (ret)
970 			return ret;
971 	}
972 
973 	return 0;
974 }
975 
976 int bch2_fs_mark_dirty(struct bch_fs *c)
977 {
978 	int ret;
979 
980 	/*
981 	 * Unconditionally write superblock, to verify it hasn't changed before
982 	 * we go rw:
983 	 */
984 
985 	mutex_lock(&c->sb_lock);
986 	SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
987 	c->disk_sb.sb->features[0] |= cpu_to_le64(BCH_SB_FEATURES_ALWAYS);
988 	c->disk_sb.sb->compat[0] &= cpu_to_le64((1ULL << BCH_COMPAT_NR) - 1);
989 	ret = bch2_write_super(c);
990 	mutex_unlock(&c->sb_lock);
991 
992 	return ret;
993 }
994 
995 static struct jset_entry *jset_entry_init(struct jset_entry **end, size_t size)
996 {
997 	struct jset_entry *entry = *end;
998 	unsigned u64s = DIV_ROUND_UP(size, sizeof(u64));
999 
1000 	memset(entry, 0, u64s * sizeof(u64));
1001 	/*
1002 	 * The u64s field counts from the start of data, ignoring the shared
1003 	 * fields.
1004 	 */
1005 	entry->u64s = cpu_to_le16(u64s - 1);
1006 
1007 	*end = vstruct_next(*end);
1008 	return entry;
1009 }
1010 
1011 void bch2_journal_super_entries_add_common(struct bch_fs *c,
1012 					   struct jset_entry **end,
1013 					   u64 journal_seq)
1014 {
1015 	struct bch_dev *ca;
1016 	unsigned i, dev;
1017 
1018 	percpu_down_read(&c->mark_lock);
1019 
1020 	if (!journal_seq) {
1021 		for (i = 0; i < ARRAY_SIZE(c->usage); i++)
1022 			bch2_fs_usage_acc_to_base(c, i);
1023 	} else {
1024 		bch2_fs_usage_acc_to_base(c, journal_seq & JOURNAL_BUF_MASK);
1025 	}
1026 
1027 	{
1028 		struct jset_entry_usage *u =
1029 			container_of(jset_entry_init(end, sizeof(*u)),
1030 				     struct jset_entry_usage, entry);
1031 
1032 		u->entry.type	= BCH_JSET_ENTRY_usage;
1033 		u->entry.btree_id = FS_USAGE_INODES;
1034 		u->v		= cpu_to_le64(c->usage_base->nr_inodes);
1035 	}
1036 
1037 	{
1038 		struct jset_entry_usage *u =
1039 			container_of(jset_entry_init(end, sizeof(*u)),
1040 				     struct jset_entry_usage, entry);
1041 
1042 		u->entry.type	= BCH_JSET_ENTRY_usage;
1043 		u->entry.btree_id = FS_USAGE_KEY_VERSION;
1044 		u->v		= cpu_to_le64(atomic64_read(&c->key_version));
1045 	}
1046 
1047 	for (i = 0; i < BCH_REPLICAS_MAX; i++) {
1048 		struct jset_entry_usage *u =
1049 			container_of(jset_entry_init(end, sizeof(*u)),
1050 				     struct jset_entry_usage, entry);
1051 
1052 		u->entry.type	= BCH_JSET_ENTRY_usage;
1053 		u->entry.btree_id = FS_USAGE_RESERVED;
1054 		u->entry.level	= i;
1055 		u->v		= cpu_to_le64(c->usage_base->persistent_reserved[i]);
1056 	}
1057 
1058 	for (i = 0; i < c->replicas.nr; i++) {
1059 		struct bch_replicas_entry *e =
1060 			cpu_replicas_entry(&c->replicas, i);
1061 		struct jset_entry_data_usage *u =
1062 			container_of(jset_entry_init(end, sizeof(*u) + e->nr_devs),
1063 				     struct jset_entry_data_usage, entry);
1064 
1065 		u->entry.type	= BCH_JSET_ENTRY_data_usage;
1066 		u->v		= cpu_to_le64(c->usage_base->replicas[i]);
1067 		unsafe_memcpy(&u->r, e, replicas_entry_bytes(e),
1068 			      "embedded variable length struct");
1069 	}
1070 
1071 	for_each_member_device(ca, c, dev) {
1072 		unsigned b = sizeof(struct jset_entry_dev_usage) +
1073 			sizeof(struct jset_entry_dev_usage_type) * BCH_DATA_NR;
1074 		struct jset_entry_dev_usage *u =
1075 			container_of(jset_entry_init(end, b),
1076 				     struct jset_entry_dev_usage, entry);
1077 
1078 		u->entry.type = BCH_JSET_ENTRY_dev_usage;
1079 		u->dev = cpu_to_le32(dev);
1080 		u->buckets_ec		= cpu_to_le64(ca->usage_base->buckets_ec);
1081 		u->buckets_unavailable	= cpu_to_le64(ca->usage_base->buckets_unavailable);
1082 
1083 		for (i = 0; i < BCH_DATA_NR; i++) {
1084 			u->d[i].buckets = cpu_to_le64(ca->usage_base->d[i].buckets);
1085 			u->d[i].sectors	= cpu_to_le64(ca->usage_base->d[i].sectors);
1086 			u->d[i].fragmented = cpu_to_le64(ca->usage_base->d[i].fragmented);
1087 		}
1088 	}
1089 
1090 	percpu_up_read(&c->mark_lock);
1091 
1092 	for (i = 0; i < 2; i++) {
1093 		struct jset_entry_clock *clock =
1094 			container_of(jset_entry_init(end, sizeof(*clock)),
1095 				     struct jset_entry_clock, entry);
1096 
1097 		clock->entry.type = BCH_JSET_ENTRY_clock;
1098 		clock->rw	= i;
1099 		clock->time	= cpu_to_le64(atomic64_read(&c->io_clock[i].now));
1100 	}
1101 }
1102 
1103 void bch2_fs_mark_clean(struct bch_fs *c)
1104 {
1105 	struct bch_sb_field_clean *sb_clean;
1106 	struct jset_entry *entry;
1107 	unsigned u64s;
1108 	int ret;
1109 
1110 	mutex_lock(&c->sb_lock);
1111 	if (BCH_SB_CLEAN(c->disk_sb.sb))
1112 		goto out;
1113 
1114 	SET_BCH_SB_CLEAN(c->disk_sb.sb, true);
1115 
1116 	c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_info);
1117 	c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_metadata);
1118 	c->disk_sb.sb->features[0] &= cpu_to_le64(~(1ULL << BCH_FEATURE_extents_above_btree_updates));
1119 	c->disk_sb.sb->features[0] &= cpu_to_le64(~(1ULL << BCH_FEATURE_btree_updates_journalled));
1120 
1121 	u64s = sizeof(*sb_clean) / sizeof(u64) + c->journal.entry_u64s_reserved;
1122 
1123 	sb_clean = bch2_sb_resize_clean(&c->disk_sb, u64s);
1124 	if (!sb_clean) {
1125 		bch_err(c, "error resizing superblock while setting filesystem clean");
1126 		goto out;
1127 	}
1128 
1129 	sb_clean->flags		= 0;
1130 	sb_clean->journal_seq	= cpu_to_le64(journal_cur_seq(&c->journal) - 1);
1131 
1132 	/* Trying to catch outstanding bug: */
1133 	BUG_ON(le64_to_cpu(sb_clean->journal_seq) > S64_MAX);
1134 
1135 	entry = sb_clean->start;
1136 	bch2_journal_super_entries_add_common(c, &entry, 0);
1137 	entry = bch2_btree_roots_to_journal_entries(c, entry, entry);
1138 	BUG_ON((void *) entry > vstruct_end(&sb_clean->field));
1139 
1140 	memset(entry, 0,
1141 	       vstruct_end(&sb_clean->field) - (void *) entry);
1142 
1143 	/*
1144 	 * this should be in the write path, and we should be validating every
1145 	 * superblock section:
1146 	 */
1147 	ret = bch2_sb_clean_validate(c, sb_clean, WRITE);
1148 	if (ret) {
1149 		bch_err(c, "error writing marking filesystem clean: validate error");
1150 		goto out;
1151 	}
1152 
1153 	bch2_write_super(c);
1154 out:
1155 	mutex_unlock(&c->sb_lock);
1156 }
1157 
1158 static const char *bch2_sb_validate_clean(struct bch_sb *sb,
1159 					  struct bch_sb_field *f)
1160 {
1161 	struct bch_sb_field_clean *clean = field_to_type(f, clean);
1162 
1163 	if (vstruct_bytes(&clean->field) < sizeof(*clean))
1164 		return "invalid field crypt: wrong size";
1165 
1166 	return NULL;
1167 }
1168 
1169 static const struct bch_sb_field_ops bch_sb_field_ops_clean = {
1170 	.validate	= bch2_sb_validate_clean,
1171 };
1172 
1173 static const struct bch_sb_field_ops *bch2_sb_field_ops[] = {
1174 #define x(f, nr)					\
1175 	[BCH_SB_FIELD_##f] = &bch_sb_field_ops_##f,
1176 	BCH_SB_FIELDS()
1177 #undef x
1178 };
1179 
1180 static const char *bch2_sb_field_validate(struct bch_sb *sb,
1181 					  struct bch_sb_field *f)
1182 {
1183 	unsigned type = le32_to_cpu(f->type);
1184 
1185 	return type < BCH_SB_FIELD_NR
1186 		? bch2_sb_field_ops[type]->validate(sb, f)
1187 		: NULL;
1188 }
1189 
1190 void bch2_sb_field_to_text(struct printbuf *out, struct bch_sb *sb,
1191 			   struct bch_sb_field *f)
1192 {
1193 	unsigned type = le32_to_cpu(f->type);
1194 	const struct bch_sb_field_ops *ops = type < BCH_SB_FIELD_NR
1195 		? bch2_sb_field_ops[type] : NULL;
1196 
1197 	if (ops)
1198 		pr_buf(out, "%s", bch2_sb_fields[type]);
1199 	else
1200 		pr_buf(out, "(unknown field %u)", type);
1201 
1202 	pr_buf(out, " (size %llu):", vstruct_bytes(f));
1203 
1204 	if (ops && ops->to_text)
1205 		bch2_sb_field_ops[type]->to_text(out, sb, f);
1206 }
1207