]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/super-io.c
Update bcachefs sources to da7d42a9a2 bcachefs: Add new assertions for shutdown path
[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.version_upgrade_complete = BCH_SB_VERSION_UPGRADE_COMPLETE(src) ?: c->sb.version;
449         c->sb.nr_devices        = src->nr_devices;
450         c->sb.clean             = BCH_SB_CLEAN(src);
451         c->sb.encryption_type   = BCH_SB_ENCRYPTION_TYPE(src);
452
453         c->sb.nsec_per_time_unit = le32_to_cpu(src->time_precision);
454         c->sb.time_units_per_sec = NSEC_PER_SEC / c->sb.nsec_per_time_unit;
455
456         /* XXX this is wrong, we need a 96 or 128 bit integer type */
457         c->sb.time_base_lo      = div_u64(le64_to_cpu(src->time_base_lo),
458                                           c->sb.nsec_per_time_unit);
459         c->sb.time_base_hi      = le32_to_cpu(src->time_base_hi);
460
461         c->sb.features          = le64_to_cpu(src->features[0]);
462         c->sb.compat            = le64_to_cpu(src->compat[0]);
463
464         for_each_member_device(ca, c, i)
465                 ca->mi = bch2_mi_to_cpu(mi->members + i);
466 }
467
468 static int __copy_super(struct bch_sb_handle *dst_handle, struct bch_sb *src)
469 {
470         struct bch_sb_field *src_f, *dst_f;
471         struct bch_sb *dst = dst_handle->sb;
472         unsigned i;
473
474         dst->version            = src->version;
475         dst->version_min        = src->version_min;
476         dst->seq                = src->seq;
477         dst->uuid               = src->uuid;
478         dst->user_uuid          = src->user_uuid;
479         memcpy(dst->label,      src->label, sizeof(dst->label));
480
481         dst->block_size         = src->block_size;
482         dst->nr_devices         = src->nr_devices;
483
484         dst->time_base_lo       = src->time_base_lo;
485         dst->time_base_hi       = src->time_base_hi;
486         dst->time_precision     = src->time_precision;
487
488         memcpy(dst->flags,      src->flags,     sizeof(dst->flags));
489         memcpy(dst->features,   src->features,  sizeof(dst->features));
490         memcpy(dst->compat,     src->compat,    sizeof(dst->compat));
491
492         for (i = 0; i < BCH_SB_FIELD_NR; i++) {
493                 int d;
494
495                 if ((1U << i) & BCH_SINGLE_DEVICE_SB_FIELDS)
496                         continue;
497
498                 src_f = bch2_sb_field_get(src, i);
499                 dst_f = bch2_sb_field_get(dst, i);
500
501                 d = (src_f ? le32_to_cpu(src_f->u64s) : 0) -
502                     (dst_f ? le32_to_cpu(dst_f->u64s) : 0);
503                 if (d > 0) {
504                         int ret = bch2_sb_realloc(dst_handle, le32_to_cpu(dst_handle->sb->u64s) + d);
505                         if (ret)
506                                 return ret;
507
508                         dst = dst_handle->sb;
509                         dst_f = bch2_sb_field_get(dst, i);
510                 }
511
512                 dst_f = __bch2_sb_field_resize(dst_handle, dst_f,
513                                 src_f ? le32_to_cpu(src_f->u64s) : 0);
514
515                 if (src_f)
516                         memcpy(dst_f, src_f, vstruct_bytes(src_f));
517         }
518
519         return 0;
520 }
521
522 int bch2_sb_to_fs(struct bch_fs *c, struct bch_sb *src)
523 {
524         int ret;
525
526         lockdep_assert_held(&c->sb_lock);
527
528         ret =   bch2_sb_realloc(&c->disk_sb, 0) ?:
529                 __copy_super(&c->disk_sb, src) ?:
530                 bch2_sb_replicas_to_cpu_replicas(c) ?:
531                 bch2_sb_disk_groups_to_cpu(c);
532         if (ret)
533                 return ret;
534
535         bch2_sb_update(c);
536         return 0;
537 }
538
539 int bch2_sb_from_fs(struct bch_fs *c, struct bch_dev *ca)
540 {
541         return __copy_super(&ca->disk_sb, c->disk_sb.sb);
542 }
543
544 /* read superblock: */
545
546 static int read_one_super(struct bch_sb_handle *sb, u64 offset, struct printbuf *err)
547 {
548         struct bch_csum csum;
549         size_t bytes;
550         int ret;
551 reread:
552         bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
553         sb->bio->bi_iter.bi_sector = offset;
554         bch2_bio_map(sb->bio, sb->sb, sb->buffer_size);
555
556         ret = submit_bio_wait(sb->bio);
557         if (ret) {
558                 prt_printf(err, "IO error: %i", ret);
559                 return ret;
560         }
561
562         if (!uuid_equal(&sb->sb->magic, &BCACHE_MAGIC) &&
563             !uuid_equal(&sb->sb->magic, &BCHFS_MAGIC)) {
564                 prt_printf(err, "Not a bcachefs superblock");
565                 return -BCH_ERR_invalid_sb_magic;
566         }
567
568         ret = bch2_sb_compatible(sb->sb, err);
569         if (ret)
570                 return ret;
571
572         bytes = vstruct_bytes(sb->sb);
573
574         if (bytes > 512 << sb->sb->layout.sb_max_size_bits) {
575                 prt_printf(err, "Invalid superblock: too big (got %zu bytes, layout max %lu)",
576                        bytes, 512UL << sb->sb->layout.sb_max_size_bits);
577                 return -BCH_ERR_invalid_sb_too_big;
578         }
579
580         if (bytes > sb->buffer_size) {
581                 ret = bch2_sb_realloc(sb, le32_to_cpu(sb->sb->u64s));
582                 if (ret)
583                         return ret;
584                 goto reread;
585         }
586
587         if (BCH_SB_CSUM_TYPE(sb->sb) >= BCH_CSUM_NR) {
588                 prt_printf(err, "unknown checksum type %llu", BCH_SB_CSUM_TYPE(sb->sb));
589                 return -BCH_ERR_invalid_sb_csum_type;
590         }
591
592         /* XXX: verify MACs */
593         csum = csum_vstruct(NULL, BCH_SB_CSUM_TYPE(sb->sb),
594                             null_nonce(), sb->sb);
595
596         if (bch2_crc_cmp(csum, sb->sb->csum)) {
597                 prt_printf(err, "bad checksum");
598                 return -BCH_ERR_invalid_sb_csum;
599         }
600
601         sb->seq = le64_to_cpu(sb->sb->seq);
602
603         return 0;
604 }
605
606 int bch2_read_super(const char *path, struct bch_opts *opts,
607                     struct bch_sb_handle *sb)
608 {
609         u64 offset = opt_get(*opts, sb);
610         struct bch_sb_layout layout;
611         struct printbuf err = PRINTBUF;
612         __le64 *i;
613         int ret;
614
615         memset(sb, 0, sizeof(*sb));
616         sb->mode        = FMODE_READ;
617         sb->have_bio    = true;
618
619         if (!opt_get(*opts, noexcl))
620                 sb->mode |= FMODE_EXCL;
621
622         if (!opt_get(*opts, nochanges))
623                 sb->mode |= FMODE_WRITE;
624
625         sb->bdev = blkdev_get_by_path(path, sb->mode, sb);
626         if (IS_ERR(sb->bdev) &&
627             PTR_ERR(sb->bdev) == -EACCES &&
628             opt_get(*opts, read_only)) {
629                 sb->mode &= ~FMODE_WRITE;
630
631                 sb->bdev = blkdev_get_by_path(path, sb->mode, sb);
632                 if (!IS_ERR(sb->bdev))
633                         opt_set(*opts, nochanges, true);
634         }
635
636         if (IS_ERR(sb->bdev)) {
637                 ret = PTR_ERR(sb->bdev);
638                 goto out;
639         }
640
641         ret = bch2_sb_realloc(sb, 0);
642         if (ret) {
643                 prt_printf(&err, "error allocating memory for superblock");
644                 goto err;
645         }
646
647         if (bch2_fs_init_fault("read_super")) {
648                 prt_printf(&err, "dynamic fault");
649                 ret = -EFAULT;
650                 goto err;
651         }
652
653         ret = read_one_super(sb, offset, &err);
654         if (!ret)
655                 goto got_super;
656
657         if (opt_defined(*opts, sb))
658                 goto err;
659
660         printk(KERN_ERR "bcachefs (%s): error reading default superblock: %s",
661                path, err.buf);
662         printbuf_reset(&err);
663
664         /*
665          * Error reading primary superblock - read location of backup
666          * superblocks:
667          */
668         bio_reset(sb->bio, sb->bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
669         sb->bio->bi_iter.bi_sector = BCH_SB_LAYOUT_SECTOR;
670         /*
671          * use sb buffer to read layout, since sb buffer is page aligned but
672          * layout won't be:
673          */
674         bch2_bio_map(sb->bio, sb->sb, sizeof(struct bch_sb_layout));
675
676         ret = submit_bio_wait(sb->bio);
677         if (ret) {
678                 prt_printf(&err, "IO error: %i", ret);
679                 goto err;
680         }
681
682         memcpy(&layout, sb->sb, sizeof(layout));
683         ret = validate_sb_layout(&layout, &err);
684         if (ret)
685                 goto err;
686
687         for (i = layout.sb_offset;
688              i < layout.sb_offset + layout.nr_superblocks; i++) {
689                 offset = le64_to_cpu(*i);
690
691                 if (offset == opt_get(*opts, sb))
692                         continue;
693
694                 ret = read_one_super(sb, offset, &err);
695                 if (!ret)
696                         goto got_super;
697         }
698
699         goto err;
700
701 got_super:
702         if (le16_to_cpu(sb->sb->block_size) << 9 <
703             bdev_logical_block_size(sb->bdev)) {
704                 prt_printf(&err, "block size (%u) smaller than device block size (%u)",
705                        le16_to_cpu(sb->sb->block_size) << 9,
706                        bdev_logical_block_size(sb->bdev));
707                 ret = -BCH_ERR_block_size_too_small;
708                 goto err;
709         }
710
711         ret = 0;
712         sb->have_layout = true;
713
714         ret = bch2_sb_validate(sb, &err, READ);
715         if (ret) {
716                 printk(KERN_ERR "bcachefs (%s): error validating superblock: %s",
717                        path, err.buf);
718                 goto err_no_print;
719         }
720 out:
721         printbuf_exit(&err);
722         return ret;
723 err:
724         printk(KERN_ERR "bcachefs (%s): error reading superblock: %s",
725                path, err.buf);
726 err_no_print:
727         bch2_free_super(sb);
728         goto out;
729 }
730
731 /* write superblock: */
732
733 static void write_super_endio(struct bio *bio)
734 {
735         struct bch_dev *ca = bio->bi_private;
736
737         /* XXX: return errors directly */
738
739         if (bch2_dev_io_err_on(bio->bi_status, ca, "superblock write error: %s",
740                                bch2_blk_status_to_str(bio->bi_status)))
741                 ca->sb_write_error = 1;
742
743         closure_put(&ca->fs->sb_write);
744         percpu_ref_put(&ca->io_ref);
745 }
746
747 static void read_back_super(struct bch_fs *c, struct bch_dev *ca)
748 {
749         struct bch_sb *sb = ca->disk_sb.sb;
750         struct bio *bio = ca->disk_sb.bio;
751
752         bio_reset(bio, ca->disk_sb.bdev, REQ_OP_READ|REQ_SYNC|REQ_META);
753         bio->bi_iter.bi_sector  = le64_to_cpu(sb->layout.sb_offset[0]);
754         bio->bi_end_io          = write_super_endio;
755         bio->bi_private         = ca;
756         bch2_bio_map(bio, ca->sb_read_scratch, PAGE_SIZE);
757
758         this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_sb],
759                      bio_sectors(bio));
760
761         percpu_ref_get(&ca->io_ref);
762         closure_bio_submit(bio, &c->sb_write);
763 }
764
765 static void write_one_super(struct bch_fs *c, struct bch_dev *ca, unsigned idx)
766 {
767         struct bch_sb *sb = ca->disk_sb.sb;
768         struct bio *bio = ca->disk_sb.bio;
769
770         sb->offset = sb->layout.sb_offset[idx];
771
772         SET_BCH_SB_CSUM_TYPE(sb, bch2_csum_opt_to_type(c->opts.metadata_checksum, false));
773         sb->csum = csum_vstruct(c, BCH_SB_CSUM_TYPE(sb),
774                                 null_nonce(), sb);
775
776         bio_reset(bio, ca->disk_sb.bdev, REQ_OP_WRITE|REQ_SYNC|REQ_META);
777         bio->bi_iter.bi_sector  = le64_to_cpu(sb->offset);
778         bio->bi_end_io          = write_super_endio;
779         bio->bi_private         = ca;
780         bch2_bio_map(bio, sb,
781                      roundup((size_t) vstruct_bytes(sb),
782                              bdev_logical_block_size(ca->disk_sb.bdev)));
783
784         this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_sb],
785                      bio_sectors(bio));
786
787         percpu_ref_get(&ca->io_ref);
788         closure_bio_submit(bio, &c->sb_write);
789 }
790
791 int bch2_write_super(struct bch_fs *c)
792 {
793         struct closure *cl = &c->sb_write;
794         struct bch_dev *ca;
795         struct printbuf err = PRINTBUF;
796         unsigned i, sb = 0, nr_wrote;
797         struct bch_devs_mask sb_written;
798         bool wrote, can_mount_without_written, can_mount_with_written;
799         unsigned degraded_flags = BCH_FORCE_IF_DEGRADED;
800         int ret = 0;
801
802         trace_and_count(c, write_super, c, _RET_IP_);
803
804         if (c->opts.very_degraded)
805                 degraded_flags |= BCH_FORCE_IF_LOST;
806
807         lockdep_assert_held(&c->sb_lock);
808
809         closure_init_stack(cl);
810         memset(&sb_written, 0, sizeof(sb_written));
811
812         if (test_bit(BCH_FS_VERSION_UPGRADE, &c->flags)) {
813                 c->disk_sb.sb->magic = BCHFS_MAGIC;
814                 c->disk_sb.sb->layout.magic = BCHFS_MAGIC;
815         }
816
817         le64_add_cpu(&c->disk_sb.sb->seq, 1);
818
819         if (test_bit(BCH_FS_ERROR, &c->flags))
820                 SET_BCH_SB_HAS_ERRORS(c->disk_sb.sb, 1);
821         if (test_bit(BCH_FS_TOPOLOGY_ERROR, &c->flags))
822                 SET_BCH_SB_HAS_TOPOLOGY_ERRORS(c->disk_sb.sb, 1);
823
824         SET_BCH_SB_BIG_ENDIAN(c->disk_sb.sb, CPU_BIG_ENDIAN);
825
826         bch2_sb_counters_from_cpu(c);
827
828         for_each_online_member(ca, c, i)
829                 bch2_sb_from_fs(c, ca);
830
831         for_each_online_member(ca, c, i) {
832                 printbuf_reset(&err);
833
834                 ret = bch2_sb_validate(&ca->disk_sb, &err, WRITE);
835                 if (ret) {
836                         bch2_fs_inconsistent(c, "sb invalid before write: %s", err.buf);
837                         percpu_ref_put(&ca->io_ref);
838                         goto out;
839                 }
840         }
841
842         if (c->opts.nochanges)
843                 goto out;
844
845         /*
846          * Defer writing the superblock until filesystem initialization is
847          * complete - don't write out a partly initialized superblock:
848          */
849         if (!BCH_SB_INITIALIZED(c->disk_sb.sb))
850                 goto out;
851
852         for_each_online_member(ca, c, i) {
853                 __set_bit(ca->dev_idx, sb_written.d);
854                 ca->sb_write_error = 0;
855         }
856
857         for_each_online_member(ca, c, i)
858                 read_back_super(c, ca);
859         closure_sync(cl);
860
861         for_each_online_member(ca, c, i) {
862                 if (ca->sb_write_error)
863                         continue;
864
865                 if (le64_to_cpu(ca->sb_read_scratch->seq) < ca->disk_sb.seq) {
866                         bch2_fs_fatal_error(c,
867                                 "Superblock write was silently dropped! (seq %llu expected %llu)",
868                                 le64_to_cpu(ca->sb_read_scratch->seq),
869                                 ca->disk_sb.seq);
870                         percpu_ref_put(&ca->io_ref);
871                         ret = -BCH_ERR_erofs_sb_err;
872                         goto out;
873                 }
874
875                 if (le64_to_cpu(ca->sb_read_scratch->seq) > ca->disk_sb.seq) {
876                         bch2_fs_fatal_error(c,
877                                 "Superblock modified by another process (seq %llu expected %llu)",
878                                 le64_to_cpu(ca->sb_read_scratch->seq),
879                                 ca->disk_sb.seq);
880                         percpu_ref_put(&ca->io_ref);
881                         ret = -BCH_ERR_erofs_sb_err;
882                         goto out;
883                 }
884         }
885
886         do {
887                 wrote = false;
888                 for_each_online_member(ca, c, i)
889                         if (!ca->sb_write_error &&
890                             sb < ca->disk_sb.sb->layout.nr_superblocks) {
891                                 write_one_super(c, ca, sb);
892                                 wrote = true;
893                         }
894                 closure_sync(cl);
895                 sb++;
896         } while (wrote);
897
898         for_each_online_member(ca, c, i) {
899                 if (ca->sb_write_error)
900                         __clear_bit(ca->dev_idx, sb_written.d);
901                 else
902                         ca->disk_sb.seq = le64_to_cpu(ca->disk_sb.sb->seq);
903         }
904
905         nr_wrote = dev_mask_nr(&sb_written);
906
907         can_mount_with_written =
908                 bch2_have_enough_devs(c, sb_written, degraded_flags, false);
909
910         for (i = 0; i < ARRAY_SIZE(sb_written.d); i++)
911                 sb_written.d[i] = ~sb_written.d[i];
912
913         can_mount_without_written =
914                 bch2_have_enough_devs(c, sb_written, degraded_flags, false);
915
916         /*
917          * If we would be able to mount _without_ the devices we successfully
918          * wrote superblocks to, we weren't able to write to enough devices:
919          *
920          * Exception: if we can mount without the successes because we haven't
921          * written anything (new filesystem), we continue if we'd be able to
922          * mount with the devices we did successfully write to:
923          */
924         if (bch2_fs_fatal_err_on(!nr_wrote ||
925                                  !can_mount_with_written ||
926                                  (can_mount_without_written &&
927                                   !can_mount_with_written), c,
928                 "Unable to write superblock to sufficient devices (from %ps)",
929                 (void *) _RET_IP_))
930                 ret = -1;
931 out:
932         /* Make new options visible after they're persistent: */
933         bch2_sb_update(c);
934         printbuf_exit(&err);
935         return ret;
936 }
937
938 void __bch2_check_set_feature(struct bch_fs *c, unsigned feat)
939 {
940         mutex_lock(&c->sb_lock);
941         if (!(c->sb.features & (1ULL << feat))) {
942                 c->disk_sb.sb->features[0] |= cpu_to_le64(1ULL << feat);
943
944                 bch2_write_super(c);
945         }
946         mutex_unlock(&c->sb_lock);
947 }
948
949 /* BCH_SB_FIELD_members: */
950
951 static int bch2_sb_members_validate(struct bch_sb *sb,
952                                     struct bch_sb_field *f,
953                                     struct printbuf *err)
954 {
955         struct bch_sb_field_members *mi = field_to_type(f, members);
956         unsigned i;
957
958         if ((void *) (mi->members + sb->nr_devices) >
959             vstruct_end(&mi->field)) {
960                 prt_printf(err, "too many devices for section size");
961                 return -BCH_ERR_invalid_sb_members;
962         }
963
964         for (i = 0; i < sb->nr_devices; i++) {
965                 struct bch_member *m = mi->members + i;
966
967                 if (!bch2_member_exists(m))
968                         continue;
969
970                 if (le64_to_cpu(m->nbuckets) > LONG_MAX) {
971                         prt_printf(err, "device %u: too many buckets (got %llu, max %lu)",
972                                i, le64_to_cpu(m->nbuckets), LONG_MAX);
973                         return -BCH_ERR_invalid_sb_members;
974                 }
975
976                 if (le64_to_cpu(m->nbuckets) -
977                     le16_to_cpu(m->first_bucket) < BCH_MIN_NR_NBUCKETS) {
978                         prt_printf(err, "device %u: not enough buckets (got %llu, max %u)",
979                                i, le64_to_cpu(m->nbuckets), BCH_MIN_NR_NBUCKETS);
980                         return -BCH_ERR_invalid_sb_members;
981                 }
982
983                 if (le16_to_cpu(m->bucket_size) <
984                     le16_to_cpu(sb->block_size)) {
985                         prt_printf(err, "device %u: bucket size %u smaller than block size %u",
986                                i, le16_to_cpu(m->bucket_size), le16_to_cpu(sb->block_size));
987                         return -BCH_ERR_invalid_sb_members;
988                 }
989
990                 if (le16_to_cpu(m->bucket_size) <
991                     BCH_SB_BTREE_NODE_SIZE(sb)) {
992                         prt_printf(err, "device %u: bucket size %u smaller than btree node size %llu",
993                                i, le16_to_cpu(m->bucket_size), BCH_SB_BTREE_NODE_SIZE(sb));
994                         return -BCH_ERR_invalid_sb_members;
995                 }
996         }
997
998         return 0;
999 }
1000
1001 static void bch2_sb_members_to_text(struct printbuf *out, struct bch_sb *sb,
1002                                     struct bch_sb_field *f)
1003 {
1004         struct bch_sb_field_members *mi = field_to_type(f, members);
1005         struct bch_sb_field_disk_groups *gi = bch2_sb_get_disk_groups(sb);
1006         unsigned i;
1007
1008         for (i = 0; i < sb->nr_devices; i++) {
1009                 struct bch_member *m = mi->members + i;
1010                 unsigned data_have = bch2_sb_dev_has_data(sb, i);
1011                 u64 bucket_size = le16_to_cpu(m->bucket_size);
1012                 u64 device_size = le64_to_cpu(m->nbuckets) * bucket_size;
1013
1014                 if (!bch2_member_exists(m))
1015                         continue;
1016
1017                 prt_printf(out, "Device:");
1018                 prt_tab(out);
1019                 prt_printf(out, "%u", i);
1020                 prt_newline(out);
1021
1022                 printbuf_indent_add(out, 2);
1023
1024                 prt_printf(out, "UUID:");
1025                 prt_tab(out);
1026                 pr_uuid(out, m->uuid.b);
1027                 prt_newline(out);
1028
1029                 prt_printf(out, "Size:");
1030                 prt_tab(out);
1031                 prt_units_u64(out, device_size << 9);
1032                 prt_newline(out);
1033
1034                 prt_printf(out, "Bucket size:");
1035                 prt_tab(out);
1036                 prt_units_u64(out, bucket_size << 9);
1037                 prt_newline(out);
1038
1039                 prt_printf(out, "First bucket:");
1040                 prt_tab(out);
1041                 prt_printf(out, "%u", le16_to_cpu(m->first_bucket));
1042                 prt_newline(out);
1043
1044                 prt_printf(out, "Buckets:");
1045                 prt_tab(out);
1046                 prt_printf(out, "%llu", le64_to_cpu(m->nbuckets));
1047                 prt_newline(out);
1048
1049                 prt_printf(out, "Last mount:");
1050                 prt_tab(out);
1051                 if (m->last_mount)
1052                         pr_time(out, le64_to_cpu(m->last_mount));
1053                 else
1054                         prt_printf(out, "(never)");
1055                 prt_newline(out);
1056
1057                 prt_printf(out, "State:");
1058                 prt_tab(out);
1059                 prt_printf(out, "%s",
1060                        BCH_MEMBER_STATE(m) < BCH_MEMBER_STATE_NR
1061                        ? bch2_member_states[BCH_MEMBER_STATE(m)]
1062                        : "unknown");
1063                 prt_newline(out);
1064
1065                 prt_printf(out, "Label:");
1066                 prt_tab(out);
1067                 if (BCH_MEMBER_GROUP(m)) {
1068                         unsigned idx = BCH_MEMBER_GROUP(m) - 1;
1069
1070                         if (idx < disk_groups_nr(gi))
1071                                 prt_printf(out, "%s (%u)",
1072                                        gi->entries[idx].label, idx);
1073                         else
1074                                 prt_printf(out, "(bad disk labels section)");
1075                 } else {
1076                         prt_printf(out, "(none)");
1077                 }
1078                 prt_newline(out);
1079
1080                 prt_printf(out, "Data allowed:");
1081                 prt_tab(out);
1082                 if (BCH_MEMBER_DATA_ALLOWED(m))
1083                         prt_bitflags(out, bch2_data_types, BCH_MEMBER_DATA_ALLOWED(m));
1084                 else
1085                         prt_printf(out, "(none)");
1086                 prt_newline(out);
1087
1088                 prt_printf(out, "Has data:");
1089                 prt_tab(out);
1090                 if (data_have)
1091                         prt_bitflags(out, bch2_data_types, data_have);
1092                 else
1093                         prt_printf(out, "(none)");
1094                 prt_newline(out);
1095
1096                 prt_printf(out, "Discard:");
1097                 prt_tab(out);
1098                 prt_printf(out, "%llu", BCH_MEMBER_DISCARD(m));
1099                 prt_newline(out);
1100
1101                 prt_printf(out, "Freespace initialized:");
1102                 prt_tab(out);
1103                 prt_printf(out, "%llu", BCH_MEMBER_FREESPACE_INITIALIZED(m));
1104                 prt_newline(out);
1105
1106                 printbuf_indent_sub(out, 2);
1107         }
1108 }
1109
1110 static const struct bch_sb_field_ops bch_sb_field_ops_members = {
1111         .validate       = bch2_sb_members_validate,
1112         .to_text        = bch2_sb_members_to_text,
1113 };
1114
1115 /* BCH_SB_FIELD_crypt: */
1116
1117 static int bch2_sb_crypt_validate(struct bch_sb *sb,
1118                                   struct bch_sb_field *f,
1119                                   struct printbuf *err)
1120 {
1121         struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
1122
1123         if (vstruct_bytes(&crypt->field) < sizeof(*crypt)) {
1124                 prt_printf(err, "wrong size (got %zu should be %zu)",
1125                        vstruct_bytes(&crypt->field), sizeof(*crypt));
1126                 return -BCH_ERR_invalid_sb_crypt;
1127         }
1128
1129         if (BCH_CRYPT_KDF_TYPE(crypt)) {
1130                 prt_printf(err, "bad kdf type %llu", BCH_CRYPT_KDF_TYPE(crypt));
1131                 return -BCH_ERR_invalid_sb_crypt;
1132         }
1133
1134         return 0;
1135 }
1136
1137 static void bch2_sb_crypt_to_text(struct printbuf *out, struct bch_sb *sb,
1138                                   struct bch_sb_field *f)
1139 {
1140         struct bch_sb_field_crypt *crypt = field_to_type(f, crypt);
1141
1142         prt_printf(out, "KFD:               %llu", BCH_CRYPT_KDF_TYPE(crypt));
1143         prt_newline(out);
1144         prt_printf(out, "scrypt n:          %llu", BCH_KDF_SCRYPT_N(crypt));
1145         prt_newline(out);
1146         prt_printf(out, "scrypt r:          %llu", BCH_KDF_SCRYPT_R(crypt));
1147         prt_newline(out);
1148         prt_printf(out, "scrypt p:          %llu", BCH_KDF_SCRYPT_P(crypt));
1149         prt_newline(out);
1150 }
1151
1152 static const struct bch_sb_field_ops bch_sb_field_ops_crypt = {
1153         .validate       = bch2_sb_crypt_validate,
1154         .to_text        = bch2_sb_crypt_to_text,
1155 };
1156
1157 /* BCH_SB_FIELD_clean: */
1158
1159 int bch2_sb_clean_validate_late(struct bch_fs *c, struct bch_sb_field_clean *clean, int write)
1160 {
1161         struct jset_entry *entry;
1162         int ret;
1163
1164         for (entry = clean->start;
1165              entry < (struct jset_entry *) vstruct_end(&clean->field);
1166              entry = vstruct_next(entry)) {
1167                 ret = bch2_journal_entry_validate(c, NULL, entry,
1168                                                   le16_to_cpu(c->disk_sb.sb->version),
1169                                                   BCH_SB_BIG_ENDIAN(c->disk_sb.sb),
1170                                                   write);
1171                 if (ret)
1172                         return ret;
1173         }
1174
1175         return 0;
1176 }
1177
1178 int bch2_fs_mark_dirty(struct bch_fs *c)
1179 {
1180         int ret;
1181
1182         /*
1183          * Unconditionally write superblock, to verify it hasn't changed before
1184          * we go rw:
1185          */
1186
1187         mutex_lock(&c->sb_lock);
1188         SET_BCH_SB_CLEAN(c->disk_sb.sb, false);
1189
1190         if (BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb) > bcachefs_metadata_version_current)
1191                 SET_BCH_SB_VERSION_UPGRADE_COMPLETE(c->disk_sb.sb, bcachefs_metadata_version_current);
1192
1193         if (test_bit(BCH_FS_VERSION_UPGRADE, &c->flags) ||
1194             c->sb.version > bcachefs_metadata_version_current)
1195                 c->disk_sb.sb->version = cpu_to_le16(bcachefs_metadata_version_current);
1196
1197         if (test_bit(BCH_FS_VERSION_UPGRADE, &c->flags))
1198                 c->disk_sb.sb->features[0] |= cpu_to_le64(BCH_SB_FEATURES_ALL);
1199
1200         c->disk_sb.sb->features[0] |= cpu_to_le64(BCH_SB_FEATURES_ALWAYS);
1201
1202         c->disk_sb.sb->compat[0] &= cpu_to_le64((1ULL << BCH_COMPAT_NR) - 1);
1203         ret = bch2_write_super(c);
1204         mutex_unlock(&c->sb_lock);
1205
1206         return ret;
1207 }
1208
1209 static struct jset_entry *jset_entry_init(struct jset_entry **end, size_t size)
1210 {
1211         struct jset_entry *entry = *end;
1212         unsigned u64s = DIV_ROUND_UP(size, sizeof(u64));
1213
1214         memset(entry, 0, u64s * sizeof(u64));
1215         /*
1216          * The u64s field counts from the start of data, ignoring the shared
1217          * fields.
1218          */
1219         entry->u64s = cpu_to_le16(u64s - 1);
1220
1221         *end = vstruct_next(*end);
1222         return entry;
1223 }
1224
1225 void bch2_journal_super_entries_add_common(struct bch_fs *c,
1226                                            struct jset_entry **end,
1227                                            u64 journal_seq)
1228 {
1229         struct bch_dev *ca;
1230         unsigned i, dev;
1231
1232         percpu_down_read(&c->mark_lock);
1233
1234         if (!journal_seq) {
1235                 for (i = 0; i < ARRAY_SIZE(c->usage); i++)
1236                         bch2_fs_usage_acc_to_base(c, i);
1237         } else {
1238                 bch2_fs_usage_acc_to_base(c, journal_seq & JOURNAL_BUF_MASK);
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_inodes;
1248                 u->v            = cpu_to_le64(c->usage_base->nr_inodes);
1249         }
1250
1251         {
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_key_version;
1258                 u->v            = cpu_to_le64(atomic64_read(&c->key_version));
1259         }
1260
1261         for (i = 0; i < BCH_REPLICAS_MAX; i++) {
1262                 struct jset_entry_usage *u =
1263                         container_of(jset_entry_init(end, sizeof(*u)),
1264                                      struct jset_entry_usage, entry);
1265
1266                 u->entry.type   = BCH_JSET_ENTRY_usage;
1267                 u->entry.btree_id = BCH_FS_USAGE_reserved;
1268                 u->entry.level  = i;
1269                 u->v            = cpu_to_le64(c->usage_base->persistent_reserved[i]);
1270         }
1271
1272         for (i = 0; i < c->replicas.nr; i++) {
1273                 struct bch_replicas_entry *e =
1274                         cpu_replicas_entry(&c->replicas, i);
1275                 struct jset_entry_data_usage *u =
1276                         container_of(jset_entry_init(end, sizeof(*u) + e->nr_devs),
1277                                      struct jset_entry_data_usage, entry);
1278
1279                 u->entry.type   = BCH_JSET_ENTRY_data_usage;
1280                 u->v            = cpu_to_le64(c->usage_base->replicas[i]);
1281                 unsafe_memcpy(&u->r, e, replicas_entry_bytes(e),
1282                               "embedded variable length struct");
1283         }
1284
1285         for_each_member_device(ca, c, dev) {
1286                 unsigned b = sizeof(struct jset_entry_dev_usage) +
1287                         sizeof(struct jset_entry_dev_usage_type) * BCH_DATA_NR;
1288                 struct jset_entry_dev_usage *u =
1289                         container_of(jset_entry_init(end, b),
1290                                      struct jset_entry_dev_usage, entry);
1291
1292                 u->entry.type = BCH_JSET_ENTRY_dev_usage;
1293                 u->dev = cpu_to_le32(dev);
1294                 u->buckets_ec           = cpu_to_le64(ca->usage_base->buckets_ec);
1295
1296                 for (i = 0; i < BCH_DATA_NR; i++) {
1297                         u->d[i].buckets = cpu_to_le64(ca->usage_base->d[i].buckets);
1298                         u->d[i].sectors = cpu_to_le64(ca->usage_base->d[i].sectors);
1299                         u->d[i].fragmented = cpu_to_le64(ca->usage_base->d[i].fragmented);
1300                 }
1301         }
1302
1303         percpu_up_read(&c->mark_lock);
1304
1305         for (i = 0; i < 2; i++) {
1306                 struct jset_entry_clock *clock =
1307                         container_of(jset_entry_init(end, sizeof(*clock)),
1308                                      struct jset_entry_clock, entry);
1309
1310                 clock->entry.type = BCH_JSET_ENTRY_clock;
1311                 clock->rw       = i;
1312                 clock->time     = cpu_to_le64(atomic64_read(&c->io_clock[i].now));
1313         }
1314 }
1315
1316 void bch2_fs_mark_clean(struct bch_fs *c)
1317 {
1318         struct bch_sb_field_clean *sb_clean;
1319         struct jset_entry *entry;
1320         unsigned u64s;
1321         int ret;
1322
1323         mutex_lock(&c->sb_lock);
1324         if (BCH_SB_CLEAN(c->disk_sb.sb))
1325                 goto out;
1326
1327         SET_BCH_SB_CLEAN(c->disk_sb.sb, true);
1328
1329         c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_info);
1330         c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_alloc_metadata);
1331         c->disk_sb.sb->features[0] &= cpu_to_le64(~(1ULL << BCH_FEATURE_extents_above_btree_updates));
1332         c->disk_sb.sb->features[0] &= cpu_to_le64(~(1ULL << BCH_FEATURE_btree_updates_journalled));
1333
1334         u64s = sizeof(*sb_clean) / sizeof(u64) + c->journal.entry_u64s_reserved;
1335
1336         sb_clean = bch2_sb_resize_clean(&c->disk_sb, u64s);
1337         if (!sb_clean) {
1338                 bch_err(c, "error resizing superblock while setting filesystem clean");
1339                 goto out;
1340         }
1341
1342         sb_clean->flags         = 0;
1343         sb_clean->journal_seq   = cpu_to_le64(atomic64_read(&c->journal.seq));
1344
1345         /* Trying to catch outstanding bug: */
1346         BUG_ON(le64_to_cpu(sb_clean->journal_seq) > S64_MAX);
1347
1348         entry = sb_clean->start;
1349         bch2_journal_super_entries_add_common(c, &entry, 0);
1350         entry = bch2_btree_roots_to_journal_entries(c, entry, entry);
1351         BUG_ON((void *) entry > vstruct_end(&sb_clean->field));
1352
1353         memset(entry, 0,
1354                vstruct_end(&sb_clean->field) - (void *) entry);
1355
1356         /*
1357          * this should be in the write path, and we should be validating every
1358          * superblock section:
1359          */
1360         ret = bch2_sb_clean_validate_late(c, sb_clean, WRITE);
1361         if (ret) {
1362                 bch_err(c, "error writing marking filesystem clean: validate error");
1363                 goto out;
1364         }
1365
1366         bch2_write_super(c);
1367 out:
1368         mutex_unlock(&c->sb_lock);
1369 }
1370
1371 static int bch2_sb_clean_validate(struct bch_sb *sb,
1372                                   struct bch_sb_field *f,
1373                                   struct printbuf *err)
1374 {
1375         struct bch_sb_field_clean *clean = field_to_type(f, clean);
1376
1377         if (vstruct_bytes(&clean->field) < sizeof(*clean)) {
1378                 prt_printf(err, "wrong size (got %zu should be %zu)",
1379                        vstruct_bytes(&clean->field), sizeof(*clean));
1380                 return -BCH_ERR_invalid_sb_clean;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static void bch2_sb_clean_to_text(struct printbuf *out, struct bch_sb *sb,
1387                                   struct bch_sb_field *f)
1388 {
1389         struct bch_sb_field_clean *clean = field_to_type(f, clean);
1390         struct jset_entry *entry;
1391
1392         prt_printf(out, "flags:          %x",   le32_to_cpu(clean->flags));
1393         prt_newline(out);
1394         prt_printf(out, "journal_seq:    %llu", le64_to_cpu(clean->journal_seq));
1395         prt_newline(out);
1396
1397         for (entry = clean->start;
1398              entry != vstruct_end(&clean->field);
1399              entry = vstruct_next(entry)) {
1400                 if (entry->type == BCH_JSET_ENTRY_btree_keys &&
1401                     !entry->u64s)
1402                         continue;
1403
1404                 bch2_journal_entry_to_text(out, NULL, entry);
1405                 prt_newline(out);
1406         }
1407 }
1408
1409 static const struct bch_sb_field_ops bch_sb_field_ops_clean = {
1410         .validate       = bch2_sb_clean_validate,
1411         .to_text        = bch2_sb_clean_to_text,
1412 };
1413
1414 static const struct bch_sb_field_ops *bch2_sb_field_ops[] = {
1415 #define x(f, nr)                                        \
1416         [BCH_SB_FIELD_##f] = &bch_sb_field_ops_##f,
1417         BCH_SB_FIELDS()
1418 #undef x
1419 };
1420
1421 static const struct bch_sb_field_ops bch2_sb_field_null_ops = {
1422         NULL
1423 };
1424
1425 static const struct bch_sb_field_ops *bch2_sb_field_type_ops(unsigned type)
1426 {
1427         return likely(type < ARRAY_SIZE(bch2_sb_field_ops))
1428                 ? bch2_sb_field_ops[type]
1429                 : &bch2_sb_field_null_ops;
1430 }
1431
1432 static int bch2_sb_field_validate(struct bch_sb *sb, struct bch_sb_field *f,
1433                                   struct printbuf *err)
1434 {
1435         unsigned type = le32_to_cpu(f->type);
1436         struct printbuf field_err = PRINTBUF;
1437         const struct bch_sb_field_ops *ops = bch2_sb_field_type_ops(type);
1438         int ret;
1439
1440         ret = ops->validate ? ops->validate(sb, f, &field_err) : 0;
1441         if (ret) {
1442                 prt_printf(err, "Invalid superblock section %s: %s",
1443                            bch2_sb_fields[type], field_err.buf);
1444                 prt_newline(err);
1445                 bch2_sb_field_to_text(err, sb, f);
1446         }
1447
1448         printbuf_exit(&field_err);
1449         return ret;
1450 }
1451
1452 void bch2_sb_field_to_text(struct printbuf *out, struct bch_sb *sb,
1453                            struct bch_sb_field *f)
1454 {
1455         unsigned type = le32_to_cpu(f->type);
1456         const struct bch_sb_field_ops *ops = bch2_sb_field_type_ops(type);
1457
1458         if (!out->nr_tabstops)
1459                 printbuf_tabstop_push(out, 32);
1460
1461         if (type < BCH_SB_FIELD_NR)
1462                 prt_printf(out, "%s", bch2_sb_fields[type]);
1463         else
1464                 prt_printf(out, "(unknown field %u)", type);
1465
1466         prt_printf(out, " (size %zu):", vstruct_bytes(f));
1467         prt_newline(out);
1468
1469         if (ops->to_text) {
1470                 printbuf_indent_add(out, 2);
1471                 ops->to_text(out, sb, f);
1472                 printbuf_indent_sub(out, 2);
1473         }
1474 }
1475
1476 void bch2_sb_layout_to_text(struct printbuf *out, struct bch_sb_layout *l)
1477 {
1478         unsigned i;
1479
1480         prt_printf(out, "Type:                    %u", l->layout_type);
1481         prt_newline(out);
1482
1483         prt_str(out, "Superblock max size:     ");
1484         prt_units_u64(out, 512 << l->sb_max_size_bits);
1485         prt_newline(out);
1486
1487         prt_printf(out, "Nr superblocks:          %u", l->nr_superblocks);
1488         prt_newline(out);
1489
1490         prt_str(out, "Offsets:                 ");
1491         for (i = 0; i < l->nr_superblocks; i++) {
1492                 if (i)
1493                         prt_str(out, ", ");
1494                 prt_printf(out, "%llu", le64_to_cpu(l->sb_offset[i]));
1495         }
1496         prt_newline(out);
1497 }
1498
1499 void bch2_sb_to_text(struct printbuf *out, struct bch_sb *sb,
1500                      bool print_layout, unsigned fields)
1501 {
1502         struct bch_sb_field_members *mi;
1503         struct bch_sb_field *f;
1504         u64 fields_have = 0;
1505         unsigned nr_devices = 0;
1506
1507         if (!out->nr_tabstops)
1508                 printbuf_tabstop_push(out, 44);
1509
1510         mi = bch2_sb_get_members(sb);
1511         if (mi) {
1512                 struct bch_member *m;
1513
1514                 for (m = mi->members;
1515                      m < mi->members + sb->nr_devices;
1516                      m++)
1517                         nr_devices += bch2_member_exists(m);
1518         }
1519
1520         prt_printf(out, "External UUID:");
1521         prt_tab(out);
1522         pr_uuid(out, sb->user_uuid.b);
1523         prt_newline(out);
1524
1525         prt_printf(out, "Internal UUID:");
1526         prt_tab(out);
1527         pr_uuid(out, sb->uuid.b);
1528         prt_newline(out);
1529
1530         prt_str(out, "Device index:");
1531         prt_tab(out);
1532         prt_printf(out, "%u", sb->dev_idx);
1533         prt_newline(out);
1534
1535         prt_str(out, "Label:");
1536         prt_tab(out);
1537         prt_printf(out, "%.*s", (int) sizeof(sb->label), sb->label);
1538         prt_newline(out);
1539
1540         prt_str(out, "Version:");
1541         prt_tab(out);
1542         bch2_version_to_text(out, le16_to_cpu(sb->version));
1543         prt_newline(out);
1544
1545         prt_str(out, "Version upgrade complete:");
1546         prt_tab(out);
1547         bch2_version_to_text(out, BCH_SB_VERSION_UPGRADE_COMPLETE(sb));
1548         prt_newline(out);
1549
1550         prt_printf(out, "Oldest version on disk:");
1551         prt_tab(out);
1552         bch2_version_to_text(out, le16_to_cpu(sb->version_min));
1553         prt_newline(out);
1554
1555         prt_printf(out, "Created:");
1556         prt_tab(out);
1557         if (sb->time_base_lo)
1558                 pr_time(out, div_u64(le64_to_cpu(sb->time_base_lo), NSEC_PER_SEC));
1559         else
1560                 prt_printf(out, "(not set)");
1561         prt_newline(out);
1562
1563         prt_printf(out, "Sequence number:");
1564         prt_tab(out);
1565         prt_printf(out, "%llu", le64_to_cpu(sb->seq));
1566         prt_newline(out);
1567
1568         prt_printf(out, "Superblock size:");
1569         prt_tab(out);
1570         prt_printf(out, "%zu", vstruct_bytes(sb));
1571         prt_newline(out);
1572
1573         prt_printf(out, "Clean:");
1574         prt_tab(out);
1575         prt_printf(out, "%llu", BCH_SB_CLEAN(sb));
1576         prt_newline(out);
1577
1578         prt_printf(out, "Devices:");
1579         prt_tab(out);
1580         prt_printf(out, "%u", nr_devices);
1581         prt_newline(out);
1582
1583         prt_printf(out, "Sections:");
1584         vstruct_for_each(sb, f)
1585                 fields_have |= 1 << le32_to_cpu(f->type);
1586         prt_tab(out);
1587         prt_bitflags(out, bch2_sb_fields, fields_have);
1588         prt_newline(out);
1589
1590         prt_printf(out, "Features:");
1591         prt_tab(out);
1592         prt_bitflags(out, bch2_sb_features, le64_to_cpu(sb->features[0]));
1593         prt_newline(out);
1594
1595         prt_printf(out, "Compat features:");
1596         prt_tab(out);
1597         prt_bitflags(out, bch2_sb_compat, le64_to_cpu(sb->compat[0]));
1598         prt_newline(out);
1599
1600         prt_newline(out);
1601         prt_printf(out, "Options:");
1602         prt_newline(out);
1603         printbuf_indent_add(out, 2);
1604         {
1605                 enum bch_opt_id id;
1606
1607                 for (id = 0; id < bch2_opts_nr; id++) {
1608                         const struct bch_option *opt = bch2_opt_table + id;
1609
1610                         if (opt->get_sb != BCH2_NO_SB_OPT) {
1611                                 u64 v = bch2_opt_from_sb(sb, id);
1612
1613                                 prt_printf(out, "%s:", opt->attr.name);
1614                                 prt_tab(out);
1615                                 bch2_opt_to_text(out, NULL, sb, opt, v,
1616                                                  OPT_HUMAN_READABLE|OPT_SHOW_FULL_LIST);
1617                                 prt_newline(out);
1618                         }
1619                 }
1620         }
1621
1622         printbuf_indent_sub(out, 2);
1623
1624         if (print_layout) {
1625                 prt_newline(out);
1626                 prt_printf(out, "layout:");
1627                 prt_newline(out);
1628                 printbuf_indent_add(out, 2);
1629                 bch2_sb_layout_to_text(out, &sb->layout);
1630                 printbuf_indent_sub(out, 2);
1631         }
1632
1633         vstruct_for_each(sb, f)
1634                 if (fields & (1 << le32_to_cpu(f->type))) {
1635                         prt_newline(out);
1636                         bch2_sb_field_to_text(out, sb, f);
1637                 }
1638 }