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