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