]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/journal_io.c
Update bcachefs sources to 783085c3cc44 kbuild: Allow gcov to be enabled on the comma...
[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         int ret = 0;
552
553         if (journal_entry_err_on(bytes < sizeof(*u) ||
554                                  bytes < sizeof(*u) + u->r.nr_devs,
555                                  c, version, jset, entry,
556                                  journal_entry_data_usage_bad_size,
557                                  "invalid journal entry usage: bad size")) {
558                 journal_entry_null_range(entry, vstruct_next(entry));
559                 return ret;
560         }
561
562 fsck_err:
563         return ret;
564 }
565
566 static void journal_entry_data_usage_to_text(struct printbuf *out, struct bch_fs *c,
567                                              struct jset_entry *entry)
568 {
569         struct jset_entry_data_usage *u =
570                 container_of(entry, struct jset_entry_data_usage, entry);
571
572         bch2_replicas_entry_to_text(out, &u->r);
573         prt_printf(out, "=%llu", le64_to_cpu(u->v));
574 }
575
576 static int journal_entry_clock_validate(struct bch_fs *c,
577                                 struct jset *jset,
578                                 struct jset_entry *entry,
579                                 unsigned version, int big_endian,
580                                 enum bkey_invalid_flags flags)
581 {
582         struct jset_entry_clock *clock =
583                 container_of(entry, struct jset_entry_clock, entry);
584         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
585         int ret = 0;
586
587         if (journal_entry_err_on(bytes != sizeof(*clock),
588                                  c, version, jset, entry,
589                                  journal_entry_clock_bad_size,
590                                  "bad size")) {
591                 journal_entry_null_range(entry, vstruct_next(entry));
592                 return ret;
593         }
594
595         if (journal_entry_err_on(clock->rw > 1,
596                                  c, version, jset, entry,
597                                  journal_entry_clock_bad_rw,
598                                  "bad rw")) {
599                 journal_entry_null_range(entry, vstruct_next(entry));
600                 return ret;
601         }
602
603 fsck_err:
604         return ret;
605 }
606
607 static void journal_entry_clock_to_text(struct printbuf *out, struct bch_fs *c,
608                                         struct jset_entry *entry)
609 {
610         struct jset_entry_clock *clock =
611                 container_of(entry, struct jset_entry_clock, entry);
612
613         prt_printf(out, "%s=%llu", clock->rw ? "write" : "read", le64_to_cpu(clock->time));
614 }
615
616 static int journal_entry_dev_usage_validate(struct bch_fs *c,
617                                 struct jset *jset,
618                                 struct jset_entry *entry,
619                                 unsigned version, int big_endian,
620                                 enum bkey_invalid_flags flags)
621 {
622         struct jset_entry_dev_usage *u =
623                 container_of(entry, struct jset_entry_dev_usage, entry);
624         unsigned bytes = jset_u64s(le16_to_cpu(entry->u64s)) * sizeof(u64);
625         unsigned expected = sizeof(*u);
626         unsigned dev;
627         int ret = 0;
628
629         if (journal_entry_err_on(bytes < expected,
630                                  c, version, jset, entry,
631                                  journal_entry_dev_usage_bad_size,
632                                  "bad size (%u < %u)",
633                                  bytes, expected)) {
634                 journal_entry_null_range(entry, vstruct_next(entry));
635                 return ret;
636         }
637
638         dev = le32_to_cpu(u->dev);
639
640         if (journal_entry_err_on(!bch2_dev_exists2(c, dev),
641                                  c, version, jset, entry,
642                                  journal_entry_dev_usage_bad_dev,
643                                  "bad dev")) {
644                 journal_entry_null_range(entry, vstruct_next(entry));
645                 return ret;
646         }
647
648         if (journal_entry_err_on(u->pad,
649                                  c, version, jset, entry,
650                                  journal_entry_dev_usage_bad_pad,
651                                  "bad pad")) {
652                 journal_entry_null_range(entry, vstruct_next(entry));
653                 return ret;
654         }
655
656 fsck_err:
657         return ret;
658 }
659
660 static void journal_entry_dev_usage_to_text(struct printbuf *out, struct bch_fs *c,
661                                             struct jset_entry *entry)
662 {
663         struct jset_entry_dev_usage *u =
664                 container_of(entry, struct jset_entry_dev_usage, entry);
665         unsigned i, nr_types = jset_entry_dev_usage_nr_types(u);
666
667         prt_printf(out, "dev=%u", le32_to_cpu(u->dev));
668
669         for (i = 0; i < nr_types; i++) {
670                 if (i < BCH_DATA_NR)
671                         prt_printf(out, " %s", bch2_data_types[i]);
672                 else
673                         prt_printf(out, " (unknown data type %u)", i);
674                 prt_printf(out, ": buckets=%llu sectors=%llu fragmented=%llu",
675                        le64_to_cpu(u->d[i].buckets),
676                        le64_to_cpu(u->d[i].sectors),
677                        le64_to_cpu(u->d[i].fragmented));
678         }
679
680         prt_printf(out, " buckets_ec: %llu", le64_to_cpu(u->buckets_ec));
681 }
682
683 static int journal_entry_log_validate(struct bch_fs *c,
684                                 struct jset *jset,
685                                 struct jset_entry *entry,
686                                 unsigned version, int big_endian,
687                                 enum bkey_invalid_flags flags)
688 {
689         return 0;
690 }
691
692 static void journal_entry_log_to_text(struct printbuf *out, struct bch_fs *c,
693                                       struct jset_entry *entry)
694 {
695         struct jset_entry_log *l = container_of(entry, struct jset_entry_log, entry);
696         unsigned bytes = vstruct_bytes(entry) - offsetof(struct jset_entry_log, d);
697
698         prt_printf(out, "%.*s", bytes, l->d);
699 }
700
701 static int journal_entry_overwrite_validate(struct bch_fs *c,
702                                 struct jset *jset,
703                                 struct jset_entry *entry,
704                                 unsigned version, int big_endian,
705                                 enum bkey_invalid_flags flags)
706 {
707         return journal_entry_btree_keys_validate(c, jset, entry,
708                                 version, big_endian, READ);
709 }
710
711 static void journal_entry_overwrite_to_text(struct printbuf *out, struct bch_fs *c,
712                                             struct jset_entry *entry)
713 {
714         journal_entry_btree_keys_to_text(out, c, entry);
715 }
716
717 static int journal_entry_write_buffer_keys_validate(struct bch_fs *c,
718                                 struct jset *jset,
719                                 struct jset_entry *entry,
720                                 unsigned version, int big_endian,
721                                 enum bkey_invalid_flags flags)
722 {
723         return journal_entry_btree_keys_validate(c, jset, entry,
724                                 version, big_endian, READ);
725 }
726
727 static void journal_entry_write_buffer_keys_to_text(struct printbuf *out, struct bch_fs *c,
728                                             struct jset_entry *entry)
729 {
730         journal_entry_btree_keys_to_text(out, c, entry);
731 }
732
733 struct jset_entry_ops {
734         int (*validate)(struct bch_fs *, struct jset *,
735                         struct jset_entry *, unsigned, int,
736                         enum bkey_invalid_flags);
737         void (*to_text)(struct printbuf *, struct bch_fs *, struct jset_entry *);
738 };
739
740 static const struct jset_entry_ops bch2_jset_entry_ops[] = {
741 #define x(f, nr)                                                \
742         [BCH_JSET_ENTRY_##f]    = (struct jset_entry_ops) {     \
743                 .validate       = journal_entry_##f##_validate, \
744                 .to_text        = journal_entry_##f##_to_text,  \
745         },
746         BCH_JSET_ENTRY_TYPES()
747 #undef x
748 };
749
750 int bch2_journal_entry_validate(struct bch_fs *c,
751                                 struct jset *jset,
752                                 struct jset_entry *entry,
753                                 unsigned version, int big_endian,
754                                 enum bkey_invalid_flags flags)
755 {
756         return entry->type < BCH_JSET_ENTRY_NR
757                 ? bch2_jset_entry_ops[entry->type].validate(c, jset, entry,
758                                 version, big_endian, flags)
759                 : 0;
760 }
761
762 void bch2_journal_entry_to_text(struct printbuf *out, struct bch_fs *c,
763                                 struct jset_entry *entry)
764 {
765         if (entry->type < BCH_JSET_ENTRY_NR) {
766                 prt_printf(out, "%s: ", bch2_jset_entry_types[entry->type]);
767                 bch2_jset_entry_ops[entry->type].to_text(out, c, entry);
768         } else {
769                 prt_printf(out, "(unknown type %u)", entry->type);
770         }
771 }
772
773 static int jset_validate_entries(struct bch_fs *c, struct jset *jset,
774                                  enum bkey_invalid_flags flags)
775 {
776         struct jset_entry *entry;
777         unsigned version = le32_to_cpu(jset->version);
778         int ret = 0;
779
780         vstruct_for_each(jset, entry) {
781                 if (journal_entry_err_on(vstruct_next(entry) > vstruct_last(jset),
782                                 c, version, jset, entry,
783                                 journal_entry_past_jset_end,
784                                 "journal entry extends past end of jset")) {
785                         jset->u64s = cpu_to_le32((u64 *) entry - jset->_data);
786                         break;
787                 }
788
789                 ret = bch2_journal_entry_validate(c, jset, entry,
790                                         version, JSET_BIG_ENDIAN(jset), flags);
791                 if (ret)
792                         break;
793         }
794 fsck_err:
795         return ret;
796 }
797
798 static int jset_validate(struct bch_fs *c,
799                          struct bch_dev *ca,
800                          struct jset *jset, u64 sector,
801                          enum bkey_invalid_flags flags)
802 {
803         unsigned version;
804         int ret = 0;
805
806         if (le64_to_cpu(jset->magic) != jset_magic(c))
807                 return JOURNAL_ENTRY_NONE;
808
809         version = le32_to_cpu(jset->version);
810         if (journal_entry_err_on(!bch2_version_compatible(version),
811                         c, version, jset, NULL,
812                         jset_unsupported_version,
813                         "%s sector %llu seq %llu: incompatible journal entry version %u.%u",
814                         ca ? ca->name : c->name,
815                         sector, le64_to_cpu(jset->seq),
816                         BCH_VERSION_MAJOR(version),
817                         BCH_VERSION_MINOR(version))) {
818                 /* don't try to continue: */
819                 return -EINVAL;
820         }
821
822         if (journal_entry_err_on(!bch2_checksum_type_valid(c, JSET_CSUM_TYPE(jset)),
823                         c, version, jset, NULL,
824                         jset_unknown_csum,
825                         "%s sector %llu seq %llu: journal entry with unknown csum type %llu",
826                         ca ? ca->name : c->name,
827                         sector, le64_to_cpu(jset->seq),
828                         JSET_CSUM_TYPE(jset)))
829                 ret = JOURNAL_ENTRY_BAD;
830
831         /* last_seq is ignored when JSET_NO_FLUSH is true */
832         if (journal_entry_err_on(!JSET_NO_FLUSH(jset) &&
833                                  le64_to_cpu(jset->last_seq) > le64_to_cpu(jset->seq),
834                                  c, version, jset, NULL,
835                                  jset_last_seq_newer_than_seq,
836                                  "invalid journal entry: last_seq > seq (%llu > %llu)",
837                                  le64_to_cpu(jset->last_seq),
838                                  le64_to_cpu(jset->seq))) {
839                 jset->last_seq = jset->seq;
840                 return JOURNAL_ENTRY_BAD;
841         }
842
843         ret = jset_validate_entries(c, jset, flags);
844 fsck_err:
845         return ret;
846 }
847
848 static int jset_validate_early(struct bch_fs *c,
849                          struct bch_dev *ca,
850                          struct jset *jset, u64 sector,
851                          unsigned bucket_sectors_left,
852                          unsigned sectors_read)
853 {
854         size_t bytes = vstruct_bytes(jset);
855         unsigned version;
856         enum bkey_invalid_flags flags = BKEY_INVALID_JOURNAL;
857         int ret = 0;
858
859         if (le64_to_cpu(jset->magic) != jset_magic(c))
860                 return JOURNAL_ENTRY_NONE;
861
862         version = le32_to_cpu(jset->version);
863         if (journal_entry_err_on(!bch2_version_compatible(version),
864                         c, version, jset, NULL,
865                         jset_unsupported_version,
866                         "%s sector %llu seq %llu: unknown journal entry version %u.%u",
867                         ca ? ca->name : c->name,
868                         sector, le64_to_cpu(jset->seq),
869                         BCH_VERSION_MAJOR(version),
870                         BCH_VERSION_MINOR(version))) {
871                 /* don't try to continue: */
872                 return -EINVAL;
873         }
874
875         if (bytes > (sectors_read << 9) &&
876             sectors_read < bucket_sectors_left)
877                 return JOURNAL_ENTRY_REREAD;
878
879         if (journal_entry_err_on(bytes > bucket_sectors_left << 9,
880                         c, version, jset, NULL,
881                         jset_past_bucket_end,
882                         "%s sector %llu seq %llu: journal entry too big (%zu bytes)",
883                         ca ? ca->name : c->name,
884                         sector, le64_to_cpu(jset->seq), bytes))
885                 le32_add_cpu(&jset->u64s,
886                              -((bytes - (bucket_sectors_left << 9)) / 8));
887 fsck_err:
888         return ret;
889 }
890
891 struct journal_read_buf {
892         void            *data;
893         size_t          size;
894 };
895
896 static int journal_read_buf_realloc(struct journal_read_buf *b,
897                                     size_t new_size)
898 {
899         void *n;
900
901         /* the bios are sized for this many pages, max: */
902         if (new_size > JOURNAL_ENTRY_SIZE_MAX)
903                 return -BCH_ERR_ENOMEM_journal_read_buf_realloc;
904
905         new_size = roundup_pow_of_two(new_size);
906         n = kvpmalloc(new_size, GFP_KERNEL);
907         if (!n)
908                 return -BCH_ERR_ENOMEM_journal_read_buf_realloc;
909
910         kvpfree(b->data, b->size);
911         b->data = n;
912         b->size = new_size;
913         return 0;
914 }
915
916 static int journal_read_bucket(struct bch_dev *ca,
917                                struct journal_read_buf *buf,
918                                struct journal_list *jlist,
919                                unsigned bucket)
920 {
921         struct bch_fs *c = ca->fs;
922         struct journal_device *ja = &ca->journal;
923         struct jset *j = NULL;
924         unsigned sectors, sectors_read = 0;
925         u64 offset = bucket_to_sector(ca, ja->buckets[bucket]),
926             end = offset + ca->mi.bucket_size;
927         bool saw_bad = false, csum_good;
928         int ret = 0;
929
930         pr_debug("reading %u", bucket);
931
932         while (offset < end) {
933                 if (!sectors_read) {
934                         struct bio *bio;
935                         unsigned nr_bvecs;
936 reread:
937                         sectors_read = min_t(unsigned,
938                                 end - offset, buf->size >> 9);
939                         nr_bvecs = buf_pages(buf->data, sectors_read << 9);
940
941                         bio = bio_kmalloc(nr_bvecs, GFP_KERNEL);
942                         bio_init(bio, ca->disk_sb.bdev, bio->bi_inline_vecs, nr_bvecs, REQ_OP_READ);
943
944                         bio->bi_iter.bi_sector = offset;
945                         bch2_bio_map(bio, buf->data, sectors_read << 9);
946
947                         ret = submit_bio_wait(bio);
948                         kfree(bio);
949
950                         if (bch2_dev_io_err_on(ret, ca, BCH_MEMBER_ERROR_read,
951                                                "journal read error: sector %llu",
952                                                offset) ||
953                             bch2_meta_read_fault("journal")) {
954                                 /*
955                                  * We don't error out of the recovery process
956                                  * here, since the relevant journal entry may be
957                                  * found on a different device, and missing or
958                                  * no journal entries will be handled later
959                                  */
960                                 return 0;
961                         }
962
963                         j = buf->data;
964                 }
965
966                 ret = jset_validate_early(c, ca, j, offset,
967                                     end - offset, sectors_read);
968                 switch (ret) {
969                 case 0:
970                         sectors = vstruct_sectors(j, c->block_bits);
971                         break;
972                 case JOURNAL_ENTRY_REREAD:
973                         if (vstruct_bytes(j) > buf->size) {
974                                 ret = journal_read_buf_realloc(buf,
975                                                         vstruct_bytes(j));
976                                 if (ret)
977                                         return ret;
978                         }
979                         goto reread;
980                 case JOURNAL_ENTRY_NONE:
981                         if (!saw_bad)
982                                 return 0;
983                         /*
984                          * On checksum error we don't really trust the size
985                          * field of the journal entry we read, so try reading
986                          * again at next block boundary:
987                          */
988                         sectors = block_sectors(c);
989                         goto next_block;
990                 default:
991                         return ret;
992                 }
993
994                 /*
995                  * This happens sometimes if we don't have discards on -
996                  * when we've partially overwritten a bucket with new
997                  * journal entries. We don't need the rest of the
998                  * bucket:
999                  */
1000                 if (le64_to_cpu(j->seq) < ja->bucket_seq[bucket])
1001                         return 0;
1002
1003                 ja->bucket_seq[bucket] = le64_to_cpu(j->seq);
1004
1005                 csum_good = jset_csum_good(c, j);
1006                 if (bch2_dev_io_err_on(!csum_good, ca, BCH_MEMBER_ERROR_checksum,
1007                                        "journal checksum error"))
1008                         saw_bad = true;
1009
1010                 ret = bch2_encrypt(c, JSET_CSUM_TYPE(j), journal_nonce(j),
1011                              j->encrypted_start,
1012                              vstruct_end(j) - (void *) j->encrypted_start);
1013                 bch2_fs_fatal_err_on(ret, c,
1014                                 "error decrypting journal entry: %i", ret);
1015
1016                 mutex_lock(&jlist->lock);
1017                 ret = journal_entry_add(c, ca, (struct journal_ptr) {
1018                                         .csum_good      = csum_good,
1019                                         .dev            = ca->dev_idx,
1020                                         .bucket         = bucket,
1021                                         .bucket_offset  = offset -
1022                                                 bucket_to_sector(ca, ja->buckets[bucket]),
1023                                         .sector         = offset,
1024                                         }, jlist, j);
1025                 mutex_unlock(&jlist->lock);
1026
1027                 switch (ret) {
1028                 case JOURNAL_ENTRY_ADD_OK:
1029                         break;
1030                 case JOURNAL_ENTRY_ADD_OUT_OF_RANGE:
1031                         break;
1032                 default:
1033                         return ret;
1034                 }
1035 next_block:
1036                 pr_debug("next");
1037                 offset          += sectors;
1038                 sectors_read    -= sectors;
1039                 j = ((void *) j) + (sectors << 9);
1040         }
1041
1042         return 0;
1043 }
1044
1045 static CLOSURE_CALLBACK(bch2_journal_read_device)
1046 {
1047         closure_type(ja, struct journal_device, read);
1048         struct bch_dev *ca = container_of(ja, struct bch_dev, journal);
1049         struct bch_fs *c = ca->fs;
1050         struct journal_list *jlist =
1051                 container_of(cl->parent, struct journal_list, cl);
1052         struct journal_replay *r, **_r;
1053         struct genradix_iter iter;
1054         struct journal_read_buf buf = { NULL, 0 };
1055         unsigned i;
1056         int ret = 0;
1057
1058         if (!ja->nr)
1059                 goto out;
1060
1061         ret = journal_read_buf_realloc(&buf, PAGE_SIZE);
1062         if (ret)
1063                 goto err;
1064
1065         pr_debug("%u journal buckets", ja->nr);
1066
1067         for (i = 0; i < ja->nr; i++) {
1068                 ret = journal_read_bucket(ca, &buf, jlist, i);
1069                 if (ret)
1070                         goto err;
1071         }
1072
1073         ja->sectors_free = ca->mi.bucket_size;
1074
1075         mutex_lock(&jlist->lock);
1076         genradix_for_each_reverse(&c->journal_entries, iter, _r) {
1077                 r = *_r;
1078
1079                 if (!r)
1080                         continue;
1081
1082                 for (i = 0; i < r->nr_ptrs; i++) {
1083                         if (r->ptrs[i].dev == ca->dev_idx) {
1084                                 unsigned wrote = bucket_remainder(ca, r->ptrs[i].sector) +
1085                                         vstruct_sectors(&r->j, c->block_bits);
1086
1087                                 ja->cur_idx = r->ptrs[i].bucket;
1088                                 ja->sectors_free = ca->mi.bucket_size - wrote;
1089                                 goto found;
1090                         }
1091                 }
1092         }
1093 found:
1094         mutex_unlock(&jlist->lock);
1095
1096         if (ja->bucket_seq[ja->cur_idx] &&
1097             ja->sectors_free == ca->mi.bucket_size) {
1098 #if 0
1099                 /*
1100                  * Debug code for ZNS support, where we (probably) want to be
1101                  * correlated where we stopped in the journal to the zone write
1102                  * points:
1103                  */
1104                 bch_err(c, "ja->sectors_free == ca->mi.bucket_size");
1105                 bch_err(c, "cur_idx %u/%u", ja->cur_idx, ja->nr);
1106                 for (i = 0; i < 3; i++) {
1107                         unsigned idx = (ja->cur_idx + ja->nr - 1 + i) % ja->nr;
1108
1109                         bch_err(c, "bucket_seq[%u] = %llu", idx, ja->bucket_seq[idx]);
1110                 }
1111 #endif
1112                 ja->sectors_free = 0;
1113         }
1114
1115         /*
1116          * Set dirty_idx to indicate the entire journal is full and needs to be
1117          * reclaimed - journal reclaim will immediately reclaim whatever isn't
1118          * pinned when it first runs:
1119          */
1120         ja->discard_idx = ja->dirty_idx_ondisk =
1121                 ja->dirty_idx = (ja->cur_idx + 1) % ja->nr;
1122 out:
1123         bch_verbose(c, "journal read done on device %s, ret %i", ca->name, ret);
1124         kvpfree(buf.data, buf.size);
1125         percpu_ref_put(&ca->io_ref);
1126         closure_return(cl);
1127         return;
1128 err:
1129         mutex_lock(&jlist->lock);
1130         jlist->ret = ret;
1131         mutex_unlock(&jlist->lock);
1132         goto out;
1133 }
1134
1135 void bch2_journal_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
1136                                struct journal_replay *j)
1137 {
1138         unsigned i;
1139
1140         for (i = 0; i < j->nr_ptrs; i++) {
1141                 struct bch_dev *ca = bch_dev_bkey_exists(c, j->ptrs[i].dev);
1142                 u64 offset;
1143
1144                 div64_u64_rem(j->ptrs[i].sector, ca->mi.bucket_size, &offset);
1145
1146                 if (i)
1147                         prt_printf(out, " ");
1148                 prt_printf(out, "%u:%u:%u (sector %llu)",
1149                        j->ptrs[i].dev,
1150                        j->ptrs[i].bucket,
1151                        j->ptrs[i].bucket_offset,
1152                        j->ptrs[i].sector);
1153         }
1154 }
1155
1156 int bch2_journal_read(struct bch_fs *c,
1157                       u64 *last_seq,
1158                       u64 *blacklist_seq,
1159                       u64 *start_seq)
1160 {
1161         struct journal_list jlist;
1162         struct journal_replay *i, **_i, *prev = NULL;
1163         struct genradix_iter radix_iter;
1164         struct bch_dev *ca;
1165         unsigned iter;
1166         struct printbuf buf = PRINTBUF;
1167         bool degraded = false, last_write_torn = false;
1168         u64 seq;
1169         int ret = 0;
1170
1171         closure_init_stack(&jlist.cl);
1172         mutex_init(&jlist.lock);
1173         jlist.last_seq = 0;
1174         jlist.ret = 0;
1175
1176         for_each_member_device(ca, c, iter) {
1177                 if (!c->opts.fsck &&
1178                     !(bch2_dev_has_data(c, ca) & (1 << BCH_DATA_journal)))
1179                         continue;
1180
1181                 if ((ca->mi.state == BCH_MEMBER_STATE_rw ||
1182                      ca->mi.state == BCH_MEMBER_STATE_ro) &&
1183                     percpu_ref_tryget(&ca->io_ref))
1184                         closure_call(&ca->journal.read,
1185                                      bch2_journal_read_device,
1186                                      system_unbound_wq,
1187                                      &jlist.cl);
1188                 else
1189                         degraded = true;
1190         }
1191
1192         closure_sync(&jlist.cl);
1193
1194         if (jlist.ret)
1195                 return jlist.ret;
1196
1197         *last_seq       = 0;
1198         *start_seq      = 0;
1199         *blacklist_seq  = 0;
1200
1201         /*
1202          * Find most recent flush entry, and ignore newer non flush entries -
1203          * those entries will be blacklisted:
1204          */
1205         genradix_for_each_reverse(&c->journal_entries, radix_iter, _i) {
1206                 enum bkey_invalid_flags flags = BKEY_INVALID_JOURNAL;
1207
1208                 i = *_i;
1209
1210                 if (!i || i->ignore)
1211                         continue;
1212
1213                 if (!*start_seq)
1214                         *blacklist_seq = *start_seq = le64_to_cpu(i->j.seq) + 1;
1215
1216                 if (JSET_NO_FLUSH(&i->j)) {
1217                         i->ignore = true;
1218                         continue;
1219                 }
1220
1221                 if (!last_write_torn && !i->csum_good) {
1222                         last_write_torn = true;
1223                         i->ignore = true;
1224                         continue;
1225                 }
1226
1227                 if (journal_entry_err_on(le64_to_cpu(i->j.last_seq) > le64_to_cpu(i->j.seq),
1228                                          c, le32_to_cpu(i->j.version), &i->j, NULL,
1229                                          jset_last_seq_newer_than_seq,
1230                                          "invalid journal entry: last_seq > seq (%llu > %llu)",
1231                                          le64_to_cpu(i->j.last_seq),
1232                                          le64_to_cpu(i->j.seq)))
1233                         i->j.last_seq = i->j.seq;
1234
1235                 *last_seq       = le64_to_cpu(i->j.last_seq);
1236                 *blacklist_seq  = le64_to_cpu(i->j.seq) + 1;
1237                 break;
1238         }
1239
1240         if (!*start_seq) {
1241                 bch_info(c, "journal read done, but no entries found");
1242                 return 0;
1243         }
1244
1245         if (!*last_seq) {
1246                 fsck_err(c, dirty_but_no_journal_entries_post_drop_nonflushes,
1247                          "journal read done, but no entries found after dropping non-flushes");
1248                 return 0;
1249         }
1250
1251         bch_info(c, "journal read done, replaying entries %llu-%llu",
1252                  *last_seq, *blacklist_seq - 1);
1253
1254         if (*start_seq != *blacklist_seq)
1255                 bch_info(c, "dropped unflushed entries %llu-%llu",
1256                          *blacklist_seq, *start_seq - 1);
1257
1258         /* Drop blacklisted entries and entries older than last_seq: */
1259         genradix_for_each(&c->journal_entries, radix_iter, _i) {
1260                 i = *_i;
1261
1262                 if (!i || i->ignore)
1263                         continue;
1264
1265                 seq = le64_to_cpu(i->j.seq);
1266                 if (seq < *last_seq) {
1267                         journal_replay_free(c, i);
1268                         continue;
1269                 }
1270
1271                 if (bch2_journal_seq_is_blacklisted(c, seq, true)) {
1272                         fsck_err_on(!JSET_NO_FLUSH(&i->j), c,
1273                                     jset_seq_blacklisted,
1274                                     "found blacklisted journal entry %llu", seq);
1275                         i->ignore = true;
1276                 }
1277         }
1278
1279         /* Check for missing entries: */
1280         seq = *last_seq;
1281         genradix_for_each(&c->journal_entries, radix_iter, _i) {
1282                 i = *_i;
1283
1284                 if (!i || i->ignore)
1285                         continue;
1286
1287                 BUG_ON(seq > le64_to_cpu(i->j.seq));
1288
1289                 while (seq < le64_to_cpu(i->j.seq)) {
1290                         u64 missing_start, missing_end;
1291                         struct printbuf buf1 = PRINTBUF, buf2 = PRINTBUF;
1292
1293                         while (seq < le64_to_cpu(i->j.seq) &&
1294                                bch2_journal_seq_is_blacklisted(c, seq, false))
1295                                 seq++;
1296
1297                         if (seq == le64_to_cpu(i->j.seq))
1298                                 break;
1299
1300                         missing_start = seq;
1301
1302                         while (seq < le64_to_cpu(i->j.seq) &&
1303                                !bch2_journal_seq_is_blacklisted(c, seq, false))
1304                                 seq++;
1305
1306                         if (prev) {
1307                                 bch2_journal_ptrs_to_text(&buf1, c, prev);
1308                                 prt_printf(&buf1, " size %zu", vstruct_sectors(&prev->j, c->block_bits));
1309                         } else
1310                                 prt_printf(&buf1, "(none)");
1311                         bch2_journal_ptrs_to_text(&buf2, c, i);
1312
1313                         missing_end = seq - 1;
1314                         fsck_err(c, journal_entries_missing,
1315                                  "journal entries %llu-%llu missing! (replaying %llu-%llu)\n"
1316                                  "  prev at %s\n"
1317                                  "  next at %s",
1318                                  missing_start, missing_end,
1319                                  *last_seq, *blacklist_seq - 1,
1320                                  buf1.buf, buf2.buf);
1321
1322                         printbuf_exit(&buf1);
1323                         printbuf_exit(&buf2);
1324                 }
1325
1326                 prev = i;
1327                 seq++;
1328         }
1329
1330         genradix_for_each(&c->journal_entries, radix_iter, _i) {
1331                 struct bch_replicas_padded replicas = {
1332                         .e.data_type = BCH_DATA_journal,
1333                         .e.nr_required = 1,
1334                 };
1335                 unsigned ptr;
1336
1337                 i = *_i;
1338                 if (!i || i->ignore)
1339                         continue;
1340
1341                 for (ptr = 0; ptr < i->nr_ptrs; ptr++) {
1342                         ca = bch_dev_bkey_exists(c, i->ptrs[ptr].dev);
1343
1344                         if (!i->ptrs[ptr].csum_good)
1345                                 bch_err_dev_offset(ca, i->ptrs[ptr].sector,
1346                                                    "invalid journal checksum, seq %llu%s",
1347                                                    le64_to_cpu(i->j.seq),
1348                                                    i->csum_good ? " (had good copy on another device)" : "");
1349                 }
1350
1351                 ret = jset_validate(c,
1352                                     bch_dev_bkey_exists(c, i->ptrs[0].dev),
1353                                     &i->j,
1354                                     i->ptrs[0].sector,
1355                                     READ);
1356                 if (ret)
1357                         goto err;
1358
1359                 for (ptr = 0; ptr < i->nr_ptrs; ptr++)
1360                         replicas.e.devs[replicas.e.nr_devs++] = i->ptrs[ptr].dev;
1361
1362                 bch2_replicas_entry_sort(&replicas.e);
1363
1364                 printbuf_reset(&buf);
1365                 bch2_replicas_entry_to_text(&buf, &replicas.e);
1366
1367                 if (!degraded &&
1368                     !bch2_replicas_marked(c, &replicas.e) &&
1369                     (le64_to_cpu(i->j.seq) == *last_seq ||
1370                      fsck_err(c, journal_entry_replicas_not_marked,
1371                               "superblock not marked as containing replicas for journal entry %llu\n  %s",
1372                               le64_to_cpu(i->j.seq), buf.buf))) {
1373                         ret = bch2_mark_replicas(c, &replicas.e);
1374                         if (ret)
1375                                 goto err;
1376                 }
1377         }
1378 err:
1379 fsck_err:
1380         printbuf_exit(&buf);
1381         return ret;
1382 }
1383
1384 /* journal write: */
1385
1386 static void __journal_write_alloc(struct journal *j,
1387                                   struct journal_buf *w,
1388                                   struct dev_alloc_list *devs_sorted,
1389                                   unsigned sectors,
1390                                   unsigned *replicas,
1391                                   unsigned replicas_want)
1392 {
1393         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1394         struct journal_device *ja;
1395         struct bch_dev *ca;
1396         unsigned i;
1397
1398         if (*replicas >= replicas_want)
1399                 return;
1400
1401         for (i = 0; i < devs_sorted->nr; i++) {
1402                 ca = rcu_dereference(c->devs[devs_sorted->devs[i]]);
1403                 if (!ca)
1404                         continue;
1405
1406                 ja = &ca->journal;
1407
1408                 /*
1409                  * Check that we can use this device, and aren't already using
1410                  * it:
1411                  */
1412                 if (!ca->mi.durability ||
1413                     ca->mi.state != BCH_MEMBER_STATE_rw ||
1414                     !ja->nr ||
1415                     bch2_bkey_has_device_c(bkey_i_to_s_c(&w->key), ca->dev_idx) ||
1416                     sectors > ja->sectors_free)
1417                         continue;
1418
1419                 bch2_dev_stripe_increment(ca, &j->wp.stripe);
1420
1421                 bch2_bkey_append_ptr(&w->key,
1422                         (struct bch_extent_ptr) {
1423                                   .offset = bucket_to_sector(ca,
1424                                         ja->buckets[ja->cur_idx]) +
1425                                         ca->mi.bucket_size -
1426                                         ja->sectors_free,
1427                                   .dev = ca->dev_idx,
1428                 });
1429
1430                 ja->sectors_free -= sectors;
1431                 ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq);
1432
1433                 *replicas += ca->mi.durability;
1434
1435                 if (*replicas >= replicas_want)
1436                         break;
1437         }
1438 }
1439
1440 /**
1441  * journal_write_alloc - decide where to write next journal entry
1442  *
1443  * @j:          journal object
1444  * @w:          journal buf (entry to be written)
1445  *
1446  * Returns: 0 on success, or -EROFS on failure
1447  */
1448 static int journal_write_alloc(struct journal *j, struct journal_buf *w)
1449 {
1450         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1451         struct bch_devs_mask devs;
1452         struct journal_device *ja;
1453         struct bch_dev *ca;
1454         struct dev_alloc_list devs_sorted;
1455         unsigned sectors = vstruct_sectors(w->data, c->block_bits);
1456         unsigned target = c->opts.metadata_target ?:
1457                 c->opts.foreground_target;
1458         unsigned i, replicas = 0, replicas_want =
1459                 READ_ONCE(c->opts.metadata_replicas);
1460
1461         rcu_read_lock();
1462 retry:
1463         devs = target_rw_devs(c, BCH_DATA_journal, target);
1464
1465         devs_sorted = bch2_dev_alloc_list(c, &j->wp.stripe, &devs);
1466
1467         __journal_write_alloc(j, w, &devs_sorted,
1468                               sectors, &replicas, replicas_want);
1469
1470         if (replicas >= replicas_want)
1471                 goto done;
1472
1473         for (i = 0; i < devs_sorted.nr; i++) {
1474                 ca = rcu_dereference(c->devs[devs_sorted.devs[i]]);
1475                 if (!ca)
1476                         continue;
1477
1478                 ja = &ca->journal;
1479
1480                 if (sectors > ja->sectors_free &&
1481                     sectors <= ca->mi.bucket_size &&
1482                     bch2_journal_dev_buckets_available(j, ja,
1483                                         journal_space_discarded)) {
1484                         ja->cur_idx = (ja->cur_idx + 1) % ja->nr;
1485                         ja->sectors_free = ca->mi.bucket_size;
1486
1487                         /*
1488                          * ja->bucket_seq[ja->cur_idx] must always have
1489                          * something sensible:
1490                          */
1491                         ja->bucket_seq[ja->cur_idx] = le64_to_cpu(w->data->seq);
1492                 }
1493         }
1494
1495         __journal_write_alloc(j, w, &devs_sorted,
1496                               sectors, &replicas, replicas_want);
1497
1498         if (replicas < replicas_want && target) {
1499                 /* Retry from all devices: */
1500                 target = 0;
1501                 goto retry;
1502         }
1503 done:
1504         rcu_read_unlock();
1505
1506         BUG_ON(bkey_val_u64s(&w->key.k) > BCH_REPLICAS_MAX);
1507
1508         return replicas >= c->opts.metadata_replicas_required ? 0 : -EROFS;
1509 }
1510
1511 static void journal_buf_realloc(struct journal *j, struct journal_buf *buf)
1512 {
1513         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1514
1515         /* we aren't holding j->lock: */
1516         unsigned new_size = READ_ONCE(j->buf_size_want);
1517         void *new_buf;
1518
1519         if (buf->buf_size >= new_size)
1520                 return;
1521
1522         size_t btree_write_buffer_size = new_size / 64;
1523
1524         if (bch2_btree_write_buffer_resize(c, btree_write_buffer_size))
1525                 return;
1526
1527         new_buf = kvpmalloc(new_size, GFP_NOFS|__GFP_NOWARN);
1528         if (!new_buf)
1529                 return;
1530
1531         memcpy(new_buf, buf->data, buf->buf_size);
1532
1533         spin_lock(&j->lock);
1534         swap(buf->data,         new_buf);
1535         swap(buf->buf_size,     new_size);
1536         spin_unlock(&j->lock);
1537
1538         kvpfree(new_buf, new_size);
1539 }
1540
1541 static inline struct journal_buf *journal_last_unwritten_buf(struct journal *j)
1542 {
1543         return j->buf + (journal_last_unwritten_seq(j) & JOURNAL_BUF_MASK);
1544 }
1545
1546 static CLOSURE_CALLBACK(journal_write_done)
1547 {
1548         closure_type(j, struct journal, io);
1549         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1550         struct journal_buf *w = journal_last_unwritten_buf(j);
1551         struct bch_replicas_padded replicas;
1552         union journal_res_state old, new;
1553         u64 v, seq;
1554         int err = 0;
1555
1556         bch2_time_stats_update(!JSET_NO_FLUSH(w->data)
1557                                ? j->flush_write_time
1558                                : j->noflush_write_time, j->write_start_time);
1559
1560         if (!w->devs_written.nr) {
1561                 bch_err(c, "unable to write journal to sufficient devices");
1562                 err = -EIO;
1563         } else {
1564                 bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
1565                                          w->devs_written);
1566                 if (bch2_mark_replicas(c, &replicas.e))
1567                         err = -EIO;
1568         }
1569
1570         if (err)
1571                 bch2_fatal_error(c);
1572
1573         spin_lock(&j->lock);
1574         seq = le64_to_cpu(w->data->seq);
1575
1576         if (seq >= j->pin.front)
1577                 journal_seq_pin(j, seq)->devs = w->devs_written;
1578
1579         if (!err) {
1580                 if (!JSET_NO_FLUSH(w->data)) {
1581                         j->flushed_seq_ondisk = seq;
1582                         j->last_seq_ondisk = w->last_seq;
1583
1584                         bch2_do_discards(c);
1585                         closure_wake_up(&c->freelist_wait);
1586
1587                         bch2_reset_alloc_cursors(c);
1588                 }
1589         } else if (!j->err_seq || seq < j->err_seq)
1590                 j->err_seq      = seq;
1591
1592         j->seq_ondisk           = seq;
1593
1594         /*
1595          * Updating last_seq_ondisk may let bch2_journal_reclaim_work() discard
1596          * more buckets:
1597          *
1598          * Must come before signaling write completion, for
1599          * bch2_fs_journal_stop():
1600          */
1601         if (j->watermark != BCH_WATERMARK_stripe)
1602                 journal_reclaim_kick(&c->journal);
1603
1604         /* also must come before signalling write completion: */
1605         closure_debug_destroy(cl);
1606
1607         v = atomic64_read(&j->reservations.counter);
1608         do {
1609                 old.v = new.v = v;
1610                 BUG_ON(journal_state_count(new, new.unwritten_idx));
1611
1612                 new.unwritten_idx++;
1613         } while ((v = atomic64_cmpxchg(&j->reservations.counter,
1614                                        old.v, new.v)) != old.v);
1615
1616         bch2_journal_reclaim_fast(j);
1617         bch2_journal_space_available(j);
1618
1619         track_event_change(&c->times[BCH_TIME_blocked_journal_max_in_flight],
1620                            &j->max_in_flight_start, false);
1621
1622         closure_wake_up(&w->wait);
1623         journal_wake(j);
1624
1625         if (!journal_state_count(new, new.unwritten_idx) &&
1626             journal_last_unwritten_seq(j) <= journal_cur_seq(j)) {
1627                 spin_unlock(&j->lock);
1628                 closure_call(&j->io, bch2_journal_write, c->io_complete_wq, NULL);
1629         } else if (journal_last_unwritten_seq(j) == journal_cur_seq(j) &&
1630                    new.cur_entry_offset < JOURNAL_ENTRY_CLOSED_VAL) {
1631                 struct journal_buf *buf = journal_cur_buf(j);
1632                 long delta = buf->expires - jiffies;
1633
1634                 /*
1635                  * We don't close a journal entry to write it while there's
1636                  * previous entries still in flight - the current journal entry
1637                  * might want to be written now:
1638                  */
1639
1640                 spin_unlock(&j->lock);
1641                 mod_delayed_work(c->io_complete_wq, &j->write_work, max(0L, delta));
1642         } else {
1643                 spin_unlock(&j->lock);
1644         }
1645 }
1646
1647 static void journal_write_endio(struct bio *bio)
1648 {
1649         struct bch_dev *ca = bio->bi_private;
1650         struct journal *j = &ca->fs->journal;
1651         struct journal_buf *w = journal_last_unwritten_buf(j);
1652         unsigned long flags;
1653
1654         if (bch2_dev_io_err_on(bio->bi_status, ca, BCH_MEMBER_ERROR_write,
1655                                "error writing journal entry %llu: %s",
1656                                le64_to_cpu(w->data->seq),
1657                                bch2_blk_status_to_str(bio->bi_status)) ||
1658             bch2_meta_write_fault("journal")) {
1659                 spin_lock_irqsave(&j->err_lock, flags);
1660                 bch2_dev_list_drop_dev(&w->devs_written, ca->dev_idx);
1661                 spin_unlock_irqrestore(&j->err_lock, flags);
1662         }
1663
1664         closure_put(&j->io);
1665         percpu_ref_put(&ca->io_ref);
1666 }
1667
1668 static CLOSURE_CALLBACK(do_journal_write)
1669 {
1670         closure_type(j, struct journal, io);
1671         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1672         struct bch_dev *ca;
1673         struct journal_buf *w = journal_last_unwritten_buf(j);
1674         struct bch_extent_ptr *ptr;
1675         struct bio *bio;
1676         unsigned sectors = vstruct_sectors(w->data, c->block_bits);
1677
1678         extent_for_each_ptr(bkey_i_to_s_extent(&w->key), ptr) {
1679                 ca = bch_dev_bkey_exists(c, ptr->dev);
1680                 if (!percpu_ref_tryget(&ca->io_ref)) {
1681                         /* XXX: fix this */
1682                         bch_err(c, "missing device for journal write\n");
1683                         continue;
1684                 }
1685
1686                 this_cpu_add(ca->io_done->sectors[WRITE][BCH_DATA_journal],
1687                              sectors);
1688
1689                 bio = ca->journal.bio;
1690                 bio_reset(bio, ca->disk_sb.bdev, REQ_OP_WRITE|REQ_SYNC|REQ_META);
1691                 bio->bi_iter.bi_sector  = ptr->offset;
1692                 bio->bi_end_io          = journal_write_endio;
1693                 bio->bi_private         = ca;
1694
1695                 BUG_ON(bio->bi_iter.bi_sector == ca->prev_journal_sector);
1696                 ca->prev_journal_sector = bio->bi_iter.bi_sector;
1697
1698                 if (!JSET_NO_FLUSH(w->data))
1699                         bio->bi_opf    |= REQ_FUA;
1700                 if (!JSET_NO_FLUSH(w->data) && !w->separate_flush)
1701                         bio->bi_opf    |= REQ_PREFLUSH;
1702
1703                 bch2_bio_map(bio, w->data, sectors << 9);
1704
1705                 trace_and_count(c, journal_write, bio);
1706                 closure_bio_submit(bio, cl);
1707
1708                 ca->journal.bucket_seq[ca->journal.cur_idx] =
1709                         le64_to_cpu(w->data->seq);
1710         }
1711
1712         continue_at(cl, journal_write_done, c->io_complete_wq);
1713 }
1714
1715 static int bch2_journal_write_prep(struct journal *j, struct journal_buf *w)
1716 {
1717         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1718         struct jset_entry *start, *end, *i, *next, *prev = NULL;
1719         struct jset *jset = w->data;
1720         struct journal_keys_to_wb wb = { NULL };
1721         unsigned sectors, bytes, u64s;
1722         unsigned long btree_roots_have = 0;
1723         bool validate_before_checksum = false;
1724         u64 seq = le64_to_cpu(jset->seq);
1725         int ret;
1726
1727         /*
1728          * Simple compaction, dropping empty jset_entries (from journal
1729          * reservations that weren't fully used) and merging jset_entries that
1730          * can be.
1731          *
1732          * If we wanted to be really fancy here, we could sort all the keys in
1733          * the jset and drop keys that were overwritten - probably not worth it:
1734          */
1735         vstruct_for_each_safe(jset, i, next) {
1736                 unsigned u64s = le16_to_cpu(i->u64s);
1737
1738                 /* Empty entry: */
1739                 if (!u64s)
1740                         continue;
1741
1742                 /*
1743                  * New btree roots are set by journalling them; when the journal
1744                  * entry gets written we have to propagate them to
1745                  * c->btree_roots
1746                  *
1747                  * But, every journal entry we write has to contain all the
1748                  * btree roots (at least for now); so after we copy btree roots
1749                  * to c->btree_roots we have to get any missing btree roots and
1750                  * add them to this journal entry:
1751                  */
1752                 switch (i->type) {
1753                 case BCH_JSET_ENTRY_btree_root:
1754                         bch2_journal_entry_to_btree_root(c, i);
1755                         __set_bit(i->btree_id, &btree_roots_have);
1756                         break;
1757                 case BCH_JSET_ENTRY_write_buffer_keys:
1758                         EBUG_ON(!w->need_flush_to_write_buffer);
1759
1760                         if (!wb.wb)
1761                                 bch2_journal_keys_to_write_buffer_start(c, &wb, seq);
1762
1763                         struct bkey_i *k;
1764                         jset_entry_for_each_key(i, k) {
1765                                 ret = bch2_journal_key_to_wb(c, &wb, i->btree_id, k);
1766                                 if (ret) {
1767                                         bch2_fs_fatal_error(c, "-ENOMEM flushing journal keys to btree write buffer");
1768                                         bch2_journal_keys_to_write_buffer_end(c, &wb);
1769                                         return ret;
1770                                 }
1771                         }
1772                         i->type = BCH_JSET_ENTRY_btree_keys;
1773                         break;
1774                 }
1775
1776                 /* Can we merge with previous entry? */
1777                 if (prev &&
1778                     i->btree_id == prev->btree_id &&
1779                     i->level    == prev->level &&
1780                     i->type     == prev->type &&
1781                     i->type     == BCH_JSET_ENTRY_btree_keys &&
1782                     le16_to_cpu(prev->u64s) + u64s <= U16_MAX) {
1783                         memmove_u64s_down(vstruct_next(prev),
1784                                           i->_data,
1785                                           u64s);
1786                         le16_add_cpu(&prev->u64s, u64s);
1787                         continue;
1788                 }
1789
1790                 /* Couldn't merge, move i into new position (after prev): */
1791                 prev = prev ? vstruct_next(prev) : jset->start;
1792                 if (i != prev)
1793                         memmove_u64s_down(prev, i, jset_u64s(u64s));
1794         }
1795
1796         if (wb.wb)
1797                 bch2_journal_keys_to_write_buffer_end(c, &wb);
1798         w->need_flush_to_write_buffer = false;
1799
1800         prev = prev ? vstruct_next(prev) : jset->start;
1801         jset->u64s = cpu_to_le32((u64 *) prev - jset->_data);
1802
1803         start = end = vstruct_last(jset);
1804
1805         end     = bch2_btree_roots_to_journal_entries(c, end, btree_roots_have);
1806
1807         bch2_journal_super_entries_add_common(c, &end, seq);
1808         u64s    = (u64 *) end - (u64 *) start;
1809         BUG_ON(u64s > j->entry_u64s_reserved);
1810
1811         le32_add_cpu(&jset->u64s, u64s);
1812
1813         sectors = vstruct_sectors(jset, c->block_bits);
1814         bytes   = vstruct_bytes(jset);
1815
1816         if (sectors > w->sectors) {
1817                 bch2_fs_fatal_error(c, "aieeee! journal write overran available space, %zu > %u (extra %u reserved %u/%u)",
1818                                     vstruct_bytes(jset), w->sectors << 9,
1819                                     u64s, w->u64s_reserved, j->entry_u64s_reserved);
1820                 return -EINVAL;
1821         }
1822
1823         jset->magic             = cpu_to_le64(jset_magic(c));
1824         jset->version           = cpu_to_le32(c->sb.version);
1825
1826         SET_JSET_BIG_ENDIAN(jset, CPU_BIG_ENDIAN);
1827         SET_JSET_CSUM_TYPE(jset, bch2_meta_checksum_type(c));
1828
1829         if (!JSET_NO_FLUSH(jset) && journal_entry_empty(jset))
1830                 j->last_empty_seq = seq;
1831
1832         if (bch2_csum_type_is_encryption(JSET_CSUM_TYPE(jset)))
1833                 validate_before_checksum = true;
1834
1835         if (le32_to_cpu(jset->version) < bcachefs_metadata_version_current)
1836                 validate_before_checksum = true;
1837
1838         if (validate_before_checksum &&
1839             (ret = jset_validate(c, NULL, jset, 0, WRITE)))
1840                 return ret;
1841
1842         ret = bch2_encrypt(c, JSET_CSUM_TYPE(jset), journal_nonce(jset),
1843                     jset->encrypted_start,
1844                     vstruct_end(jset) - (void *) jset->encrypted_start);
1845         if (bch2_fs_fatal_err_on(ret, c,
1846                         "error decrypting journal entry: %i", ret))
1847                 return ret;
1848
1849         jset->csum = csum_vstruct(c, JSET_CSUM_TYPE(jset),
1850                                   journal_nonce(jset), jset);
1851
1852         if (!validate_before_checksum &&
1853             (ret = jset_validate(c, NULL, jset, 0, WRITE)))
1854                 return ret;
1855
1856         memset((void *) jset + bytes, 0, (sectors << 9) - bytes);
1857         return 0;
1858 }
1859
1860 static int bch2_journal_write_pick_flush(struct journal *j, struct journal_buf *w)
1861 {
1862         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1863         int error = bch2_journal_error(j);
1864
1865         /*
1866          * If the journal is in an error state - we did an emergency shutdown -
1867          * we prefer to continue doing journal writes. We just mark them as
1868          * noflush so they'll never be used, but they'll still be visible by the
1869          * list_journal tool - this helps in debugging.
1870          *
1871          * There's a caveat: the first journal write after marking the
1872          * superblock dirty must always be a flush write, because on startup
1873          * from a clean shutdown we didn't necessarily read the journal and the
1874          * new journal write might overwrite whatever was in the journal
1875          * previously - we can't leave the journal without any flush writes in
1876          * it.
1877          *
1878          * So if we're in an error state, and we're still starting up, we don't
1879          * write anything at all.
1880          */
1881         if (error && test_bit(JOURNAL_NEED_FLUSH_WRITE, &j->flags))
1882                 return -EIO;
1883
1884         if (error ||
1885             w->noflush ||
1886             (!w->must_flush &&
1887              (jiffies - j->last_flush_write) < msecs_to_jiffies(c->opts.journal_flush_delay) &&
1888              test_bit(JOURNAL_MAY_SKIP_FLUSH, &j->flags))) {
1889                 w->noflush = true;
1890                 SET_JSET_NO_FLUSH(w->data, true);
1891                 w->data->last_seq       = 0;
1892                 w->last_seq             = 0;
1893
1894                 j->nr_noflush_writes++;
1895         } else {
1896                 j->last_flush_write = jiffies;
1897                 j->nr_flush_writes++;
1898                 clear_bit(JOURNAL_NEED_FLUSH_WRITE, &j->flags);
1899         }
1900
1901         return 0;
1902 }
1903
1904 CLOSURE_CALLBACK(bch2_journal_write)
1905 {
1906         closure_type(j, struct journal, io);
1907         struct bch_fs *c = container_of(j, struct bch_fs, journal);
1908         struct bch_dev *ca;
1909         struct journal_buf *w = journal_last_unwritten_buf(j);
1910         struct bch_replicas_padded replicas;
1911         struct bio *bio;
1912         struct printbuf journal_debug_buf = PRINTBUF;
1913         unsigned i, nr_rw_members = 0;
1914         int ret;
1915
1916         BUG_ON(BCH_SB_CLEAN(c->disk_sb.sb));
1917
1918         j->write_start_time = local_clock();
1919
1920         spin_lock(&j->lock);
1921         ret = bch2_journal_write_pick_flush(j, w);
1922         spin_unlock(&j->lock);
1923         if (ret)
1924                 goto err;
1925
1926         mutex_lock(&j->buf_lock);
1927         journal_buf_realloc(j, w);
1928
1929         ret = bch2_journal_write_prep(j, w);
1930         mutex_unlock(&j->buf_lock);
1931         if (ret)
1932                 goto err;
1933
1934         j->entry_bytes_written += vstruct_bytes(w->data);
1935
1936         while (1) {
1937                 spin_lock(&j->lock);
1938                 ret = journal_write_alloc(j, w);
1939                 if (!ret || !j->can_discard)
1940                         break;
1941
1942                 spin_unlock(&j->lock);
1943                 bch2_journal_do_discards(j);
1944         }
1945
1946         if (ret) {
1947                 __bch2_journal_debug_to_text(&journal_debug_buf, j);
1948                 spin_unlock(&j->lock);
1949                 bch_err(c, "Unable to allocate journal write:\n%s",
1950                         journal_debug_buf.buf);
1951                 printbuf_exit(&journal_debug_buf);
1952                 goto err;
1953         }
1954
1955         /*
1956          * write is allocated, no longer need to account for it in
1957          * bch2_journal_space_available():
1958          */
1959         w->sectors = 0;
1960
1961         /*
1962          * journal entry has been compacted and allocated, recalculate space
1963          * available:
1964          */
1965         bch2_journal_space_available(j);
1966         spin_unlock(&j->lock);
1967
1968         w->devs_written = bch2_bkey_devs(bkey_i_to_s_c(&w->key));
1969
1970         if (c->opts.nochanges)
1971                 goto no_io;
1972
1973         for_each_rw_member(ca, c, i)
1974                 nr_rw_members++;
1975
1976         if (nr_rw_members > 1)
1977                 w->separate_flush = true;
1978
1979         /*
1980          * Mark journal replicas before we submit the write to guarantee
1981          * recovery will find the journal entries after a crash.
1982          */
1983         bch2_devlist_to_replicas(&replicas.e, BCH_DATA_journal,
1984                                  w->devs_written);
1985         ret = bch2_mark_replicas(c, &replicas.e);
1986         if (ret)
1987                 goto err;
1988
1989         if (!JSET_NO_FLUSH(w->data) && w->separate_flush) {
1990                 for_each_rw_member(ca, c, i) {
1991                         percpu_ref_get(&ca->io_ref);
1992
1993                         bio = ca->journal.bio;
1994                         bio_reset(bio, ca->disk_sb.bdev, REQ_OP_FLUSH);
1995                         bio->bi_end_io          = journal_write_endio;
1996                         bio->bi_private         = ca;
1997                         closure_bio_submit(bio, cl);
1998                 }
1999         }
2000
2001         continue_at(cl, do_journal_write, c->io_complete_wq);
2002         return;
2003 no_io:
2004         continue_at(cl, journal_write_done, c->io_complete_wq);
2005         return;
2006 err:
2007         bch2_fatal_error(c);
2008         continue_at(cl, journal_write_done, c->io_complete_wq);
2009 }