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