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