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