]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/journal_io.c
Update bcachefs sources to 18686af684 bcachefs: Inode backpointers
[bcachefs-tools-debian] / libbcachefs / journal_io.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "bcachefs.h"
3 #include "alloc_foreground.h"
4 #include "btree_io.h"
5 #include "btree_update_interior.h"
6 #include "buckets.h"
7 #include "checksum.h"
8 #include "disk_groups.h"
9 #include "error.h"
10 #include "io.h"
11 #include "journal.h"
12 #include "journal_io.h"
13 #include "journal_reclaim.h"
14 #include "journal_seq_blacklist.h"
15 #include "replicas.h"
16
17 #include <trace/events/bcachefs.h>
18
19 static void __journal_replay_free(struct journal_replay *i)
20 {
21         list_del(&i->list);
22         kvpfree(i, offsetof(struct journal_replay, j) +
23                 vstruct_bytes(&i->j));
24
25 }
26
27 static void journal_replay_free(struct bch_fs *c, struct journal_replay *i)
28 {
29         i->ignore = true;
30
31         if (!c->opts.read_entire_journal)
32                 __journal_replay_free(i);
33 }
34
35 struct journal_list {
36         struct closure          cl;
37         struct mutex            lock;
38         struct list_head        *head;
39         int                     ret;
40 };
41
42 #define JOURNAL_ENTRY_ADD_OK            0
43 #define JOURNAL_ENTRY_ADD_OUT_OF_RANGE  5
44
45 /*
46  * Given a journal entry we just read, add it to the list of journal entries to
47  * be replayed:
48  */
49 static int journal_entry_add(struct bch_fs *c, struct bch_dev *ca,
50                              struct bch_extent_ptr entry_ptr,
51                              struct journal_list *jlist, struct jset *j,
52                              bool bad)
53 {
54         struct journal_replay *i, *pos, *dup = NULL;
55         struct bch_extent_ptr *ptr;
56         struct list_head *where;
57         size_t bytes = vstruct_bytes(j);
58         u64 last_seq = 0;
59         int ret = JOURNAL_ENTRY_ADD_OK;
60
61         list_for_each_entry_reverse(i, jlist->head, list) {
62                 if (!JSET_NO_FLUSH(&i->j)) {
63                         last_seq = le64_to_cpu(i->j.last_seq);
64                         break;
65                 }
66         }
67
68         /* Is this entry older than the range we need? */
69         if (!c->opts.read_entire_journal &&
70             le64_to_cpu(j->seq) < last_seq) {
71                 ret = JOURNAL_ENTRY_ADD_OUT_OF_RANGE;
72                 goto out;
73         }
74
75         /* Drop entries we don't need anymore */
76         if (!JSET_NO_FLUSH(j)) {
77                 list_for_each_entry_safe(i, pos, jlist->head, list) {
78                         if (le64_to_cpu(i->j.seq) >= le64_to_cpu(j->last_seq))
79                                 break;
80                         journal_replay_free(c, i);
81                 }
82         }
83
84         list_for_each_entry_reverse(i, jlist->head, list) {
85                 if (le64_to_cpu(j->seq) > le64_to_cpu(i->j.seq)) {
86                         where = &i->list;
87                         goto add;
88                 }
89         }
90
91         where = jlist->head;
92 add:
93         dup = where->next != jlist->head
94                 ? container_of(where->next, struct journal_replay, list)
95                 : NULL;
96
97         if (dup && le64_to_cpu(j->seq) != le64_to_cpu(dup->j.seq))
98                 dup = NULL;
99
100         /*
101          * Duplicate journal entries? If so we want the one that didn't have a
102          * checksum error:
103          */
104         if (dup) {
105                 if (dup->bad) {
106                         /* we'll replace @dup: */
107                 } else if (bad) {
108                         i = dup;
109                         goto found;
110                 } else {
111                         fsck_err_on(bytes != vstruct_bytes(&dup->j) ||
112                                     memcmp(j, &dup->j, bytes), c,
113                                     "found duplicate but non identical journal entries (seq %llu)",
114                                     le64_to_cpu(j->seq));
115                         i = dup;
116                         goto found;
117                 }
118         }
119
120         i = kvpmalloc(offsetof(struct journal_replay, j) + bytes, GFP_KERNEL);
121         if (!i) {
122                 ret = -ENOMEM;
123                 goto out;
124         }
125
126         i->nr_ptrs       = 0;
127         i->bad          = bad;
128         i->ignore       = false;
129         memcpy(&i->j, j, bytes);
130
131         if (dup) {
132                 i->nr_ptrs = dup->nr_ptrs;
133                 memcpy(i->ptrs, dup->ptrs, sizeof(dup->ptrs));
134                 __journal_replay_free(dup);
135         }
136
137         list_add(&i->list, where);
138 found:
139         for (ptr = i->ptrs; ptr < i->ptrs + i->nr_ptrs; ptr++) {
140                 if (ptr->dev == ca->dev_idx) {
141                         bch_err(c, "duplicate journal entry %llu on same device",
142                                 le64_to_cpu(i->j.seq));
143                         goto out;
144                 }
145         }
146
147         if (i->nr_ptrs >= ARRAY_SIZE(i->ptrs)) {
148                 bch_err(c, "found too many copies of journal entry %llu",
149                         le64_to_cpu(i->j.seq));
150                 goto out;
151         }
152
153         i->ptrs[i->nr_ptrs++] = entry_ptr;
154 out:
155 fsck_err:
156         return ret;
157 }
158
159 static struct nonce journal_nonce(const struct jset *jset)
160 {
161         return (struct nonce) {{
162                 [0] = 0,
163                 [1] = ((__le32 *) &jset->seq)[0],
164                 [2] = ((__le32 *) &jset->seq)[1],
165                 [3] = BCH_NONCE_JOURNAL,
166         }};
167 }
168
169 /* this fills in a range with empty jset_entries: */
170 static void journal_entry_null_range(void *start, void *end)
171 {
172         struct jset_entry *entry;
173
174         for (entry = start; entry != end; entry = vstruct_next(entry))
175                 memset(entry, 0, sizeof(*entry));
176 }
177
178 #define JOURNAL_ENTRY_REREAD    5
179 #define JOURNAL_ENTRY_NONE      6
180 #define JOURNAL_ENTRY_BAD       7
181
182 #define journal_entry_err(c, msg, ...)                                  \
183 ({                                                                      \
184         switch (write) {                                                \
185         case READ:                                                      \
186                 mustfix_fsck_err(c, msg, ##__VA_ARGS__);                \
187                 break;                                                  \
188         case WRITE:                                                     \
189                 bch_err(c, "corrupt metadata before write:\n"           \
190                         msg, ##__VA_ARGS__);                            \
191                 if (bch2_fs_inconsistent(c)) {                          \
192                         ret = BCH_FSCK_ERRORS_NOT_FIXED;                \
193                         goto fsck_err;                                  \
194                 }                                                       \
195                 break;                                                  \
196         }                                                               \
197         true;                                                           \
198 })
199
200 #define journal_entry_err_on(cond, c, msg, ...)                         \
201         ((cond) ? journal_entry_err(c, msg, ##__VA_ARGS__) : false)
202
203 #define FSCK_DELETED_KEY        5
204
205 static int journal_validate_key(struct bch_fs *c, const char *where,
206                                 struct jset_entry *entry,
207                                 unsigned level, enum btree_id btree_id,
208                                 struct bkey_i *k, const char *type,
209                                 unsigned version, int big_endian, int write)
210 {
211         void *next = vstruct_next(entry);
212         const char *invalid;
213         int ret = 0;
214
215         if (journal_entry_err_on(!k->k.u64s, c,
216                         "invalid %s in %s entry offset %zi/%u: k->u64s 0",
217                         type, where,
218                         (u64 *) k - entry->_data,
219                         le16_to_cpu(entry->u64s))) {
220                 entry->u64s = cpu_to_le16((u64 *) k - entry->_data);
221                 journal_entry_null_range(vstruct_next(entry), next);
222                 return FSCK_DELETED_KEY;
223         }
224
225         if (journal_entry_err_on((void *) bkey_next(k) >
226                                 (void *) vstruct_next(entry), c,
227                         "invalid %s in %s entry offset %zi/%u: extends past end of journal entry",
228                         type, where,
229                         (u64 *) k - entry->_data,
230                         le16_to_cpu(entry->u64s))) {
231                 entry->u64s = cpu_to_le16((u64 *) k - entry->_data);
232                 journal_entry_null_range(vstruct_next(entry), next);
233                 return FSCK_DELETED_KEY;
234         }
235
236         if (journal_entry_err_on(k->k.format != KEY_FORMAT_CURRENT, c,
237                         "invalid %s in %s entry offset %zi/%u: bad format %u",
238                         type, where,
239                         (u64 *) k - entry->_data,
240                         le16_to_cpu(entry->u64s),
241                         k->k.format)) {
242                 le16_add_cpu(&entry->u64s, -((u16) k->k.u64s));
243                 memmove(k, bkey_next(k), next - (void *) bkey_next(k));
244                 journal_entry_null_range(vstruct_next(entry), next);
245                 return FSCK_DELETED_KEY;
246         }
247
248         if (!write)
249                 bch2_bkey_compat(level, btree_id, version, big_endian,
250                                  write, NULL, bkey_to_packed(k));
251
252         invalid = bch2_bkey_invalid(c, bkey_i_to_s_c(k),
253                                     __btree_node_type(level, btree_id));
254         if (invalid) {
255                 char buf[160];
256
257                 bch2_bkey_val_to_text(&PBUF(buf), c, bkey_i_to_s_c(k));
258                 mustfix_fsck_err(c, "invalid %s in %s entry offset %zi/%u: %s\n%s",
259                                  type, where,
260                                  (u64 *) k - entry->_data,
261                                  le16_to_cpu(entry->u64s),
262                                  invalid, buf);
263
264                 le16_add_cpu(&entry->u64s, -((u16) k->k.u64s));
265                 memmove(k, bkey_next(k), next - (void *) bkey_next(k));
266                 journal_entry_null_range(vstruct_next(entry), next);
267                 return FSCK_DELETED_KEY;
268         }
269
270         if (write)
271                 bch2_bkey_compat(level, btree_id, version, big_endian,
272                                  write, NULL, bkey_to_packed(k));
273 fsck_err:
274         return ret;
275 }
276
277 static int journal_entry_validate_btree_keys(struct bch_fs *c,
278                                              const char *where,
279                                              struct jset_entry *entry,
280                                              unsigned version, int big_endian, int write)
281 {
282         struct bkey_i *k = entry->start;
283
284         while (k != vstruct_last(entry)) {
285                 int ret = journal_validate_key(c, where, entry,
286                                                entry->level,
287                                                entry->btree_id,
288                                                k, "key", version, big_endian, write);
289                 if (ret == FSCK_DELETED_KEY)
290                         continue;
291
292                 k = bkey_next(k);
293         }
294
295         return 0;
296 }
297
298 static int journal_entry_validate_btree_root(struct bch_fs *c,
299                                              const char *where,
300                                              struct jset_entry *entry,
301                                              unsigned version, int big_endian, int write)
302 {
303         struct bkey_i *k = entry->start;
304         int ret = 0;
305
306         if (journal_entry_err_on(!entry->u64s ||
307                                  le16_to_cpu(entry->u64s) != k->k.u64s, c,
308                                  "invalid btree root journal entry: wrong number of keys")) {
309                 void *next = vstruct_next(entry);
310                 /*
311                  * we don't want to null out this jset_entry,
312                  * just the contents, so that later we can tell
313                  * we were _supposed_ to have a btree root
314                  */
315                 entry->u64s = 0;
316                 journal_entry_null_range(vstruct_next(entry), next);
317                 return 0;
318         }
319
320         return journal_validate_key(c, where, entry, 1, entry->btree_id, k,
321                                     "btree root", version, big_endian, write);
322 fsck_err:
323         return ret;
324 }
325
326 static int journal_entry_validate_prio_ptrs(struct bch_fs *c,
327                                             const char *where,
328                                             struct jset_entry *entry,
329                                             unsigned version, int big_endian, int write)
330 {
331         /* obsolete, don't care: */
332         return 0;
333 }
334
335 static int journal_entry_validate_blacklist(struct bch_fs *c,
336                                             const char *where,
337                                             struct jset_entry *entry,
338                                             unsigned version, int big_endian, int write)
339 {
340         int ret = 0;
341
342         if (journal_entry_err_on(le16_to_cpu(entry->u64s) != 1, c,
343                 "invalid journal seq blacklist entry: bad size")) {
344                 journal_entry_null_range(entry, vstruct_next(entry));
345         }
346 fsck_err:
347         return ret;
348 }
349
350 static int journal_entry_validate_blacklist_v2(struct bch_fs *c,
351                                                const char *where,
352                                                struct jset_entry *entry,
353                                                unsigned version, int big_endian, int write)
354 {
355         struct jset_entry_blacklist_v2 *bl_entry;
356         int ret = 0;
357
358         if (journal_entry_err_on(le16_to_cpu(entry->u64s) != 2, c,
359                 "invalid journal seq blacklist entry: bad size")) {
360                 journal_entry_null_range(entry, vstruct_next(entry));
361                 goto out;
362         }
363
364         bl_entry = container_of(entry, struct jset_entry_blacklist_v2, entry);
365
366         if (journal_entry_err_on(le64_to_cpu(bl_entry->start) >
367                                  le64_to_cpu(bl_entry->end), c,
368                 "invalid journal seq blacklist entry: start > end")) {
369                 journal_entry_null_range(entry, vstruct_next(entry));
370         }
371 out:
372 fsck_err:
373         return ret;
374 }
375
376 static int journal_entry_validate_usage(struct bch_fs *c,
377                                         const char *where,
378                                         struct jset_entry *entry,
379                                         unsigned version, int big_endian, int write)
380 {
381         struct jset_entry_usage *u =
382                 container_of(entry, struct jset_entry_usage, entry);
383         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
384         int ret = 0;
385
386         if (journal_entry_err_on(bytes < sizeof(*u),
387                                  c,
388                                  "invalid journal entry usage: bad size")) {
389                 journal_entry_null_range(entry, vstruct_next(entry));
390                 return ret;
391         }
392
393 fsck_err:
394         return ret;
395 }
396
397 static int journal_entry_validate_data_usage(struct bch_fs *c,
398                                         const char *where,
399                                         struct jset_entry *entry,
400                                         unsigned version, int big_endian, int write)
401 {
402         struct jset_entry_data_usage *u =
403                 container_of(entry, struct jset_entry_data_usage, entry);
404         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
405         int ret = 0;
406
407         if (journal_entry_err_on(bytes < sizeof(*u) ||
408                                  bytes < sizeof(*u) + u->r.nr_devs,
409                                  c,
410                                  "invalid journal entry usage: bad size")) {
411                 journal_entry_null_range(entry, vstruct_next(entry));
412                 return ret;
413         }
414
415 fsck_err:
416         return ret;
417 }
418
419 static int journal_entry_validate_clock(struct bch_fs *c,
420                                         const char *where,
421                                         struct jset_entry *entry,
422                                         unsigned version, int big_endian, int write)
423 {
424         struct jset_entry_clock *clock =
425                 container_of(entry, struct jset_entry_clock, entry);
426         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
427         int ret = 0;
428
429         if (journal_entry_err_on(bytes != sizeof(*clock),
430                                  c, "invalid journal entry clock: bad size")) {
431                 journal_entry_null_range(entry, vstruct_next(entry));
432                 return ret;
433         }
434
435         if (journal_entry_err_on(clock->rw > 1,
436                                  c, "invalid journal entry clock: bad rw")) {
437                 journal_entry_null_range(entry, vstruct_next(entry));
438                 return ret;
439         }
440
441 fsck_err:
442         return ret;
443 }
444
445 static int journal_entry_validate_dev_usage(struct bch_fs *c,
446                                             const char *where,
447                                             struct jset_entry *entry,
448                                             unsigned version, int big_endian, int write)
449 {
450         struct jset_entry_dev_usage *u =
451                 container_of(entry, struct jset_entry_dev_usage, entry);
452         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
453         unsigned expected = sizeof(*u) + sizeof(u->d[0]) * 7; /* Current value of BCH_DATA_NR */
454         unsigned dev;
455         int ret = 0;
456
457         if (journal_entry_err_on(bytes < expected,
458                                  c, "invalid journal entry dev usage: bad size (%u < %u)",
459                                  bytes, expected)) {
460                 journal_entry_null_range(entry, vstruct_next(entry));
461                 return ret;
462         }
463
464         dev = le32_to_cpu(u->dev);
465
466         if (journal_entry_err_on(!bch2_dev_exists2(c, dev),
467                                  c, "invalid journal entry dev usage: bad dev")) {
468                 journal_entry_null_range(entry, vstruct_next(entry));
469                 return ret;
470         }
471
472         if (journal_entry_err_on(u->pad,
473                                  c, "invalid journal entry dev usage: bad pad")) {
474                 journal_entry_null_range(entry, vstruct_next(entry));
475                 return ret;
476         }
477
478 fsck_err:
479         return ret;
480 }
481
482 struct jset_entry_ops {
483         int (*validate)(struct bch_fs *, const char *,
484                         struct jset_entry *, unsigned, int, int);
485 };
486
487 static const struct jset_entry_ops bch2_jset_entry_ops[] = {
488 #define x(f, nr)                                                \
489         [BCH_JSET_ENTRY_##f]    = (struct jset_entry_ops) {     \
490                 .validate       = journal_entry_validate_##f,   \
491         },
492         BCH_JSET_ENTRY_TYPES()
493 #undef x
494 };
495
496 int bch2_journal_entry_validate(struct bch_fs *c, const char *where,
497                                 struct jset_entry *entry,
498                                 unsigned version, int big_endian, int write)
499 {
500         return entry->type < BCH_JSET_ENTRY_NR
501                 ? bch2_jset_entry_ops[entry->type].validate(c, where, entry,
502                                 version, big_endian, write)
503                 : 0;
504 }
505
506 static int jset_validate_entries(struct bch_fs *c, struct jset *jset,
507                                  int write)
508 {
509         char buf[100];
510         struct jset_entry *entry;
511         int ret = 0;
512
513         vstruct_for_each(jset, entry) {
514                 scnprintf(buf, sizeof(buf), "jset %llu entry offset %zi/%u",
515                           le64_to_cpu(jset->seq),
516                           (u64 *) entry - jset->_data,
517                           le32_to_cpu(jset->u64s));
518
519                 if (journal_entry_err_on(vstruct_next(entry) >
520                                          vstruct_last(jset), c,
521                                 "journal entry extends past end of jset")) {
522                         jset->u64s = cpu_to_le32((u64 *) entry - jset->_data);
523                         break;
524                 }
525
526                 ret = bch2_journal_entry_validate(c, buf, entry,
527                                         le32_to_cpu(jset->version),
528                                         JSET_BIG_ENDIAN(jset), write);
529                 if (ret)
530                         break;
531         }
532 fsck_err:
533         return ret;
534 }
535
536 static int jset_validate(struct bch_fs *c,
537                          struct bch_dev *ca,
538                          struct jset *jset, u64 sector,
539                          unsigned bucket_sectors_left,
540                          unsigned sectors_read,
541                          int write)
542 {
543         size_t bytes = vstruct_bytes(jset);
544         struct bch_csum csum;
545         unsigned version;
546         int ret = 0;
547
548         if (le64_to_cpu(jset->magic) != jset_magic(c))
549                 return JOURNAL_ENTRY_NONE;
550
551         version = le32_to_cpu(jset->version);
552         if (journal_entry_err_on((version != BCH_JSET_VERSION_OLD &&
553                                   version < bcachefs_metadata_version_min) ||
554                                  version >= bcachefs_metadata_version_max, c,
555                         "%s sector %llu seq %llu: unknown journal entry version %u",
556                         ca ? ca->name : c->name,
557                         sector, le64_to_cpu(jset->seq),
558                         version)) {
559                 /* don't try to continue: */
560                 return EINVAL;
561         }
562
563         if (bytes > (sectors_read << 9) &&
564             sectors_read < bucket_sectors_left)
565                 return JOURNAL_ENTRY_REREAD;
566
567         if (journal_entry_err_on(bytes > bucket_sectors_left << 9, c,
568                         "%s sector %llu seq %llu: journal entry too big (%zu bytes)",
569                         ca ? ca->name : c->name,
570                         sector, le64_to_cpu(jset->seq), bytes)) {
571                 ret = JOURNAL_ENTRY_BAD;
572                 le32_add_cpu(&jset->u64s,
573                              -((bytes - (bucket_sectors_left << 9)) / 8));
574         }
575
576         if (journal_entry_err_on(!bch2_checksum_type_valid(c, JSET_CSUM_TYPE(jset)), c,
577                         "%s sector %llu seq %llu: journal entry with unknown csum type %llu",
578                         ca ? ca->name : c->name,
579                         sector, le64_to_cpu(jset->seq),
580                         JSET_CSUM_TYPE(jset))) {
581                 ret = JOURNAL_ENTRY_BAD;
582                 goto csum_done;
583         }
584
585         if (write)
586                 goto csum_done;
587
588         csum = csum_vstruct(c, JSET_CSUM_TYPE(jset), journal_nonce(jset), jset);
589         if (journal_entry_err_on(bch2_crc_cmp(csum, jset->csum), c,
590                                  "%s sector %llu seq %llu: journal checksum bad",
591                                  ca ? ca->name : c->name,
592                                  sector, le64_to_cpu(jset->seq)))
593                 ret = JOURNAL_ENTRY_BAD;
594
595         bch2_encrypt(c, JSET_CSUM_TYPE(jset), journal_nonce(jset),
596                      jset->encrypted_start,
597                      vstruct_end(jset) - (void *) jset->encrypted_start);
598 csum_done:
599         /* last_seq is ignored when JSET_NO_FLUSH is true */
600         if (journal_entry_err_on(!JSET_NO_FLUSH(jset) &&
601                                  le64_to_cpu(jset->last_seq) > le64_to_cpu(jset->seq), c,
602                                  "invalid journal entry: last_seq > seq (%llu > %llu)",
603                                  le64_to_cpu(jset->last_seq),
604                                  le64_to_cpu(jset->seq))) {
605                 jset->last_seq = jset->seq;
606                 return JOURNAL_ENTRY_BAD;
607         }
608 fsck_err:
609         return ret;
610 }
611
612 static int jset_validate_for_write(struct bch_fs *c, struct jset *jset)
613 {
614         unsigned sectors = vstruct_sectors(jset, c->block_bits);
615
616         return jset_validate(c, NULL, jset, 0, sectors, sectors, WRITE) ?:
617                 jset_validate_entries(c, jset, WRITE);
618 }
619
620 struct journal_read_buf {
621         void            *data;
622         size_t          size;
623 };
624
625 static int journal_read_buf_realloc(struct journal_read_buf *b,
626                                     size_t new_size)
627 {
628         void *n;
629
630         /* the bios are sized for this many pages, max: */
631         if (new_size > JOURNAL_ENTRY_SIZE_MAX)
632                 return -ENOMEM;
633
634         new_size = roundup_pow_of_two(new_size);
635         n = kvpmalloc(new_size, GFP_KERNEL);
636         if (!n)
637                 return -ENOMEM;
638
639         kvpfree(b->data, b->size);
640         b->data = n;
641         b->size = new_size;
642         return 0;
643 }
644
645 static int journal_read_bucket(struct bch_dev *ca,
646                                struct journal_read_buf *buf,
647                                struct journal_list *jlist,
648                                unsigned bucket)
649 {
650         struct bch_fs *c = ca->fs;
651         struct journal_device *ja = &ca->journal;
652         struct jset *j = NULL;
653         unsigned sectors, sectors_read = 0;
654         u64 offset = bucket_to_sector(ca, ja->buckets[bucket]),
655             end = offset + ca->mi.bucket_size;
656         bool saw_bad = false;
657         int ret = 0;
658
659         pr_debug("reading %u", bucket);
660
661         while (offset < end) {
662                 if (!sectors_read) {
663                         struct bio *bio;
664 reread:
665                         sectors_read = min_t(unsigned,
666                                 end - offset, buf->size >> 9);
667
668                         bio = bio_kmalloc(GFP_KERNEL,
669                                           buf_pages(buf->data,
670                                                     sectors_read << 9));
671                         bio_set_dev(bio, ca->disk_sb.bdev);
672                         bio->bi_iter.bi_sector  = offset;
673                         bio_set_op_attrs(bio, REQ_OP_READ, 0);
674                         bch2_bio_map(bio, buf->data, sectors_read << 9);
675
676                         ret = submit_bio_wait(bio);
677                         bio_put(bio);
678
679                         if (bch2_dev_io_err_on(ret, ca,
680                                                "journal read error: sector %llu",
681                                                offset) ||
682                             bch2_meta_read_fault("journal")) {
683                                 /*
684                                  * We don't error out of the recovery process
685                                  * here, since the relevant journal entry may be
686                                  * found on a different device, and missing or
687                                  * no journal entries will be handled later
688                                  */
689                                 return 0;
690                         }
691
692                         j = buf->data;
693                 }
694
695                 ret = jset_validate(c, ca, j, offset,
696                                     end - offset, sectors_read,
697                                     READ);
698                 switch (ret) {
699                 case BCH_FSCK_OK:
700                         sectors = vstruct_sectors(j, c->block_bits);
701                         break;
702                 case JOURNAL_ENTRY_REREAD:
703                         if (vstruct_bytes(j) > buf->size) {
704                                 ret = journal_read_buf_realloc(buf,
705                                                         vstruct_bytes(j));
706                                 if (ret)
707                                         return ret;
708                         }
709                         goto reread;
710                 case JOURNAL_ENTRY_NONE:
711                         if (!saw_bad)
712                                 return 0;
713                         sectors = c->opts.block_size;
714                         goto next_block;
715                 case JOURNAL_ENTRY_BAD:
716                         saw_bad = true;
717                         /*
718                          * On checksum error we don't really trust the size
719                          * field of the journal entry we read, so try reading
720                          * again at next block boundary:
721                          */
722                         sectors = c->opts.block_size;
723                         break;
724                 default:
725                         return ret;
726                 }
727
728                 /*
729                  * This happens sometimes if we don't have discards on -
730                  * when we've partially overwritten a bucket with new
731                  * journal entries. We don't need the rest of the
732                  * bucket:
733                  */
734                 if (le64_to_cpu(j->seq) < ja->bucket_seq[bucket])
735                         return 0;
736
737                 ja->bucket_seq[bucket] = le64_to_cpu(j->seq);
738
739                 mutex_lock(&jlist->lock);
740                 ret = journal_entry_add(c, ca, (struct bch_extent_ptr) {
741                                         .dev = ca->dev_idx,
742                                         .offset = offset,
743                                         }, jlist, j, ret != 0);
744                 mutex_unlock(&jlist->lock);
745
746                 switch (ret) {
747                 case JOURNAL_ENTRY_ADD_OK:
748                         break;
749                 case JOURNAL_ENTRY_ADD_OUT_OF_RANGE:
750                         break;
751                 default:
752                         return ret;
753                 }
754 next_block:
755                 pr_debug("next");
756                 offset          += sectors;
757                 sectors_read    -= sectors;
758                 j = ((void *) j) + (sectors << 9);
759         }
760
761         return 0;
762 }
763
764 static void bch2_journal_read_device(struct closure *cl)
765 {
766         struct journal_device *ja =
767                 container_of(cl, struct journal_device, read);
768         struct bch_dev *ca = container_of(ja, struct bch_dev, journal);
769         struct journal_list *jlist =
770                 container_of(cl->parent, struct journal_list, cl);
771         struct journal_read_buf buf = { NULL, 0 };
772         u64 min_seq = U64_MAX;
773         unsigned i;
774         int ret;
775
776         if (!ja->nr)
777                 goto out;
778
779         ret = journal_read_buf_realloc(&buf, PAGE_SIZE);
780         if (ret)
781                 goto err;
782
783         pr_debug("%u journal buckets", ja->nr);
784
785         for (i = 0; i < ja->nr; i++) {
786                 ret = journal_read_bucket(ca, &buf, jlist, i);
787                 if (ret)
788                         goto err;
789         }
790
791         /* Find the journal bucket with the highest sequence number: */
792         for (i = 0; i < ja->nr; i++) {
793                 if (ja->bucket_seq[i] > ja->bucket_seq[ja->cur_idx])
794                         ja->cur_idx = i;
795
796                 min_seq = min(ja->bucket_seq[i], min_seq);
797         }
798
799         /*
800          * If there's duplicate journal entries in multiple buckets (which
801          * definitely isn't supposed to happen, but...) - make sure to start
802          * cur_idx at the last of those buckets, so we don't deadlock trying to
803          * allocate
804          */
805         while (ja->bucket_seq[ja->cur_idx] > min_seq &&
806                ja->bucket_seq[ja->cur_idx] >
807                ja->bucket_seq[(ja->cur_idx + 1) % ja->nr])
808                 ja->cur_idx = (ja->cur_idx + 1) % ja->nr;
809
810         ja->sectors_free = 0;
811
812         /*
813          * Set dirty_idx to indicate the entire journal is full and needs to be
814          * reclaimed - journal reclaim will immediately reclaim whatever isn't
815          * pinned when it first runs:
816          */
817         ja->discard_idx = ja->dirty_idx_ondisk =
818                 ja->dirty_idx = (ja->cur_idx + 1) % ja->nr;
819 out:
820         kvpfree(buf.data, buf.size);
821         percpu_ref_put(&ca->io_ref);
822         closure_return(cl);
823         return;
824 err:
825         mutex_lock(&jlist->lock);
826         jlist->ret = ret;
827         mutex_unlock(&jlist->lock);
828         goto out;
829 }
830
831 static void bch2_journal_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
832                                       struct journal_replay *j)
833 {
834         unsigned i;
835
836         for (i = 0; i < j->nr_ptrs; i++) {
837                 struct bch_dev *ca = c->devs[j->ptrs[i].dev];
838                 u64 offset;
839
840                 div64_u64_rem(j->ptrs[i].offset, ca->mi.bucket_size, &offset);
841
842                 if (i)
843                         pr_buf(out, " ");
844                 pr_buf(out, "%u:%llu (offset %llu)",
845                        j->ptrs[i].dev,
846                        (u64) j->ptrs[i].offset, offset);
847         }
848 }
849
850 int bch2_journal_read(struct bch_fs *c, struct list_head *list,
851                       u64 *blacklist_seq, u64 *start_seq)
852 {
853         struct journal_list jlist;
854         struct journal_replay *i, *t;
855         struct bch_dev *ca;
856         unsigned iter;
857         size_t keys = 0, entries = 0;
858         bool degraded = false;
859         u64 seq, last_seq = 0;
860         int ret = 0;
861
862         closure_init_stack(&jlist.cl);
863         mutex_init(&jlist.lock);
864         jlist.head = list;
865         jlist.ret = 0;
866
867         for_each_member_device(ca, c, iter) {
868                 if (!test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) &&
869                     !(bch2_dev_has_data(c, ca) & (1 << BCH_DATA_journal)))
870                         continue;
871
872                 if ((ca->mi.state == BCH_MEMBER_STATE_rw ||
873                      ca->mi.state == BCH_MEMBER_STATE_ro) &&
874                     percpu_ref_tryget(&ca->io_ref))
875                         closure_call(&ca->journal.read,
876                                      bch2_journal_read_device,
877                                      system_unbound_wq,
878                                      &jlist.cl);
879                 else
880                         degraded = true;
881         }
882
883         closure_sync(&jlist.cl);
884
885         if (jlist.ret)
886                 return jlist.ret;
887
888         if (list_empty(list)) {
889                 bch_info(c, "journal read done, but no entries found");
890                 return 0;
891         }
892
893         i = list_last_entry(list, struct journal_replay, list);
894         *start_seq = le64_to_cpu(i->j.seq) + 1;
895
896         /*
897          * Find most recent flush entry, and ignore newer non flush entries -
898          * those entries will be blacklisted:
899          */
900         list_for_each_entry_safe_reverse(i, t, list, list) {
901                 if (i->ignore)
902                         continue;
903
904                 if (!JSET_NO_FLUSH(&i->j)) {
905                         last_seq        = le64_to_cpu(i->j.last_seq);
906                         *blacklist_seq  = le64_to_cpu(i->j.seq) + 1;
907                         break;
908                 }
909
910                 journal_replay_free(c, i);
911         }
912
913         if (!last_seq) {
914                 fsck_err(c, "journal read done, but no entries found after dropping non-flushes");
915                 return -1;
916         }
917
918         /* Drop blacklisted entries and entries older than last_seq: */
919         list_for_each_entry_safe(i, t, list, list) {
920                 if (i->ignore)
921                         continue;
922
923                 seq = le64_to_cpu(i->j.seq);
924                 if (seq < last_seq) {
925                         journal_replay_free(c, i);
926                         continue;
927                 }
928
929                 if (bch2_journal_seq_is_blacklisted(c, seq, true)) {
930                         fsck_err_on(!JSET_NO_FLUSH(&i->j), c,
931                                     "found blacklisted journal entry %llu", seq);
932
933                         journal_replay_free(c, i);
934                 }
935         }
936
937         /* Check for missing entries: */
938         seq = last_seq;
939         list_for_each_entry(i, list, list) {
940                 if (i->ignore)
941                         continue;
942
943                 BUG_ON(seq > le64_to_cpu(i->j.seq));
944
945                 while (seq < le64_to_cpu(i->j.seq)) {
946                         u64 missing_start, missing_end;
947                         char buf1[200], buf2[200];
948
949                         while (seq < le64_to_cpu(i->j.seq) &&
950                                bch2_journal_seq_is_blacklisted(c, seq, false))
951                                 seq++;
952
953                         if (seq == le64_to_cpu(i->j.seq))
954                                 break;
955
956                         missing_start = seq;
957
958                         while (seq < le64_to_cpu(i->j.seq) &&
959                                !bch2_journal_seq_is_blacklisted(c, seq, false))
960                                 seq++;
961
962                         if (i->list.prev != list) {
963                                 struct printbuf out = PBUF(buf1);
964                                 struct journal_replay *p = list_prev_entry(i, list);
965
966                                 bch2_journal_ptrs_to_text(&out, c, p);
967                                 pr_buf(&out, " size %llu", vstruct_sectors(&p->j, c->block_bits));
968                         } else
969                                 sprintf(buf1, "(none)");
970                         bch2_journal_ptrs_to_text(&PBUF(buf2), c, i);
971
972                         missing_end = seq - 1;
973                         fsck_err(c, "journal entries %llu-%llu missing! (replaying %llu-%llu)\n"
974                                  "  prev at %s\n"
975                                  "  next at %s",
976                                  missing_start, missing_end,
977                                  last_seq, *blacklist_seq - 1,
978                                  buf1, buf2);
979                 }
980
981                 seq++;
982         }
983
984         list_for_each_entry(i, list, list) {
985                 struct jset_entry *entry;
986                 struct bkey_i *k, *_n;
987                 struct bch_replicas_padded replicas = {
988                         .e.data_type = BCH_DATA_journal,
989                         .e.nr_required = 1,
990                 };
991                 unsigned ptr;
992                 char buf[80];
993
994                 if (i->ignore)
995                         continue;
996
997                 ret = jset_validate_entries(c, &i->j, READ);
998                 if (ret)
999                         goto fsck_err;
1000
1001                 for (ptr = 0; ptr < i->nr_ptrs; ptr++)
1002                         replicas.e.devs[replicas.e.nr_devs++] = i->ptrs[ptr].dev;
1003
1004                 bch2_replicas_entry_sort(&replicas.e);
1005
1006                 /*
1007                  * If we're mounting in degraded mode - if we didn't read all
1008                  * the devices - this is wrong:
1009                  */
1010
1011                 if (!degraded &&
1012                     (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
1013                      fsck_err_on(!bch2_replicas_marked(c, &replicas.e), c,
1014                                  "superblock not marked as containing replicas %s",
1015                                  (bch2_replicas_entry_to_text(&PBUF(buf),
1016                                                               &replicas.e), buf)))) {
1017                         ret = bch2_mark_replicas(c, &replicas.e);
1018                         if (ret)
1019                                 return ret;
1020                 }
1021
1022                 for_each_jset_key(k, _n, entry, &i->j)
1023                         keys++;
1024                 entries++;
1025         }
1026
1027         bch_info(c, "journal read done, %zu keys in %zu entries, seq %llu",
1028                  keys, entries, *start_seq);
1029
1030         if (*start_seq != *blacklist_seq)
1031                 bch_info(c, "dropped unflushed entries %llu-%llu",
1032                          *blacklist_seq, *start_seq - 1);
1033 fsck_err:
1034         return ret;
1035 }
1036
1037 /* journal write: */
1038
1039 static void __journal_write_alloc(struct journal *j,
1040                                   struct journal_buf *w,
1041                                   struct dev_alloc_list *devs_sorted,
1042                                   unsigned sectors,
1043                                   unsigned *replicas,
1044                                   unsigned replicas_want)
1045 {
1046         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1047         struct journal_device *ja;
1048         struct bch_dev *ca;
1049         unsigned i;
1050
1051         if (*replicas >= replicas_want)
1052                 return;
1053
1054         for (i = 0; i < devs_sorted->nr; i++) {
1055                 ca = rcu_dereference(c->devs[devs_sorted->devs[i]]);
1056                 if (!ca)
1057                         continue;
1058
1059                 ja = &ca->journal;
1060
1061                 /*
1062                  * Check that we can use this device, and aren't already using
1063                  * it:
1064                  */
1065                 if (!ca->mi.durability ||
1066                     ca->mi.state != BCH_MEMBER_STATE_rw ||
1067                     !ja->nr ||
1068                     bch2_bkey_has_device(bkey_i_to_s_c(&w->key),
1069                                          ca->dev_idx) ||
1070                     sectors > ja->sectors_free)
1071                         continue;
1072
1073                 bch2_dev_stripe_increment(ca, &j->wp.stripe);
1074
1075                 bch2_bkey_append_ptr(&w->key,
1076                         (struct bch_extent_ptr) {
1077                                   .offset = bucket_to_sector(ca,
1078                                         ja->buckets[ja->cur_idx]) +
1079                                         ca->mi.bucket_size -
1080                                         ja->sectors_free,
1081                                   .dev = ca->dev_idx,
1082                 });
1083
1084                 ja->sectors_free -= sectors;
1085                 ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq);
1086
1087                 *replicas += ca->mi.durability;
1088
1089                 if (*replicas >= replicas_want)
1090                         break;
1091         }
1092 }
1093
1094 /**
1095  * journal_next_bucket - move on to the next journal bucket if possible
1096  */
1097 static int journal_write_alloc(struct journal *j, struct journal_buf *w,
1098                                unsigned sectors)
1099 {
1100         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1101         struct bch_devs_mask devs;
1102         struct journal_device *ja;
1103         struct bch_dev *ca;
1104         struct dev_alloc_list devs_sorted;
1105         unsigned target = c->opts.metadata_target ?:
1106                 c->opts.foreground_target;
1107         unsigned i, replicas = 0, replicas_want =
1108                 READ_ONCE(c->opts.metadata_replicas);
1109
1110         rcu_read_lock();
1111 retry:
1112         devs = target_rw_devs(c, BCH_DATA_journal, target);
1113
1114         devs_sorted = bch2_dev_alloc_list(c, &j->wp.stripe, &devs);
1115
1116         __journal_write_alloc(j, w, &devs_sorted,
1117                               sectors, &replicas, replicas_want);
1118
1119         if (replicas >= replicas_want)
1120                 goto done;
1121
1122         for (i = 0; i < devs_sorted.nr; i++) {
1123                 ca = rcu_dereference(c->devs[devs_sorted.devs[i]]);
1124                 if (!ca)
1125                         continue;
1126
1127                 ja = &ca->journal;
1128
1129                 if (sectors > ja->sectors_free &&
1130                     sectors <= ca->mi.bucket_size &&
1131                     bch2_journal_dev_buckets_available(j, ja,
1132                                         journal_space_discarded)) {
1133                         ja->cur_idx = (ja->cur_idx + 1) % ja->nr;
1134                         ja->sectors_free = ca->mi.bucket_size;
1135
1136                         /*
1137                          * ja->bucket_seq[ja->cur_idx] must always have
1138                          * something sensible:
1139                          */
1140                         ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq);
1141                 }
1142         }
1143
1144         __journal_write_alloc(j, w, &devs_sorted,
1145                               sectors, &replicas, replicas_want);
1146
1147         if (replicas < replicas_want && target) {
1148                 /* Retry from all devices: */
1149                 target = 0;
1150                 goto retry;
1151         }
1152 done:
1153         rcu_read_unlock();
1154
1155         BUG_ON(bkey_val_u64s(&w->key.k) > BCH_REPLICAS_MAX);
1156
1157         return replicas >= c->opts.metadata_replicas_required ? 0 : -EROFS;
1158 }
1159
1160 static void journal_write_compact(struct jset *jset)
1161 {
1162         struct jset_entry *i, *next, *prev = NULL;
1163
1164         /*
1165          * Simple compaction, dropping empty jset_entries (from journal
1166          * reservations that weren't fully used) and merging jset_entries that
1167          * can be.
1168          *
1169          * If we wanted to be really fancy here, we could sort all the keys in
1170          * the jset and drop keys that were overwritten - probably not worth it:
1171          */
1172         vstruct_for_each_safe(jset, i, next) {
1173                 unsigned u64s = le16_to_cpu(i->u64s);
1174
1175                 /* Empty entry: */
1176                 if (!u64s)
1177                         continue;
1178
1179                 /* Can we merge with previous entry? */
1180                 if (prev &&
1181                     i->btree_id == prev->btree_id &&
1182                     i->level    == prev->level &&
1183                     i->type     == prev->type &&
1184                     i->type     == BCH_JSET_ENTRY_btree_keys &&
1185                     le16_to_cpu(prev->u64s) + u64s <= U16_MAX) {
1186                         memmove_u64s_down(vstruct_next(prev),
1187                                           i->_data,
1188                                           u64s);
1189                         le16_add_cpu(&prev->u64s, u64s);
1190                         continue;
1191                 }
1192
1193                 /* Couldn't merge, move i into new position (after prev): */
1194                 prev = prev ? vstruct_next(prev) : jset->start;
1195                 if (i != prev)
1196                         memmove_u64s_down(prev, i, jset_u64s(u64s));
1197         }
1198
1199         prev = prev ? vstruct_next(prev) : jset->start;
1200         jset->u64s = cpu_to_le32((u64 *) prev - jset->_data);
1201 }
1202
1203 static void journal_buf_realloc(struct journal *j, struct journal_buf *buf)
1204 {
1205         /* we aren't holding j->lock: */
1206         unsigned new_size = READ_ONCE(j->buf_size_want);
1207         void *new_buf;
1208
1209         if (buf->buf_size >= new_size)
1210                 return;
1211
1212         new_buf = kvpmalloc(new_size, GFP_NOIO|__GFP_NOWARN);
1213         if (!new_buf)
1214                 return;
1215
1216         memcpy(new_buf, buf->data, buf->buf_size);
1217
1218         spin_lock(&j->lock);
1219         swap(buf->data,         new_buf);
1220         swap(buf->buf_size,     new_size);
1221         spin_unlock(&j->lock);
1222
1223         kvpfree(new_buf, new_size);
1224 }
1225
1226 static inline struct journal_buf *journal_last_unwritten_buf(struct journal *j)
1227 {
1228         return j->buf + j->reservations.unwritten_idx;
1229 }
1230
1231 static void journal_write_done(struct closure *cl)
1232 {
1233         struct journal *j = container_of(cl, struct journal, io);
1234         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1235         struct journal_buf *w = journal_last_unwritten_buf(j);
1236         struct bch_devs_list devs =
1237                 bch2_bkey_devs(bkey_i_to_s_c(&w->key));
1238         struct bch_replicas_padded replicas;
1239         union journal_res_state old, new;
1240         u64 v, seq, last_seq;
1241         int err = 0;
1242
1243         bch2_time_stats_update(j->write_time, j->write_start_time);
1244
1245         if (!devs.nr) {
1246                 bch_err(c, "unable to write journal to sufficient devices");
1247                 err = -EIO;
1248         } else {
1249                 bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal, devs);
1250                 if (bch2_mark_replicas(c, &replicas.e))
1251                         err = -EIO;
1252         }
1253
1254         if (err)
1255                 bch2_fatal_error(c);
1256
1257         spin_lock(&j->lock);
1258         seq = le64_to_cpu(w->data->seq);
1259         last_seq = le64_to_cpu(w->data->last_seq);
1260
1261         if (seq >= j->pin.front)
1262                 journal_seq_pin(j, seq)->devs = devs;
1263
1264         j->seq_ondisk           = seq;
1265         if (err && (!j->err_seq || seq < j->err_seq))
1266                 j->err_seq      = seq;
1267
1268         if (!JSET_NO_FLUSH(w->data)) {
1269                 j->flushed_seq_ondisk = seq;
1270                 j->last_seq_ondisk = last_seq;
1271         }
1272
1273         /*
1274          * Updating last_seq_ondisk may let bch2_journal_reclaim_work() discard
1275          * more buckets:
1276          *
1277          * Must come before signaling write completion, for
1278          * bch2_fs_journal_stop():
1279          */
1280         journal_reclaim_kick(&c->journal);
1281
1282         /* also must come before signalling write completion: */
1283         closure_debug_destroy(cl);
1284
1285         v = atomic64_read(&j->reservations.counter);
1286         do {
1287                 old.v = new.v = v;
1288                 BUG_ON(new.idx == new.unwritten_idx);
1289
1290                 new.unwritten_idx++;
1291         } while ((v = atomic64_cmpxchg(&j->reservations.counter,
1292                                        old.v, new.v)) != old.v);
1293
1294         bch2_journal_space_available(j);
1295
1296         closure_wake_up(&w->wait);
1297         journal_wake(j);
1298
1299         if (test_bit(JOURNAL_NEED_WRITE, &j->flags))
1300                 mod_delayed_work(system_freezable_wq, &j->write_work, 0);
1301         spin_unlock(&j->lock);
1302
1303         if (new.unwritten_idx != new.idx &&
1304             !journal_state_count(new, new.unwritten_idx))
1305                 closure_call(&j->io, bch2_journal_write, system_highpri_wq, NULL);
1306 }
1307
1308 static void journal_write_endio(struct bio *bio)
1309 {
1310         struct bch_dev *ca = bio->bi_private;
1311         struct journal *j = &ca->fs->journal;
1312
1313         if (bch2_dev_io_err_on(bio->bi_status, ca, "journal write error: %s",
1314                                bch2_blk_status_to_str(bio->bi_status)) ||
1315             bch2_meta_write_fault("journal")) {
1316                 struct journal_buf *w = journal_last_unwritten_buf(j);
1317                 unsigned long flags;
1318
1319                 spin_lock_irqsave(&j->err_lock, flags);
1320                 bch2_bkey_drop_device(bkey_i_to_s(&w->key), ca->dev_idx);
1321                 spin_unlock_irqrestore(&j->err_lock, flags);
1322         }
1323
1324         closure_put(&j->io);
1325         percpu_ref_put(&ca->io_ref);
1326 }
1327
1328 static void do_journal_write(struct closure *cl)
1329 {
1330         struct journal *j = container_of(cl, struct journal, io);
1331         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1332         struct bch_dev *ca;
1333         struct journal_buf *w = journal_last_unwritten_buf(j);
1334         struct bch_extent_ptr *ptr;
1335         struct bio *bio;
1336         unsigned sectors = vstruct_sectors(w->data, c->block_bits);
1337
1338         extent_for_each_ptr(bkey_i_to_s_extent(&w->key), ptr) {
1339                 ca = bch_dev_bkey_exists(c, ptr->dev);
1340                 if (!percpu_ref_tryget(&ca->io_ref)) {
1341                         /* XXX: fix this */
1342                         bch_err(c, "missing device for journal write\n");
1343                         continue;
1344                 }
1345
1346                 this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_journal],
1347                              sectors);
1348
1349                 bio = ca->journal.bio;
1350                 bio_reset(bio);
1351                 bio_set_dev(bio, ca->disk_sb.bdev);
1352                 bio->bi_iter.bi_sector  = ptr->offset;
1353                 bio->bi_end_io          = journal_write_endio;
1354                 bio->bi_private         = ca;
1355                 bio->bi_opf             = REQ_OP_WRITE|REQ_SYNC|REQ_META;
1356
1357                 BUG_ON(bio->bi_iter.bi_sector == ca->prev_journal_sector);
1358                 ca->prev_journal_sector = bio->bi_iter.bi_sector;
1359
1360                 if (!JSET_NO_FLUSH(w->data))
1361                         bio->bi_opf    |= REQ_FUA;
1362                 if (!JSET_NO_FLUSH(w->data) && !w->separate_flush)
1363                         bio->bi_opf    |= REQ_PREFLUSH;
1364
1365                 bch2_bio_map(bio, w->data, sectors << 9);
1366
1367                 trace_journal_write(bio);
1368                 closure_bio_submit(bio, cl);
1369
1370                 ca->journal.bucket_seq[ca->journal.cur_idx] =
1371                         le64_to_cpu(w->data->seq);
1372         }
1373
1374         continue_at(cl, journal_write_done, system_highpri_wq);
1375         return;
1376 }
1377
1378 void bch2_journal_write(struct closure *cl)
1379 {
1380         struct journal *j = container_of(cl, struct journal, io);
1381         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1382         struct bch_dev *ca;
1383         struct journal_buf *w = journal_last_unwritten_buf(j);
1384         struct jset_entry *start, *end;
1385         struct jset *jset;
1386         struct bio *bio;
1387         char *journal_debug_buf = NULL;
1388         bool validate_before_checksum = false;
1389         unsigned i, sectors, bytes, u64s, nr_rw_members = 0;
1390         int ret;
1391
1392         BUG_ON(BCH_SB_CLEAN(c->disk_sb.sb));
1393
1394         journal_buf_realloc(j, w);
1395         jset = w->data;
1396
1397         j->write_start_time = local_clock();
1398
1399         spin_lock(&j->lock);
1400         if (c->sb.features & (1ULL << BCH_FEATURE_journal_no_flush) &&
1401             !w->must_flush &&
1402             (jiffies - j->last_flush_write) < msecs_to_jiffies(j->write_delay_ms) &&
1403             test_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags)) {
1404                 w->noflush = true;
1405                 SET_JSET_NO_FLUSH(jset, true);
1406                 jset->last_seq = 0;
1407
1408                 j->nr_noflush_writes++;
1409         } else {
1410                 j->last_flush_write = jiffies;
1411                 j->nr_flush_writes++;
1412         }
1413         spin_unlock(&j->lock);
1414
1415         /*
1416          * New btree roots are set by journalling them; when the journal entry
1417          * gets written we have to propagate them to c->btree_roots
1418          *
1419          * But, every journal entry we write has to contain all the btree roots
1420          * (at least for now); so after we copy btree roots to c->btree_roots we
1421          * have to get any missing btree roots and add them to this journal
1422          * entry:
1423          */
1424
1425         bch2_journal_entries_to_btree_roots(c, jset);
1426
1427         start = end = vstruct_last(jset);
1428
1429         end     = bch2_btree_roots_to_journal_entries(c, jset->start, end);
1430
1431         bch2_journal_super_entries_add_common(c, &end,
1432                                 le64_to_cpu(jset->seq));
1433         u64s    = (u64 *) end - (u64 *) start;
1434         BUG_ON(u64s > j->entry_u64s_reserved);
1435
1436         le32_add_cpu(&jset->u64s, u64s);
1437         BUG_ON(vstruct_sectors(jset, c->block_bits) > w->sectors);
1438
1439         journal_write_compact(jset);
1440
1441         jset->magic             = cpu_to_le64(jset_magic(c));
1442         jset->version           = c->sb.version < bcachefs_metadata_version_new_versioning
1443                 ? cpu_to_le32(BCH_JSET_VERSION_OLD)
1444                 : cpu_to_le32(c->sb.version);
1445
1446         SET_JSET_BIG_ENDIAN(jset, CPU_BIG_ENDIAN);
1447         SET_JSET_CSUM_TYPE(jset, bch2_meta_checksum_type(c));
1448
1449         if (journal_entry_empty(jset))
1450                 j->last_empty_seq = le64_to_cpu(jset->seq);
1451
1452         if (bch2_csum_type_is_encryption(JSET_CSUM_TYPE(jset)))
1453                 validate_before_checksum = true;
1454
1455         if (le32_to_cpu(jset->version) < bcachefs_metadata_version_current)
1456                 validate_before_checksum = true;
1457
1458         if (validate_before_checksum &&
1459             jset_validate_for_write(c, jset))
1460                 goto err;
1461
1462         bch2_encrypt(c, JSET_CSUM_TYPE(jset), journal_nonce(jset),
1463                     jset->encrypted_start,
1464                     vstruct_end(jset) - (void *) jset->encrypted_start);
1465
1466         jset->csum = csum_vstruct(c, JSET_CSUM_TYPE(jset),
1467                                   journal_nonce(jset), jset);
1468
1469         if (!validate_before_checksum &&
1470             jset_validate_for_write(c, jset))
1471                 goto err;
1472
1473         sectors = vstruct_sectors(jset, c->block_bits);
1474         BUG_ON(sectors > w->sectors);
1475
1476         bytes = vstruct_bytes(jset);
1477         memset((void *) jset + bytes, 0, (sectors << 9) - bytes);
1478
1479 retry_alloc:
1480         spin_lock(&j->lock);
1481         ret = journal_write_alloc(j, w, sectors);
1482
1483         if (ret && j->can_discard) {
1484                 spin_unlock(&j->lock);
1485                 bch2_journal_do_discards(j);
1486                 goto retry_alloc;
1487         }
1488
1489         if (ret) {
1490                 journal_debug_buf = kmalloc(4096, GFP_ATOMIC);
1491                 if (journal_debug_buf)
1492                         __bch2_journal_debug_to_text(&_PBUF(journal_debug_buf, 4096), j);
1493         }
1494
1495         /*
1496          * write is allocated, no longer need to account for it in
1497          * bch2_journal_space_available():
1498          */
1499         w->sectors = 0;
1500
1501         /*
1502          * journal entry has been compacted and allocated, recalculate space
1503          * available:
1504          */
1505         bch2_journal_space_available(j);
1506         spin_unlock(&j->lock);
1507
1508         if (ret) {
1509                 bch_err(c, "Unable to allocate journal write:\n%s",
1510                         journal_debug_buf);
1511                 kfree(journal_debug_buf);
1512                 bch2_fatal_error(c);
1513                 continue_at(cl, journal_write_done, system_highpri_wq);
1514                 return;
1515         }
1516
1517         /*
1518          * XXX: we really should just disable the entire journal in nochanges
1519          * mode
1520          */
1521         if (c->opts.nochanges)
1522                 goto no_io;
1523
1524         for_each_rw_member(ca, c, i)
1525                 nr_rw_members++;
1526
1527         if (nr_rw_members > 1)
1528                 w->separate_flush = true;
1529
1530         if (!JSET_NO_FLUSH(jset) && w->separate_flush) {
1531                 for_each_rw_member(ca, c, i) {
1532                         percpu_ref_get(&ca->io_ref);
1533
1534                         bio = ca->journal.bio;
1535                         bio_reset(bio);
1536                         bio_set_dev(bio, ca->disk_sb.bdev);
1537                         bio->bi_opf             = REQ_OP_FLUSH;
1538                         bio->bi_end_io          = journal_write_endio;
1539                         bio->bi_private         = ca;
1540                         closure_bio_submit(bio, cl);
1541                 }
1542         }
1543
1544         bch2_bucket_seq_cleanup(c);
1545
1546         continue_at(cl, do_journal_write, system_highpri_wq);
1547         return;
1548 no_io:
1549         bch2_bucket_seq_cleanup(c);
1550
1551         continue_at(cl, journal_write_done, system_highpri_wq);
1552         return;
1553 err:
1554         bch2_inconsistent_error(c);
1555         continue_at(cl, journal_write_done, system_highpri_wq);
1556 }