xref: /linux/fs/bcachefs/super-io.c (revision 0f52fd4f67c67f7f2ea3063c627e466255f027fd)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "checksum.h"
5 #include "disk_groups.h"
6 #include "ec.h"
7 #include "error.h"
8 #include "journal.h"
9 #include "journal_sb.h"
10 #include "journal_seq_blacklist.h"
11 #include "recovery_passes.h"
12 #include "replicas.h"
13 #include "quota.h"
14 #include "sb-clean.h"
15 #include "sb-counters.h"
16 #include "sb-downgrade.h"
17 #include "sb-errors.h"
18 #include "sb-members.h"
19 #include "super-io.h"
20 #include "super.h"
21 #include "trace.h"
22 #include "vstructs.h"
23 
24 #include <linux/backing-dev.h>
25 #include <linux/sort.h>
26 #include <linux/string_choices.h>
27 
28 static const struct blk_holder_ops bch2_sb_handle_bdev_ops = {
29 };
30 
31 struct bch2_metadata_version {
32 	u16		version;
33 	const char	*name;
34 };
35 
36 static const struct bch2_metadata_version bch2_metadata_versions[] = {
37 #define x(n, v) {		\
38 	.version = v,				\
39 	.name = #n,				\
40 },
41 	BCH_METADATA_VERSIONS()
42 #undef x
43 };
44 
bch2_version_to_text(struct printbuf * out,enum bcachefs_metadata_version v)45 void bch2_version_to_text(struct printbuf *out, enum bcachefs_metadata_version v)
46 {
47 	const char *str = "(unknown version)";
48 
49 	for (unsigned i = 0; i < ARRAY_SIZE(bch2_metadata_versions); i++)
50 		if (bch2_metadata_versions[i].version == v) {
51 			str = bch2_metadata_versions[i].name;
52 			break;
53 		}
54 
55 	prt_printf(out, "%u.%u: %s", BCH_VERSION_MAJOR(v), BCH_VERSION_MINOR(v), str);
56 }
57 
bch2_latest_compatible_version(enum bcachefs_metadata_version v)58 enum bcachefs_metadata_version bch2_latest_compatible_version(enum bcachefs_metadata_version v)
59 {
60 	if (!BCH_VERSION_MAJOR(v))
61 		return v;
62 
63 	for (unsigned i = 0; i < ARRAY_SIZE(bch2_metadata_versions); i++)
64 		if (bch2_metadata_versions[i].version > v &&
65 		    BCH_VERSION_MAJOR(bch2_metadata_versions[i].version) ==
66 		    BCH_VERSION_MAJOR(v))
67 			v = bch2_metadata_versions[i].version;
68 
69 	return v;
70 }
71 
bch2_set_version_incompat(struct bch_fs * c,enum bcachefs_metadata_version version)72 bool bch2_set_version_incompat(struct bch_fs *c, enum bcachefs_metadata_version version)
73 {
74 	bool ret = (c->sb.features & BIT_ULL(BCH_FEATURE_incompat_version_field)) &&
75 		   version <= c->sb.version_incompat_allowed;
76 
77 	if (ret) {
78 		mutex_lock(&c->sb_lock);
79 		SET_BCH_SB_VERSION_INCOMPAT(c->disk_sb.sb,
80 			max(BCH_SB_VERSION_INCOMPAT(c->disk_sb.sb), version));
81 		bch2_write_super(c);
82 		mutex_unlock(&c->sb_lock);
83 	}
84 
85 	return ret;
86 }
87 
88 const char * const bch2_sb_fields[] = {
89 #define x(name, nr)	#name,
90 	BCH_SB_FIELDS()
91 #undef x
92 	NULL
93 };
94 
95 static int bch2_sb_field_validate(struct bch_sb *, struct bch_sb_field *,
96 				  enum bch_validate_flags, struct printbuf *);
97 
bch2_sb_field_get_id(struct bch_sb * sb,enum bch_sb_field_type type)98 struct bch_sb_field *bch2_sb_field_get_id(struct bch_sb *sb,
99 				      enum bch_sb_field_type type)
100 {
101 	/* XXX: need locking around superblock to access optional fields */
102 
103 	vstruct_for_each(sb, f)
104 		if (le32_to_cpu(f->type) == type)
105 			return f;
106 	return NULL;
107 }
108 
__bch2_sb_field_resize(struct bch_sb_handle * sb,struct bch_sb_field * f,unsigned u64s)109 static struct bch_sb_field *__bch2_sb_field_resize(struct bch_sb_handle *sb,
110 						   struct bch_sb_field *f,
111 						   unsigned u64s)
112 {
113 	unsigned old_u64s = f ? le32_to_cpu(f->u64s) : 0;
114 	unsigned sb_u64s = le32_to_cpu(sb->sb->u64s) + u64s - old_u64s;
115 
116 	BUG_ON(__vstruct_bytes(struct bch_sb, sb_u64s) > sb->buffer_size);
117 
118 	if (!f && !u64s) {
119 		/* nothing to do: */
120 	} else if (!f) {
121 		f = vstruct_last(sb->sb);
122 		memset(f, 0, sizeof(u64) * u64s);
123 		f->u64s = cpu_to_le32(u64s);
124 		f->type = 0;
125 	} else {
126 		void *src, *dst;
127 
128 		src = vstruct_end(f);
129 
130 		if (u64s) {
131 			f->u64s = cpu_to_le32(u64s);
132 			dst = vstruct_end(f);
133 		} else {
134 			dst = f;
135 		}
136 
137 		memmove(dst, src, vstruct_end(sb->sb) - src);
138 
139 		if (dst > src)
140 			memset(src, 0, dst - src);
141 	}
142 
143 	sb->sb->u64s = cpu_to_le32(sb_u64s);
144 
145 	return u64s ? f : NULL;
146 }
147 
bch2_sb_field_delete(struct bch_sb_handle * sb,enum bch_sb_field_type type)148 void bch2_sb_field_delete(struct bch_sb_handle *sb,
149 			  enum bch_sb_field_type type)
150 {
151 	struct bch_sb_field *f = bch2_sb_field_get_id(sb->sb, type);
152 
153 	if (f)
154 		__bch2_sb_field_resize(sb, f, 0);
155 }
156 
157 /* Superblock realloc/free: */
158 
bch2_free_super(struct bch_sb_handle * sb)159 void bch2_free_super(struct bch_sb_handle *sb)
160 {
161 	kfree(sb->bio);
162 	if (!IS_ERR_OR_NULL(sb->s_bdev_file))
163 		bdev_fput(sb->s_bdev_file);
164 	kfree(sb->holder);
165 	kfree(sb->sb_name);
166 
167 	kfree(sb->sb);
168 	memset(sb, 0, sizeof(*sb));
169 }
170 
bch2_sb_realloc(struct bch_sb_handle * sb,unsigned u64s)171 int bch2_sb_realloc(struct bch_sb_handle *sb, unsigned u64s)
172 {
173 	size_t new_bytes = __vstruct_bytes(struct bch_sb, u64s);
174 	size_t new_buffer_size;
175 	struct bch_sb *new_sb;
176 	struct bio *bio;
177 
178 	if (sb->bdev)
179 		new_bytes = max_t(size_t, new_bytes, bdev_logical_block_size(sb->bdev));
180 
181 	new_buffer_size = roundup_pow_of_two(new_bytes);
182 
183 	if (sb->sb && sb->buffer_size >= new_buffer_size)
184 		return 0;
185 
186 	if (sb->sb && sb->have_layout) {
187 		u64 max_bytes = 512 << sb->sb->layout.sb_max_size_bits;
188 
189 		if (new_bytes > max_bytes) {
190 			struct printbuf buf = PRINTBUF;
191 
192 			prt_bdevname(&buf, sb->bdev);
193 			prt_printf(&buf, ": superblock too big: want %zu but have %llu", new_bytes, max_bytes);
194 			pr_err("%s", buf.buf);
195 			printbuf_exit(&buf);
196 			return -BCH_ERR_ENOSPC_sb;
197 		}
198 	}
199 
200 	if (sb->buffer_size >= new_buffer_size && sb->sb)
201 		return 0;
202 
203 	if (dynamic_fault("bcachefs:add:super_realloc"))
204 		return -BCH_ERR_ENOMEM_sb_realloc_injected;
205 
206 	new_sb = krealloc(sb->sb, new_buffer_size, GFP_NOFS|__GFP_ZERO);
207 	if (!new_sb)
208 		return -BCH_ERR_ENOMEM_sb_buf_realloc;
209 
210 	sb->sb = new_sb;
211 
212 	if (sb->have_bio) {
213 		unsigned nr_bvecs = buf_pages(sb->sb, new_buffer_size);
214 
215 		bio = bio_kmalloc(nr_bvecs, GFP_KERNEL);
216 		if (!bio)
217 			return -BCH_ERR_ENOMEM_sb_bio_realloc;
218 
219 		bio_init(bio, NULL, bio->bi_inline_vecs, nr_bvecs, 0);
220 
221 		kfree(sb->bio);
222 		sb->bio = bio;
223 	}
224 
225 	sb->buffer_size = new_buffer_size;
226 
227 	return 0;
228 }
229 
bch2_sb_field_resize_id(struct bch_sb_handle * sb,enum bch_sb_field_type type,unsigned u64s)230 struct bch_sb_field *bch2_sb_field_resize_id(struct bch_sb_handle *sb,
231 					  enum bch_sb_field_type type,
232 					  unsigned u64s)
233 {
234 	struct bch_sb_field *f = bch2_sb_field_get_id(sb->sb, type);
235 	ssize_t old_u64s = f ? le32_to_cpu(f->u64s) : 0;
236 	ssize_t d = -old_u64s + u64s;
237 
238 	if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s) + d))
239 		return NULL;
240 
241 	if (sb->fs_sb) {
242 		struct bch_fs *c = container_of(sb, struct bch_fs, disk_sb);
243 
244 		lockdep_assert_held(&c->sb_lock);
245 
246 		/* XXX: we're not checking that offline device have enough space */
247 
248 		for_each_online_member(c, ca) {
249 			struct bch_sb_handle *dev_sb = &ca->disk_sb;
250 
251 			if (bch2_sb_realloc(dev_sb, le32_to_cpu(dev_sb->sb->u64s) + d)) {
252 				percpu_ref_put(&ca->io_ref);
253 				return NULL;
254 			}
255 		}
256 	}
257 
258 	f = bch2_sb_field_get_id(sb->sb, type);
259 	f = __bch2_sb_field_resize(sb, f, u64s);
260 	if (f)
261 		f->type = cpu_to_le32(type);
262 	return f;
263 }
264 
bch2_sb_field_get_minsize_id(struct bch_sb_handle * sb,enum bch_sb_field_type type,unsigned u64s)265 struct bch_sb_field *bch2_sb_field_get_minsize_id(struct bch_sb_handle *sb,
266 						  enum bch_sb_field_type type,
267 						  unsigned u64s)
268 {
269 	struct bch_sb_field *f = bch2_sb_field_get_id(sb->sb, type);
270 
271 	if (!f || le32_to_cpu(f->u64s) < u64s)
272 		f = bch2_sb_field_resize_id(sb, type, u64s);
273 	return f;
274 }
275 
276 /* Superblock validate: */
277 
validate_sb_layout(struct bch_sb_layout * layout,struct printbuf * out)278 static int validate_sb_layout(struct bch_sb_layout *layout, struct printbuf *out)
279 {
280 	u64 offset, prev_offset, max_sectors;
281 	unsigned i;
282 
283 	BUILD_BUG_ON(sizeof(struct bch_sb_layout) != 512);
284 
285 	if (!uuid_equal(&layout->magic, &BCACHE_MAGIC) &&
286 	    !uuid_equal(&layout->magic, &BCHFS_MAGIC)) {
287 		prt_printf(out, "Not a bcachefs superblock layout");
288 		return -BCH_ERR_invalid_sb_layout;
289 	}
290 
291 	if (layout->layout_type != 0) {
292 		prt_printf(out, "Invalid superblock layout type %u",
293 		       layout->layout_type);
294 		return -BCH_ERR_invalid_sb_layout_type;
295 	}
296 
297 	if (!layout->nr_superblocks) {
298 		prt_printf(out, "Invalid superblock layout: no superblocks");
299 		return -BCH_ERR_invalid_sb_layout_nr_superblocks;
300 	}
301 
302 	if (layout->nr_superblocks > ARRAY_SIZE(layout->sb_offset)) {
303 		prt_printf(out, "Invalid superblock layout: too many superblocks");
304 		return -BCH_ERR_invalid_sb_layout_nr_superblocks;
305 	}
306 
307 	if (layout->sb_max_size_bits > BCH_SB_LAYOUT_SIZE_BITS_MAX) {
308 		prt_printf(out, "Invalid superblock layout: max_size_bits too high");
309 		return -BCH_ERR_invalid_sb_layout_sb_max_size_bits;
310 	}
311 
312 	max_sectors = 1 << layout->sb_max_size_bits;
313 
314 	prev_offset = le64_to_cpu(layout->sb_offset[0]);
315 
316 	for (i = 1; i < layout->nr_superblocks; i++) {
317 		offset = le64_to_cpu(layout->sb_offset[i]);
318 
319 		if (offset < prev_offset + max_sectors) {
320 			prt_printf(out, "Invalid superblock layout: superblocks overlap\n"
321 			       "  (sb %u ends at %llu next starts at %llu",
322 			       i - 1, prev_offset + max_sectors, offset);
323 			return -BCH_ERR_invalid_sb_layout_superblocks_overlap;
324 		}
325 		prev_offset = offset;
326 	}
327 
328 	return 0;
329 }
330 
bch2_sb_compatible(struct bch_sb * sb,struct printbuf * out)331 static int bch2_sb_compatible(struct bch_sb *sb, struct printbuf *out)
332 {
333 	u16 version		= le16_to_cpu(sb->version);
334 	u16 version_min		= le16_to_cpu(sb->version_min);
335 
336 	if (!bch2_version_compatible(version)) {
337 		prt_str(out, "Unsupported superblock version ");
338 		bch2_version_to_text(out, version);
339 		prt_str(out, " (min ");
340 		bch2_version_to_text(out, bcachefs_metadata_version_min);
341 		prt_str(out, ", max ");
342 		bch2_version_to_text(out, bcachefs_metadata_version_current);
343 		prt_str(out, ")");
344 		return -BCH_ERR_invalid_sb_version;
345 	}
346 
347 	if (!bch2_version_compatible(version_min)) {
348 		prt_str(out, "Unsupported superblock version_min ");
349 		bch2_version_to_text(out, version_min);
350 		prt_str(out, " (min ");
351 		bch2_version_to_text(out, bcachefs_metadata_version_min);
352 		prt_str(out, ", max ");
353 		bch2_version_to_text(out, bcachefs_metadata_version_current);
354 		prt_str(out, ")");
355 		return -BCH_ERR_invalid_sb_version;
356 	}
357 
358 	if (version_min > version) {
359 		prt_str(out, "Bad minimum version ");
360 		bch2_version_to_text(out, version_min);
361 		prt_str(out, ", greater than version field ");
362 		bch2_version_to_text(out, version);
363 		return -BCH_ERR_invalid_sb_version;
364 	}
365 
366 	return 0;
367 }
368 
bch2_sb_validate(struct bch_sb_handle * disk_sb,enum bch_validate_flags flags,struct printbuf * out)369 static int bch2_sb_validate(struct bch_sb_handle *disk_sb,
370 			    enum bch_validate_flags flags, struct printbuf *out)
371 {
372 	struct bch_sb *sb = disk_sb->sb;
373 	struct bch_sb_field_members_v1 *mi;
374 	enum bch_opt_id opt_id;
375 	u16 block_size;
376 	int ret;
377 
378 	ret = bch2_sb_compatible(sb, out);
379 	if (ret)
380 		return ret;
381 
382 	if (sb->features[1] ||
383 	    (le64_to_cpu(sb->features[0]) & (~0ULL << BCH_FEATURE_NR))) {
384 		prt_printf(out, "Filesystem has incompatible features");
385 		return -BCH_ERR_invalid_sb_features;
386 	}
387 
388 	if (BCH_VERSION_MAJOR(le16_to_cpu(sb->version)) > BCH_VERSION_MAJOR(bcachefs_metadata_version_current) ||
389 	    BCH_SB_VERSION_INCOMPAT(sb) > bcachefs_metadata_version_current) {
390 		prt_printf(out, "Filesystem has incompatible version");
391 		return -BCH_ERR_invalid_sb_features;
392 	}
393 
394 	block_size = le16_to_cpu(sb->block_size);
395 
396 	if (block_size > PAGE_SECTORS) {
397 		prt_printf(out, "Block size too big (got %u, max %u)",
398 		       block_size, PAGE_SECTORS);
399 		return -BCH_ERR_invalid_sb_block_size;
400 	}
401 
402 	if (bch2_is_zero(sb->user_uuid.b, sizeof(sb->user_uuid))) {
403 		prt_printf(out, "Bad user UUID (got zeroes)");
404 		return -BCH_ERR_invalid_sb_uuid;
405 	}
406 
407 	if (bch2_is_zero(sb->uuid.b, sizeof(sb->uuid))) {
408 		prt_printf(out, "Bad internal UUID (got zeroes)");
409 		return -BCH_ERR_invalid_sb_uuid;
410 	}
411 
412 	if (!sb->nr_devices ||
413 	    sb->nr_devices > BCH_SB_MEMBERS_MAX) {
414 		prt_printf(out, "Bad number of member devices %u (max %u)",
415 		       sb->nr_devices, BCH_SB_MEMBERS_MAX);
416 		return -BCH_ERR_invalid_sb_too_many_members;
417 	}
418 
419 	if (sb->dev_idx >= sb->nr_devices) {
420 		prt_printf(out, "Bad dev_idx (got %u, nr_devices %u)",
421 		       sb->dev_idx, sb->nr_devices);
422 		return -BCH_ERR_invalid_sb_dev_idx;
423 	}
424 
425 	if (!sb->time_precision ||
426 	    le32_to_cpu(sb->time_precision) > NSEC_PER_SEC) {
427 		prt_printf(out, "Invalid time precision: %u (min 1, max %lu)",
428 		       le32_to_cpu(sb->time_precision), NSEC_PER_SEC);
429 		return -BCH_ERR_invalid_sb_time_precision;
430 	}
431 
432 	/* old versions didn't know to downgrade this field */
433 	if (BCH_SB_VERSION_INCOMPAT_ALLOWED(sb) > le16_to_cpu(sb->version))
434 		SET_BCH_SB_VERSION_INCOMPAT_ALLOWED(sb, le16_to_cpu(sb->version));
435 
436 	if (BCH_SB_VERSION_INCOMPAT(sb) > BCH_SB_VERSION_INCOMPAT_ALLOWED(sb)) {
437 		prt_printf(out, "Invalid version_incompat ");
438 		bch2_version_to_text(out, BCH_SB_VERSION_INCOMPAT(sb));
439 		prt_str(out, " > incompat_allowed ");
440 		bch2_version_to_text(out, BCH_SB_VERSION_INCOMPAT_ALLOWED(sb));
441 		if (flags & BCH_VALIDATE_write)
442 			return -BCH_ERR_invalid_sb_version;
443 		else
444 			SET_BCH_SB_VERSION_INCOMPAT_ALLOWED(sb, BCH_SB_VERSION_INCOMPAT(sb));
445 	}
446 
447 	if (!flags) {
448 		/*
449 		 * Been seeing a bug where these are getting inexplicably
450 		 * zeroed, so we're now validating them, but we have to be
451 		 * careful not to preven people's filesystems from mounting:
452 		 */
453 		if (!BCH_SB_JOURNAL_FLUSH_DELAY(sb))
454 			SET_BCH_SB_JOURNAL_FLUSH_DELAY(sb, 1000);
455 		if (!BCH_SB_JOURNAL_RECLAIM_DELAY(sb))
456 			SET_BCH_SB_JOURNAL_RECLAIM_DELAY(sb, 1000);
457 
458 		if (!BCH_SB_VERSION_UPGRADE_COMPLETE(sb))
459 			SET_BCH_SB_VERSION_UPGRADE_COMPLETE(sb, le16_to_cpu(sb->version));
460 
461 		if (le16_to_cpu(sb->version) <= bcachefs_metadata_version_disk_accounting_v2 &&
462 		    !BCH_SB_ALLOCATOR_STUCK_TIMEOUT(sb))
463 			SET_BCH_SB_ALLOCATOR_STUCK_TIMEOUT(sb, 30);
464 
465 		if (le16_to_cpu(sb->version) <= bcachefs_metadata_version_disk_accounting_v2)
466 			SET_BCH_SB_PROMOTE_WHOLE_EXTENTS(sb, true);
467 	}
468 
469 #ifdef __KERNEL__
470 	if (!BCH_SB_SHARD_INUMS_NBITS(sb))
471 		SET_BCH_SB_SHARD_INUMS_NBITS(sb, ilog2(roundup_pow_of_two(num_online_cpus())));
472 #endif
473 
474 	for (opt_id = 0; opt_id < bch2_opts_nr; opt_id++) {
475 		const struct bch_option *opt = bch2_opt_table + opt_id;
476 
477 		if (opt->get_sb != BCH2_NO_SB_OPT) {
478 			u64 v = bch2_opt_from_sb(sb, opt_id);
479 
480 			prt_printf(out, "Invalid option ");
481 			ret = bch2_opt_validate(opt, v, out);
482 			if (ret)
483 				return ret;
484 
485 			printbuf_reset(out);
486 		}
487 	}
488 
489 	/* validate layout */
490 	ret = validate_sb_layout(&sb->layout, out);
491 	if (ret)
492 		return ret;
493 
494 	vstruct_for_each(sb, f) {
495 		if (!f->u64s) {
496 			prt_printf(out, "Invalid superblock: optional field with size 0 (type %u)",
497 			       le32_to_cpu(f->type));
498 			return -BCH_ERR_invalid_sb_field_size;
499 		}
500 
501 		if (vstruct_next(f) > vstruct_last(sb)) {
502 			prt_printf(out, "Invalid superblock: optional field extends past end of superblock (type %u)",
503 			       le32_to_cpu(f->type));
504 			return -BCH_ERR_invalid_sb_field_size;
505 		}
506 	}
507 
508 	/* members must be validated first: */
509 	mi = bch2_sb_field_get(sb, members_v1);
510 	if (!mi) {
511 		prt_printf(out, "Invalid superblock: member info area missing");
512 		return -BCH_ERR_invalid_sb_members_missing;
513 	}
514 
515 	ret = bch2_sb_field_validate(sb, &mi->field, flags, out);
516 	if (ret)
517 		return ret;
518 
519 	vstruct_for_each(sb, f) {
520 		if (le32_to_cpu(f->type) == BCH_SB_FIELD_members_v1)
521 			continue;
522 
523 		ret = bch2_sb_field_validate(sb, f, flags, out);
524 		if (ret)
525 			return ret;
526 	}
527 
528 	if ((flags & BCH_VALIDATE_write) &&
529 	    bch2_sb_member_get(sb, sb->dev_idx).seq != sb->seq) {
530 		prt_printf(out, "Invalid superblock: member seq %llu != sb seq %llu",
531 			   le64_to_cpu(bch2_sb_member_get(sb, sb->dev_idx).seq),
532 			   le64_to_cpu(sb->seq));
533 		return -BCH_ERR_invalid_sb_members_missing;
534 	}
535 
536 	return 0;
537 }
538 
539 /* device open: */
540 
le_ulong_to_cpu(unsigned long v)541 static unsigned long le_ulong_to_cpu(unsigned long v)
542 {
543 	return sizeof(unsigned long) == 8
544 		? le64_to_cpu(v)
545 		: le32_to_cpu(v);
546 }
547 
le_bitvector_to_cpu(unsigned long * dst,unsigned long * src,unsigned nr)548 static void le_bitvector_to_cpu(unsigned long *dst, unsigned long *src, unsigned nr)
549 {
550 	BUG_ON(nr & (BITS_PER_TYPE(long) - 1));
551 
552 	for (unsigned i = 0; i < BITS_TO_LONGS(nr); i++)
553 		dst[i] = le_ulong_to_cpu(src[i]);
554 }
555 
bch2_sb_update(struct bch_fs * c)556 static void bch2_sb_update(struct bch_fs *c)
557 {
558 	struct bch_sb *src = c->disk_sb.sb;
559 
560 	lockdep_assert_held(&c->sb_lock);
561 
562 	c->sb.uuid		= src->uuid;
563 	c->sb.user_uuid		= src->user_uuid;
564 	c->sb.version		= le16_to_cpu(src->version);
565 	c->sb.version_incompat	= BCH_SB_VERSION_INCOMPAT(src);
566 	c->sb.version_incompat_allowed
567 				= BCH_SB_VERSION_INCOMPAT_ALLOWED(src);
568 	c->sb.version_min	= le16_to_cpu(src->version_min);
569 	c->sb.version_upgrade_complete = BCH_SB_VERSION_UPGRADE_COMPLETE(src);
570 	c->sb.nr_devices	= src->nr_devices;
571 	c->sb.clean		= BCH_SB_CLEAN(src);
572 	c->sb.encryption_type	= BCH_SB_ENCRYPTION_TYPE(src);
573 
574 	c->sb.nsec_per_time_unit = le32_to_cpu(src->time_precision);
575 	c->sb.time_units_per_sec = NSEC_PER_SEC / c->sb.nsec_per_time_unit;
576 
577 	/* XXX this is wrong, we need a 96 or 128 bit integer type */
578 	c->sb.time_base_lo	= div_u64(le64_to_cpu(src->time_base_lo),
579 					  c->sb.nsec_per_time_unit);
580 	c->sb.time_base_hi	= le32_to_cpu(src->time_base_hi);
581 
582 	c->sb.features		= le64_to_cpu(src->features[0]);
583 	c->sb.compat		= le64_to_cpu(src->compat[0]);
584 
585 	memset(c->sb.errors_silent, 0, sizeof(c->sb.errors_silent));
586 
587 	struct bch_sb_field_ext *ext = bch2_sb_field_get(src, ext);
588 	if (ext) {
589 		le_bitvector_to_cpu(c->sb.errors_silent, (void *) ext->errors_silent,
590 				    sizeof(c->sb.errors_silent) * 8);
591 		c->sb.btrees_lost_data = le64_to_cpu(ext->btrees_lost_data);
592 	}
593 
594 	for_each_member_device(c, ca) {
595 		struct bch_member m = bch2_sb_member_get(src, ca->dev_idx);
596 		ca->mi = bch2_mi_to_cpu(&m);
597 	}
598 }
599 
__copy_super(struct bch_sb_handle * dst_handle,struct bch_sb * src)600 static int __copy_super(struct bch_sb_handle *dst_handle, struct bch_sb *src)
601 {
602 	struct bch_sb_field *src_f, *dst_f;
603 	struct bch_sb *dst = dst_handle->sb;
604 	unsigned i;
605 
606 	dst->version		= src->version;
607 	dst->version_min	= src->version_min;
608 	dst->seq		= src->seq;
609 	dst->uuid		= src->uuid;
610 	dst->user_uuid		= src->user_uuid;
611 	memcpy(dst->label,	src->label, sizeof(dst->label));
612 
613 	dst->block_size		= src->block_size;
614 	dst->nr_devices		= src->nr_devices;
615 
616 	dst->time_base_lo	= src->time_base_lo;
617 	dst->time_base_hi	= src->time_base_hi;
618 	dst->time_precision	= src->time_precision;
619 	dst->write_time		= src->write_time;
620 
621 	memcpy(dst->flags,	src->flags,	sizeof(dst->flags));
622 	memcpy(dst->features,	src->features,	sizeof(dst->features));
623 	memcpy(dst->compat,	src->compat,	sizeof(dst->compat));
624 
625 	for (i = 0; i < BCH_SB_FIELD_NR; i++) {
626 		int d;
627 
628 		if ((1U << i) & BCH_SINGLE_DEVICE_SB_FIELDS)
629 			continue;
630 
631 		src_f = bch2_sb_field_get_id(src, i);
632 		dst_f = bch2_sb_field_get_id(dst, i);
633 
634 		d = (src_f ? le32_to_cpu(src_f->u64s) : 0) -
635 		    (dst_f ? le32_to_cpu(dst_f->u64s) : 0);
636 		if (d > 0) {
637 			int ret = bch2_sb_realloc(dst_handle,
638 					le32_to_cpu(dst_handle->sb->u64s) + d);
639 
640 			if (ret)
641 				return ret;
642 
643 			dst = dst_handle->sb;
644 			dst_f = bch2_sb_field_get_id(dst, i);
645 		}
646 
647 		dst_f = __bch2_sb_field_resize(dst_handle, dst_f,
648 				src_f ? le32_to_cpu(src_f->u64s) : 0);
649 
650 		if (src_f)
651 			memcpy(dst_f, src_f, vstruct_bytes(src_f));
652 	}
653 
654 	return 0;
655 }
656 
bch2_sb_to_fs(struct bch_fs * c,struct bch_sb * src)657 int bch2_sb_to_fs(struct bch_fs *c, struct bch_sb *src)
658 {
659 	int ret;
660 
661 	lockdep_assert_held(&c->sb_lock);
662 
663 	ret =   bch2_sb_realloc(&c->disk_sb, 0) ?:
664 		__copy_super(&c->disk_sb, src) ?:
665 		bch2_sb_replicas_to_cpu_replicas(c) ?:
666 		bch2_sb_disk_groups_to_cpu(c);
667 	if (ret)
668 		return ret;
669 
670 	bch2_sb_update(c);
671 	return 0;
672 }
673 
bch2_sb_from_fs(struct bch_fs * c,struct bch_dev * ca)674 int bch2_sb_from_fs(struct bch_fs *c, struct bch_dev *ca)
675 {
676 	return __copy_super(&ca->disk_sb, c->disk_sb.sb);
677 }
678 
679 /* read superblock: */
680 
read_one_super(struct bch_sb_handle * sb,u64 offset,struct printbuf * err)681 static int read_one_super(struct bch_sb_handle *sb, u64 offset, struct printbuf *err)
682 {
683 	size_t bytes;
684 	int ret;
685 reread:
686 	bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
687 	sb->bio->bi_iter.bi_sector = offset;
688 	bch2_bio_map(sb->bio, sb->sb, sb->buffer_size);
689 
690 	ret = submit_bio_wait(sb->bio);
691 	if (ret) {
692 		prt_printf(err, "IO error: %i", ret);
693 		return ret;
694 	}
695 
696 	if (!uuid_equal(&sb->sb->magic, &BCACHE_MAGIC) &&
697 	    !uuid_equal(&sb->sb->magic, &BCHFS_MAGIC)) {
698 		prt_str(err, "Not a bcachefs superblock (got magic ");
699 		pr_uuid(err, sb->sb->magic.b);
700 		prt_str(err, ")");
701 		return -BCH_ERR_invalid_sb_magic;
702 	}
703 
704 	ret = bch2_sb_compatible(sb->sb, err);
705 	if (ret)
706 		return ret;
707 
708 	bytes = vstruct_bytes(sb->sb);
709 
710 	u64 sb_size = 512ULL << min(BCH_SB_LAYOUT_SIZE_BITS_MAX, sb->sb->layout.sb_max_size_bits);
711 	if (bytes > sb_size) {
712 		prt_printf(err, "Invalid superblock: too big (got %zu bytes, layout max %llu)",
713 			   bytes, sb_size);
714 		return -BCH_ERR_invalid_sb_too_big;
715 	}
716 
717 	if (bytes > sb->buffer_size) {
718 		ret = bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s));
719 		if (ret)
720 			return ret;
721 		goto reread;
722 	}
723 
724 	enum bch_csum_type csum_type = BCH_SB_CSUM_TYPE(sb->sb);
725 	if (csum_type >= BCH_CSUM_NR ||
726 	    bch2_csum_type_is_encryption(csum_type)) {
727 		prt_printf(err, "unknown checksum type %llu", BCH_SB_CSUM_TYPE(sb->sb));
728 		return -BCH_ERR_invalid_sb_csum_type;
729 	}
730 
731 	/* XXX: verify MACs */
732 	struct bch_csum csum = csum_vstruct(NULL, csum_type, null_nonce(), sb->sb);
733 	if (bch2_crc_cmp(csum, sb->sb->csum)) {
734 		bch2_csum_err_msg(err, csum_type, sb->sb->csum, csum);
735 		return -BCH_ERR_invalid_sb_csum;
736 	}
737 
738 	sb->seq = le64_to_cpu(sb->sb->seq);
739 
740 	return 0;
741 }
742 
__bch2_read_super(const char * path,struct bch_opts * opts,struct bch_sb_handle * sb,bool ignore_notbchfs_msg)743 static int __bch2_read_super(const char *path, struct bch_opts *opts,
744 		    struct bch_sb_handle *sb, bool ignore_notbchfs_msg)
745 {
746 	u64 offset = opt_get(*opts, sb);
747 	struct bch_sb_layout layout;
748 	struct printbuf err = PRINTBUF;
749 	struct printbuf err2 = PRINTBUF;
750 	__le64 *i;
751 	int ret;
752 #ifndef __KERNEL__
753 retry:
754 #endif
755 	memset(sb, 0, sizeof(*sb));
756 	sb->mode	= BLK_OPEN_READ;
757 	sb->have_bio	= true;
758 	sb->holder	= kmalloc(1, GFP_KERNEL);
759 	if (!sb->holder)
760 		return -ENOMEM;
761 
762 	sb->sb_name = kstrdup(path, GFP_KERNEL);
763 	if (!sb->sb_name) {
764 		ret = -ENOMEM;
765 		prt_printf(&err, "error allocating memory for sb_name");
766 		goto err;
767 	}
768 
769 #ifndef __KERNEL__
770 	if (opt_get(*opts, direct_io) == false)
771 		sb->mode |= BLK_OPEN_BUFFERED;
772 #endif
773 
774 	if (!opt_get(*opts, noexcl))
775 		sb->mode |= BLK_OPEN_EXCL;
776 
777 	if (!opt_get(*opts, nochanges))
778 		sb->mode |= BLK_OPEN_WRITE;
779 
780 	sb->s_bdev_file = bdev_file_open_by_path(path, sb->mode, sb->holder, &bch2_sb_handle_bdev_ops);
781 	if (IS_ERR(sb->s_bdev_file) &&
782 	    PTR_ERR(sb->s_bdev_file) == -EACCES &&
783 	    opt_get(*opts, read_only)) {
784 		sb->mode &= ~BLK_OPEN_WRITE;
785 
786 		sb->s_bdev_file = bdev_file_open_by_path(path, sb->mode, sb->holder, &bch2_sb_handle_bdev_ops);
787 		if (!IS_ERR(sb->s_bdev_file))
788 			opt_set(*opts, nochanges, true);
789 	}
790 
791 	if (IS_ERR(sb->s_bdev_file)) {
792 		ret = PTR_ERR(sb->s_bdev_file);
793 		prt_printf(&err, "error opening %s: %s", path, bch2_err_str(ret));
794 		goto err;
795 	}
796 	sb->bdev = file_bdev(sb->s_bdev_file);
797 
798 	ret = bch2_sb_realloc(sb, 0);
799 	if (ret) {
800 		prt_printf(&err, "error allocating memory for superblock");
801 		goto err;
802 	}
803 
804 	if (bch2_fs_init_fault("read_super")) {
805 		prt_printf(&err, "dynamic fault");
806 		ret = -EFAULT;
807 		goto err;
808 	}
809 
810 	ret = read_one_super(sb, offset, &err);
811 	if (!ret)
812 		goto got_super;
813 
814 	if (opt_defined(*opts, sb))
815 		goto err;
816 
817 	prt_printf(&err2, "bcachefs (%s): error reading default superblock: %s\n",
818 	       path, err.buf);
819 	if (ret == -BCH_ERR_invalid_sb_magic && ignore_notbchfs_msg)
820 		bch2_print_opts(opts, KERN_INFO "%s", err2.buf);
821 	else
822 		bch2_print_opts(opts, KERN_ERR "%s", err2.buf);
823 
824 	printbuf_exit(&err2);
825 	printbuf_reset(&err);
826 
827 	/*
828 	 * Error reading primary superblock - read location of backup
829 	 * superblocks:
830 	 */
831 	bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
832 	sb->bio->bi_iter.bi_sector = BCH_SB_LAYOUT_SECTOR;
833 	/*
834 	 * use sb buffer to read layout, since sb buffer is page aligned but
835 	 * layout won't be:
836 	 */
837 	bch2_bio_map(sb->bio, sb->sb, sizeof(struct bch_sb_layout));
838 
839 	ret = submit_bio_wait(sb->bio);
840 	if (ret) {
841 		prt_printf(&err, "IO error: %i", ret);
842 		goto err;
843 	}
844 
845 	memcpy(&layout, sb->sb, sizeof(layout));
846 	ret = validate_sb_layout(&layout, &err);
847 	if (ret)
848 		goto err;
849 
850 	for (i = layout.sb_offset;
851 	     i < layout.sb_offset + layout.nr_superblocks; i++) {
852 		offset = le64_to_cpu(*i);
853 
854 		if (offset == opt_get(*opts, sb)) {
855 			ret = -BCH_ERR_invalid;
856 			continue;
857 		}
858 
859 		ret = read_one_super(sb, offset, &err);
860 		if (!ret)
861 			goto got_super;
862 	}
863 
864 	goto err;
865 
866 got_super:
867 	if (le16_to_cpu(sb->sb->block_size) << 9 <
868 	    bdev_logical_block_size(sb->bdev) &&
869 	    opt_get(*opts, direct_io)) {
870 #ifndef __KERNEL__
871 		opt_set(*opts, direct_io, false);
872 		bch2_free_super(sb);
873 		goto retry;
874 #endif
875 		prt_printf(&err, "block size (%u) smaller than device block size (%u)",
876 		       le16_to_cpu(sb->sb->block_size) << 9,
877 		       bdev_logical_block_size(sb->bdev));
878 		ret = -BCH_ERR_block_size_too_small;
879 		goto err;
880 	}
881 
882 	sb->have_layout = true;
883 
884 	ret = bch2_sb_validate(sb, 0, &err);
885 	if (ret) {
886 		bch2_print_opts(opts, KERN_ERR "bcachefs (%s): error validating superblock: %s\n",
887 				path, err.buf);
888 		goto err_no_print;
889 	}
890 out:
891 	printbuf_exit(&err);
892 	return ret;
893 err:
894 	bch2_print_opts(opts, KERN_ERR "bcachefs (%s): error reading superblock: %s\n",
895 			path, err.buf);
896 err_no_print:
897 	bch2_free_super(sb);
898 	goto out;
899 }
900 
bch2_read_super(const char * path,struct bch_opts * opts,struct bch_sb_handle * sb)901 int bch2_read_super(const char *path, struct bch_opts *opts,
902 		    struct bch_sb_handle *sb)
903 {
904 	return __bch2_read_super(path, opts, sb, false);
905 }
906 
907 /* provide a silenced version for mount.bcachefs */
908 
bch2_read_super_silent(const char * path,struct bch_opts * opts,struct bch_sb_handle * sb)909 int bch2_read_super_silent(const char *path, struct bch_opts *opts,
910 		    struct bch_sb_handle *sb)
911 {
912 	return __bch2_read_super(path, opts, sb, true);
913 }
914 
915 /* write superblock: */
916 
write_super_endio(struct bio * bio)917 static void write_super_endio(struct bio *bio)
918 {
919 	struct bch_dev *ca = bio->bi_private;
920 
921 	/* XXX: return errors directly */
922 
923 	if (bch2_dev_io_err_on(bio->bi_status, ca,
924 			       bio_data_dir(bio)
925 			       ? BCH_MEMBER_ERROR_write
926 			       : BCH_MEMBER_ERROR_read,
927 			       "superblock %s error: %s",
928 			       str_write_read(bio_data_dir(bio)),
929 			       bch2_blk_status_to_str(bio->bi_status)))
930 		ca->sb_write_error = 1;
931 
932 	closure_put(&ca->fs->sb_write);
933 	percpu_ref_put(&ca->io_ref);
934 }
935 
read_back_super(struct bch_fs * c,struct bch_dev * ca)936 static void read_back_super(struct bch_fs *c, struct bch_dev *ca)
937 {
938 	struct bch_sb *sb = ca->disk_sb.sb;
939 	struct bio *bio = ca->disk_sb.bio;
940 
941 	memset(ca->sb_read_scratch, 0, BCH_SB_READ_SCRATCH_BUF_SIZE);
942 
943 	bio_reset(bio, ca->disk_sb.bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
944 	bio->bi_iter.bi_sector	= le64_to_cpu(sb->layout.sb_offset[0]);
945 	bio->bi_end_io		= write_super_endio;
946 	bio->bi_private		= ca;
947 	bch2_bio_map(bio, ca->sb_read_scratch, BCH_SB_READ_SCRATCH_BUF_SIZE);
948 
949 	this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_sb], bio_sectors(bio));
950 
951 	percpu_ref_get(&ca->io_ref);
952 	closure_bio_submit(bio, &c->sb_write);
953 }
954 
write_one_super(struct bch_fs * c,struct bch_dev * ca,unsigned idx)955 static void write_one_super(struct bch_fs *c, struct bch_dev *ca, unsigned idx)
956 {
957 	struct bch_sb *sb = ca->disk_sb.sb;
958 	struct bio *bio = ca->disk_sb.bio;
959 
960 	sb->offset = sb->layout.sb_offset[idx];
961 
962 	SET_BCH_SB_CSUM_TYPE(sb, bch2_csum_opt_to_type(c->opts.metadata_checksum, false));
963 	sb->csum = csum_vstruct(c, BCH_SB_CSUM_TYPE(sb),
964 				null_nonce(), sb);
965 
966 	bio_reset(bio, ca->disk_sb.bdev, REQ_OP_WRITE|REQ_SYNC|REQ_META);
967 	bio->bi_iter.bi_sector	= le64_to_cpu(sb->offset);
968 	bio->bi_end_io		= write_super_endio;
969 	bio->bi_private		= ca;
970 	bch2_bio_map(bio, sb,
971 		     roundup((size_t) vstruct_bytes(sb),
972 			     bdev_logical_block_size(ca->disk_sb.bdev)));
973 
974 	this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_sb],
975 		     bio_sectors(bio));
976 
977 	percpu_ref_get(&ca->io_ref);
978 	closure_bio_submit(bio, &c->sb_write);
979 }
980 
bch2_write_super(struct bch_fs * c)981 int bch2_write_super(struct bch_fs *c)
982 {
983 	struct closure *cl = &c->sb_write;
984 	struct printbuf err = PRINTBUF;
985 	unsigned sb = 0, nr_wrote;
986 	struct bch_devs_mask sb_written;
987 	bool wrote, can_mount_without_written, can_mount_with_written;
988 	unsigned degraded_flags = BCH_FORCE_IF_DEGRADED;
989 	DARRAY(struct bch_dev *) online_devices = {};
990 	int ret = 0;
991 
992 	trace_and_count(c, write_super, c, _RET_IP_);
993 
994 	if (c->opts.very_degraded)
995 		degraded_flags |= BCH_FORCE_IF_LOST;
996 
997 	lockdep_assert_held(&c->sb_lock);
998 
999 	closure_init_stack(cl);
1000 	memset(&sb_written, 0, sizeof(sb_written));
1001 
1002 	for_each_online_member(c, ca) {
1003 		ret = darray_push(&online_devices, ca);
1004 		if (bch2_fs_fatal_err_on(ret, c, "%s: error allocating online devices", __func__)) {
1005 			percpu_ref_put(&ca->io_ref);
1006 			goto out;
1007 		}
1008 		percpu_ref_get(&ca->io_ref);
1009 	}
1010 
1011 	/* Make sure we're using the new magic numbers: */
1012 	c->disk_sb.sb->magic = BCHFS_MAGIC;
1013 	c->disk_sb.sb->layout.magic = BCHFS_MAGIC;
1014 
1015 	le64_add_cpu(&c->disk_sb.sb->seq, 1);
1016 
1017 	struct bch_sb_field_members_v2 *mi = bch2_sb_field_get(c->disk_sb.sb, members_v2);
1018 	darray_for_each(online_devices, ca)
1019 		__bch2_members_v2_get_mut(mi, (*ca)->dev_idx)->seq = c->disk_sb.sb->seq;
1020 	c->disk_sb.sb->write_time = cpu_to_le64(ktime_get_real_seconds());
1021 
1022 	if (test_bit(BCH_FS_error, &c->flags))
1023 		SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 1);
1024 	if (test_bit(BCH_FS_topology_error, &c->flags))
1025 		SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 1);
1026 
1027 	SET_BCH_SB_BIG_ENDIAN(c->disk_sb.sb, CPU_BIG_ENDIAN);
1028 
1029 	bch2_sb_counters_from_cpu(c);
1030 	bch2_sb_members_from_cpu(c);
1031 	bch2_sb_members_cpy_v2_v1(&c->disk_sb);
1032 	bch2_sb_errors_from_cpu(c);
1033 	bch2_sb_downgrade_update(c);
1034 
1035 	darray_for_each(online_devices, ca)
1036 		bch2_sb_from_fs(c, (*ca));
1037 
1038 	darray_for_each(online_devices, ca) {
1039 		printbuf_reset(&err);
1040 
1041 		ret = bch2_sb_validate(&(*ca)->disk_sb, BCH_VALIDATE_write, &err);
1042 		if (ret) {
1043 			bch2_fs_inconsistent(c, "sb invalid before write: %s", err.buf);
1044 			goto out;
1045 		}
1046 	}
1047 
1048 	if (c->opts.nochanges)
1049 		goto out;
1050 
1051 	/*
1052 	 * Defer writing the superblock until filesystem initialization is
1053 	 * complete - don't write out a partly initialized superblock:
1054 	 */
1055 	if (!BCH_SB_INITIALIZED(c->disk_sb.sb))
1056 		goto out;
1057 
1058 	if (le16_to_cpu(c->disk_sb.sb->version) > bcachefs_metadata_version_current) {
1059 		struct printbuf buf = PRINTBUF;
1060 		prt_printf(&buf, "attempting to write superblock that wasn't version downgraded (");
1061 		bch2_version_to_text(&buf, le16_to_cpu(c->disk_sb.sb->version));
1062 		prt_str(&buf, " > ");
1063 		bch2_version_to_text(&buf, bcachefs_metadata_version_current);
1064 		prt_str(&buf, ")");
1065 		bch2_fs_fatal_error(c, ": %s", buf.buf);
1066 		printbuf_exit(&buf);
1067 		return -BCH_ERR_sb_not_downgraded;
1068 	}
1069 
1070 	darray_for_each(online_devices, ca) {
1071 		__set_bit((*ca)->dev_idx, sb_written.d);
1072 		(*ca)->sb_write_error = 0;
1073 	}
1074 
1075 	darray_for_each(online_devices, ca)
1076 		read_back_super(c, *ca);
1077 	closure_sync(cl);
1078 
1079 	darray_for_each(online_devices, cap) {
1080 		struct bch_dev *ca = *cap;
1081 
1082 		if (ca->sb_write_error)
1083 			continue;
1084 
1085 		if (le64_to_cpu(ca->sb_read_scratch->seq) < ca->disk_sb.seq) {
1086 			struct printbuf buf = PRINTBUF;
1087 			prt_char(&buf, ' ');
1088 			prt_bdevname(&buf, ca->disk_sb.bdev);
1089 			prt_printf(&buf,
1090 				": Superblock write was silently dropped! (seq %llu expected %llu)",
1091 				le64_to_cpu(ca->sb_read_scratch->seq),
1092 				ca->disk_sb.seq);
1093 
1094 			if (c->opts.errors != BCH_ON_ERROR_continue &&
1095 			    c->opts.errors != BCH_ON_ERROR_fix_safe) {
1096 				ret = -BCH_ERR_erofs_sb_err;
1097 				bch2_fs_fatal_error(c, "%s", buf.buf);
1098 			} else {
1099 				bch_err(c, "%s", buf.buf);
1100 			}
1101 
1102 			printbuf_exit(&buf);
1103 		}
1104 
1105 		if (le64_to_cpu(ca->sb_read_scratch->seq) > ca->disk_sb.seq) {
1106 			struct printbuf buf = PRINTBUF;
1107 			prt_char(&buf, ' ');
1108 			prt_bdevname(&buf, ca->disk_sb.bdev);
1109 			prt_printf(&buf,
1110 				": Superblock modified by another process (seq %llu expected %llu)",
1111 				le64_to_cpu(ca->sb_read_scratch->seq),
1112 				ca->disk_sb.seq);
1113 			bch2_fs_fatal_error(c, "%s", buf.buf);
1114 			printbuf_exit(&buf);
1115 			ret = -BCH_ERR_erofs_sb_err;
1116 		}
1117 	}
1118 
1119 	if (ret)
1120 		goto out;
1121 
1122 	do {
1123 		wrote = false;
1124 		darray_for_each(online_devices, cap) {
1125 			struct bch_dev *ca = *cap;
1126 			if (!ca->sb_write_error &&
1127 			    sb < ca->disk_sb.sb->layout.nr_superblocks) {
1128 				write_one_super(c, ca, sb);
1129 				wrote = true;
1130 			}
1131 		}
1132 		closure_sync(cl);
1133 		sb++;
1134 	} while (wrote);
1135 
1136 	darray_for_each(online_devices, cap) {
1137 		struct bch_dev *ca = *cap;
1138 		if (ca->sb_write_error)
1139 			__clear_bit(ca->dev_idx, sb_written.d);
1140 		else
1141 			ca->disk_sb.seq = le64_to_cpu(ca->disk_sb.sb->seq);
1142 	}
1143 
1144 	nr_wrote = dev_mask_nr(&sb_written);
1145 
1146 	can_mount_with_written =
1147 		bch2_have_enough_devs(c, sb_written, degraded_flags, false);
1148 
1149 	for (unsigned i = 0; i < ARRAY_SIZE(sb_written.d); i++)
1150 		sb_written.d[i] = ~sb_written.d[i];
1151 
1152 	can_mount_without_written =
1153 		bch2_have_enough_devs(c, sb_written, degraded_flags, false);
1154 
1155 	/*
1156 	 * If we would be able to mount _without_ the devices we successfully
1157 	 * wrote superblocks to, we weren't able to write to enough devices:
1158 	 *
1159 	 * Exception: if we can mount without the successes because we haven't
1160 	 * written anything (new filesystem), we continue if we'd be able to
1161 	 * mount with the devices we did successfully write to:
1162 	 */
1163 	if (bch2_fs_fatal_err_on(!nr_wrote ||
1164 				 !can_mount_with_written ||
1165 				 (can_mount_without_written &&
1166 				  !can_mount_with_written), c,
1167 		": Unable to write superblock to sufficient devices (from %ps)",
1168 		(void *) _RET_IP_))
1169 		ret = -1;
1170 out:
1171 	/* Make new options visible after they're persistent: */
1172 	bch2_sb_update(c);
1173 	darray_for_each(online_devices, ca)
1174 		percpu_ref_put(&(*ca)->io_ref);
1175 	darray_exit(&online_devices);
1176 	printbuf_exit(&err);
1177 	return ret;
1178 }
1179 
__bch2_check_set_feature(struct bch_fs * c,unsigned feat)1180 void __bch2_check_set_feature(struct bch_fs *c, unsigned feat)
1181 {
1182 	mutex_lock(&c->sb_lock);
1183 	if (!(c->sb.features & (1ULL << feat))) {
1184 		c->disk_sb.sb->features[0] |= cpu_to_le64(1ULL << feat);
1185 
1186 		bch2_write_super(c);
1187 	}
1188 	mutex_unlock(&c->sb_lock);
1189 }
1190 
1191 /* Downgrade if superblock is at a higher version than currently supported: */
bch2_check_version_downgrade(struct bch_fs * c)1192 bool bch2_check_version_downgrade(struct bch_fs *c)
1193 {
1194 	bool ret = bcachefs_metadata_version_current < c->sb.version;
1195 
1196 	lockdep_assert_held(&c->sb_lock);
1197 
1198 	/*
1199 	 * Downgrade, if superblock is at a higher version than currently
1200 	 * supported:
1201 	 *
1202 	 * c->sb will be checked before we write the superblock, so update it as
1203 	 * well:
1204 	 */
1205 	if (BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb) > bcachefs_metadata_version_current)
1206 		SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, bcachefs_metadata_version_current);
1207 	if (BCH_SB_VERSION_INCOMPAT_ALLOWED(c->disk_sb.sb) > bcachefs_metadata_version_current)
1208 		SET_BCH_SB_VERSION_INCOMPAT_ALLOWED(c->disk_sb.sb, bcachefs_metadata_version_current);
1209 	if (c->sb.version > bcachefs_metadata_version_current)
1210 		c->disk_sb.sb->version = cpu_to_le16(bcachefs_metadata_version_current);
1211 	if (c->sb.version_min > bcachefs_metadata_version_current)
1212 		c->disk_sb.sb->version_min = cpu_to_le16(bcachefs_metadata_version_current);
1213 	c->disk_sb.sb->compat[0] &= cpu_to_le64((1ULL << BCH_COMPAT_NR) - 1);
1214 	return ret;
1215 }
1216 
bch2_sb_upgrade(struct bch_fs * c,unsigned new_version,bool incompat)1217 void bch2_sb_upgrade(struct bch_fs *c, unsigned new_version, bool incompat)
1218 {
1219 	lockdep_assert_held(&c->sb_lock);
1220 
1221 	if (BCH_VERSION_MAJOR(new_version) >
1222 	    BCH_VERSION_MAJOR(le16_to_cpu(c->disk_sb.sb->version)))
1223 		bch2_sb_field_resize(&c->disk_sb, downgrade, 0);
1224 
1225 	c->disk_sb.sb->version = cpu_to_le16(new_version);
1226 	c->disk_sb.sb->features[0] |= cpu_to_le64(BCH_SB_FEATURES_ALL);
1227 
1228 	if (incompat) {
1229 		SET_BCH_SB_VERSION_INCOMPAT_ALLOWED(c->disk_sb.sb,
1230 			max(BCH_SB_VERSION_INCOMPAT_ALLOWED(c->disk_sb.sb), new_version));
1231 		c->disk_sb.sb->features[0] |= cpu_to_le64(BCH_FEATURE_incompat_version_field);
1232 	}
1233 }
1234 
bch2_sb_ext_validate(struct bch_sb * sb,struct bch_sb_field * f,enum bch_validate_flags flags,struct printbuf * err)1235 static int bch2_sb_ext_validate(struct bch_sb *sb, struct bch_sb_field *f,
1236 				enum bch_validate_flags flags, struct printbuf *err)
1237 {
1238 	if (vstruct_bytes(f) < 88) {
1239 		prt_printf(err, "field too small (%zu < %u)", vstruct_bytes(f), 88);
1240 		return -BCH_ERR_invalid_sb_ext;
1241 	}
1242 
1243 	return 0;
1244 }
1245 
bch2_sb_ext_to_text(struct printbuf * out,struct bch_sb * sb,struct bch_sb_field * f)1246 static void bch2_sb_ext_to_text(struct printbuf *out, struct bch_sb *sb,
1247 				struct bch_sb_field *f)
1248 {
1249 	struct bch_sb_field_ext *e = field_to_type(f, ext);
1250 
1251 	prt_printf(out, "Recovery passes required:\t");
1252 	prt_bitflags(out, bch2_recovery_passes,
1253 		     bch2_recovery_passes_from_stable(le64_to_cpu(e->recovery_passes_required[0])));
1254 	prt_newline(out);
1255 
1256 	unsigned long *errors_silent = kmalloc(sizeof(e->errors_silent), GFP_KERNEL);
1257 	if (errors_silent) {
1258 		le_bitvector_to_cpu(errors_silent, (void *) e->errors_silent, sizeof(e->errors_silent) * 8);
1259 
1260 		prt_printf(out, "Errors to silently fix:\t");
1261 		prt_bitflags_vector(out, bch2_sb_error_strs, errors_silent,
1262 				    min(BCH_FSCK_ERR_MAX, sizeof(e->errors_silent) * 8));
1263 		prt_newline(out);
1264 
1265 		kfree(errors_silent);
1266 	}
1267 
1268 	prt_printf(out, "Btrees with missing data:\t");
1269 	prt_bitflags(out, __bch2_btree_ids, le64_to_cpu(e->btrees_lost_data));
1270 	prt_newline(out);
1271 }
1272 
1273 static const struct bch_sb_field_ops bch_sb_field_ops_ext = {
1274 	.validate	= bch2_sb_ext_validate,
1275 	.to_text	= bch2_sb_ext_to_text,
1276 };
1277 
1278 static const struct bch_sb_field_ops *bch2_sb_field_ops[] = {
1279 #define x(f, nr)					\
1280 	[BCH_SB_FIELD_##f] = &bch_sb_field_ops_##f,
1281 	BCH_SB_FIELDS()
1282 #undef x
1283 };
1284 
1285 static const struct bch_sb_field_ops bch2_sb_field_null_ops;
1286 
bch2_sb_field_type_ops(unsigned type)1287 static const struct bch_sb_field_ops *bch2_sb_field_type_ops(unsigned type)
1288 {
1289 	return likely(type < ARRAY_SIZE(bch2_sb_field_ops))
1290 		? bch2_sb_field_ops[type]
1291 		: &bch2_sb_field_null_ops;
1292 }
1293 
bch2_sb_field_validate(struct bch_sb * sb,struct bch_sb_field * f,enum bch_validate_flags flags,struct printbuf * err)1294 static int bch2_sb_field_validate(struct bch_sb *sb, struct bch_sb_field *f,
1295 				  enum bch_validate_flags flags, struct printbuf *err)
1296 {
1297 	unsigned type = le32_to_cpu(f->type);
1298 	struct printbuf field_err = PRINTBUF;
1299 	const struct bch_sb_field_ops *ops = bch2_sb_field_type_ops(type);
1300 	int ret;
1301 
1302 	ret = ops->validate ? ops->validate(sb, f, flags, &field_err) : 0;
1303 	if (ret) {
1304 		prt_printf(err, "Invalid superblock section %s: %s",
1305 			   bch2_sb_fields[type], field_err.buf);
1306 		prt_newline(err);
1307 		bch2_sb_field_to_text(err, sb, f);
1308 	}
1309 
1310 	printbuf_exit(&field_err);
1311 	return ret;
1312 }
1313 
__bch2_sb_field_to_text(struct printbuf * out,struct bch_sb * sb,struct bch_sb_field * f)1314 void __bch2_sb_field_to_text(struct printbuf *out, struct bch_sb *sb,
1315 			     struct bch_sb_field *f)
1316 {
1317 	unsigned type = le32_to_cpu(f->type);
1318 	const struct bch_sb_field_ops *ops = bch2_sb_field_type_ops(type);
1319 
1320 	if (!out->nr_tabstops)
1321 		printbuf_tabstop_push(out, 32);
1322 
1323 	if (ops->to_text)
1324 		ops->to_text(out, sb, f);
1325 }
1326 
bch2_sb_field_to_text(struct printbuf * out,struct bch_sb * sb,struct bch_sb_field * f)1327 void bch2_sb_field_to_text(struct printbuf *out, struct bch_sb *sb,
1328 			   struct bch_sb_field *f)
1329 {
1330 	unsigned type = le32_to_cpu(f->type);
1331 
1332 	if (type < BCH_SB_FIELD_NR)
1333 		prt_printf(out, "%s", bch2_sb_fields[type]);
1334 	else
1335 		prt_printf(out, "(unknown field %u)", type);
1336 
1337 	prt_printf(out, " (size %zu):", vstruct_bytes(f));
1338 	prt_newline(out);
1339 
1340 	__bch2_sb_field_to_text(out, sb, f);
1341 }
1342 
bch2_sb_layout_to_text(struct printbuf * out,struct bch_sb_layout * l)1343 void bch2_sb_layout_to_text(struct printbuf *out, struct bch_sb_layout *l)
1344 {
1345 	unsigned i;
1346 
1347 	prt_printf(out, "Type:                    %u", l->layout_type);
1348 	prt_newline(out);
1349 
1350 	prt_str(out, "Superblock max size:     ");
1351 	prt_units_u64(out, 512 << l->sb_max_size_bits);
1352 	prt_newline(out);
1353 
1354 	prt_printf(out, "Nr superblocks:          %u", l->nr_superblocks);
1355 	prt_newline(out);
1356 
1357 	prt_str(out, "Offsets:                 ");
1358 	for (i = 0; i < l->nr_superblocks; i++) {
1359 		if (i)
1360 			prt_str(out, ", ");
1361 		prt_printf(out, "%llu", le64_to_cpu(l->sb_offset[i]));
1362 	}
1363 	prt_newline(out);
1364 }
1365 
bch2_sb_to_text(struct printbuf * out,struct bch_sb * sb,bool print_layout,unsigned fields)1366 void bch2_sb_to_text(struct printbuf *out, struct bch_sb *sb,
1367 		     bool print_layout, unsigned fields)
1368 {
1369 	if (!out->nr_tabstops)
1370 		printbuf_tabstop_push(out, 44);
1371 
1372 	prt_printf(out, "External UUID:\t");
1373 	pr_uuid(out, sb->user_uuid.b);
1374 	prt_newline(out);
1375 
1376 	prt_printf(out, "Internal UUID:\t");
1377 	pr_uuid(out, sb->uuid.b);
1378 	prt_newline(out);
1379 
1380 	prt_printf(out, "Magic number:\t");
1381 	pr_uuid(out, sb->magic.b);
1382 	prt_newline(out);
1383 
1384 	prt_printf(out, "Device index:\t%u\n", sb->dev_idx);
1385 
1386 	prt_printf(out, "Label:\t");
1387 	if (!strlen(sb->label))
1388 		prt_printf(out, "(none)");
1389 	else
1390 		prt_printf(out, "%.*s", (int) sizeof(sb->label), sb->label);
1391 	prt_newline(out);
1392 
1393 	prt_printf(out, "Version:\t");
1394 	bch2_version_to_text(out, le16_to_cpu(sb->version));
1395 	prt_newline(out);
1396 
1397 	prt_printf(out, "Incompatible features allowed:\t");
1398 	bch2_version_to_text(out, BCH_SB_VERSION_INCOMPAT_ALLOWED(sb));
1399 	prt_newline(out);
1400 
1401 	prt_printf(out, "Incompatible features in use:\t");
1402 	bch2_version_to_text(out, BCH_SB_VERSION_INCOMPAT(sb));
1403 	prt_newline(out);
1404 
1405 	prt_printf(out, "Version upgrade complete:\t");
1406 	bch2_version_to_text(out, BCH_SB_VERSION_UPGRADE_COMPLETE(sb));
1407 	prt_newline(out);
1408 
1409 	prt_printf(out, "Oldest version on disk:\t");
1410 	bch2_version_to_text(out, le16_to_cpu(sb->version_min));
1411 	prt_newline(out);
1412 
1413 	prt_printf(out, "Created:\t");
1414 	if (sb->time_base_lo)
1415 		bch2_prt_datetime(out, div_u64(le64_to_cpu(sb->time_base_lo), NSEC_PER_SEC));
1416 	else
1417 		prt_printf(out, "(not set)");
1418 	prt_newline(out);
1419 
1420 	prt_printf(out, "Sequence number:\t");
1421 	prt_printf(out, "%llu", le64_to_cpu(sb->seq));
1422 	prt_newline(out);
1423 
1424 	prt_printf(out, "Time of last write:\t");
1425 	bch2_prt_datetime(out, le64_to_cpu(sb->write_time));
1426 	prt_newline(out);
1427 
1428 	prt_printf(out, "Superblock size:\t");
1429 	prt_units_u64(out, vstruct_bytes(sb));
1430 	prt_str(out, "/");
1431 	prt_units_u64(out, 512ULL << sb->layout.sb_max_size_bits);
1432 	prt_newline(out);
1433 
1434 	prt_printf(out, "Clean:\t%llu\n", BCH_SB_CLEAN(sb));
1435 	prt_printf(out, "Devices:\t%u\n", bch2_sb_nr_devices(sb));
1436 
1437 	prt_printf(out, "Sections:\t");
1438 	u64 fields_have = 0;
1439 	vstruct_for_each(sb, f)
1440 		fields_have |= 1 << le32_to_cpu(f->type);
1441 	prt_bitflags(out, bch2_sb_fields, fields_have);
1442 	prt_newline(out);
1443 
1444 	prt_printf(out, "Features:\t");
1445 	prt_bitflags(out, bch2_sb_features, le64_to_cpu(sb->features[0]));
1446 	prt_newline(out);
1447 
1448 	prt_printf(out, "Compat features:\t");
1449 	prt_bitflags(out, bch2_sb_compat, le64_to_cpu(sb->compat[0]));
1450 	prt_newline(out);
1451 
1452 	prt_newline(out);
1453 	prt_printf(out, "Options:");
1454 	prt_newline(out);
1455 	printbuf_indent_add(out, 2);
1456 	{
1457 		enum bch_opt_id id;
1458 
1459 		for (id = 0; id < bch2_opts_nr; id++) {
1460 			const struct bch_option *opt = bch2_opt_table + id;
1461 
1462 			if (opt->get_sb != BCH2_NO_SB_OPT) {
1463 				u64 v = bch2_opt_from_sb(sb, id);
1464 
1465 				prt_printf(out, "%s:\t", opt->attr.name);
1466 				bch2_opt_to_text(out, NULL, sb, opt, v,
1467 						 OPT_HUMAN_READABLE|OPT_SHOW_FULL_LIST);
1468 				prt_newline(out);
1469 			}
1470 		}
1471 	}
1472 
1473 	printbuf_indent_sub(out, 2);
1474 
1475 	if (print_layout) {
1476 		prt_newline(out);
1477 		prt_printf(out, "layout:");
1478 		prt_newline(out);
1479 		printbuf_indent_add(out, 2);
1480 		bch2_sb_layout_to_text(out, &sb->layout);
1481 		printbuf_indent_sub(out, 2);
1482 	}
1483 
1484 	vstruct_for_each(sb, f)
1485 		if (fields & (1 << le32_to_cpu(f->type))) {
1486 			prt_newline(out);
1487 			bch2_sb_field_to_text(out, sb, f);
1488 		}
1489 }
1490