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