]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/journal_io.c
Update bcachefs sources to 5d0a6c2b32f1 bcachefs: check_directory_structure() can...
[bcachefs-tools-debian] / libbcachefs / journal_io.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "bcachefs.h"
3 #include "alloc_background.h"
4 #include "alloc_foreground.h"
5 #include "btree_io.h"
6 #include "btree_update_interior.h"
7 #include "btree_write_buffer.h"
8 #include "buckets.h"
9 #include "checksum.h"
10 #include "disk_groups.h"
11 #include "error.h"
12 #include "journal.h"
13 #include "journal_io.h"
14 #include "journal_reclaim.h"
15 #include "journal_seq_blacklist.h"
16 #include "replicas.h"
17 #include "sb-clean.h"
18 #include "trace.h"
19
20 static struct nonce journal_nonce(const struct jset *jset)
21 {
22         return (struct nonce) {{
23                 [0] = 0,
24                 [1] = ((__le32 *) &jset->seq)[0],
25                 [2] = ((__le32 *) &jset->seq)[1],
26                 [3] = BCH_NONCE_JOURNAL,
27         }};
28 }
29
30 static bool jset_csum_good(struct bch_fs *c, struct jset *j)
31 {
32         return bch2_checksum_type_valid(c, JSET_CSUM_TYPE(j)) &&
33                 !bch2_crc_cmp(j->csum,
34                               csum_vstruct(c, JSET_CSUM_TYPE(j), journal_nonce(j), j));
35 }
36
37 static inline u32 journal_entry_radix_idx(struct bch_fs *c, u64 seq)
38 {
39         return (seq - c->journal_entries_base_seq) & (~0U >> 1);
40 }
41
42 static void __journal_replay_free(struct bch_fs *c,
43                                   struct journal_replay *i)
44 {
45         struct journal_replay **p =
46                 genradix_ptr(&c->journal_entries,
47                              journal_entry_radix_idx(c, le64_to_cpu(i->j.seq)));
48
49         BUG_ON(*p != i);
50         *p = NULL;
51         kvpfree(i, offsetof(struct journal_replay, j) +
52                 vstruct_bytes(&i->j));
53 }
54
55 static void journal_replay_free(struct bch_fs *c, struct journal_replay *i)
56 {
57         i->ignore = true;
58
59         if (!c->opts.read_entire_journal)
60                 __journal_replay_free(c, i);
61 }
62
63 struct journal_list {
64         struct closure          cl;
65         u64                     last_seq;
66         struct mutex            lock;
67         int                     ret;
68 };
69
70 #define JOURNAL_ENTRY_ADD_OK            0
71 #define JOURNAL_ENTRY_ADD_OUT_OF_RANGE  5
72
73 /*
74  * Given a journal entry we just read, add it to the list of journal entries to
75  * be replayed:
76  */
77 static int journal_entry_add(struct bch_fs *c, struct bch_dev *ca,
78                              struct journal_ptr entry_ptr,
79                              struct journal_list *jlist, struct jset *j)
80 {
81         struct genradix_iter iter;
82         struct journal_replay **_i, *i, *dup;
83         struct journal_ptr *ptr;
84         size_t bytes = vstruct_bytes(j);
85         u64 last_seq = !JSET_NO_FLUSH(j) ? le64_to_cpu(j->last_seq) : 0;
86         int ret = JOURNAL_ENTRY_ADD_OK;
87
88         /* Is this entry older than the range we need? */
89         if (!c->opts.read_entire_journal &&
90             le64_to_cpu(j->seq) < jlist->last_seq)
91                 return JOURNAL_ENTRY_ADD_OUT_OF_RANGE;
92
93         /*
94          * genradixes are indexed by a ulong, not a u64, so we can't index them
95          * by sequence number directly: Assume instead that they will all fall
96          * within the range of +-2billion of the filrst one we find.
97          */
98         if (!c->journal_entries_base_seq)
99                 c->journal_entries_base_seq = max_t(s64, 1, le64_to_cpu(j->seq) - S32_MAX);
100
101         /* Drop entries we don't need anymore */
102         if (last_seq > jlist->last_seq && !c->opts.read_entire_journal) {
103                 genradix_for_each_from(&c->journal_entries, iter, _i,
104                                        journal_entry_radix_idx(c, jlist->last_seq)) {
105                         i = *_i;
106
107                         if (!i || i->ignore)
108                                 continue;
109
110                         if (le64_to_cpu(i->j.seq) >= last_seq)
111                                 break;
112                         journal_replay_free(c, i);
113                 }
114         }
115
116         jlist->last_seq = max(jlist->last_seq, last_seq);
117
118         _i = genradix_ptr_alloc(&c->journal_entries,
119                                 journal_entry_radix_idx(c, le64_to_cpu(j->seq)),
120                                 GFP_KERNEL);
121         if (!_i)
122                 return -BCH_ERR_ENOMEM_journal_entry_add;
123
124         /*
125          * Duplicate journal entries? If so we want the one that didn't have a
126          * checksum error:
127          */
128         dup = *_i;
129         if (dup) {
130                 if (bytes == vstruct_bytes(&dup->j) &&
131                     !memcmp(j, &dup->j, bytes)) {
132                         i = dup;
133                         goto found;
134                 }
135
136                 if (!entry_ptr.csum_good) {
137                         i = dup;
138                         goto found;
139                 }
140
141                 if (!dup->csum_good)
142                         goto replace;
143
144                 fsck_err(c, journal_entry_replicas_data_mismatch,
145                          "found duplicate but non identical journal entries (seq %llu)",
146                          le64_to_cpu(j->seq));
147                 i = dup;
148                 goto found;
149         }
150 replace:
151         i = kvpmalloc(offsetof(struct journal_replay, j) + bytes, GFP_KERNEL);
152         if (!i)
153                 return -BCH_ERR_ENOMEM_journal_entry_add;
154
155         i->nr_ptrs      = 0;
156         i->csum_good    = entry_ptr.csum_good;
157         i->ignore       = false;
158         unsafe_memcpy(&i->j, j, bytes, "embedded variable length struct");
159         i->ptrs[i->nr_ptrs++] = entry_ptr;
160
161         if (dup) {
162                 if (dup->nr_ptrs >= ARRAY_SIZE(dup->ptrs)) {
163                         bch_err(c, "found too many copies of journal entry %llu",
164                                 le64_to_cpu(i->j.seq));
165                         dup->nr_ptrs = ARRAY_SIZE(dup->ptrs) - 1;
166                 }
167
168                 /* The first ptr should represent the jset we kept: */
169                 memcpy(i->ptrs + i->nr_ptrs,
170                        dup->ptrs,
171                        sizeof(dup->ptrs[0]) * dup->nr_ptrs);
172                 i->nr_ptrs += dup->nr_ptrs;
173                 __journal_replay_free(c, dup);
174         }
175
176         *_i = i;
177         return 0;
178 found:
179         for (ptr = i->ptrs; ptr < i->ptrs + i->nr_ptrs; ptr++) {
180                 if (ptr->dev == ca->dev_idx) {
181                         bch_err(c, "duplicate journal entry %llu on same device",
182                                 le64_to_cpu(i->j.seq));
183                         goto out;
184                 }
185         }
186
187         if (i->nr_ptrs >= ARRAY_SIZE(i->ptrs)) {
188                 bch_err(c, "found too many copies of journal entry %llu",
189                         le64_to_cpu(i->j.seq));
190                 goto out;
191         }
192
193         i->ptrs[i->nr_ptrs++] = entry_ptr;
194 out:
195 fsck_err:
196         return ret;
197 }
198
199 /* this fills in a range with empty jset_entries: */
200 static void journal_entry_null_range(void *start, void *end)
201 {
202         struct jset_entry *entry;
203
204         for (entry = start; entry != end; entry = vstruct_next(entry))
205                 memset(entry, 0, sizeof(*entry));
206 }
207
208 #define JOURNAL_ENTRY_REREAD    5
209 #define JOURNAL_ENTRY_NONE      6
210 #define JOURNAL_ENTRY_BAD       7
211
212 static void journal_entry_err_msg(struct printbuf *out,
213                                   u32 version,
214                                   struct jset *jset,
215                                   struct jset_entry *entry)
216 {
217         prt_str(out, "invalid journal entry, version=");
218         bch2_version_to_text(out, version);
219
220         if (entry) {
221                 prt_str(out, " type=");
222                 prt_str(out, bch2_jset_entry_types[entry->type]);
223         }
224
225         if (!jset) {
226                 prt_printf(out, " in superblock");
227         } else {
228
229                 prt_printf(out, " seq=%llu", le64_to_cpu(jset->seq));
230
231                 if (entry)
232                         prt_printf(out, " offset=%zi/%u",
233                                    (u64 *) entry - jset->_data,
234                                    le32_to_cpu(jset->u64s));
235         }
236
237         prt_str(out, ": ");
238 }
239
240 #define journal_entry_err(c, version, jset, entry, _err, msg, ...)      \
241 ({                                                                      \
242         struct printbuf _buf = PRINTBUF;                                \
243                                                                         \
244         journal_entry_err_msg(&_buf, version, jset, entry);             \
245         prt_printf(&_buf, msg, ##__VA_ARGS__);                          \
246                                                                         \
247         switch (flags & BKEY_INVALID_WRITE) {                           \
248         case READ:                                                      \
249                 mustfix_fsck_err(c, _err, "%s", _buf.buf);              \
250                 break;                                                  \
251         case WRITE:                                                     \
252                 bch2_sb_error_count(c, BCH_FSCK_ERR_##_err);            \
253                 bch_err(c, "corrupt metadata before write: %s\n", _buf.buf);\
254                 if (bch2_fs_inconsistent(c)) {                          \
255                         ret = -BCH_ERR_fsck_errors_not_fixed;           \
256                         goto fsck_err;                                  \
257                 }                                                       \
258                 break;                                                  \
259         }                                                               \
260                                                                         \
261         printbuf_exit(&_buf);                                           \
262         true;                                                           \
263 })
264
265 #define journal_entry_err_on(cond, ...)                                 \
266         ((cond) ? journal_entry_err(__VA_ARGS__) : false)
267
268 #define FSCK_DELETED_KEY        5
269
270 static int journal_validate_key(struct bch_fs *c,
271                                 struct jset *jset,
272                                 struct jset_entry *entry,
273                                 unsigned level, enum btree_id btree_id,
274                                 struct bkey_i *k,
275                                 unsigned version, int big_endian,
276                                 enum bkey_invalid_flags flags)
277 {
278         int write = flags & BKEY_INVALID_WRITE;
279         void *next = vstruct_next(entry);
280         struct printbuf buf = PRINTBUF;
281         int ret = 0;
282
283         if (journal_entry_err_on(!k->k.u64s,
284                                  c, version, jset, entry,
285                                  journal_entry_bkey_u64s_0,
286                                  "k->u64s 0")) {
287                 entry->u64s = cpu_to_le16((u64 *) k - entry->_data);
288                 journal_entry_null_range(vstruct_next(entry), next);
289                 return FSCK_DELETED_KEY;
290         }
291
292         if (journal_entry_err_on((void *) bkey_next(k) >
293                                  (void *) vstruct_next(entry),
294                                  c, version, jset, entry,
295                                  journal_entry_bkey_past_end,
296                                  "extends past end of journal entry")) {
297                 entry->u64s = cpu_to_le16((u64 *) k - entry->_data);
298                 journal_entry_null_range(vstruct_next(entry), next);
299                 return FSCK_DELETED_KEY;
300         }
301
302         if (journal_entry_err_on(k->k.format != KEY_FORMAT_CURRENT,
303                                  c, version, jset, entry,
304                                  journal_entry_bkey_bad_format,
305                                  "bad format %u", k->k.format)) {
306                 le16_add_cpu(&entry->u64s, -((u16) k->k.u64s));
307                 memmove(k, bkey_next(k), next - (void *) bkey_next(k));
308                 journal_entry_null_range(vstruct_next(entry), next);
309                 return FSCK_DELETED_KEY;
310         }
311
312         if (!write)
313                 bch2_bkey_compat(level, btree_id, version, big_endian,
314                                  write, NULL, bkey_to_packed(k));
315
316         if (bch2_bkey_invalid(c, bkey_i_to_s_c(k),
317                               __btree_node_type(level, btree_id), write, &buf)) {
318                 printbuf_reset(&buf);
319                 journal_entry_err_msg(&buf, version, jset, entry);
320                 prt_newline(&buf);
321                 printbuf_indent_add(&buf, 2);
322
323                 bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(k));
324                 prt_newline(&buf);
325                 bch2_bkey_invalid(c, bkey_i_to_s_c(k),
326                                   __btree_node_type(level, btree_id), write, &buf);
327
328                 mustfix_fsck_err(c, journal_entry_bkey_invalid,
329                                  "%s", buf.buf);
330
331                 le16_add_cpu(&entry->u64s, -((u16) k->k.u64s));
332                 memmove(k, bkey_next(k), next - (void *) bkey_next(k));
333                 journal_entry_null_range(vstruct_next(entry), next);
334
335                 printbuf_exit(&buf);
336                 return FSCK_DELETED_KEY;
337         }
338
339         if (write)
340                 bch2_bkey_compat(level, btree_id, version, big_endian,
341                                  write, NULL, bkey_to_packed(k));
342 fsck_err:
343         printbuf_exit(&buf);
344         return ret;
345 }
346
347 static int journal_entry_btree_keys_validate(struct bch_fs *c,
348                                 struct jset *jset,
349                                 struct jset_entry *entry,
350                                 unsigned version, int big_endian,
351                                 enum bkey_invalid_flags flags)
352 {
353         struct bkey_i *k = entry->start;
354
355         while (k != vstruct_last(entry)) {
356                 int ret = journal_validate_key(c, jset, entry,
357                                                entry->level,
358                                                entry->btree_id,
359                                                k, version, big_endian,
360                                                flags|BKEY_INVALID_JOURNAL);
361                 if (ret == FSCK_DELETED_KEY)
362                         continue;
363
364                 k = bkey_next(k);
365         }
366
367         return 0;
368 }
369
370 static void journal_entry_btree_keys_to_text(struct printbuf *out, struct bch_fs *c,
371                                              struct jset_entry *entry)
372 {
373         struct bkey_i *k;
374         bool first = true;
375
376         jset_entry_for_each_key(entry, k) {
377                 if (!first) {
378                         prt_newline(out);
379                         prt_printf(out, "%s: ", bch2_jset_entry_types[entry->type]);
380                 }
381                 prt_printf(out, "btree=%s l=%u ", bch2_btree_id_str(entry->btree_id), entry->level);
382                 bch2_bkey_val_to_text(out, c, bkey_i_to_s_c(k));
383                 first = false;
384         }
385 }
386
387 static int journal_entry_btree_root_validate(struct bch_fs *c,
388                                 struct jset *jset,
389                                 struct jset_entry *entry,
390                                 unsigned version, int big_endian,
391                                 enum bkey_invalid_flags flags)
392 {
393         struct bkey_i *k = entry->start;
394         int ret = 0;
395
396         if (journal_entry_err_on(!entry->u64s ||
397                                  le16_to_cpu(entry->u64s) != k->k.u64s,
398                                  c, version, jset, entry,
399                                  journal_entry_btree_root_bad_size,
400                                  "invalid btree root journal entry: wrong number of keys")) {
401                 void *next = vstruct_next(entry);
402                 /*
403                  * we don't want to null out this jset_entry,
404                  * just the contents, so that later we can tell
405                  * we were _supposed_ to have a btree root
406                  */
407                 entry->u64s = 0;
408                 journal_entry_null_range(vstruct_next(entry), next);
409                 return 0;
410         }
411
412         return journal_validate_key(c, jset, entry, 1, entry->btree_id, k,
413                                     version, big_endian, flags);
414 fsck_err:
415         return ret;
416 }
417
418 static void journal_entry_btree_root_to_text(struct printbuf *out, struct bch_fs *c,
419                                              struct jset_entry *entry)
420 {
421         journal_entry_btree_keys_to_text(out, c, entry);
422 }
423
424 static int journal_entry_prio_ptrs_validate(struct bch_fs *c,
425                                 struct jset *jset,
426                                 struct jset_entry *entry,
427                                 unsigned version, int big_endian,
428                                 enum bkey_invalid_flags flags)
429 {
430         /* obsolete, don't care: */
431         return 0;
432 }
433
434 static void journal_entry_prio_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
435                                             struct jset_entry *entry)
436 {
437 }
438
439 static int journal_entry_blacklist_validate(struct bch_fs *c,
440                                 struct jset *jset,
441                                 struct jset_entry *entry,
442                                 unsigned version, int big_endian,
443                                 enum bkey_invalid_flags flags)
444 {
445         int ret = 0;
446
447         if (journal_entry_err_on(le16_to_cpu(entry->u64s) != 1,
448                                  c, version, jset, entry,
449                                  journal_entry_blacklist_bad_size,
450                 "invalid journal seq blacklist entry: bad size")) {
451                 journal_entry_null_range(entry, vstruct_next(entry));
452         }
453 fsck_err:
454         return ret;
455 }
456
457 static void journal_entry_blacklist_to_text(struct printbuf *out, struct bch_fs *c,
458                                             struct jset_entry *entry)
459 {
460         struct jset_entry_blacklist *bl =
461                 container_of(entry, struct jset_entry_blacklist, entry);
462
463         prt_printf(out, "seq=%llu", le64_to_cpu(bl->seq));
464 }
465
466 static int journal_entry_blacklist_v2_validate(struct bch_fs *c,
467                                 struct jset *jset,
468                                 struct jset_entry *entry,
469                                 unsigned version, int big_endian,
470                                 enum bkey_invalid_flags flags)
471 {
472         struct jset_entry_blacklist_v2 *bl_entry;
473         int ret = 0;
474
475         if (journal_entry_err_on(le16_to_cpu(entry->u64s) != 2,
476                                  c, version, jset, entry,
477                                  journal_entry_blacklist_v2_bad_size,
478                 "invalid journal seq blacklist entry: bad size")) {
479                 journal_entry_null_range(entry, vstruct_next(entry));
480                 goto out;
481         }
482
483         bl_entry = container_of(entry, struct jset_entry_blacklist_v2, entry);
484
485         if (journal_entry_err_on(le64_to_cpu(bl_entry->start) >
486                                  le64_to_cpu(bl_entry->end),
487                                  c, version, jset, entry,
488                                  journal_entry_blacklist_v2_start_past_end,
489                 "invalid journal seq blacklist entry: start > end")) {
490                 journal_entry_null_range(entry, vstruct_next(entry));
491         }
492 out:
493 fsck_err:
494         return ret;
495 }
496
497 static void journal_entry_blacklist_v2_to_text(struct printbuf *out, struct bch_fs *c,
498                                                struct jset_entry *entry)
499 {
500         struct jset_entry_blacklist_v2 *bl =
501                 container_of(entry, struct jset_entry_blacklist_v2, entry);
502
503         prt_printf(out, "start=%llu end=%llu",
504                le64_to_cpu(bl->start),
505                le64_to_cpu(bl->end));
506 }
507
508 static int journal_entry_usage_validate(struct bch_fs *c,
509                                 struct jset *jset,
510                                 struct jset_entry *entry,
511                                 unsigned version, int big_endian,
512                                 enum bkey_invalid_flags flags)
513 {
514         struct jset_entry_usage *u =
515                 container_of(entry, struct jset_entry_usage, entry);
516         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
517         int ret = 0;
518
519         if (journal_entry_err_on(bytes < sizeof(*u),
520                                  c, version, jset, entry,
521                                  journal_entry_usage_bad_size,
522                                  "invalid journal entry usage: bad size")) {
523                 journal_entry_null_range(entry, vstruct_next(entry));
524                 return ret;
525         }
526
527 fsck_err:
528         return ret;
529 }
530
531 static void journal_entry_usage_to_text(struct printbuf *out, struct bch_fs *c,
532                                         struct jset_entry *entry)
533 {
534         struct jset_entry_usage *u =
535                 container_of(entry, struct jset_entry_usage, entry);
536
537         prt_printf(out, "type=%s v=%llu",
538                bch2_fs_usage_types[u->entry.btree_id],
539                le64_to_cpu(u->v));
540 }
541
542 static int journal_entry_data_usage_validate(struct bch_fs *c,
543                                 struct jset *jset,
544                                 struct jset_entry *entry,
545                                 unsigned version, int big_endian,
546                                 enum bkey_invalid_flags flags)
547 {
548         struct jset_entry_data_usage *u =
549                 container_of(entry, struct jset_entry_data_usage, entry);
550         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
551         struct printbuf err = PRINTBUF;
552         int ret = 0;
553
554         if (journal_entry_err_on(bytes < sizeof(*u) ||
555                                  bytes < sizeof(*u) + u->r.nr_devs,
556                                  c, version, jset, entry,
557                                  journal_entry_data_usage_bad_size,
558                                  "invalid journal entry usage: bad size")) {
559                 journal_entry_null_range(entry, vstruct_next(entry));
560                 goto out;
561         }
562
563         if (journal_entry_err_on(bch2_replicas_entry_validate(&u->r, c->disk_sb.sb, &err),
564                                  c, version, jset, entry,
565                                  journal_entry_data_usage_bad_size,
566                                  "invalid journal entry usage: %s", err.buf)) {
567                 journal_entry_null_range(entry, vstruct_next(entry));
568                 goto out;
569         }
570 out:
571 fsck_err:
572         printbuf_exit(&err);
573         return ret;
574 }
575
576 static void journal_entry_data_usage_to_text(struct printbuf *out, struct bch_fs *c,
577                                              struct jset_entry *entry)
578 {
579         struct jset_entry_data_usage *u =
580                 container_of(entry, struct jset_entry_data_usage, entry);
581
582         bch2_replicas_entry_to_text(out, &u->r);
583         prt_printf(out, "=%llu", le64_to_cpu(u->v));
584 }
585
586 static int journal_entry_clock_validate(struct bch_fs *c,
587                                 struct jset *jset,
588                                 struct jset_entry *entry,
589                                 unsigned version, int big_endian,
590                                 enum bkey_invalid_flags flags)
591 {
592         struct jset_entry_clock *clock =
593                 container_of(entry, struct jset_entry_clock, entry);
594         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
595         int ret = 0;
596
597         if (journal_entry_err_on(bytes != sizeof(*clock),
598                                  c, version, jset, entry,
599                                  journal_entry_clock_bad_size,
600                                  "bad size")) {
601                 journal_entry_null_range(entry, vstruct_next(entry));
602                 return ret;
603         }
604
605         if (journal_entry_err_on(clock->rw > 1,
606                                  c, version, jset, entry,
607                                  journal_entry_clock_bad_rw,
608                                  "bad rw")) {
609                 journal_entry_null_range(entry, vstruct_next(entry));
610                 return ret;
611         }
612
613 fsck_err:
614         return ret;
615 }
616
617 static void journal_entry_clock_to_text(struct printbuf *out, struct bch_fs *c,
618                                         struct jset_entry *entry)
619 {
620         struct jset_entry_clock *clock =
621                 container_of(entry, struct jset_entry_clock, entry);
622
623         prt_printf(out, "%s=%llu", clock->rw ? "write" : "read", le64_to_cpu(clock->time));
624 }
625
626 static int journal_entry_dev_usage_validate(struct bch_fs *c,
627                                 struct jset *jset,
628                                 struct jset_entry *entry,
629                                 unsigned version, int big_endian,
630                                 enum bkey_invalid_flags flags)
631 {
632         struct jset_entry_dev_usage *u =
633                 container_of(entry, struct jset_entry_dev_usage, entry);
634         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
635         unsigned expected = sizeof(*u);
636         unsigned dev;
637         int ret = 0;
638
639         if (journal_entry_err_on(bytes < expected,
640                                  c, version, jset, entry,
641                                  journal_entry_dev_usage_bad_size,
642                                  "bad size (%u < %u)",
643                                  bytes, expected)) {
644                 journal_entry_null_range(entry, vstruct_next(entry));
645                 return ret;
646         }
647
648         dev = le32_to_cpu(u->dev);
649
650         if (journal_entry_err_on(!bch2_dev_exists2(c, dev),
651                                  c, version, jset, entry,
652                                  journal_entry_dev_usage_bad_dev,
653                                  "bad dev")) {
654                 journal_entry_null_range(entry, vstruct_next(entry));
655                 return ret;
656         }
657
658         if (journal_entry_err_on(u->pad,
659                                  c, version, jset, entry,
660                                  journal_entry_dev_usage_bad_pad,
661                                  "bad pad")) {
662                 journal_entry_null_range(entry, vstruct_next(entry));
663                 return ret;
664         }
665
666 fsck_err:
667         return ret;
668 }
669
670 static void journal_entry_dev_usage_to_text(struct printbuf *out, struct bch_fs *c,
671                                             struct jset_entry *entry)
672 {
673         struct jset_entry_dev_usage *u =
674                 container_of(entry, struct jset_entry_dev_usage, entry);
675         unsigned i, nr_types = jset_entry_dev_usage_nr_types(u);
676
677         prt_printf(out, "dev=%u", le32_to_cpu(u->dev));
678
679         for (i = 0; i < nr_types; i++) {
680                 if (i < BCH_DATA_NR)
681                         prt_printf(out, " %s", bch2_data_types[i]);
682                 else
683                         prt_printf(out, " (unknown data type %u)", i);
684                 prt_printf(out, ": buckets=%llu sectors=%llu fragmented=%llu",
685                        le64_to_cpu(u->d[i].buckets),
686                        le64_to_cpu(u->d[i].sectors),
687                        le64_to_cpu(u->d[i].fragmented));
688         }
689 }
690
691 static int journal_entry_log_validate(struct bch_fs *c,
692                                 struct jset *jset,
693                                 struct jset_entry *entry,
694                                 unsigned version, int big_endian,
695                                 enum bkey_invalid_flags flags)
696 {
697         return 0;
698 }
699
700 static void journal_entry_log_to_text(struct printbuf *out, struct bch_fs *c,
701                                       struct jset_entry *entry)
702 {
703         struct jset_entry_log *l = container_of(entry, struct jset_entry_log, entry);
704         unsigned bytes = vstruct_bytes(entry) - offsetof(struct jset_entry_log, d);
705
706         prt_printf(out, "%.*s", bytes, l->d);
707 }
708
709 static int journal_entry_overwrite_validate(struct bch_fs *c,
710                                 struct jset *jset,
711                                 struct jset_entry *entry,
712                                 unsigned version, int big_endian,
713                                 enum bkey_invalid_flags flags)
714 {
715         return journal_entry_btree_keys_validate(c, jset, entry,
716                                 version, big_endian, READ);
717 }
718
719 static void journal_entry_overwrite_to_text(struct printbuf *out, struct bch_fs *c,
720                                             struct jset_entry *entry)
721 {
722         journal_entry_btree_keys_to_text(out, c, entry);
723 }
724
725 static int journal_entry_write_buffer_keys_validate(struct bch_fs *c,
726                                 struct jset *jset,
727                                 struct jset_entry *entry,
728                                 unsigned version, int big_endian,
729                                 enum bkey_invalid_flags flags)
730 {
731         return journal_entry_btree_keys_validate(c, jset, entry,
732                                 version, big_endian, READ);
733 }
734
735 static void journal_entry_write_buffer_keys_to_text(struct printbuf *out, struct bch_fs *c,
736                                             struct jset_entry *entry)
737 {
738         journal_entry_btree_keys_to_text(out, c, entry);
739 }
740
741 struct jset_entry_ops {
742         int (*validate)(struct bch_fs *, struct jset *,
743                         struct jset_entry *, unsigned, int,
744                         enum bkey_invalid_flags);
745         void (*to_text)(struct printbuf *, struct bch_fs *, struct jset_entry *);
746 };
747
748 static const struct jset_entry_ops bch2_jset_entry_ops[] = {
749 #define x(f, nr)                                                \
750         [BCH_JSET_ENTRY_##f]    = (struct jset_entry_ops) {     \
751                 .validate       = journal_entry_##f##_validate, \
752                 .to_text        = journal_entry_##f##_to_text,  \
753         },
754         BCH_JSET_ENTRY_TYPES()
755 #undef x
756 };
757
758 int bch2_journal_entry_validate(struct bch_fs *c,
759                                 struct jset *jset,
760                                 struct jset_entry *entry,
761                                 unsigned version, int big_endian,
762                                 enum bkey_invalid_flags flags)
763 {
764         return entry->type < BCH_JSET_ENTRY_NR
765                 ? bch2_jset_entry_ops[entry->type].validate(c, jset, entry,
766                                 version, big_endian, flags)
767                 : 0;
768 }
769
770 void bch2_journal_entry_to_text(struct printbuf *out, struct bch_fs *c,
771                                 struct jset_entry *entry)
772 {
773         if (entry->type < BCH_JSET_ENTRY_NR) {
774                 prt_printf(out, "%s: ", bch2_jset_entry_types[entry->type]);
775                 bch2_jset_entry_ops[entry->type].to_text(out, c, entry);
776         } else {
777                 prt_printf(out, "(unknown type %u)", entry->type);
778         }
779 }
780
781 static int jset_validate_entries(struct bch_fs *c, struct jset *jset,
782                                  enum bkey_invalid_flags flags)
783 {
784         unsigned version = le32_to_cpu(jset->version);
785         int ret = 0;
786
787         vstruct_for_each(jset, entry) {
788                 if (journal_entry_err_on(vstruct_next(entry) > vstruct_last(jset),
789                                 c, version, jset, entry,
790                                 journal_entry_past_jset_end,
791                                 "journal entry extends past end of jset")) {
792                         jset->u64s = cpu_to_le32((u64 *) entry - jset->_data);
793                         break;
794                 }
795
796                 ret = bch2_journal_entry_validate(c, jset, entry,
797                                         version, JSET_BIG_ENDIAN(jset), flags);
798                 if (ret)
799                         break;
800         }
801 fsck_err:
802         return ret;
803 }
804
805 static int jset_validate(struct bch_fs *c,
806                          struct bch_dev *ca,
807                          struct jset *jset, u64 sector,
808                          enum bkey_invalid_flags flags)
809 {
810         unsigned version;
811         int ret = 0;
812
813         if (le64_to_cpu(jset->magic) != jset_magic(c))
814                 return JOURNAL_ENTRY_NONE;
815
816         version = le32_to_cpu(jset->version);
817         if (journal_entry_err_on(!bch2_version_compatible(version),
818                         c, version, jset, NULL,
819                         jset_unsupported_version,
820                         "%s sector %llu seq %llu: incompatible journal entry version %u.%u",
821                         ca ? ca->name : c->name,
822                         sector, le64_to_cpu(jset->seq),
823                         BCH_VERSION_MAJOR(version),
824                         BCH_VERSION_MINOR(version))) {
825                 /* don't try to continue: */
826                 return -EINVAL;
827         }
828
829         if (journal_entry_err_on(!bch2_checksum_type_valid(c, JSET_CSUM_TYPE(jset)),
830                         c, version, jset, NULL,
831                         jset_unknown_csum,
832                         "%s sector %llu seq %llu: journal entry with unknown csum type %llu",
833                         ca ? ca->name : c->name,
834                         sector, le64_to_cpu(jset->seq),
835                         JSET_CSUM_TYPE(jset)))
836                 ret = JOURNAL_ENTRY_BAD;
837
838         /* last_seq is ignored when JSET_NO_FLUSH is true */
839         if (journal_entry_err_on(!JSET_NO_FLUSH(jset) &&
840                                  le64_to_cpu(jset->last_seq) > le64_to_cpu(jset->seq),
841                                  c, version, jset, NULL,
842                                  jset_last_seq_newer_than_seq,
843                                  "invalid journal entry: last_seq > seq (%llu > %llu)",
844                                  le64_to_cpu(jset->last_seq),
845                                  le64_to_cpu(jset->seq))) {
846                 jset->last_seq = jset->seq;
847                 return JOURNAL_ENTRY_BAD;
848         }
849
850         ret = jset_validate_entries(c, jset, flags);
851 fsck_err:
852         return ret;
853 }
854
855 static int jset_validate_early(struct bch_fs *c,
856                          struct bch_dev *ca,
857                          struct jset *jset, u64 sector,
858                          unsigned bucket_sectors_left,
859                          unsigned sectors_read)
860 {
861         size_t bytes = vstruct_bytes(jset);
862         unsigned version;
863         enum bkey_invalid_flags flags = BKEY_INVALID_JOURNAL;
864         int ret = 0;
865
866         if (le64_to_cpu(jset->magic) != jset_magic(c))
867                 return JOURNAL_ENTRY_NONE;
868
869         version = le32_to_cpu(jset->version);
870         if (journal_entry_err_on(!bch2_version_compatible(version),
871                         c, version, jset, NULL,
872                         jset_unsupported_version,
873                         "%s sector %llu seq %llu: unknown journal entry version %u.%u",
874                         ca ? ca->name : c->name,
875                         sector, le64_to_cpu(jset->seq),
876                         BCH_VERSION_MAJOR(version),
877                         BCH_VERSION_MINOR(version))) {
878                 /* don't try to continue: */
879                 return -EINVAL;
880         }
881
882         if (bytes > (sectors_read << 9) &&
883             sectors_read < bucket_sectors_left)
884                 return JOURNAL_ENTRY_REREAD;
885
886         if (journal_entry_err_on(bytes > bucket_sectors_left << 9,
887                         c, version, jset, NULL,
888                         jset_past_bucket_end,
889                         "%s sector %llu seq %llu: journal entry too big (%zu bytes)",
890                         ca ? ca->name : c->name,
891                         sector, le64_to_cpu(jset->seq), bytes))
892                 le32_add_cpu(&jset->u64s,
893                              -((bytes - (bucket_sectors_left << 9)) / 8));
894 fsck_err:
895         return ret;
896 }
897
898 struct journal_read_buf {
899         void            *data;
900         size_t          size;
901 };
902
903 static int journal_read_buf_realloc(struct journal_read_buf *b,
904                                     size_t new_size)
905 {
906         void *n;
907
908         /* the bios are sized for this many pages, max: */
909         if (new_size > JOURNAL_ENTRY_SIZE_MAX)
910                 return -BCH_ERR_ENOMEM_journal_read_buf_realloc;
911
912         new_size = roundup_pow_of_two(new_size);
913         n = kvpmalloc(new_size, GFP_KERNEL);
914         if (!n)
915                 return -BCH_ERR_ENOMEM_journal_read_buf_realloc;
916
917         kvpfree(b->data, b->size);
918         b->data = n;
919         b->size = new_size;
920         return 0;
921 }
922
923 static int journal_read_bucket(struct bch_dev *ca,
924                                struct journal_read_buf *buf,
925                                struct journal_list *jlist,
926                                unsigned bucket)
927 {
928         struct bch_fs *c = ca->fs;
929         struct journal_device *ja = &ca->journal;
930         struct jset *j = NULL;
931         unsigned sectors, sectors_read = 0;
932         u64 offset = bucket_to_sector(ca, ja->buckets[bucket]),
933             end = offset + ca->mi.bucket_size;
934         bool saw_bad = false, csum_good;
935         int ret = 0;
936
937         pr_debug("reading %u", bucket);
938
939         while (offset < end) {
940                 if (!sectors_read) {
941                         struct bio *bio;
942                         unsigned nr_bvecs;
943 reread:
944                         sectors_read = min_t(unsigned,
945                                 end - offset, buf->size >> 9);
946                         nr_bvecs = buf_pages(buf->data, sectors_read << 9);
947
948                         bio = bio_kmalloc(nr_bvecs, GFP_KERNEL);
949                         bio_init(bio, ca->disk_sb.bdev, bio->bi_inline_vecs, nr_bvecs, REQ_OP_READ);
950
951                         bio->bi_iter.bi_sector = offset;
952                         bch2_bio_map(bio, buf->data, sectors_read << 9);
953
954                         ret = submit_bio_wait(bio);
955                         kfree(bio);
956
957                         if (bch2_dev_io_err_on(ret, ca, BCH_MEMBER_ERROR_read,
958                                                "journal read error: sector %llu",
959                                                offset) ||
960                             bch2_meta_read_fault("journal")) {
961                                 /*
962                                  * We don't error out of the recovery process
963                                  * here, since the relevant journal entry may be
964                                  * found on a different device, and missing or
965                                  * no journal entries will be handled later
966                                  */
967                                 return 0;
968                         }
969
970                         j = buf->data;
971                 }
972
973                 ret = jset_validate_early(c, ca, j, offset,
974                                     end - offset, sectors_read);
975                 switch (ret) {
976                 case 0:
977                         sectors = vstruct_sectors(j, c->block_bits);
978                         break;
979                 case JOURNAL_ENTRY_REREAD:
980                         if (vstruct_bytes(j) > buf->size) {
981                                 ret = journal_read_buf_realloc(buf,
982                                                         vstruct_bytes(j));
983                                 if (ret)
984                                         return ret;
985                         }
986                         goto reread;
987                 case JOURNAL_ENTRY_NONE:
988                         if (!saw_bad)
989                                 return 0;
990                         /*
991                          * On checksum error we don't really trust the size
992                          * field of the journal entry we read, so try reading
993                          * again at next block boundary:
994                          */
995                         sectors = block_sectors(c);
996                         goto next_block;
997                 default:
998                         return ret;
999                 }
1000
1001                 /*
1002                  * This happens sometimes if we don't have discards on -
1003                  * when we've partially overwritten a bucket with new
1004                  * journal entries. We don't need the rest of the
1005                  * bucket:
1006                  */
1007                 if (le64_to_cpu(j->seq) < ja->bucket_seq[bucket])
1008                         return 0;
1009
1010                 ja->bucket_seq[bucket] = le64_to_cpu(j->seq);
1011
1012                 csum_good = jset_csum_good(c, j);
1013                 if (bch2_dev_io_err_on(!csum_good, ca, BCH_MEMBER_ERROR_checksum,
1014                                        "journal checksum error"))
1015                         saw_bad = true;
1016
1017                 ret = bch2_encrypt(c, JSET_CSUM_TYPE(j), journal_nonce(j),
1018                              j->encrypted_start,
1019                              vstruct_end(j) - (void *) j->encrypted_start);
1020                 bch2_fs_fatal_err_on(ret, c,
1021                                 "error decrypting journal entry: %i", ret);
1022
1023                 mutex_lock(&jlist->lock);
1024                 ret = journal_entry_add(c, ca, (struct journal_ptr) {
1025                                         .csum_good      = csum_good,
1026                                         .dev            = ca->dev_idx,
1027                                         .bucket         = bucket,
1028                                         .bucket_offset  = offset -
1029                                                 bucket_to_sector(ca, ja->buckets[bucket]),
1030                                         .sector         = offset,
1031                                         }, jlist, j);
1032                 mutex_unlock(&jlist->lock);
1033
1034                 switch (ret) {
1035                 case JOURNAL_ENTRY_ADD_OK:
1036                         break;
1037                 case JOURNAL_ENTRY_ADD_OUT_OF_RANGE:
1038                         break;
1039                 default:
1040                         return ret;
1041                 }
1042 next_block:
1043                 pr_debug("next");
1044                 offset          += sectors;
1045                 sectors_read    -= sectors;
1046                 j = ((void *) j) + (sectors << 9);
1047         }
1048
1049         return 0;
1050 }
1051
1052 static CLOSURE_CALLBACK(bch2_journal_read_device)
1053 {
1054         closure_type(ja, struct journal_device, read);
1055         struct bch_dev *ca = container_of(ja, struct bch_dev, journal);
1056         struct bch_fs *c = ca->fs;
1057         struct journal_list *jlist =
1058                 container_of(cl->parent, struct journal_list, cl);
1059         struct journal_replay *r, **_r;
1060         struct genradix_iter iter;
1061         struct journal_read_buf buf = { NULL, 0 };
1062         unsigned i;
1063         int ret = 0;
1064
1065         if (!ja->nr)
1066                 goto out;
1067
1068         ret = journal_read_buf_realloc(&buf, PAGE_SIZE);
1069         if (ret)
1070                 goto err;
1071
1072         pr_debug("%u journal buckets", ja->nr);
1073
1074         for (i = 0; i < ja->nr; i++) {
1075                 ret = journal_read_bucket(ca, &buf, jlist, i);
1076                 if (ret)
1077                         goto err;
1078         }
1079
1080         ja->sectors_free = ca->mi.bucket_size;
1081
1082         mutex_lock(&jlist->lock);
1083         genradix_for_each_reverse(&c->journal_entries, iter, _r) {
1084                 r = *_r;
1085
1086                 if (!r)
1087                         continue;
1088
1089                 for (i = 0; i < r->nr_ptrs; i++) {
1090                         if (r->ptrs[i].dev == ca->dev_idx) {
1091                                 unsigned wrote = bucket_remainder(ca, r->ptrs[i].sector) +
1092                                         vstruct_sectors(&r->j, c->block_bits);
1093
1094                                 ja->cur_idx = r->ptrs[i].bucket;
1095                                 ja->sectors_free = ca->mi.bucket_size - wrote;
1096                                 goto found;
1097                         }
1098                 }
1099         }
1100 found:
1101         mutex_unlock(&jlist->lock);
1102
1103         if (ja->bucket_seq[ja->cur_idx] &&
1104             ja->sectors_free == ca->mi.bucket_size) {
1105 #if 0
1106                 /*
1107                  * Debug code for ZNS support, where we (probably) want to be
1108                  * correlated where we stopped in the journal to the zone write
1109                  * points:
1110                  */
1111                 bch_err(c, "ja->sectors_free == ca->mi.bucket_size");
1112                 bch_err(c, "cur_idx %u/%u", ja->cur_idx, ja->nr);
1113                 for (i = 0; i < 3; i++) {
1114                         unsigned idx = (ja->cur_idx + ja->nr - 1 + i) % ja->nr;
1115
1116                         bch_err(c, "bucket_seq[%u] = %llu", idx, ja->bucket_seq[idx]);
1117                 }
1118 #endif
1119                 ja->sectors_free = 0;
1120         }
1121
1122         /*
1123          * Set dirty_idx to indicate the entire journal is full and needs to be
1124          * reclaimed - journal reclaim will immediately reclaim whatever isn't
1125          * pinned when it first runs:
1126          */
1127         ja->discard_idx = ja->dirty_idx_ondisk =
1128                 ja->dirty_idx = (ja->cur_idx + 1) % ja->nr;
1129 out:
1130         bch_verbose(c, "journal read done on device %s, ret %i", ca->name, ret);
1131         kvpfree(buf.data, buf.size);
1132         percpu_ref_put(&ca->io_ref);
1133         closure_return(cl);
1134         return;
1135 err:
1136         mutex_lock(&jlist->lock);
1137         jlist->ret = ret;
1138         mutex_unlock(&jlist->lock);
1139         goto out;
1140 }
1141
1142 void bch2_journal_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
1143                                struct journal_replay *j)
1144 {
1145         unsigned i;
1146
1147         for (i = 0; i < j->nr_ptrs; i++) {
1148                 struct bch_dev *ca = bch_dev_bkey_exists(c, j->ptrs[i].dev);
1149                 u64 offset;
1150
1151                 div64_u64_rem(j->ptrs[i].sector, ca->mi.bucket_size, &offset);
1152
1153                 if (i)
1154                         prt_printf(out, " ");
1155                 prt_printf(out, "%u:%u:%u (sector %llu)",
1156                        j->ptrs[i].dev,
1157                        j->ptrs[i].bucket,
1158                        j->ptrs[i].bucket_offset,
1159                        j->ptrs[i].sector);
1160         }
1161 }
1162
1163 int bch2_journal_read(struct bch_fs *c,
1164                       u64 *last_seq,
1165                       u64 *blacklist_seq,
1166                       u64 *start_seq)
1167 {
1168         struct journal_list jlist;
1169         struct journal_replay *i, **_i, *prev = NULL;
1170         struct genradix_iter radix_iter;
1171         struct printbuf buf = PRINTBUF;
1172         bool degraded = false, last_write_torn = false;
1173         u64 seq;
1174         int ret = 0;
1175
1176         closure_init_stack(&jlist.cl);
1177         mutex_init(&jlist.lock);
1178         jlist.last_seq = 0;
1179         jlist.ret = 0;
1180
1181         for_each_member_device(c, ca) {
1182                 if (!c->opts.fsck &&
1183                     !(bch2_dev_has_data(c, ca) & (1 << BCH_DATA_journal)))
1184                         continue;
1185
1186                 if ((ca->mi.state == BCH_MEMBER_STATE_rw ||
1187                      ca->mi.state == BCH_MEMBER_STATE_ro) &&
1188                     percpu_ref_tryget(&ca->io_ref))
1189                         closure_call(&ca->journal.read,
1190                                      bch2_journal_read_device,
1191                                      system_unbound_wq,
1192                                      &jlist.cl);
1193                 else
1194                         degraded = true;
1195         }
1196
1197         closure_sync(&jlist.cl);
1198
1199         if (jlist.ret)
1200                 return jlist.ret;
1201
1202         *last_seq       = 0;
1203         *start_seq      = 0;
1204         *blacklist_seq  = 0;
1205
1206         /*
1207          * Find most recent flush entry, and ignore newer non flush entries -
1208          * those entries will be blacklisted:
1209          */
1210         genradix_for_each_reverse(&c->journal_entries, radix_iter, _i) {
1211                 enum bkey_invalid_flags flags = BKEY_INVALID_JOURNAL;
1212
1213                 i = *_i;
1214
1215                 if (!i || i->ignore)
1216                         continue;
1217
1218                 if (!*start_seq)
1219                         *blacklist_seq = *start_seq = le64_to_cpu(i->j.seq) + 1;
1220
1221                 if (JSET_NO_FLUSH(&i->j)) {
1222                         i->ignore = true;
1223                         continue;
1224                 }
1225
1226                 if (!last_write_torn && !i->csum_good) {
1227                         last_write_torn = true;
1228                         i->ignore = true;
1229                         continue;
1230                 }
1231
1232                 if (journal_entry_err_on(le64_to_cpu(i->j.last_seq) > le64_to_cpu(i->j.seq),
1233                                          c, le32_to_cpu(i->j.version), &i->j, NULL,
1234                                          jset_last_seq_newer_than_seq,
1235                                          "invalid journal entry: last_seq > seq (%llu > %llu)",
1236                                          le64_to_cpu(i->j.last_seq),
1237                                          le64_to_cpu(i->j.seq)))
1238                         i->j.last_seq = i->j.seq;
1239
1240                 *last_seq       = le64_to_cpu(i->j.last_seq);
1241                 *blacklist_seq  = le64_to_cpu(i->j.seq) + 1;
1242                 break;
1243         }
1244
1245         if (!*start_seq) {
1246                 bch_info(c, "journal read done, but no entries found");
1247                 return 0;
1248         }
1249
1250         if (!*last_seq) {
1251                 fsck_err(c, dirty_but_no_journal_entries_post_drop_nonflushes,
1252                          "journal read done, but no entries found after dropping non-flushes");
1253                 return 0;
1254         }
1255
1256         bch_info(c, "journal read done, replaying entries %llu-%llu",
1257                  *last_seq, *blacklist_seq - 1);
1258
1259         if (*start_seq != *blacklist_seq)
1260                 bch_info(c, "dropped unflushed entries %llu-%llu",
1261                          *blacklist_seq, *start_seq - 1);
1262
1263         /* Drop blacklisted entries and entries older than last_seq: */
1264         genradix_for_each(&c->journal_entries, radix_iter, _i) {
1265                 i = *_i;
1266
1267                 if (!i || i->ignore)
1268                         continue;
1269
1270                 seq = le64_to_cpu(i->j.seq);
1271                 if (seq < *last_seq) {
1272                         journal_replay_free(c, i);
1273                         continue;
1274                 }
1275
1276                 if (bch2_journal_seq_is_blacklisted(c, seq, true)) {
1277                         fsck_err_on(!JSET_NO_FLUSH(&i->j), c,
1278                                     jset_seq_blacklisted,
1279                                     "found blacklisted journal entry %llu", seq);
1280                         i->ignore = true;
1281                 }
1282         }
1283
1284         /* Check for missing entries: */
1285         seq = *last_seq;
1286         genradix_for_each(&c->journal_entries, radix_iter, _i) {
1287                 i = *_i;
1288
1289                 if (!i || i->ignore)
1290                         continue;
1291
1292                 BUG_ON(seq > le64_to_cpu(i->j.seq));
1293
1294                 while (seq < le64_to_cpu(i->j.seq)) {
1295                         u64 missing_start, missing_end;
1296                         struct printbuf buf1 = PRINTBUF, buf2 = PRINTBUF;
1297
1298                         while (seq < le64_to_cpu(i->j.seq) &&
1299                                bch2_journal_seq_is_blacklisted(c, seq, false))
1300                                 seq++;
1301
1302                         if (seq == le64_to_cpu(i->j.seq))
1303                                 break;
1304
1305                         missing_start = seq;
1306
1307                         while (seq < le64_to_cpu(i->j.seq) &&
1308                                !bch2_journal_seq_is_blacklisted(c, seq, false))
1309                                 seq++;
1310
1311                         if (prev) {
1312                                 bch2_journal_ptrs_to_text(&buf1, c, prev);
1313                                 prt_printf(&buf1, " size %zu", vstruct_sectors(&prev->j, c->block_bits));
1314                         } else
1315                                 prt_printf(&buf1, "(none)");
1316                         bch2_journal_ptrs_to_text(&buf2, c, i);
1317
1318                         missing_end = seq - 1;
1319                         fsck_err(c, journal_entries_missing,
1320                                  "journal entries %llu-%llu missing! (replaying %llu-%llu)\n"
1321                                  "  prev at %s\n"
1322                                  "  next at %s",
1323                                  missing_start, missing_end,
1324                                  *last_seq, *blacklist_seq - 1,
1325                                  buf1.buf, buf2.buf);
1326
1327                         printbuf_exit(&buf1);
1328                         printbuf_exit(&buf2);
1329                 }
1330
1331                 prev = i;
1332                 seq++;
1333         }
1334
1335         genradix_for_each(&c->journal_entries, radix_iter, _i) {
1336                 struct bch_replicas_padded replicas = {
1337                         .e.data_type = BCH_DATA_journal,
1338                         .e.nr_required = 1,
1339                 };
1340                 unsigned ptr;
1341
1342                 i = *_i;
1343                 if (!i || i->ignore)
1344                         continue;
1345
1346                 for (ptr = 0; ptr < i->nr_ptrs; ptr++) {
1347                         struct bch_dev *ca = bch_dev_bkey_exists(c, i->ptrs[ptr].dev);
1348
1349                         if (!i->ptrs[ptr].csum_good)
1350                                 bch_err_dev_offset(ca, i->ptrs[ptr].sector,
1351                                                    "invalid journal checksum, seq %llu%s",
1352                                                    le64_to_cpu(i->j.seq),
1353                                                    i->csum_good ? " (had good copy on another device)" : "");
1354                 }
1355
1356                 ret = jset_validate(c,
1357                                     bch_dev_bkey_exists(c, i->ptrs[0].dev),
1358                                     &i->j,
1359                                     i->ptrs[0].sector,
1360                                     READ);
1361                 if (ret)
1362                         goto err;
1363
1364                 for (ptr = 0; ptr < i->nr_ptrs; ptr++)
1365                         replicas.e.devs[replicas.e.nr_devs++] = i->ptrs[ptr].dev;
1366
1367                 bch2_replicas_entry_sort(&replicas.e);
1368
1369                 printbuf_reset(&buf);
1370                 bch2_replicas_entry_to_text(&buf, &replicas.e);
1371
1372                 if (!degraded &&
1373                     !bch2_replicas_marked(c, &replicas.e) &&
1374                     (le64_to_cpu(i->j.seq) == *last_seq ||
1375                      fsck_err(c, journal_entry_replicas_not_marked,
1376                               "superblock not marked as containing replicas for journal entry %llu\n  %s",
1377                               le64_to_cpu(i->j.seq), buf.buf))) {
1378                         ret = bch2_mark_replicas(c, &replicas.e);
1379                         if (ret)
1380                                 goto err;
1381                 }
1382         }
1383 err:
1384 fsck_err:
1385         printbuf_exit(&buf);
1386         return ret;
1387 }
1388
1389 /* journal write: */
1390
1391 static void __journal_write_alloc(struct journal *j,
1392                                   struct journal_buf *w,
1393                                   struct dev_alloc_list *devs_sorted,
1394                                   unsigned sectors,
1395                                   unsigned *replicas,
1396                                   unsigned replicas_want)
1397 {
1398         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1399         struct journal_device *ja;
1400         struct bch_dev *ca;
1401         unsigned i;
1402
1403         if (*replicas >= replicas_want)
1404                 return;
1405
1406         for (i = 0; i < devs_sorted->nr; i++) {
1407                 ca = rcu_dereference(c->devs[devs_sorted->devs[i]]);
1408                 if (!ca)
1409                         continue;
1410
1411                 ja = &ca->journal;
1412
1413                 /*
1414                  * Check that we can use this device, and aren't already using
1415                  * it:
1416                  */
1417                 if (!ca->mi.durability ||
1418                     ca->mi.state != BCH_MEMBER_STATE_rw ||
1419                     !ja->nr ||
1420                     bch2_bkey_has_device_c(bkey_i_to_s_c(&w->key), ca->dev_idx) ||
1421                     sectors > ja->sectors_free)
1422                         continue;
1423
1424                 bch2_dev_stripe_increment(ca, &j->wp.stripe);
1425
1426                 bch2_bkey_append_ptr(&w->key,
1427                         (struct bch_extent_ptr) {
1428                                   .offset = bucket_to_sector(ca,
1429                                         ja->buckets[ja->cur_idx]) +
1430                                         ca->mi.bucket_size -
1431                                         ja->sectors_free,
1432                                   .dev = ca->dev_idx,
1433                 });
1434
1435                 ja->sectors_free -= sectors;
1436                 ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq);
1437
1438                 *replicas += ca->mi.durability;
1439
1440                 if (*replicas >= replicas_want)
1441                         break;
1442         }
1443 }
1444
1445 /**
1446  * journal_write_alloc - decide where to write next journal entry
1447  *
1448  * @j:          journal object
1449  * @w:          journal buf (entry to be written)
1450  *
1451  * Returns: 0 on success, or -EROFS on failure
1452  */
1453 static int journal_write_alloc(struct journal *j, struct journal_buf *w)
1454 {
1455         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1456         struct bch_devs_mask devs;
1457         struct journal_device *ja;
1458         struct bch_dev *ca;
1459         struct dev_alloc_list devs_sorted;
1460         unsigned sectors = vstruct_sectors(w->data, c->block_bits);
1461         unsigned target = c->opts.metadata_target ?:
1462                 c->opts.foreground_target;
1463         unsigned i, replicas = 0, replicas_want =
1464                 READ_ONCE(c->opts.metadata_replicas);
1465
1466         rcu_read_lock();
1467 retry:
1468         devs = target_rw_devs(c, BCH_DATA_journal, target);
1469
1470         devs_sorted = bch2_dev_alloc_list(c, &j->wp.stripe, &devs);
1471
1472         __journal_write_alloc(j, w, &devs_sorted,
1473                               sectors, &replicas, replicas_want);
1474
1475         if (replicas >= replicas_want)
1476                 goto done;
1477
1478         for (i = 0; i < devs_sorted.nr; i++) {
1479                 ca = rcu_dereference(c->devs[devs_sorted.devs[i]]);
1480                 if (!ca)
1481                         continue;
1482
1483                 ja = &ca->journal;
1484
1485                 if (sectors > ja->sectors_free &&
1486                     sectors <= ca->mi.bucket_size &&
1487                     bch2_journal_dev_buckets_available(j, ja,
1488                                         journal_space_discarded)) {
1489                         ja->cur_idx = (ja->cur_idx + 1) % ja->nr;
1490                         ja->sectors_free = ca->mi.bucket_size;
1491
1492                         /*
1493                          * ja->bucket_seq[ja->cur_idx] must always have
1494                          * something sensible:
1495                          */
1496                         ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq);
1497                 }
1498         }
1499
1500         __journal_write_alloc(j, w, &devs_sorted,
1501                               sectors, &replicas, replicas_want);
1502
1503         if (replicas < replicas_want && target) {
1504                 /* Retry from all devices: */
1505                 target = 0;
1506                 goto retry;
1507         }
1508 done:
1509         rcu_read_unlock();
1510
1511         BUG_ON(bkey_val_u64s(&w->key.k) > BCH_REPLICAS_MAX);
1512
1513         return replicas >= c->opts.metadata_replicas_required ? 0 : -EROFS;
1514 }
1515
1516 static void journal_buf_realloc(struct journal *j, struct journal_buf *buf)
1517 {
1518         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1519
1520         /* we aren't holding j->lock: */
1521         unsigned new_size = READ_ONCE(j->buf_size_want);
1522         void *new_buf;
1523
1524         if (buf->buf_size >= new_size)
1525                 return;
1526
1527         size_t btree_write_buffer_size = new_size / 64;
1528
1529         if (bch2_btree_write_buffer_resize(c, btree_write_buffer_size))
1530                 return;
1531
1532         new_buf = kvpmalloc(new_size, GFP_NOFS|__GFP_NOWARN);
1533         if (!new_buf)
1534                 return;
1535
1536         memcpy(new_buf, buf->data, buf->buf_size);
1537
1538         spin_lock(&j->lock);
1539         swap(buf->data,         new_buf);
1540         swap(buf->buf_size,     new_size);
1541         spin_unlock(&j->lock);
1542
1543         kvpfree(new_buf, new_size);
1544 }
1545
1546 static inline struct journal_buf *journal_last_unwritten_buf(struct journal *j)
1547 {
1548         return j->buf + (journal_last_unwritten_seq(j) & JOURNAL_BUF_MASK);
1549 }
1550
1551 static CLOSURE_CALLBACK(journal_write_done)
1552 {
1553         closure_type(j, struct journal, io);
1554         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1555         struct journal_buf *w = journal_last_unwritten_buf(j);
1556         struct bch_replicas_padded replicas;
1557         union journal_res_state old, new;
1558         u64 v, seq;
1559         int err = 0;
1560
1561         bch2_time_stats_update(!JSET_NO_FLUSH(w->data)
1562                                ? j->flush_write_time
1563                                : j->noflush_write_time, j->write_start_time);
1564
1565         if (!w->devs_written.nr) {
1566                 bch_err(c, "unable to write journal to sufficient devices");
1567                 err = -EIO;
1568         } else {
1569                 bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
1570                                          w->devs_written);
1571                 if (bch2_mark_replicas(c, &replicas.e))
1572                         err = -EIO;
1573         }
1574
1575         if (err)
1576                 bch2_fatal_error(c);
1577
1578         spin_lock(&j->lock);
1579         seq = le64_to_cpu(w->data->seq);
1580
1581         if (seq >= j->pin.front)
1582                 journal_seq_pin(j, seq)->devs = w->devs_written;
1583
1584         if (!err) {
1585                 if (!JSET_NO_FLUSH(w->data)) {
1586                         j->flushed_seq_ondisk = seq;
1587                         j->last_seq_ondisk = w->last_seq;
1588
1589                         bch2_do_discards(c);
1590                         closure_wake_up(&c->freelist_wait);
1591
1592                         bch2_reset_alloc_cursors(c);
1593                 }
1594         } else if (!j->err_seq || seq < j->err_seq)
1595                 j->err_seq      = seq;
1596
1597         j->seq_ondisk           = seq;
1598
1599         /*
1600          * Updating last_seq_ondisk may let bch2_journal_reclaim_work() discard
1601          * more buckets:
1602          *
1603          * Must come before signaling write completion, for
1604          * bch2_fs_journal_stop():
1605          */
1606         if (j->watermark != BCH_WATERMARK_stripe)
1607                 journal_reclaim_kick(&c->journal);
1608
1609         /* also must come before signalling write completion: */
1610         closure_debug_destroy(cl);
1611
1612         v = atomic64_read(&j->reservations.counter);
1613         do {
1614                 old.v = new.v = v;
1615                 BUG_ON(journal_state_count(new, new.unwritten_idx));
1616
1617                 new.unwritten_idx++;
1618         } while ((v = atomic64_cmpxchg(&j->reservations.counter,
1619                                        old.v, new.v)) != old.v);
1620
1621         bch2_journal_reclaim_fast(j);
1622         bch2_journal_space_available(j);
1623
1624         track_event_change(&c->times[BCH_TIME_blocked_journal_max_in_flight],
1625                            &j->max_in_flight_start, false);
1626
1627         closure_wake_up(&w->wait);
1628         journal_wake(j);
1629
1630         if (!journal_state_count(new, new.unwritten_idx) &&
1631             journal_last_unwritten_seq(j) <= journal_cur_seq(j)) {
1632                 spin_unlock(&j->lock);
1633                 closure_call(&j->io, bch2_journal_write, c->io_complete_wq, NULL);
1634         } else if (journal_last_unwritten_seq(j) == journal_cur_seq(j) &&
1635                    new.cur_entry_offset < JOURNAL_ENTRY_CLOSED_VAL) {
1636                 struct journal_buf *buf = journal_cur_buf(j);
1637                 long delta = buf->expires - jiffies;
1638
1639                 /*
1640                  * We don't close a journal entry to write it while there's
1641                  * previous entries still in flight - the current journal entry
1642                  * might want to be written now:
1643                  */
1644
1645                 spin_unlock(&j->lock);
1646                 mod_delayed_work(c->io_complete_wq, &j->write_work, max(0L, delta));
1647         } else {
1648                 spin_unlock(&j->lock);
1649         }
1650 }
1651
1652 static void journal_write_endio(struct bio *bio)
1653 {
1654         struct bch_dev *ca = bio->bi_private;
1655         struct journal *j = &ca->fs->journal;
1656         struct journal_buf *w = journal_last_unwritten_buf(j);
1657         unsigned long flags;
1658
1659         if (bch2_dev_io_err_on(bio->bi_status, ca, BCH_MEMBER_ERROR_write,
1660                                "error writing journal entry %llu: %s",
1661                                le64_to_cpu(w->data->seq),
1662                                bch2_blk_status_to_str(bio->bi_status)) ||
1663             bch2_meta_write_fault("journal")) {
1664                 spin_lock_irqsave(&j->err_lock, flags);
1665                 bch2_dev_list_drop_dev(&w->devs_written, ca->dev_idx);
1666                 spin_unlock_irqrestore(&j->err_lock, flags);
1667         }
1668
1669         closure_put(&j->io);
1670         percpu_ref_put(&ca->io_ref);
1671 }
1672
1673 static CLOSURE_CALLBACK(do_journal_write)
1674 {
1675         closure_type(j, struct journal, io);
1676         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1677         struct bch_dev *ca;
1678         struct journal_buf *w = journal_last_unwritten_buf(j);
1679         struct bch_extent_ptr *ptr;
1680         struct bio *bio;
1681         unsigned sectors = vstruct_sectors(w->data, c->block_bits);
1682
1683         extent_for_each_ptr(bkey_i_to_s_extent(&w->key), ptr) {
1684                 ca = bch_dev_bkey_exists(c, ptr->dev);
1685                 if (!percpu_ref_tryget(&ca->io_ref)) {
1686                         /* XXX: fix this */
1687                         bch_err(c, "missing device for journal write\n");
1688                         continue;
1689                 }
1690
1691                 this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_journal],
1692                              sectors);
1693
1694                 bio = ca->journal.bio;
1695                 bio_reset(bio, ca->disk_sb.bdev, REQ_OP_WRITE|REQ_SYNC|REQ_META);
1696                 bio->bi_iter.bi_sector  = ptr->offset;
1697                 bio->bi_end_io          = journal_write_endio;
1698                 bio->bi_private         = ca;
1699
1700                 BUG_ON(bio->bi_iter.bi_sector == ca->prev_journal_sector);
1701                 ca->prev_journal_sector = bio->bi_iter.bi_sector;
1702
1703                 if (!JSET_NO_FLUSH(w->data))
1704                         bio->bi_opf    |= REQ_FUA;
1705                 if (!JSET_NO_FLUSH(w->data) && !w->separate_flush)
1706                         bio->bi_opf    |= REQ_PREFLUSH;
1707
1708                 bch2_bio_map(bio, w->data, sectors << 9);
1709
1710                 trace_and_count(c, journal_write, bio);
1711                 closure_bio_submit(bio, cl);
1712
1713                 ca->journal.bucket_seq[ca->journal.cur_idx] =
1714                         le64_to_cpu(w->data->seq);
1715         }
1716
1717         continue_at(cl, journal_write_done, c->io_complete_wq);
1718 }
1719
1720 static int bch2_journal_write_prep(struct journal *j, struct journal_buf *w)
1721 {
1722         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1723         struct jset_entry *start, *end;
1724         struct jset *jset = w->data;
1725         struct journal_keys_to_wb wb = { NULL };
1726         unsigned sectors, bytes, u64s;
1727         unsigned long btree_roots_have = 0;
1728         bool validate_before_checksum = false;
1729         u64 seq = le64_to_cpu(jset->seq);
1730         int ret;
1731
1732         /*
1733          * Simple compaction, dropping empty jset_entries (from journal
1734          * reservations that weren't fully used) and merging jset_entries that
1735          * can be.
1736          *
1737          * If we wanted to be really fancy here, we could sort all the keys in
1738          * the jset and drop keys that were overwritten - probably not worth it:
1739          */
1740         vstruct_for_each(jset, i) {
1741                 unsigned u64s = le16_to_cpu(i->u64s);
1742
1743                 /* Empty entry: */
1744                 if (!u64s)
1745                         continue;
1746
1747                 /*
1748                  * New btree roots are set by journalling them; when the journal
1749                  * entry gets written we have to propagate them to
1750                  * c->btree_roots
1751                  *
1752                  * But, every journal entry we write has to contain all the
1753                  * btree roots (at least for now); so after we copy btree roots
1754                  * to c->btree_roots we have to get any missing btree roots and
1755                  * add them to this journal entry:
1756                  */
1757                 switch (i->type) {
1758                 case BCH_JSET_ENTRY_btree_root:
1759                         bch2_journal_entry_to_btree_root(c, i);
1760                         __set_bit(i->btree_id, &btree_roots_have);
1761                         break;
1762                 case BCH_JSET_ENTRY_write_buffer_keys:
1763                         EBUG_ON(!w->need_flush_to_write_buffer);
1764
1765                         if (!wb.wb)
1766                                 bch2_journal_keys_to_write_buffer_start(c, &wb, seq);
1767
1768                         struct bkey_i *k;
1769                         jset_entry_for_each_key(i, k) {
1770                                 ret = bch2_journal_key_to_wb(c, &wb, i->btree_id, k);
1771                                 if (ret) {
1772                                         bch2_fs_fatal_error(c, "-ENOMEM flushing journal keys to btree write buffer");
1773                                         bch2_journal_keys_to_write_buffer_end(c, &wb);
1774                                         return ret;
1775                                 }
1776                         }
1777                         i->type = BCH_JSET_ENTRY_btree_keys;
1778                         break;
1779                 }
1780         }
1781
1782         if (wb.wb)
1783                 bch2_journal_keys_to_write_buffer_end(c, &wb);
1784         w->need_flush_to_write_buffer = false;
1785
1786         start = end = vstruct_last(jset);
1787
1788         end     = bch2_btree_roots_to_journal_entries(c, end, btree_roots_have);
1789
1790         bch2_journal_super_entries_add_common(c, &end, seq);
1791         u64s    = (u64 *) end - (u64 *) start;
1792         BUG_ON(u64s > j->entry_u64s_reserved);
1793
1794         le32_add_cpu(&jset->u64s, u64s);
1795
1796         sectors = vstruct_sectors(jset, c->block_bits);
1797         bytes   = vstruct_bytes(jset);
1798
1799         if (sectors > w->sectors) {
1800                 bch2_fs_fatal_error(c, "aieeee! journal write overran available space, %zu > %u (extra %u reserved %u/%u)",
1801                                     vstruct_bytes(jset), w->sectors << 9,
1802                                     u64s, w->u64s_reserved, j->entry_u64s_reserved);
1803                 return -EINVAL;
1804         }
1805
1806         jset->magic             = cpu_to_le64(jset_magic(c));
1807         jset->version           = cpu_to_le32(c->sb.version);
1808
1809         SET_JSET_BIG_ENDIAN(jset, CPU_BIG_ENDIAN);
1810         SET_JSET_CSUM_TYPE(jset, bch2_meta_checksum_type(c));
1811
1812         if (!JSET_NO_FLUSH(jset) && journal_entry_empty(jset))
1813                 j->last_empty_seq = seq;
1814
1815         if (bch2_csum_type_is_encryption(JSET_CSUM_TYPE(jset)))
1816                 validate_before_checksum = true;
1817
1818         if (le32_to_cpu(jset->version) < bcachefs_metadata_version_current)
1819                 validate_before_checksum = true;
1820
1821         if (validate_before_checksum &&
1822             (ret = jset_validate(c, NULL, jset, 0, WRITE)))
1823                 return ret;
1824
1825         ret = bch2_encrypt(c, JSET_CSUM_TYPE(jset), journal_nonce(jset),
1826                     jset->encrypted_start,
1827                     vstruct_end(jset) - (void *) jset->encrypted_start);
1828         if (bch2_fs_fatal_err_on(ret, c,
1829                         "error decrypting journal entry: %i", ret))
1830                 return ret;
1831
1832         jset->csum = csum_vstruct(c, JSET_CSUM_TYPE(jset),
1833                                   journal_nonce(jset), jset);
1834
1835         if (!validate_before_checksum &&
1836             (ret = jset_validate(c, NULL, jset, 0, WRITE)))
1837                 return ret;
1838
1839         memset((void *) jset + bytes, 0, (sectors << 9) - bytes);
1840         return 0;
1841 }
1842
1843 static int bch2_journal_write_pick_flush(struct journal *j, struct journal_buf *w)
1844 {
1845         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1846         int error = bch2_journal_error(j);
1847
1848         /*
1849          * If the journal is in an error state - we did an emergency shutdown -
1850          * we prefer to continue doing journal writes. We just mark them as
1851          * noflush so they'll never be used, but they'll still be visible by the
1852          * list_journal tool - this helps in debugging.
1853          *
1854          * There's a caveat: the first journal write after marking the
1855          * superblock dirty must always be a flush write, because on startup
1856          * from a clean shutdown we didn't necessarily read the journal and the
1857          * new journal write might overwrite whatever was in the journal
1858          * previously - we can't leave the journal without any flush writes in
1859          * it.
1860          *
1861          * So if we're in an error state, and we're still starting up, we don't
1862          * write anything at all.
1863          */
1864         if (error && test_bit(JOURNAL_NEED_FLUSH_WRITE, &j->flags))
1865                 return -EIO;
1866
1867         if (error ||
1868             w->noflush ||
1869             (!w->must_flush &&
1870              (jiffies - j->last_flush_write) < msecs_to_jiffies(c->opts.journal_flush_delay) &&
1871              test_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags))) {
1872                 w->noflush = true;
1873                 SET_JSET_NO_FLUSH(w->data, true);
1874                 w->data->last_seq       = 0;
1875                 w->last_seq             = 0;
1876
1877                 j->nr_noflush_writes++;
1878         } else {
1879                 j->last_flush_write = jiffies;
1880                 j->nr_flush_writes++;
1881                 clear_bit(JOURNAL_NEED_FLUSH_WRITE, &j->flags);
1882         }
1883
1884         return 0;
1885 }
1886
1887 CLOSURE_CALLBACK(bch2_journal_write)
1888 {
1889         closure_type(j, struct journal, io);
1890         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1891         struct journal_buf *w = journal_last_unwritten_buf(j);
1892         struct bch_replicas_padded replicas;
1893         struct bio *bio;
1894         struct printbuf journal_debug_buf = PRINTBUF;
1895         unsigned nr_rw_members = 0;
1896         int ret;
1897
1898         BUG_ON(BCH_SB_CLEAN(c->disk_sb.sb));
1899
1900         j->write_start_time = local_clock();
1901
1902         spin_lock(&j->lock);
1903         ret = bch2_journal_write_pick_flush(j, w);
1904         spin_unlock(&j->lock);
1905         if (ret)
1906                 goto err;
1907
1908         mutex_lock(&j->buf_lock);
1909         journal_buf_realloc(j, w);
1910
1911         ret = bch2_journal_write_prep(j, w);
1912         mutex_unlock(&j->buf_lock);
1913         if (ret)
1914                 goto err;
1915
1916         j->entry_bytes_written += vstruct_bytes(w->data);
1917
1918         while (1) {
1919                 spin_lock(&j->lock);
1920                 ret = journal_write_alloc(j, w);
1921                 if (!ret || !j->can_discard)
1922                         break;
1923
1924                 spin_unlock(&j->lock);
1925                 bch2_journal_do_discards(j);
1926         }
1927
1928         if (ret) {
1929                 __bch2_journal_debug_to_text(&journal_debug_buf, j);
1930                 spin_unlock(&j->lock);
1931                 bch_err(c, "Unable to allocate journal write:\n%s",
1932                         journal_debug_buf.buf);
1933                 printbuf_exit(&journal_debug_buf);
1934                 goto err;
1935         }
1936
1937         /*
1938          * write is allocated, no longer need to account for it in
1939          * bch2_journal_space_available():
1940          */
1941         w->sectors = 0;
1942
1943         /*
1944          * journal entry has been compacted and allocated, recalculate space
1945          * available:
1946          */
1947         bch2_journal_space_available(j);
1948         spin_unlock(&j->lock);
1949
1950         w->devs_written = bch2_bkey_devs(bkey_i_to_s_c(&w->key));
1951
1952         if (c->opts.nochanges)
1953                 goto no_io;
1954
1955         for_each_rw_member(c, ca)
1956                 nr_rw_members++;
1957
1958         if (nr_rw_members > 1)
1959                 w->separate_flush = true;
1960
1961         /*
1962          * Mark journal replicas before we submit the write to guarantee
1963          * recovery will find the journal entries after a crash.
1964          */
1965         bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
1966                                  w->devs_written);
1967         ret = bch2_mark_replicas(c, &replicas.e);
1968         if (ret)
1969                 goto err;
1970
1971         if (!JSET_NO_FLUSH(w->data) && w->separate_flush) {
1972                 for_each_rw_member(c, ca) {
1973                         percpu_ref_get(&ca->io_ref);
1974
1975                         bio = ca->journal.bio;
1976                         bio_reset(bio, ca->disk_sb.bdev, REQ_OP_FLUSH);
1977                         bio->bi_end_io          = journal_write_endio;
1978                         bio->bi_private         = ca;
1979                         closure_bio_submit(bio, cl);
1980                 }
1981         }
1982
1983         continue_at(cl, do_journal_write, c->io_complete_wq);
1984         return;
1985 no_io:
1986         continue_at(cl, journal_write_done, c->io_complete_wq);
1987         return;
1988 err:
1989         bch2_fatal_error(c);
1990         continue_at(cl, journal_write_done, c->io_complete_wq);
1991 }