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