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