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