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