]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/super-io.c
8b8130993a59cdbf0946201a7dca766072ff4885
[bcachefs-tools-debian] / libbcachefs / super-io.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "btree_update_interior.h"
5 #include "buckets.h"
6 #include "checksum.h"
7 #include "disk_groups.h"
8 #include "ec.h"
9 #include "error.h"
10 #include "io.h"
11 #include "journal.h"
12 #include "journal_io.h"
13 #include "journal_sb.h"
14 #include "journal_seq_blacklist.h"
15 #include "replicas.h"
16 #include "quota.h"
17 #include "super-io.h"
18 #include "super.h"
19 #include "vstructs.h"
20 #include "counters.h"
21
22 #include <linux/backing-dev.h>
23 #include <linux/pretty-printers.h>
24 #include <linux/sort.h>
25
26 #include <trace/events/bcachefs.h>
27
28 const char * const bch2_sb_fields[] = {
29 #define x(name, nr)     #name,
30         BCH_SB_FIELDS()
31 #undef x
32         NULL
33 };
34
35 static int bch2_sb_field_validate(struct bch_sb *, struct bch_sb_field *,
36                                   struct printbuf *);
37
38 struct bch_sb_field *bch2_sb_field_get(struct bch_sb *sb,
39                                       enum bch_sb_field_type type)
40 {
41         struct bch_sb_field *f;
42
43         /* XXX: need locking around superblock to access optional fields */
44
45         vstruct_for_each(sb, f)
46                 if (le32_to_cpu(f->type) == type)
47                         return f;
48         return NULL;
49 }
50
51 static struct bch_sb_field *__bch2_sb_field_resize(struct bch_sb_handle *sb,
52                                                    struct bch_sb_field *f,
53                                                    unsigned u64s)
54 {
55         unsigned old_u64s = f ? le32_to_cpu(f->u64s) : 0;
56         unsigned sb_u64s = le32_to_cpu(sb->sb->u64s) + u64s - old_u64s;
57
58         BUG_ON(__vstruct_bytes(struct bch_sb, sb_u64s) > sb->buffer_size);
59
60         if (!f && !u64s) {
61                 /* nothing to do: */
62         } else if (!f) {
63                 f = vstruct_last(sb->sb);
64                 memset(f, 0, sizeof(u64) * u64s);
65                 f->u64s = cpu_to_le32(u64s);
66                 f->type = 0;
67         } else {
68                 void *src, *dst;
69
70                 src = vstruct_end(f);
71
72                 if (u64s) {
73                         f->u64s = cpu_to_le32(u64s);
74                         dst = vstruct_end(f);
75                 } else {
76                         dst = f;
77                 }
78
79                 memmove(dst, src, vstruct_end(sb->sb) - src);
80
81                 if (dst > src)
82                         memset(src, 0, dst - src);
83         }
84
85         sb->sb->u64s = cpu_to_le32(sb_u64s);
86
87         return u64s ? f : NULL;
88 }
89
90 void bch2_sb_field_delete(struct bch_sb_handle *sb,
91                           enum bch_sb_field_type type)
92 {
93         struct bch_sb_field *f = bch2_sb_field_get(sb->sb, type);
94
95         if (f)
96                 __bch2_sb_field_resize(sb, f, 0);
97 }
98
99 /* Superblock realloc/free: */
100
101 void bch2_free_super(struct bch_sb_handle *sb)
102 {
103         if (sb->bio)
104                 bio_put(sb->bio);
105         if (!IS_ERR_OR_NULL(sb->bdev))
106                 blkdev_put(sb->bdev, sb->mode);
107
108         kfree(sb->sb);
109         memset(sb, 0, sizeof(*sb));
110 }
111
112 int bch2_sb_realloc(struct bch_sb_handle *sb, unsigned u64s)
113 {
114         size_t new_bytes = __vstruct_bytes(struct bch_sb, u64s);
115         size_t new_buffer_size;
116         struct bch_sb *new_sb;
117         struct bio *bio;
118
119         if (sb->bdev)
120                 new_bytes = max_t(size_t, new_bytes, bdev_logical_block_size(sb->bdev));
121
122         new_buffer_size = roundup_pow_of_two(new_bytes);
123
124         if (sb->sb && sb->buffer_size >= new_buffer_size)
125                 return 0;
126
127         if (sb->have_layout) {
128                 u64 max_bytes = 512 << sb->sb->layout.sb_max_size_bits;
129
130                 if (new_bytes > max_bytes) {
131                         char buf[BDEVNAME_SIZE];
132
133                         pr_err("%s: superblock too big: want %zu but have %llu",
134                                bdevname(sb->bdev, buf), new_bytes, max_bytes);
135                         return -ENOSPC;
136                 }
137         }
138
139         if (sb->buffer_size >= new_buffer_size && sb->sb)
140                 return 0;
141
142         if (dynamic_fault("bcachefs:add:super_realloc"))
143                 return -ENOMEM;
144
145         if (sb->have_bio) {
146                 bio = bio_kmalloc(GFP_KERNEL,
147                         DIV_ROUND_UP(new_buffer_size, PAGE_SIZE));
148                 if (!bio)
149                         return -ENOMEM;
150
151                 if (sb->bio)
152                         bio_put(sb->bio);
153                 sb->bio = bio;
154         }
155
156         new_sb = krealloc(sb->sb, new_buffer_size, GFP_NOFS|__GFP_ZERO);
157         if (!new_sb)
158                 return -ENOMEM;
159
160         sb->sb = new_sb;
161         sb->buffer_size = new_buffer_size;
162
163         return 0;
164 }
165
166 struct bch_sb_field *bch2_sb_field_resize(struct bch_sb_handle *sb,
167                                           enum bch_sb_field_type type,
168                                           unsigned u64s)
169 {
170         struct bch_sb_field *f = bch2_sb_field_get(sb->sb, type);
171         ssize_t old_u64s = f ? le32_to_cpu(f->u64s) : 0;
172         ssize_t d = -old_u64s + u64s;
173
174         if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s) + d))
175                 return NULL;
176
177         if (sb->fs_sb) {
178                 struct bch_fs *c = container_of(sb, struct bch_fs, disk_sb);
179                 struct bch_dev *ca;
180                 unsigned i;
181
182                 lockdep_assert_held(&c->sb_lock);
183
184                 /* XXX: we're not checking that offline device have enough space */
185
186                 for_each_online_member(ca, c, i) {
187                         struct bch_sb_handle *sb = &ca->disk_sb;
188
189                         if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s) + d)) {
190                                 percpu_ref_put(&ca->ref);
191                                 return NULL;
192                         }
193                 }
194         }
195
196         f = bch2_sb_field_get(sb->sb, type);
197         f = __bch2_sb_field_resize(sb, f, u64s);
198         if (f)
199                 f->type = cpu_to_le32(type);
200         return f;
201 }
202
203 /* Superblock validate: */
204
205 static inline void __bch2_sb_layout_size_assert(void)
206 {
207         BUILD_BUG_ON(sizeof(struct bch_sb_layout) != 512);
208 }
209
210 static int validate_sb_layout(struct bch_sb_layout *layout, struct printbuf *out)
211 {
212         u64 offset, prev_offset, max_sectors;
213         unsigned i;
214
215         if (uuid_le_cmp(layout->magic, BCACHE_MAGIC)) {
216                 prt_printf(out, "Not a bcachefs superblock layout");
217                 return -EINVAL;
218         }
219
220         if (layout->layout_type != 0) {
221                 prt_printf(out, "Invalid superblock layout type %u",
222                        layout->layout_type);
223                 return -EINVAL;
224         }
225
226         if (!layout->nr_superblocks) {
227                 prt_printf(out, "Invalid superblock layout: no superblocks");
228                 return -EINVAL;
229         }
230
231         if (layout->nr_superblocks > ARRAY_SIZE(layout->sb_offset)) {
232                 prt_printf(out, "Invalid superblock layout: too many superblocks");
233                 return -EINVAL;
234         }
235
236         max_sectors = 1 << layout->sb_max_size_bits;
237
238         prev_offset = le64_to_cpu(layout->sb_offset[0]);
239
240         for (i = 1; i < layout->nr_superblocks; i++) {
241                 offset = le64_to_cpu(layout->sb_offset[i]);
242
243                 if (offset < prev_offset + max_sectors) {
244                         prt_printf(out, "Invalid superblock layout: superblocks overlap\n"
245                                "  (sb %u ends at %llu next starts at %llu",
246                                i - 1, prev_offset + max_sectors, offset);
247                         return -EINVAL;
248                 }
249                 prev_offset = offset;
250         }
251
252         return 0;
253 }
254
255 static int bch2_sb_validate(struct bch_sb_handle *disk_sb, struct printbuf *out,
256                             int rw)
257 {
258         struct bch_sb *sb = disk_sb->sb;
259         struct bch_sb_field *f;
260         struct bch_sb_field_members *mi;
261         enum bch_opt_id opt_id;
262         u32 version, version_min;
263         u16 block_size;
264         int ret;
265
266         version         = le16_to_cpu(sb->version);
267         version_min     = version >= bcachefs_metadata_version_bkey_renumber
268                 ? le16_to_cpu(sb->version_min)
269                 : version;
270
271         if (version    >= bcachefs_metadata_version_max) {
272                 prt_printf(out, "Unsupported superblock version %u (min %u, max %u)",
273                        version, bcachefs_metadata_version_min, bcachefs_metadata_version_max);
274                 return -EINVAL;
275         }
276
277         if (version_min < bcachefs_metadata_version_min) {
278                 prt_printf(out, "Unsupported superblock version %u (min %u, max %u)",
279                        version_min, bcachefs_metadata_version_min, bcachefs_metadata_version_max);
280                 return -EINVAL;
281         }
282
283         if (version_min > version) {
284                 prt_printf(out, "Bad minimum version %u, greater than version field %u",
285                        version_min, version);
286                 return -EINVAL;
287         }
288
289         if (sb->features[1] ||
290             (le64_to_cpu(sb->features[0]) & (~0ULL << BCH_FEATURE_NR))) {
291                 prt_printf(out, "Filesystem has incompatible features");
292                 return -EINVAL;
293         }
294
295         block_size = le16_to_cpu(sb->block_size);
296
297         if (block_size > PAGE_SECTORS) {
298                 prt_printf(out, "Block size too big (got %u, max %u)",
299                        block_size, PAGE_SECTORS);
300                 return -EINVAL;
301         }
302
303         if (bch2_is_zero(sb->user_uuid.b, sizeof(uuid_le))) {
304                 prt_printf(out, "Bad user UUID (got zeroes)");
305                 return -EINVAL;
306         }
307
308         if (bch2_is_zero(sb->uuid.b, sizeof(uuid_le))) {
309                 prt_printf(out, "Bad intenal UUID (got zeroes)");
310                 return -EINVAL;
311         }
312
313         if (!sb->nr_devices ||
314             sb->nr_devices > BCH_SB_MEMBERS_MAX) {
315                 prt_printf(out, "Bad number of member devices %u (max %u)",
316                        sb->nr_devices, BCH_SB_MEMBERS_MAX);
317                 return -EINVAL;
318         }
319
320         if (sb->dev_idx >= sb->nr_devices) {
321                 prt_printf(out, "Bad dev_idx (got %u, nr_devices %u)",
322                        sb->dev_idx, sb->nr_devices);
323                 return -EINVAL;
324         }
325
326         if (!sb->time_precision ||
327             le32_to_cpu(sb->time_precision) > NSEC_PER_SEC) {
328                 prt_printf(out, "Invalid time precision: %u (min 1, max %lu)",
329                        le32_to_cpu(sb->time_precision), NSEC_PER_SEC);
330                 return -EINVAL;
331         }
332
333         if (rw == READ) {
334                 /*
335                  * Been seeing a bug where these are getting inexplicably
336                  * zeroed, so we'r now validating them, but we have to be
337                  * careful not to preven people's filesystems from mounting:
338                  */
339                 if (!BCH_SB_JOURNAL_FLUSH_DELAY(sb))
340                         SET_BCH_SB_JOURNAL_FLUSH_DELAY(sb, 1000);
341                 if (!BCH_SB_JOURNAL_RECLAIM_DELAY(sb))
342                         SET_BCH_SB_JOURNAL_RECLAIM_DELAY(sb, 1000);
343         }
344
345         for (opt_id = 0; opt_id < bch2_opts_nr; opt_id++) {
346                 const struct bch_option *opt = bch2_opt_table + opt_id;
347
348                 if (opt->get_sb != BCH2_NO_SB_OPT) {
349                         u64 v = bch2_opt_from_sb(sb, opt_id);
350
351                         prt_printf(out, "Invalid option ");
352                         ret = bch2_opt_validate(opt, v, out);
353                         if (ret)
354                                 return ret;
355
356                         printbuf_reset(out);
357                 }
358         }
359
360         /* validate layout */
361         ret = validate_sb_layout(&sb->layout, out);
362         if (ret)
363                 return ret;
364
365         vstruct_for_each(sb, f) {
366                 if (!f->u64s) {
367                         prt_printf(out, "Invalid superblock: optional with size 0 (type %u)",
368                                le32_to_cpu(f->type));
369                         return -EINVAL;
370                 }
371
372                 if (vstruct_next(f) > vstruct_last(sb)) {
373                         prt_printf(out, "Invalid superblock: optional field extends past end of superblock (type %u)",
374                                le32_to_cpu(f->type));
375                         return -EINVAL;
376                 }
377         }
378
379         /* members must be validated first: */
380         mi = bch2_sb_get_members(sb);
381         if (!mi) {
382                 prt_printf(out, "Invalid superblock: member info area missing");
383                 return -EINVAL;
384         }
385
386         ret = bch2_sb_field_validate(sb, &mi->field, out);
387         if (ret)
388                 return ret;
389
390         vstruct_for_each(sb, f) {
391                 if (le32_to_cpu(f->type) == BCH_SB_FIELD_members)
392                         continue;
393
394                 ret = bch2_sb_field_validate(sb, f, out);
395                 if (ret)
396                         return ret;
397         }
398
399         return 0;
400 }
401
402 /* device open: */
403
404 static void bch2_sb_update(struct bch_fs *c)
405 {
406         struct bch_sb *src = c->disk_sb.sb;
407         struct bch_sb_field_members *mi = bch2_sb_get_members(src);
408         struct bch_dev *ca;
409         unsigned i;
410
411         lockdep_assert_held(&c->sb_lock);
412
413         c->sb.uuid              = src->uuid;
414         c->sb.user_uuid         = src->user_uuid;
415         c->sb.version           = le16_to_cpu(src->version);
416         c->sb.version_min       = le16_to_cpu(src->version_min);
417         c->sb.nr_devices        = src->nr_devices;
418         c->sb.clean             = BCH_SB_CLEAN(src);
419         c->sb.encryption_type   = BCH_SB_ENCRYPTION_TYPE(src);
420
421         c->sb.nsec_per_time_unit = le32_to_cpu(src->time_precision);
422         c->sb.time_units_per_sec = NSEC_PER_SEC / c->sb.nsec_per_time_unit;
423
424         /* XXX this is wrong, we need a 96 or 128 bit integer type */
425         c->sb.time_base_lo      = div_u64(le64_to_cpu(src->time_base_lo),
426                                           c->sb.nsec_per_time_unit);
427         c->sb.time_base_hi      = le32_to_cpu(src->time_base_hi);
428
429         c->sb.features          = le64_to_cpu(src->features[0]);
430         c->sb.compat            = le64_to_cpu(src->compat[0]);
431
432         for_each_member_device(ca, c, i)
433                 ca->mi = bch2_mi_to_cpu(mi->members + i);
434 }
435
436 static void __copy_super(struct bch_sb_handle *dst_handle, struct bch_sb *src)
437 {
438         struct bch_sb_field *src_f, *dst_f;
439         struct bch_sb *dst = dst_handle->sb;
440         unsigned i;
441
442         dst->version            = src->version;
443         dst->version_min        = src->version_min;
444         dst->seq                = src->seq;
445         dst->uuid               = src->uuid;
446         dst->user_uuid          = src->user_uuid;
447         memcpy(dst->label,      src->label, sizeof(dst->label));
448
449         dst->block_size         = src->block_size;
450         dst->nr_devices         = src->nr_devices;
451
452         dst->time_base_lo       = src->time_base_lo;
453         dst->time_base_hi       = src->time_base_hi;
454         dst->time_precision     = src->time_precision;
455
456         memcpy(dst->flags,      src->flags,     sizeof(dst->flags));
457         memcpy(dst->features,   src->features,  sizeof(dst->features));
458         memcpy(dst->compat,     src->compat,    sizeof(dst->compat));
459
460         for (i = 0; i < BCH_SB_FIELD_NR; i++) {
461                 if ((1U << i) & BCH_SINGLE_DEVICE_SB_FIELDS)
462                         continue;
463
464                 src_f = bch2_sb_field_get(src, i);
465                 dst_f = bch2_sb_field_get(dst, i);
466                 dst_f = __bch2_sb_field_resize(dst_handle, dst_f,
467                                 src_f ? le32_to_cpu(src_f->u64s) : 0);
468
469                 if (src_f)
470                         memcpy(dst_f, src_f, vstruct_bytes(src_f));
471         }
472 }
473
474 int bch2_sb_to_fs(struct bch_fs *c, struct bch_sb *src)
475 {
476         struct bch_sb_field_journal *journal_buckets =
477                 bch2_sb_get_journal(src);
478         unsigned journal_u64s = journal_buckets
479                 ? le32_to_cpu(journal_buckets->field.u64s)
480                 : 0;
481         int ret;
482
483         lockdep_assert_held(&c->sb_lock);
484
485         ret = bch2_sb_realloc(&c->disk_sb,
486                               le32_to_cpu(src->u64s) - journal_u64s);
487         if (ret)
488                 return ret;
489
490         __copy_super(&c->disk_sb, src);
491
492         ret = bch2_sb_replicas_to_cpu_replicas(c);
493         if (ret)
494                 return ret;
495
496         ret = bch2_sb_disk_groups_to_cpu(c);
497         if (ret)
498                 return ret;
499
500         bch2_sb_update(c);
501         return 0;
502 }
503
504 int bch2_sb_from_fs(struct bch_fs *c, struct bch_dev *ca)
505 {
506         struct bch_sb *src = c->disk_sb.sb, *dst = ca->disk_sb.sb;
507         struct bch_sb_field_journal *journal_buckets =
508                 bch2_sb_get_journal(dst);
509         unsigned journal_u64s = journal_buckets
510                 ? le32_to_cpu(journal_buckets->field.u64s)
511                 : 0;
512         unsigned u64s = le32_to_cpu(src->u64s) + journal_u64s;
513         int ret;
514
515         ret = bch2_sb_realloc(&ca->disk_sb, u64s);
516         if (ret)
517                 return ret;
518
519         __copy_super(&ca->disk_sb, src);
520         return 0;
521 }
522
523 /* read superblock: */
524
525 static int read_one_super(struct bch_sb_handle *sb, u64 offset, struct printbuf *err)
526 {
527         struct bch_csum csum;
528         u32 version, version_min;
529         size_t bytes;
530         int ret;
531 reread:
532         bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
533         sb->bio->bi_iter.bi_sector = offset;
534         bch2_bio_map(sb->bio, sb->sb, sb->buffer_size);
535
536         ret = submit_bio_wait(sb->bio);
537         if (ret) {
538                 prt_printf(err, "IO error: %i", ret);
539                 return ret;
540         }
541
542         if (uuid_le_cmp(sb->sb->magic, BCACHE_MAGIC)) {
543                 prt_printf(err, "Not a bcachefs superblock");
544                 return -EINVAL;
545         }
546
547         version         = le16_to_cpu(sb->sb->version);
548         version_min     = version >= bcachefs_metadata_version_bkey_renumber
549                 ? le16_to_cpu(sb->sb->version_min)
550                 : version;
551
552         if (version    >= bcachefs_metadata_version_max) {
553                 prt_printf(err, "Unsupported superblock version %u (min %u, max %u)",
554                        version, bcachefs_metadata_version_min, bcachefs_metadata_version_max);
555                 return -EINVAL;
556         }
557
558         if (version_min < bcachefs_metadata_version_min) {
559                 prt_printf(err, "Unsupported superblock version %u (min %u, max %u)",
560                        version_min, bcachefs_metadata_version_min, bcachefs_metadata_version_max);
561                 return -EINVAL;
562         }
563
564         bytes = vstruct_bytes(sb->sb);
565
566         if (bytes > 512 << sb->sb->layout.sb_max_size_bits) {
567                 prt_printf(err, "Invalid superblock: too big (got %zu bytes, layout max %lu)",
568                        bytes, 512UL << sb->sb->layout.sb_max_size_bits);
569                 return -EINVAL;
570         }
571
572         if (bytes > sb->buffer_size) {
573                 if (bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s)))
574                         return -ENOMEM;
575                 goto reread;
576         }
577
578         if (BCH_SB_CSUM_TYPE(sb->sb) >= BCH_CSUM_NR) {
579                 prt_printf(err, "unknown checksum type %llu", BCH_SB_CSUM_TYPE(sb->sb));
580                 return -EINVAL;
581         }
582
583         /* XXX: verify MACs */
584         csum = csum_vstruct(NULL, BCH_SB_CSUM_TYPE(sb->sb),
585                             null_nonce(), sb->sb);
586
587         if (bch2_crc_cmp(csum, sb->sb->csum)) {
588                 prt_printf(err, "bad checksum");
589                 return -EINVAL;
590         }
591
592         sb->seq = le64_to_cpu(sb->sb->seq);
593
594         return 0;
595 }
596
597 int bch2_read_super(const char *path, struct bch_opts *opts,
598                     struct bch_sb_handle *sb)
599 {
600         u64 offset = opt_get(*opts, sb);
601         struct bch_sb_layout layout;
602         struct printbuf err = PRINTBUF;
603         __le64 *i;
604         int ret;
605
606         pr_verbose_init(*opts, "");
607
608         memset(sb, 0, sizeof(*sb));
609         sb->mode        = FMODE_READ;
610         sb->have_bio    = true;
611
612         if (!opt_get(*opts, noexcl))
613                 sb->mode |= FMODE_EXCL;
614
615         if (!opt_get(*opts, nochanges))
616                 sb->mode |= FMODE_WRITE;
617
618         sb->bdev = blkdev_get_by_path(path, sb->mode, sb);
619         if (IS_ERR(sb->bdev) &&
620             PTR_ERR(sb->bdev) == -EACCES &&
621             opt_get(*opts, read_only)) {
622                 sb->mode &= ~FMODE_WRITE;
623
624                 sb->bdev = blkdev_get_by_path(path, sb->mode, sb);
625                 if (!IS_ERR(sb->bdev))
626                         opt_set(*opts, nochanges, true);
627         }
628
629         if (IS_ERR(sb->bdev)) {
630                 ret = PTR_ERR(sb->bdev);
631                 goto out;
632         }
633
634         ret = bch2_sb_realloc(sb, 0);
635         if (ret) {
636                 prt_printf(&err, "error allocating memory for superblock");
637                 goto err;
638         }
639
640         if (bch2_fs_init_fault("read_super")) {
641                 prt_printf(&err, "dynamic fault");
642                 ret = -EFAULT;
643                 goto err;
644         }
645
646         ret = read_one_super(sb, offset, &err);
647         if (!ret)
648                 goto got_super;
649
650         if (opt_defined(*opts, sb))
651                 goto err;
652
653         printk(KERN_ERR "bcachefs (%s): error reading default superblock: %s",
654                path, err.buf);
655         printbuf_reset(&err);
656
657         /*
658          * Error reading primary superblock - read location of backup
659          * superblocks:
660          */
661         bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
662         sb->bio->bi_iter.bi_sector = BCH_SB_LAYOUT_SECTOR;
663         /*
664          * use sb buffer to read layout, since sb buffer is page aligned but
665          * layout won't be:
666          */
667         bch2_bio_map(sb->bio, sb->sb, sizeof(struct bch_sb_layout));
668
669         ret = submit_bio_wait(sb->bio);
670         if (ret) {
671                 prt_printf(&err, "IO error: %i", ret);
672                 goto err;
673         }
674
675         memcpy(&layout, sb->sb, sizeof(layout));
676         ret = validate_sb_layout(&layout, &err);
677         if (ret)
678                 goto err;
679
680         for (i = layout.sb_offset;
681              i < layout.sb_offset + layout.nr_superblocks; i++) {
682                 offset = le64_to_cpu(*i);
683
684                 if (offset == opt_get(*opts, sb))
685                         continue;
686
687                 ret = read_one_super(sb, offset, &err);
688                 if (!ret)
689                         goto got_super;
690         }
691
692         goto err;
693
694 got_super:
695         if (le16_to_cpu(sb->sb->block_size) << 9 <
696             bdev_logical_block_size(sb->bdev)) {
697                 prt_printf(&err, "block size (%u) smaller than device block size (%u)",
698                        le16_to_cpu(sb->sb->block_size) << 9,
699                        bdev_logical_block_size(sb->bdev));
700                 ret = -EINVAL;
701                 goto err;
702         }
703
704         ret = 0;
705         sb->have_layout = true;
706
707         ret = bch2_sb_validate(sb, &err, READ);
708         if (ret) {
709                 printk(KERN_ERR "bcachefs (%s): error validating superblock: %s",
710                        path, err.buf);
711                 goto err_no_print;
712         }
713 out:
714         pr_verbose_init(*opts, "ret %i", ret);
715         printbuf_exit(&err);
716         return ret;
717 err:
718         printk(KERN_ERR "bcachefs (%s): error reading superblock: %s",
719                path, err.buf);
720 err_no_print:
721         bch2_free_super(sb);
722         goto out;
723 }
724
725 /* write superblock: */
726
727 static void write_super_endio(struct bio *bio)
728 {
729         struct bch_dev *ca = bio->bi_private;
730
731         /* XXX: return errors directly */
732
733         if (bch2_dev_io_err_on(bio->bi_status, ca, "superblock write error: %s",
734                                bch2_blk_status_to_str(bio->bi_status)))
735                 ca->sb_write_error = 1;
736
737         closure_put(&ca->fs->sb_write);
738         percpu_ref_put(&ca->io_ref);
739 }
740
741 static void read_back_super(struct bch_fs *c, struct bch_dev *ca)
742 {
743         struct bch_sb *sb = ca->disk_sb.sb;
744         struct bio *bio = ca->disk_sb.bio;
745
746         bio_reset(bio, ca->disk_sb.bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
747         bio->bi_iter.bi_sector  = le64_to_cpu(sb->layout.sb_offset[0]);
748         bio->bi_end_io          = write_super_endio;
749         bio->bi_private         = ca;
750         bch2_bio_map(bio, ca->sb_read_scratch, PAGE_SIZE);
751
752         this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_sb],
753                      bio_sectors(bio));
754
755         percpu_ref_get(&ca->io_ref);
756         closure_bio_submit(bio, &c->sb_write);
757 }
758
759 static void write_one_super(struct bch_fs *c, struct bch_dev *ca, unsigned idx)
760 {
761         struct bch_sb *sb = ca->disk_sb.sb;
762         struct bio *bio = ca->disk_sb.bio;
763
764         sb->offset = sb->layout.sb_offset[idx];
765
766         SET_BCH_SB_CSUM_TYPE(sb, bch2_csum_opt_to_type(c->opts.metadata_checksum, false));
767         sb->csum = csum_vstruct(c, BCH_SB_CSUM_TYPE(sb),
768                                 null_nonce(), sb);
769
770         bio_reset(bio, ca->disk_sb.bdev, REQ_OP_WRITE|REQ_SYNC|REQ_META);
771         bio->bi_iter.bi_sector  = le64_to_cpu(sb->offset);
772         bio->bi_end_io          = write_super_endio;
773         bio->bi_private         = ca;
774         bch2_bio_map(bio, sb,
775                      roundup((size_t) vstruct_bytes(sb),
776                              bdev_logical_block_size(ca->disk_sb.bdev)));
777
778         this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_sb],
779                      bio_sectors(bio));
780
781         percpu_ref_get(&ca->io_ref);
782         closure_bio_submit(bio, &c->sb_write);
783 }
784
785 int bch2_write_super(struct bch_fs *c)
786 {
787         struct closure *cl = &c->sb_write;
788         struct bch_dev *ca;
789         struct printbuf err = PRINTBUF;
790         unsigned i, sb = 0, nr_wrote;
791         struct bch_devs_mask sb_written;
792         bool wrote, can_mount_without_written, can_mount_with_written;
793         unsigned degraded_flags = BCH_FORCE_IF_DEGRADED;
794         int ret = 0;
795
796         trace_write_super(c, _RET_IP_);
797
798         if (c->opts.very_degraded)
799                 degraded_flags |= BCH_FORCE_IF_LOST;
800
801         lockdep_assert_held(&c->sb_lock);
802
803         closure_init_stack(cl);
804         memset(&sb_written, 0, sizeof(sb_written));
805
806         le64_add_cpu(&c->disk_sb.sb->seq, 1);
807
808         if (test_bit(BCH_FS_ERROR, &c->flags))
809                 SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 1);
810         if (test_bit(BCH_FS_TOPOLOGY_ERROR, &c->flags))
811                 SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 1);
812
813         SET_BCH_SB_BIG_ENDIAN(c->disk_sb.sb, CPU_BIG_ENDIAN);
814
815         bch2_sb_counters_from_cpu(c);
816
817         for_each_online_member(ca, c, i)
818                 bch2_sb_from_fs(c, ca);
819
820         for_each_online_member(ca, c, i) {
821                 printbuf_reset(&err);
822
823                 ret = bch2_sb_validate(&ca->disk_sb, &err, WRITE);
824                 if (ret) {
825                         bch2_fs_inconsistent(c, "sb invalid before write: %s", err.buf);
826                         percpu_ref_put(&ca->io_ref);
827                         goto out;
828                 }
829         }
830
831         if (c->opts.nochanges)
832                 goto out;
833
834         /*
835          * Defer writing the superblock until filesystem initialization is
836          * complete - don't write out a partly initialized superblock:
837          */
838         if (!BCH_SB_INITIALIZED(c->disk_sb.sb))
839                 goto out;
840
841         for_each_online_member(ca, c, i) {
842                 __set_bit(ca->dev_idx, sb_written.d);
843                 ca->sb_write_error = 0;
844         }
845
846         for_each_online_member(ca, c, i)
847                 read_back_super(c, ca);
848         closure_sync(cl);
849
850         for_each_online_member(ca, c, i) {
851                 if (ca->sb_write_error)
852                         continue;
853
854                 if (le64_to_cpu(ca->sb_read_scratch->seq) < ca->disk_sb.seq) {
855                         bch2_fs_fatal_error(c,
856                                 "Superblock write was silently dropped! (seq %llu expected %llu)",
857                                 le64_to_cpu(ca->sb_read_scratch->seq),
858                                 ca->disk_sb.seq);
859                         percpu_ref_put(&ca->io_ref);
860                         ret = -EROFS;
861                         goto out;
862                 }
863
864                 if (le64_to_cpu(ca->sb_read_scratch->seq) > ca->disk_sb.seq) {
865                         bch2_fs_fatal_error(c,
866                                 "Superblock modified by another process (seq %llu expected %llu)",
867                                 le64_to_cpu(ca->sb_read_scratch->seq),
868                                 ca->disk_sb.seq);
869                         percpu_ref_put(&ca->io_ref);
870                         ret = -EROFS;
871                         goto out;
872                 }
873         }
874
875         do {
876                 wrote = false;
877                 for_each_online_member(ca, c, i)
878                         if (!ca->sb_write_error &&
879                             sb < ca->disk_sb.sb->layout.nr_superblocks) {
880                                 write_one_super(c, ca, sb);
881                                 wrote = true;
882                         }
883                 closure_sync(cl);
884                 sb++;
885         } while (wrote);
886
887         for_each_online_member(ca, c, i) {
888                 if (ca->sb_write_error)
889                         __clear_bit(ca->dev_idx, sb_written.d);
890                 else
891                         ca->disk_sb.seq = le64_to_cpu(ca->disk_sb.sb->seq);
892         }
893
894         nr_wrote = dev_mask_nr(&sb_written);
895
896         can_mount_with_written =
897                 bch2_have_enough_devs(c, sb_written, degraded_flags, false);
898
899         for (i = 0; i < ARRAY_SIZE(sb_written.d); i++)
900                 sb_written.d[i] = ~sb_written.d[i];
901
902         can_mount_without_written =
903                 bch2_have_enough_devs(c, sb_written, degraded_flags, false);
904
905         /*
906          * If we would be able to mount _without_ the devices we successfully
907          * wrote superblocks to, we weren't able to write to enough devices:
908          *
909          * Exception: if we can mount without the successes because we haven't
910          * written anything (new filesystem), we continue if we'd be able to
911          * mount with the devices we did successfully write to:
912          */
913         if (bch2_fs_fatal_err_on(!nr_wrote ||
914                                  !can_mount_with_written ||
915                                  (can_mount_without_written &&
916                                   !can_mount_with_written), c,
917                 "Unable to write superblock to sufficient devices (from %ps)",
918                 (void *) _RET_IP_))
919                 ret = -1;
920 out:
921         /* Make new options visible after they're persistent: */
922         bch2_sb_update(c);
923         printbuf_exit(&err);
924         return ret;
925 }
926
927 void __bch2_check_set_feature(struct bch_fs *c, unsigned feat)
928 {
929         mutex_lock(&c->sb_lock);
930         if (!(c->sb.features & (1ULL << feat))) {
931                 c->disk_sb.sb->features[0] |= cpu_to_le64(1ULL << feat);
932
933                 bch2_write_super(c);
934         }
935         mutex_unlock(&c->sb_lock);
936 }
937
938 /* BCH_SB_FIELD_members: */
939
940 static int bch2_sb_members_validate(struct bch_sb *sb,
941                                     struct bch_sb_field *f,
942                                     struct printbuf *err)
943 {
944         struct bch_sb_field_members *mi = field_to_type(f, members);
945         unsigned i;
946
947         if ((void *) (mi->members + sb->nr_devices) >
948             vstruct_end(&mi->field)) {
949                 prt_printf(err, "too many devices for section size");
950                 return -EINVAL;
951         }
952
953         for (i = 0; i < sb->nr_devices; i++) {
954                 struct bch_member *m = mi->members + i;
955
956                 if (!bch2_member_exists(m))
957                         continue;
958
959                 if (le64_to_cpu(m->nbuckets) > LONG_MAX) {
960                         prt_printf(err, "device %u: too many buckets (got %llu, max %lu)",
961                                i, le64_to_cpu(m->nbuckets), LONG_MAX);
962                         return -EINVAL;
963                 }
964
965                 if (le64_to_cpu(m->nbuckets) -
966                     le16_to_cpu(m->first_bucket) < BCH_MIN_NR_NBUCKETS) {
967                         prt_printf(err, "device %u: not enough buckets (got %llu, max %u)",
968                                i, le64_to_cpu(m->nbuckets), BCH_MIN_NR_NBUCKETS);
969                         return -EINVAL;
970                 }
971
972                 if (le16_to_cpu(m->bucket_size) <
973                     le16_to_cpu(sb->block_size)) {
974                         prt_printf(err, "device %u: bucket size %u smaller than block size %u",
975                                i, le16_to_cpu(m->bucket_size), le16_to_cpu(sb->block_size));
976                         return -EINVAL;
977                 }
978
979                 if (le16_to_cpu(m->bucket_size) <
980                     BCH_SB_BTREE_NODE_SIZE(sb)) {
981                         prt_printf(err, "device %u: bucket size %u smaller than btree node size %llu",
982                                i, le16_to_cpu(m->bucket_size), BCH_SB_BTREE_NODE_SIZE(sb));
983                         return -EINVAL;
984                 }
985         }
986
987         return 0;
988 }
989
990 static void bch2_sb_members_to_text(struct printbuf *out, struct bch_sb *sb,
991                                     struct bch_sb_field *f)
992 {
993         struct bch_sb_field_members *mi = field_to_type(f, members);
994         struct bch_sb_field_disk_groups *gi = bch2_sb_get_disk_groups(sb);
995         unsigned i;
996
997         for (i = 0; i < sb->nr_devices; i++) {
998                 struct bch_member *m = mi->members + i;
999                 unsigned data_have = bch2_sb_dev_has_data(sb, i);
1000                 u64 bucket_size = le16_to_cpu(m->bucket_size);
1001                 u64 device_size = le64_to_cpu(m->nbuckets) * bucket_size;
1002
1003                 if (!bch2_member_exists(m))
1004                         continue;
1005
1006                 prt_printf(out, "Device:");
1007                 prt_tab(out);
1008                 prt_printf(out, "%u", i);
1009                 prt_newline(out);
1010
1011                 printbuf_indent_add(out, 2);
1012
1013                 prt_printf(out, "UUID:");
1014                 prt_tab(out);
1015                 pr_uuid(out, m->uuid.b);
1016                 prt_newline(out);
1017
1018                 prt_printf(out, "Size:");
1019                 prt_tab(out);
1020                 prt_units_u64(out, device_size << 9);
1021                 prt_newline(out);
1022
1023                 prt_printf(out, "Bucket size:");
1024                 prt_tab(out);
1025                 prt_units_u64(out, bucket_size << 9);
1026                 prt_newline(out);
1027
1028                 prt_printf(out, "First bucket:");
1029                 prt_tab(out);
1030                 prt_printf(out, "%u", le16_to_cpu(m->first_bucket));
1031                 prt_newline(out);
1032
1033                 prt_printf(out, "Buckets:");
1034                 prt_tab(out);
1035                 prt_printf(out, "%llu", le64_to_cpu(m->nbuckets));
1036                 prt_newline(out);
1037
1038                 prt_printf(out, "Last mount:");
1039                 prt_tab(out);
1040                 if (m->last_mount)
1041                         pr_time(out, le64_to_cpu(m->last_mount));
1042                 else
1043                         prt_printf(out, "(never)");
1044                 prt_newline(out);
1045
1046                 prt_printf(out, "State:");
1047                 prt_tab(out);
1048                 prt_printf(out, "%s",
1049                        BCH_MEMBER_STATE(m) < BCH_MEMBER_STATE_NR
1050                        ? bch2_member_states[BCH_MEMBER_STATE(m)]
1051                        : "unknown");
1052                 prt_newline(out);
1053
1054                 prt_printf(out, "Label:");
1055                 prt_tab(out);
1056                 if (BCH_MEMBER_GROUP(m)) {
1057                         unsigned idx = BCH_MEMBER_GROUP(m) - 1;
1058
1059                         if (idx < disk_groups_nr(gi))
1060                                 prt_printf(out, "%s (%u)",
1061                                        gi->entries[idx].label, idx);
1062                         else
1063                                 prt_printf(out, "(bad disk labels section)");
1064                 } else {
1065                         prt_printf(out, "(none)");
1066                 }
1067                 prt_newline(out);
1068
1069                 prt_printf(out, "Data allowed:");
1070                 prt_tab(out);
1071                 if (BCH_MEMBER_DATA_ALLOWED(m))
1072                         prt_bitflags(out, bch2_data_types, BCH_MEMBER_DATA_ALLOWED(m));
1073                 else
1074                         prt_printf(out, "(none)");
1075                 prt_newline(out);
1076
1077                 prt_printf(out, "Has data:");
1078                 prt_tab(out);
1079                 if (data_have)
1080                         prt_bitflags(out, bch2_data_types, data_have);
1081                 else
1082                         prt_printf(out, "(none)");
1083                 prt_newline(out);
1084
1085                 prt_printf(out, "Discard:");
1086                 prt_tab(out);
1087                 prt_printf(out, "%llu", BCH_MEMBER_DISCARD(m));
1088                 prt_newline(out);
1089
1090                 prt_printf(out, "Freespace initialized:");
1091                 prt_tab(out);
1092                 prt_printf(out, "%llu", BCH_MEMBER_FREESPACE_INITIALIZED(m));
1093                 prt_newline(out);
1094
1095                 printbuf_indent_sub(out, 2);
1096         }
1097 }
1098
1099 static const struct bch_sb_field_ops bch_sb_field_ops_members = {
1100         .validate       = bch2_sb_members_validate,
1101         .to_text        = bch2_sb_members_to_text,
1102 };
1103
1104 /* BCH_SB_FIELD_crypt: */
1105
1106 static int bch2_sb_crypt_validate(struct bch_sb *sb,
1107                                   struct bch_sb_field *f,
1108                                   struct printbuf *err)
1109 {
1110         struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
1111
1112         if (vstruct_bytes(&crypt->field) < sizeof(*crypt)) {
1113                 prt_printf(err, "wrong size (got %zu should be %zu)",
1114                        vstruct_bytes(&crypt->field), sizeof(*crypt));
1115                 return -EINVAL;
1116         }
1117
1118         if (BCH_CRYPT_KDF_TYPE(crypt)) {
1119                 prt_printf(err, "bad kdf type %llu", BCH_CRYPT_KDF_TYPE(crypt));
1120                 return -EINVAL;
1121         }
1122
1123         return 0;
1124 }
1125
1126 static void bch2_sb_crypt_to_text(struct printbuf *out, struct bch_sb *sb,
1127                                   struct bch_sb_field *f)
1128 {
1129         struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
1130
1131         prt_printf(out, "KFD:               %llu", BCH_CRYPT_KDF_TYPE(crypt));
1132         prt_newline(out);
1133         prt_printf(out, "scrypt n:          %llu", BCH_KDF_SCRYPT_N(crypt));
1134         prt_newline(out);
1135         prt_printf(out, "scrypt r:          %llu", BCH_KDF_SCRYPT_R(crypt));
1136         prt_newline(out);
1137         prt_printf(out, "scrypt p:          %llu", BCH_KDF_SCRYPT_P(crypt));
1138         prt_newline(out);
1139 }
1140
1141 static const struct bch_sb_field_ops bch_sb_field_ops_crypt = {
1142         .validate       = bch2_sb_crypt_validate,
1143         .to_text        = bch2_sb_crypt_to_text,
1144 };
1145
1146 /* BCH_SB_FIELD_clean: */
1147
1148 int bch2_sb_clean_validate_late(struct bch_fs *c, struct bch_sb_field_clean *clean, int write)
1149 {
1150         struct jset_entry *entry;
1151         int ret;
1152
1153         for (entry = clean->start;
1154              entry < (struct jset_entry *) vstruct_end(&clean->field);
1155              entry = vstruct_next(entry)) {
1156                 ret = bch2_journal_entry_validate(c, "superblock", entry,
1157                                                   le16_to_cpu(c->disk_sb.sb->version),
1158                                                   BCH_SB_BIG_ENDIAN(c->disk_sb.sb),
1159                                                   write);
1160                 if (ret)
1161                         return ret;
1162         }
1163
1164         return 0;
1165 }
1166
1167 int bch2_fs_mark_dirty(struct bch_fs *c)
1168 {
1169         int ret;
1170
1171         /*
1172          * Unconditionally write superblock, to verify it hasn't changed before
1173          * we go rw:
1174          */
1175
1176         mutex_lock(&c->sb_lock);
1177         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1178         c->disk_sb.sb->features[0] |= cpu_to_le64(BCH_SB_FEATURES_ALWAYS);
1179         c->disk_sb.sb->compat[0] &= cpu_to_le64((1ULL << BCH_COMPAT_NR) - 1);
1180         ret = bch2_write_super(c);
1181         mutex_unlock(&c->sb_lock);
1182
1183         return ret;
1184 }
1185
1186 static struct jset_entry *jset_entry_init(struct jset_entry **end, size_t size)
1187 {
1188         struct jset_entry *entry = *end;
1189         unsigned u64s = DIV_ROUND_UP(size, sizeof(u64));
1190
1191         memset(entry, 0, u64s * sizeof(u64));
1192         /*
1193          * The u64s field counts from the start of data, ignoring the shared
1194          * fields.
1195          */
1196         entry->u64s = cpu_to_le16(u64s - 1);
1197
1198         *end = vstruct_next(*end);
1199         return entry;
1200 }
1201
1202 void bch2_journal_super_entries_add_common(struct bch_fs *c,
1203                                            struct jset_entry **end,
1204                                            u64 journal_seq)
1205 {
1206         struct bch_dev *ca;
1207         unsigned i, dev;
1208
1209         percpu_down_read(&c->mark_lock);
1210
1211         if (!journal_seq) {
1212                 for (i = 0; i < ARRAY_SIZE(c->usage); i++)
1213                         bch2_fs_usage_acc_to_base(c, i);
1214         } else {
1215                 bch2_fs_usage_acc_to_base(c, journal_seq & JOURNAL_BUF_MASK);
1216         }
1217
1218         {
1219                 struct jset_entry_usage *u =
1220                         container_of(jset_entry_init(end, sizeof(*u)),
1221                                      struct jset_entry_usage, entry);
1222
1223                 u->entry.type   = BCH_JSET_ENTRY_usage;
1224                 u->entry.btree_id = BCH_FS_USAGE_inodes;
1225                 u->v            = cpu_to_le64(c->usage_base->nr_inodes);
1226         }
1227
1228         {
1229                 struct jset_entry_usage *u =
1230                         container_of(jset_entry_init(end, sizeof(*u)),
1231                                      struct jset_entry_usage, entry);
1232
1233                 u->entry.type   = BCH_JSET_ENTRY_usage;
1234                 u->entry.btree_id = BCH_FS_USAGE_key_version;
1235                 u->v            = cpu_to_le64(atomic64_read(&c->key_version));
1236         }
1237
1238         for (i = 0; i < BCH_REPLICAS_MAX; i++) {
1239                 struct jset_entry_usage *u =
1240                         container_of(jset_entry_init(end, sizeof(*u)),
1241                                      struct jset_entry_usage, entry);
1242
1243                 u->entry.type   = BCH_JSET_ENTRY_usage;
1244                 u->entry.btree_id = BCH_FS_USAGE_reserved;
1245                 u->entry.level  = i;
1246                 u->v            = cpu_to_le64(c->usage_base->persistent_reserved[i]);
1247         }
1248
1249         for (i = 0; i < c->replicas.nr; i++) {
1250                 struct bch_replicas_entry *e =
1251                         cpu_replicas_entry(&c->replicas, i);
1252                 struct jset_entry_data_usage *u =
1253                         container_of(jset_entry_init(end, sizeof(*u) + e->nr_devs),
1254                                      struct jset_entry_data_usage, entry);
1255
1256                 u->entry.type   = BCH_JSET_ENTRY_data_usage;
1257                 u->v            = cpu_to_le64(c->usage_base->replicas[i]);
1258                 memcpy(&u->r, e, replicas_entry_bytes(e));
1259         }
1260
1261         for_each_member_device(ca, c, dev) {
1262                 unsigned b = sizeof(struct jset_entry_dev_usage) +
1263                         sizeof(struct jset_entry_dev_usage_type) * BCH_DATA_NR;
1264                 struct jset_entry_dev_usage *u =
1265                         container_of(jset_entry_init(end, b),
1266                                      struct jset_entry_dev_usage, entry);
1267
1268                 u->entry.type = BCH_JSET_ENTRY_dev_usage;
1269                 u->dev = cpu_to_le32(dev);
1270                 u->buckets_ec           = cpu_to_le64(ca->usage_base->buckets_ec);
1271
1272                 for (i = 0; i < BCH_DATA_NR; i++) {
1273                         u->d[i].buckets = cpu_to_le64(ca->usage_base->d[i].buckets);
1274                         u->d[i].sectors = cpu_to_le64(ca->usage_base->d[i].sectors);
1275                         u->d[i].fragmented = cpu_to_le64(ca->usage_base->d[i].fragmented);
1276                 }
1277         }
1278
1279         percpu_up_read(&c->mark_lock);
1280
1281         for (i = 0; i < 2; i++) {
1282                 struct jset_entry_clock *clock =
1283                         container_of(jset_entry_init(end, sizeof(*clock)),
1284                                      struct jset_entry_clock, entry);
1285
1286                 clock->entry.type = BCH_JSET_ENTRY_clock;
1287                 clock->rw       = i;
1288                 clock->time     = cpu_to_le64(atomic64_read(&c->io_clock[i].now));
1289         }
1290 }
1291
1292 void bch2_fs_mark_clean(struct bch_fs *c)
1293 {
1294         struct bch_sb_field_clean *sb_clean;
1295         struct jset_entry *entry;
1296         unsigned u64s;
1297         int ret;
1298
1299         mutex_lock(&c->sb_lock);
1300         if (BCH_SB_CLEAN(c->disk_sb.sb))
1301                 goto out;
1302
1303         SET_BCH_SB_CLEAN(c->disk_sb.sb, true);
1304
1305         c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_info);
1306         c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_metadata);
1307         c->disk_sb.sb->features[0] &= cpu_to_le64(~(1ULL << BCH_FEATURE_extents_above_btree_updates));
1308         c->disk_sb.sb->features[0] &= cpu_to_le64(~(1ULL << BCH_FEATURE_btree_updates_journalled));
1309
1310         u64s = sizeof(*sb_clean) / sizeof(u64) + c->journal.entry_u64s_reserved;
1311
1312         sb_clean = bch2_sb_resize_clean(&c->disk_sb, u64s);
1313         if (!sb_clean) {
1314                 bch_err(c, "error resizing superblock while setting filesystem clean");
1315                 goto out;
1316         }
1317
1318         sb_clean->flags         = 0;
1319         sb_clean->journal_seq   = cpu_to_le64(atomic64_read(&c->journal.seq));
1320
1321         /* Trying to catch outstanding bug: */
1322         BUG_ON(le64_to_cpu(sb_clean->journal_seq) > S64_MAX);
1323
1324         entry = sb_clean->start;
1325         bch2_journal_super_entries_add_common(c, &entry, 0);
1326         entry = bch2_btree_roots_to_journal_entries(c, entry, entry);
1327         BUG_ON((void *) entry > vstruct_end(&sb_clean->field));
1328
1329         memset(entry, 0,
1330                vstruct_end(&sb_clean->field) - (void *) entry);
1331
1332         /*
1333          * this should be in the write path, and we should be validating every
1334          * superblock section:
1335          */
1336         ret = bch2_sb_clean_validate_late(c, sb_clean, WRITE);
1337         if (ret) {
1338                 bch_err(c, "error writing marking filesystem clean: validate error");
1339                 goto out;
1340         }
1341
1342         bch2_write_super(c);
1343 out:
1344         mutex_unlock(&c->sb_lock);
1345 }
1346
1347 static int bch2_sb_clean_validate(struct bch_sb *sb,
1348                                   struct bch_sb_field *f,
1349                                   struct printbuf *err)
1350 {
1351         struct bch_sb_field_clean *clean = field_to_type(f, clean);
1352
1353         if (vstruct_bytes(&clean->field) < sizeof(*clean)) {
1354                 prt_printf(err, "wrong size (got %zu should be %zu)",
1355                        vstruct_bytes(&clean->field), sizeof(*clean));
1356                 return -EINVAL;
1357         }
1358
1359         return 0;
1360 }
1361
1362 static void bch2_sb_clean_to_text(struct printbuf *out, struct bch_sb *sb,
1363                                   struct bch_sb_field *f)
1364 {
1365         struct bch_sb_field_clean *clean = field_to_type(f, clean);
1366         struct jset_entry *entry;
1367
1368         prt_printf(out, "flags:          %x",   le32_to_cpu(clean->flags));
1369         prt_newline(out);
1370         prt_printf(out, "journal_seq:    %llu", le64_to_cpu(clean->journal_seq));
1371         prt_newline(out);
1372
1373         for (entry = clean->start;
1374              entry != vstruct_end(&clean->field);
1375              entry = vstruct_next(entry)) {
1376                 if (entry->type == BCH_JSET_ENTRY_btree_keys &&
1377                     !entry->u64s)
1378                         continue;
1379
1380                 bch2_journal_entry_to_text(out, NULL, entry);
1381                 prt_newline(out);
1382         }
1383 }
1384
1385 static const struct bch_sb_field_ops bch_sb_field_ops_clean = {
1386         .validate       = bch2_sb_clean_validate,
1387         .to_text        = bch2_sb_clean_to_text,
1388 };
1389
1390 static const struct bch_sb_field_ops *bch2_sb_field_ops[] = {
1391 #define x(f, nr)                                        \
1392         [BCH_SB_FIELD_##f] = &bch_sb_field_ops_##f,
1393         BCH_SB_FIELDS()
1394 #undef x
1395 };
1396
1397 static int bch2_sb_field_validate(struct bch_sb *sb, struct bch_sb_field *f,
1398                                   struct printbuf *err)
1399 {
1400         unsigned type = le32_to_cpu(f->type);
1401         struct printbuf field_err = PRINTBUF;
1402         int ret;
1403
1404         if (type >= BCH_SB_FIELD_NR)
1405                 return 0;
1406
1407         ret = bch2_sb_field_ops[type]->validate(sb, f, &field_err);
1408         if (ret) {
1409                 prt_printf(err, "Invalid superblock section %s: %s",
1410                        bch2_sb_fields[type],
1411                        field_err.buf);
1412                 prt_newline(err);
1413                 bch2_sb_field_to_text(err, sb, f);
1414         }
1415
1416         printbuf_exit(&field_err);
1417         return ret;
1418 }
1419
1420 void bch2_sb_field_to_text(struct printbuf *out, struct bch_sb *sb,
1421                            struct bch_sb_field *f)
1422 {
1423         unsigned type = le32_to_cpu(f->type);
1424         const struct bch_sb_field_ops *ops = type < BCH_SB_FIELD_NR
1425                 ? bch2_sb_field_ops[type] : NULL;
1426
1427         if (!out->tabstops[0])
1428                 out->tabstops[0] = 32;
1429
1430         if (ops)
1431                 prt_printf(out, "%s", bch2_sb_fields[type]);
1432         else
1433                 prt_printf(out, "(unknown field %u)", type);
1434
1435         prt_printf(out, " (size %zu):", vstruct_bytes(f));
1436         prt_newline(out);
1437
1438         if (ops && ops->to_text) {
1439                 printbuf_indent_add(out, 2);
1440                 bch2_sb_field_ops[type]->to_text(out, sb, f);
1441                 printbuf_indent_sub(out, 2);
1442         }
1443 }
1444
1445 void bch2_sb_layout_to_text(struct printbuf *out, struct bch_sb_layout *l)
1446 {
1447         unsigned i;
1448
1449         prt_printf(out, "Type:                    %u", l->layout_type);
1450         prt_newline(out);
1451
1452         prt_str(out, "Superblock max size:     ");
1453         prt_units_u64(out, 512 << l->sb_max_size_bits);
1454         prt_newline(out);
1455
1456         prt_printf(out, "Nr superblocks:          %u", l->nr_superblocks);
1457         prt_newline(out);
1458
1459         prt_str(out, "Offsets:                 ");
1460         for (i = 0; i < l->nr_superblocks; i++) {
1461                 if (i)
1462                         prt_str(out, ", ");
1463                 prt_printf(out, "%llu", le64_to_cpu(l->sb_offset[i]));
1464         }
1465         prt_newline(out);
1466 }
1467
1468 void bch2_sb_to_text(struct printbuf *out, struct bch_sb *sb,
1469                      bool print_layout, unsigned fields)
1470 {
1471         struct bch_sb_field_members *mi;
1472         struct bch_sb_field *f;
1473         u64 fields_have = 0;
1474         unsigned nr_devices = 0;
1475
1476         if (!out->tabstops[0])
1477                 out->tabstops[0] = 32;
1478
1479         mi = bch2_sb_get_members(sb);
1480         if (mi) {
1481                 struct bch_member *m;
1482
1483                 for (m = mi->members;
1484                      m < mi->members + sb->nr_devices;
1485                      m++)
1486                         nr_devices += bch2_member_exists(m);
1487         }
1488
1489         prt_printf(out, "External UUID:");
1490         prt_tab(out);
1491         pr_uuid(out, sb->user_uuid.b);
1492         prt_newline(out);
1493
1494         prt_printf(out, "Internal UUID:");
1495         prt_tab(out);
1496         pr_uuid(out, sb->uuid.b);
1497         prt_newline(out);
1498
1499         prt_str(out, "Device index:");
1500         prt_tab(out);
1501         prt_printf(out, "%u", sb->dev_idx);
1502         prt_newline(out);
1503
1504         prt_str(out, "Label:");
1505         prt_tab(out);
1506         prt_printf(out, "%.*s", (int) sizeof(sb->label), sb->label);
1507         prt_newline(out);
1508
1509         prt_str(out, "Version:");
1510         prt_tab(out);
1511         prt_printf(out, "%s", bch2_metadata_versions[le16_to_cpu(sb->version)]);
1512         prt_newline(out);
1513
1514         prt_printf(out, "Oldest version on disk:");
1515         prt_tab(out);
1516         prt_printf(out, "%s", bch2_metadata_versions[le16_to_cpu(sb->version_min)]);
1517         prt_newline(out);
1518
1519         prt_printf(out, "Created:");
1520         prt_tab(out);
1521         if (sb->time_base_lo)
1522                 pr_time(out, div_u64(le64_to_cpu(sb->time_base_lo), NSEC_PER_SEC));
1523         else
1524                 prt_printf(out, "(not set)");
1525         prt_newline(out);
1526
1527         prt_printf(out, "Sequence number:");
1528         prt_tab(out);
1529         prt_printf(out, "%llu", le64_to_cpu(sb->seq));
1530         prt_newline(out);
1531
1532         prt_printf(out, "Superblock size:");
1533         prt_tab(out);
1534         prt_printf(out, "%zu", vstruct_bytes(sb));
1535         prt_newline(out);
1536
1537         prt_printf(out, "Clean:");
1538         prt_tab(out);
1539         prt_printf(out, "%llu", BCH_SB_CLEAN(sb));
1540         prt_newline(out);
1541
1542         prt_printf(out, "Devices:");
1543         prt_tab(out);
1544         prt_printf(out, "%u", nr_devices);
1545         prt_newline(out);
1546
1547         prt_printf(out, "Sections:");
1548         vstruct_for_each(sb, f)
1549                 fields_have |= 1 << le32_to_cpu(f->type);
1550         prt_tab(out);
1551         prt_bitflags(out, bch2_sb_fields, fields_have);
1552         prt_newline(out);
1553
1554         prt_printf(out, "Features:");
1555         prt_tab(out);
1556         prt_bitflags(out, bch2_sb_features, le64_to_cpu(sb->features[0]));
1557         prt_newline(out);
1558
1559         prt_printf(out, "Compat features:");
1560         prt_tab(out);
1561         prt_bitflags(out, bch2_sb_compat, le64_to_cpu(sb->compat[0]));
1562         prt_newline(out);
1563
1564         prt_newline(out);
1565         prt_printf(out, "Options:");
1566         prt_newline(out);
1567         printbuf_indent_add(out, 2);
1568         {
1569                 enum bch_opt_id id;
1570
1571                 for (id = 0; id < bch2_opts_nr; id++) {
1572                         const struct bch_option *opt = bch2_opt_table + id;
1573
1574                         if (opt->get_sb != BCH2_NO_SB_OPT) {
1575                                 u64 v = bch2_opt_from_sb(sb, id);
1576
1577                                 prt_printf(out, "%s:", opt->attr.name);
1578                                 prt_tab(out);
1579                                 bch2_opt_to_text(out, NULL, sb, opt, v,
1580                                                  OPT_HUMAN_READABLE|OPT_SHOW_FULL_LIST);
1581                                 prt_newline(out);
1582                         }
1583                 }
1584         }
1585
1586         printbuf_indent_sub(out, 2);
1587
1588         if (print_layout) {
1589                 prt_newline(out);
1590                 prt_printf(out, "layout:");
1591                 prt_newline(out);
1592                 printbuf_indent_add(out, 2);
1593                 bch2_sb_layout_to_text(out, &sb->layout);
1594                 printbuf_indent_sub(out, 2);
1595         }
1596
1597         vstruct_for_each(sb, f)
1598                 if (fields & (1 << le32_to_cpu(f->type))) {
1599                         prt_newline(out);
1600                         bch2_sb_field_to_text(out, sb, f);
1601                 }
1602 }