xref: /linux/fs/bcachefs/btree_io.c (revision c4bbe83d27c2446a033cc0381c3fb6be5e8c41c7)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "bkey_methods.h"
5 #include "bkey_sort.h"
6 #include "btree_cache.h"
7 #include "btree_io.h"
8 #include "btree_iter.h"
9 #include "btree_locking.h"
10 #include "btree_update.h"
11 #include "btree_update_interior.h"
12 #include "buckets.h"
13 #include "checksum.h"
14 #include "debug.h"
15 #include "error.h"
16 #include "extents.h"
17 #include "io_write.h"
18 #include "journal_reclaim.h"
19 #include "journal_seq_blacklist.h"
20 #include "recovery.h"
21 #include "super-io.h"
22 #include "trace.h"
23 
24 #include <linux/sched/mm.h>
25 
26 void bch2_btree_node_io_unlock(struct btree *b)
27 {
28 	EBUG_ON(!btree_node_write_in_flight(b));
29 
30 	clear_btree_node_write_in_flight_inner(b);
31 	clear_btree_node_write_in_flight(b);
32 	wake_up_bit(&b->flags, BTREE_NODE_write_in_flight);
33 }
34 
35 void bch2_btree_node_io_lock(struct btree *b)
36 {
37 	bch2_assert_btree_nodes_not_locked();
38 
39 	wait_on_bit_lock_io(&b->flags, BTREE_NODE_write_in_flight,
40 			    TASK_UNINTERRUPTIBLE);
41 }
42 
43 void __bch2_btree_node_wait_on_read(struct btree *b)
44 {
45 	wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
46 		       TASK_UNINTERRUPTIBLE);
47 }
48 
49 void __bch2_btree_node_wait_on_write(struct btree *b)
50 {
51 	wait_on_bit_io(&b->flags, BTREE_NODE_write_in_flight,
52 		       TASK_UNINTERRUPTIBLE);
53 }
54 
55 void bch2_btree_node_wait_on_read(struct btree *b)
56 {
57 	bch2_assert_btree_nodes_not_locked();
58 
59 	wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
60 		       TASK_UNINTERRUPTIBLE);
61 }
62 
63 void bch2_btree_node_wait_on_write(struct btree *b)
64 {
65 	bch2_assert_btree_nodes_not_locked();
66 
67 	wait_on_bit_io(&b->flags, BTREE_NODE_write_in_flight,
68 		       TASK_UNINTERRUPTIBLE);
69 }
70 
71 static void verify_no_dups(struct btree *b,
72 			   struct bkey_packed *start,
73 			   struct bkey_packed *end)
74 {
75 #ifdef CONFIG_BCACHEFS_DEBUG
76 	struct bkey_packed *k, *p;
77 
78 	if (start == end)
79 		return;
80 
81 	for (p = start, k = bkey_p_next(start);
82 	     k != end;
83 	     p = k, k = bkey_p_next(k)) {
84 		struct bkey l = bkey_unpack_key(b, p);
85 		struct bkey r = bkey_unpack_key(b, k);
86 
87 		BUG_ON(bpos_ge(l.p, bkey_start_pos(&r)));
88 	}
89 #endif
90 }
91 
92 static void set_needs_whiteout(struct bset *i, int v)
93 {
94 	struct bkey_packed *k;
95 
96 	for (k = i->start; k != vstruct_last(i); k = bkey_p_next(k))
97 		k->needs_whiteout = v;
98 }
99 
100 static void btree_bounce_free(struct bch_fs *c, size_t size,
101 			      bool used_mempool, void *p)
102 {
103 	if (used_mempool)
104 		mempool_free(p, &c->btree_bounce_pool);
105 	else
106 		vpfree(p, size);
107 }
108 
109 static void *btree_bounce_alloc(struct bch_fs *c, size_t size,
110 				bool *used_mempool)
111 {
112 	unsigned flags = memalloc_nofs_save();
113 	void *p;
114 
115 	BUG_ON(size > c->opts.btree_node_size);
116 
117 	*used_mempool = false;
118 	p = vpmalloc(size, __GFP_NOWARN|GFP_NOWAIT);
119 	if (!p) {
120 		*used_mempool = true;
121 		p = mempool_alloc(&c->btree_bounce_pool, GFP_NOFS);
122 	}
123 	memalloc_nofs_restore(flags);
124 	return p;
125 }
126 
127 static void sort_bkey_ptrs(const struct btree *bt,
128 			   struct bkey_packed **ptrs, unsigned nr)
129 {
130 	unsigned n = nr, a = nr / 2, b, c, d;
131 
132 	if (!a)
133 		return;
134 
135 	/* Heap sort: see lib/sort.c: */
136 	while (1) {
137 		if (a)
138 			a--;
139 		else if (--n)
140 			swap(ptrs[0], ptrs[n]);
141 		else
142 			break;
143 
144 		for (b = a; c = 2 * b + 1, (d = c + 1) < n;)
145 			b = bch2_bkey_cmp_packed(bt,
146 					    ptrs[c],
147 					    ptrs[d]) >= 0 ? c : d;
148 		if (d == n)
149 			b = c;
150 
151 		while (b != a &&
152 		       bch2_bkey_cmp_packed(bt,
153 				       ptrs[a],
154 				       ptrs[b]) >= 0)
155 			b = (b - 1) / 2;
156 		c = b;
157 		while (b != a) {
158 			b = (b - 1) / 2;
159 			swap(ptrs[b], ptrs[c]);
160 		}
161 	}
162 }
163 
164 static void bch2_sort_whiteouts(struct bch_fs *c, struct btree *b)
165 {
166 	struct bkey_packed *new_whiteouts, **ptrs, **ptrs_end, *k;
167 	bool used_mempool = false;
168 	size_t bytes = b->whiteout_u64s * sizeof(u64);
169 
170 	if (!b->whiteout_u64s)
171 		return;
172 
173 	new_whiteouts = btree_bounce_alloc(c, bytes, &used_mempool);
174 
175 	ptrs = ptrs_end = ((void *) new_whiteouts + bytes);
176 
177 	for (k = unwritten_whiteouts_start(b);
178 	     k != unwritten_whiteouts_end(b);
179 	     k = bkey_p_next(k))
180 		*--ptrs = k;
181 
182 	sort_bkey_ptrs(b, ptrs, ptrs_end - ptrs);
183 
184 	k = new_whiteouts;
185 
186 	while (ptrs != ptrs_end) {
187 		bkey_p_copy(k, *ptrs);
188 		k = bkey_p_next(k);
189 		ptrs++;
190 	}
191 
192 	verify_no_dups(b, new_whiteouts,
193 		       (void *) ((u64 *) new_whiteouts + b->whiteout_u64s));
194 
195 	memcpy_u64s(unwritten_whiteouts_start(b),
196 		    new_whiteouts, b->whiteout_u64s);
197 
198 	btree_bounce_free(c, bytes, used_mempool, new_whiteouts);
199 }
200 
201 static bool should_compact_bset(struct btree *b, struct bset_tree *t,
202 				bool compacting, enum compact_mode mode)
203 {
204 	if (!bset_dead_u64s(b, t))
205 		return false;
206 
207 	switch (mode) {
208 	case COMPACT_LAZY:
209 		return should_compact_bset_lazy(b, t) ||
210 			(compacting && !bset_written(b, bset(b, t)));
211 	case COMPACT_ALL:
212 		return true;
213 	default:
214 		BUG();
215 	}
216 }
217 
218 static bool bch2_drop_whiteouts(struct btree *b, enum compact_mode mode)
219 {
220 	struct bset_tree *t;
221 	bool ret = false;
222 
223 	for_each_bset(b, t) {
224 		struct bset *i = bset(b, t);
225 		struct bkey_packed *k, *n, *out, *start, *end;
226 		struct btree_node_entry *src = NULL, *dst = NULL;
227 
228 		if (t != b->set && !bset_written(b, i)) {
229 			src = container_of(i, struct btree_node_entry, keys);
230 			dst = max(write_block(b),
231 				  (void *) btree_bkey_last(b, t - 1));
232 		}
233 
234 		if (src != dst)
235 			ret = true;
236 
237 		if (!should_compact_bset(b, t, ret, mode)) {
238 			if (src != dst) {
239 				memmove(dst, src, sizeof(*src) +
240 					le16_to_cpu(src->keys.u64s) *
241 					sizeof(u64));
242 				i = &dst->keys;
243 				set_btree_bset(b, t, i);
244 			}
245 			continue;
246 		}
247 
248 		start	= btree_bkey_first(b, t);
249 		end	= btree_bkey_last(b, t);
250 
251 		if (src != dst) {
252 			memmove(dst, src, sizeof(*src));
253 			i = &dst->keys;
254 			set_btree_bset(b, t, i);
255 		}
256 
257 		out = i->start;
258 
259 		for (k = start; k != end; k = n) {
260 			n = bkey_p_next(k);
261 
262 			if (!bkey_deleted(k)) {
263 				bkey_p_copy(out, k);
264 				out = bkey_p_next(out);
265 			} else {
266 				BUG_ON(k->needs_whiteout);
267 			}
268 		}
269 
270 		i->u64s = cpu_to_le16((u64 *) out - i->_data);
271 		set_btree_bset_end(b, t);
272 		bch2_bset_set_no_aux_tree(b, t);
273 		ret = true;
274 	}
275 
276 	bch2_verify_btree_nr_keys(b);
277 
278 	bch2_btree_build_aux_trees(b);
279 
280 	return ret;
281 }
282 
283 bool bch2_compact_whiteouts(struct bch_fs *c, struct btree *b,
284 			    enum compact_mode mode)
285 {
286 	return bch2_drop_whiteouts(b, mode);
287 }
288 
289 static void btree_node_sort(struct bch_fs *c, struct btree *b,
290 			    unsigned start_idx,
291 			    unsigned end_idx,
292 			    bool filter_whiteouts)
293 {
294 	struct btree_node *out;
295 	struct sort_iter_stack sort_iter;
296 	struct bset_tree *t;
297 	struct bset *start_bset = bset(b, &b->set[start_idx]);
298 	bool used_mempool = false;
299 	u64 start_time, seq = 0;
300 	unsigned i, u64s = 0, bytes, shift = end_idx - start_idx - 1;
301 	bool sorting_entire_node = start_idx == 0 &&
302 		end_idx == b->nsets;
303 
304 	sort_iter_stack_init(&sort_iter, b);
305 
306 	for (t = b->set + start_idx;
307 	     t < b->set + end_idx;
308 	     t++) {
309 		u64s += le16_to_cpu(bset(b, t)->u64s);
310 		sort_iter_add(&sort_iter.iter,
311 			      btree_bkey_first(b, t),
312 			      btree_bkey_last(b, t));
313 	}
314 
315 	bytes = sorting_entire_node
316 		? btree_buf_bytes(b)
317 		: __vstruct_bytes(struct btree_node, u64s);
318 
319 	out = btree_bounce_alloc(c, bytes, &used_mempool);
320 
321 	start_time = local_clock();
322 
323 	u64s = bch2_sort_keys(out->keys.start, &sort_iter.iter, filter_whiteouts);
324 
325 	out->keys.u64s = cpu_to_le16(u64s);
326 
327 	BUG_ON(vstruct_end(&out->keys) > (void *) out + bytes);
328 
329 	if (sorting_entire_node)
330 		bch2_time_stats_update(&c->times[BCH_TIME_btree_node_sort],
331 				       start_time);
332 
333 	/* Make sure we preserve bset journal_seq: */
334 	for (t = b->set + start_idx; t < b->set + end_idx; t++)
335 		seq = max(seq, le64_to_cpu(bset(b, t)->journal_seq));
336 	start_bset->journal_seq = cpu_to_le64(seq);
337 
338 	if (sorting_entire_node) {
339 		u64s = le16_to_cpu(out->keys.u64s);
340 
341 		BUG_ON(bytes != btree_buf_bytes(b));
342 
343 		/*
344 		 * Our temporary buffer is the same size as the btree node's
345 		 * buffer, we can just swap buffers instead of doing a big
346 		 * memcpy()
347 		 */
348 		*out = *b->data;
349 		out->keys.u64s = cpu_to_le16(u64s);
350 		swap(out, b->data);
351 		set_btree_bset(b, b->set, &b->data->keys);
352 	} else {
353 		start_bset->u64s = out->keys.u64s;
354 		memcpy_u64s(start_bset->start,
355 			    out->keys.start,
356 			    le16_to_cpu(out->keys.u64s));
357 	}
358 
359 	for (i = start_idx + 1; i < end_idx; i++)
360 		b->nr.bset_u64s[start_idx] +=
361 			b->nr.bset_u64s[i];
362 
363 	b->nsets -= shift;
364 
365 	for (i = start_idx + 1; i < b->nsets; i++) {
366 		b->nr.bset_u64s[i]	= b->nr.bset_u64s[i + shift];
367 		b->set[i]		= b->set[i + shift];
368 	}
369 
370 	for (i = b->nsets; i < MAX_BSETS; i++)
371 		b->nr.bset_u64s[i] = 0;
372 
373 	set_btree_bset_end(b, &b->set[start_idx]);
374 	bch2_bset_set_no_aux_tree(b, &b->set[start_idx]);
375 
376 	btree_bounce_free(c, bytes, used_mempool, out);
377 
378 	bch2_verify_btree_nr_keys(b);
379 }
380 
381 void bch2_btree_sort_into(struct bch_fs *c,
382 			 struct btree *dst,
383 			 struct btree *src)
384 {
385 	struct btree_nr_keys nr;
386 	struct btree_node_iter src_iter;
387 	u64 start_time = local_clock();
388 
389 	BUG_ON(dst->nsets != 1);
390 
391 	bch2_bset_set_no_aux_tree(dst, dst->set);
392 
393 	bch2_btree_node_iter_init_from_start(&src_iter, src);
394 
395 	nr = bch2_sort_repack(btree_bset_first(dst),
396 			src, &src_iter,
397 			&dst->format,
398 			true);
399 
400 	bch2_time_stats_update(&c->times[BCH_TIME_btree_node_sort],
401 			       start_time);
402 
403 	set_btree_bset_end(dst, dst->set);
404 
405 	dst->nr.live_u64s	+= nr.live_u64s;
406 	dst->nr.bset_u64s[0]	+= nr.bset_u64s[0];
407 	dst->nr.packed_keys	+= nr.packed_keys;
408 	dst->nr.unpacked_keys	+= nr.unpacked_keys;
409 
410 	bch2_verify_btree_nr_keys(dst);
411 }
412 
413 /*
414  * We're about to add another bset to the btree node, so if there's currently
415  * too many bsets - sort some of them together:
416  */
417 static bool btree_node_compact(struct bch_fs *c, struct btree *b)
418 {
419 	unsigned unwritten_idx;
420 	bool ret = false;
421 
422 	for (unwritten_idx = 0;
423 	     unwritten_idx < b->nsets;
424 	     unwritten_idx++)
425 		if (!bset_written(b, bset(b, &b->set[unwritten_idx])))
426 			break;
427 
428 	if (b->nsets - unwritten_idx > 1) {
429 		btree_node_sort(c, b, unwritten_idx,
430 				b->nsets, false);
431 		ret = true;
432 	}
433 
434 	if (unwritten_idx > 1) {
435 		btree_node_sort(c, b, 0, unwritten_idx, false);
436 		ret = true;
437 	}
438 
439 	return ret;
440 }
441 
442 void bch2_btree_build_aux_trees(struct btree *b)
443 {
444 	struct bset_tree *t;
445 
446 	for_each_bset(b, t)
447 		bch2_bset_build_aux_tree(b, t,
448 				!bset_written(b, bset(b, t)) &&
449 				t == bset_tree_last(b));
450 }
451 
452 /*
453  * If we have MAX_BSETS (3) bsets, should we sort them all down to just one?
454  *
455  * The first bset is going to be of similar order to the size of the node, the
456  * last bset is bounded by btree_write_set_buffer(), which is set to keep the
457  * memmove on insert from being too expensive: the middle bset should, ideally,
458  * be the geometric mean of the first and the last.
459  *
460  * Returns true if the middle bset is greater than that geometric mean:
461  */
462 static inline bool should_compact_all(struct bch_fs *c, struct btree *b)
463 {
464 	unsigned mid_u64s_bits =
465 		(ilog2(btree_max_u64s(c)) + BTREE_WRITE_SET_U64s_BITS) / 2;
466 
467 	return bset_u64s(&b->set[1]) > 1U << mid_u64s_bits;
468 }
469 
470 /*
471  * @bch_btree_init_next - initialize a new (unwritten) bset that can then be
472  * inserted into
473  *
474  * Safe to call if there already is an unwritten bset - will only add a new bset
475  * if @b doesn't already have one.
476  *
477  * Returns true if we sorted (i.e. invalidated iterators
478  */
479 void bch2_btree_init_next(struct btree_trans *trans, struct btree *b)
480 {
481 	struct bch_fs *c = trans->c;
482 	struct btree_node_entry *bne;
483 	bool reinit_iter = false;
484 
485 	EBUG_ON(!six_lock_counts(&b->c.lock).n[SIX_LOCK_write]);
486 	BUG_ON(bset_written(b, bset(b, &b->set[1])));
487 	BUG_ON(btree_node_just_written(b));
488 
489 	if (b->nsets == MAX_BSETS &&
490 	    !btree_node_write_in_flight(b) &&
491 	    should_compact_all(c, b)) {
492 		bch2_btree_node_write(c, b, SIX_LOCK_write,
493 				      BTREE_WRITE_init_next_bset);
494 		reinit_iter = true;
495 	}
496 
497 	if (b->nsets == MAX_BSETS &&
498 	    btree_node_compact(c, b))
499 		reinit_iter = true;
500 
501 	BUG_ON(b->nsets >= MAX_BSETS);
502 
503 	bne = want_new_bset(c, b);
504 	if (bne)
505 		bch2_bset_init_next(b, bne);
506 
507 	bch2_btree_build_aux_trees(b);
508 
509 	if (reinit_iter)
510 		bch2_trans_node_reinit_iter(trans, b);
511 }
512 
513 static void btree_err_msg(struct printbuf *out, struct bch_fs *c,
514 			  struct bch_dev *ca,
515 			  struct btree *b, struct bset *i,
516 			  unsigned offset, int write)
517 {
518 	prt_printf(out, bch2_log_msg(c, "%s"),
519 		   write == READ
520 		   ? "error validating btree node "
521 		   : "corrupt btree node before write ");
522 	if (ca)
523 		prt_printf(out, "on %s ", ca->name);
524 	prt_printf(out, "at btree ");
525 	bch2_btree_pos_to_text(out, c, b);
526 
527 	prt_printf(out, "\n  node offset %u/%u",
528 		   b->written, btree_ptr_sectors_written(&b->key));
529 	if (i)
530 		prt_printf(out, " bset u64s %u", le16_to_cpu(i->u64s));
531 	prt_str(out, ": ");
532 }
533 
534 __printf(9, 10)
535 static int __btree_err(int ret,
536 		       struct bch_fs *c,
537 		       struct bch_dev *ca,
538 		       struct btree *b,
539 		       struct bset *i,
540 		       int write,
541 		       bool have_retry,
542 		       enum bch_sb_error_id err_type,
543 		       const char *fmt, ...)
544 {
545 	struct printbuf out = PRINTBUF;
546 	va_list args;
547 
548 	btree_err_msg(&out, c, ca, b, i, b->written, write);
549 
550 	va_start(args, fmt);
551 	prt_vprintf(&out, fmt, args);
552 	va_end(args);
553 
554 	if (write == WRITE) {
555 		bch2_print_string_as_lines(KERN_ERR, out.buf);
556 		ret = c->opts.errors == BCH_ON_ERROR_continue
557 			? 0
558 			: -BCH_ERR_fsck_errors_not_fixed;
559 		goto out;
560 	}
561 
562 	if (!have_retry && ret == -BCH_ERR_btree_node_read_err_want_retry)
563 		ret = -BCH_ERR_btree_node_read_err_fixable;
564 	if (!have_retry && ret == -BCH_ERR_btree_node_read_err_must_retry)
565 		ret = -BCH_ERR_btree_node_read_err_bad_node;
566 
567 	if (ret != -BCH_ERR_btree_node_read_err_fixable)
568 		bch2_sb_error_count(c, err_type);
569 
570 	switch (ret) {
571 	case -BCH_ERR_btree_node_read_err_fixable:
572 		ret = bch2_fsck_err(c, FSCK_CAN_FIX, err_type, "%s", out.buf);
573 		if (ret != -BCH_ERR_fsck_fix &&
574 		    ret != -BCH_ERR_fsck_ignore)
575 			goto fsck_err;
576 		ret = -BCH_ERR_fsck_fix;
577 		break;
578 	case -BCH_ERR_btree_node_read_err_want_retry:
579 	case -BCH_ERR_btree_node_read_err_must_retry:
580 		bch2_print_string_as_lines(KERN_ERR, out.buf);
581 		break;
582 	case -BCH_ERR_btree_node_read_err_bad_node:
583 		bch2_print_string_as_lines(KERN_ERR, out.buf);
584 		bch2_topology_error(c);
585 		ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_check_topology) ?: -EIO;
586 		break;
587 	case -BCH_ERR_btree_node_read_err_incompatible:
588 		bch2_print_string_as_lines(KERN_ERR, out.buf);
589 		ret = -BCH_ERR_fsck_errors_not_fixed;
590 		break;
591 	default:
592 		BUG();
593 	}
594 out:
595 fsck_err:
596 	printbuf_exit(&out);
597 	return ret;
598 }
599 
600 #define btree_err(type, c, ca, b, i, _err_type, msg, ...)		\
601 ({									\
602 	int _ret = __btree_err(type, c, ca, b, i, write, have_retry,	\
603 			       BCH_FSCK_ERR_##_err_type,		\
604 			       msg, ##__VA_ARGS__);			\
605 									\
606 	if (_ret != -BCH_ERR_fsck_fix) {				\
607 		ret = _ret;						\
608 		goto fsck_err;						\
609 	}								\
610 									\
611 	*saw_error = true;						\
612 })
613 
614 #define btree_err_on(cond, ...)	((cond) ? btree_err(__VA_ARGS__) : false)
615 
616 /*
617  * When btree topology repair changes the start or end of a node, that might
618  * mean we have to drop keys that are no longer inside the node:
619  */
620 __cold
621 void bch2_btree_node_drop_keys_outside_node(struct btree *b)
622 {
623 	struct bset_tree *t;
624 
625 	for_each_bset(b, t) {
626 		struct bset *i = bset(b, t);
627 		struct bkey_packed *k;
628 
629 		for (k = i->start; k != vstruct_last(i); k = bkey_p_next(k))
630 			if (bkey_cmp_left_packed(b, k, &b->data->min_key) >= 0)
631 				break;
632 
633 		if (k != i->start) {
634 			unsigned shift = (u64 *) k - (u64 *) i->start;
635 
636 			memmove_u64s_down(i->start, k,
637 					  (u64 *) vstruct_end(i) - (u64 *) k);
638 			i->u64s = cpu_to_le16(le16_to_cpu(i->u64s) - shift);
639 			set_btree_bset_end(b, t);
640 		}
641 
642 		for (k = i->start; k != vstruct_last(i); k = bkey_p_next(k))
643 			if (bkey_cmp_left_packed(b, k, &b->data->max_key) > 0)
644 				break;
645 
646 		if (k != vstruct_last(i)) {
647 			i->u64s = cpu_to_le16((u64 *) k - (u64 *) i->start);
648 			set_btree_bset_end(b, t);
649 		}
650 	}
651 
652 	/*
653 	 * Always rebuild search trees: eytzinger search tree nodes directly
654 	 * depend on the values of min/max key:
655 	 */
656 	bch2_bset_set_no_aux_tree(b, b->set);
657 	bch2_btree_build_aux_trees(b);
658 
659 	struct bkey_s_c k;
660 	struct bkey unpacked;
661 	struct btree_node_iter iter;
662 	for_each_btree_node_key_unpack(b, k, &iter, &unpacked) {
663 		BUG_ON(bpos_lt(k.k->p, b->data->min_key));
664 		BUG_ON(bpos_gt(k.k->p, b->data->max_key));
665 	}
666 }
667 
668 static int validate_bset(struct bch_fs *c, struct bch_dev *ca,
669 			 struct btree *b, struct bset *i,
670 			 unsigned offset, unsigned sectors,
671 			 int write, bool have_retry, bool *saw_error)
672 {
673 	unsigned version = le16_to_cpu(i->version);
674 	struct printbuf buf1 = PRINTBUF;
675 	struct printbuf buf2 = PRINTBUF;
676 	int ret = 0;
677 
678 	btree_err_on(!bch2_version_compatible(version),
679 		     -BCH_ERR_btree_node_read_err_incompatible,
680 		     c, ca, b, i,
681 		     btree_node_unsupported_version,
682 		     "unsupported bset version %u.%u",
683 		     BCH_VERSION_MAJOR(version),
684 		     BCH_VERSION_MINOR(version));
685 
686 	if (btree_err_on(version < c->sb.version_min,
687 			 -BCH_ERR_btree_node_read_err_fixable,
688 			 c, NULL, b, i,
689 			 btree_node_bset_older_than_sb_min,
690 			 "bset version %u older than superblock version_min %u",
691 			 version, c->sb.version_min)) {
692 		mutex_lock(&c->sb_lock);
693 		c->disk_sb.sb->version_min = cpu_to_le16(version);
694 		bch2_write_super(c);
695 		mutex_unlock(&c->sb_lock);
696 	}
697 
698 	if (btree_err_on(BCH_VERSION_MAJOR(version) >
699 			 BCH_VERSION_MAJOR(c->sb.version),
700 			 -BCH_ERR_btree_node_read_err_fixable,
701 			 c, NULL, b, i,
702 			 btree_node_bset_newer_than_sb,
703 			 "bset version %u newer than superblock version %u",
704 			 version, c->sb.version)) {
705 		mutex_lock(&c->sb_lock);
706 		c->disk_sb.sb->version = cpu_to_le16(version);
707 		bch2_write_super(c);
708 		mutex_unlock(&c->sb_lock);
709 	}
710 
711 	btree_err_on(BSET_SEPARATE_WHITEOUTS(i),
712 		     -BCH_ERR_btree_node_read_err_incompatible,
713 		     c, ca, b, i,
714 		     btree_node_unsupported_version,
715 		     "BSET_SEPARATE_WHITEOUTS no longer supported");
716 
717 	if (btree_err_on(offset + sectors > btree_sectors(c),
718 			 -BCH_ERR_btree_node_read_err_fixable,
719 			 c, ca, b, i,
720 			 bset_past_end_of_btree_node,
721 			 "bset past end of btree node")) {
722 		i->u64s = 0;
723 		ret = 0;
724 		goto out;
725 	}
726 
727 	btree_err_on(offset && !i->u64s,
728 		     -BCH_ERR_btree_node_read_err_fixable,
729 		     c, ca, b, i,
730 		     bset_empty,
731 		     "empty bset");
732 
733 	btree_err_on(BSET_OFFSET(i) && BSET_OFFSET(i) != offset,
734 		     -BCH_ERR_btree_node_read_err_want_retry,
735 		     c, ca, b, i,
736 		     bset_wrong_sector_offset,
737 		     "bset at wrong sector offset");
738 
739 	if (!offset) {
740 		struct btree_node *bn =
741 			container_of(i, struct btree_node, keys);
742 		/* These indicate that we read the wrong btree node: */
743 
744 		if (b->key.k.type == KEY_TYPE_btree_ptr_v2) {
745 			struct bch_btree_ptr_v2 *bp =
746 				&bkey_i_to_btree_ptr_v2(&b->key)->v;
747 
748 			/* XXX endianness */
749 			btree_err_on(bp->seq != bn->keys.seq,
750 				     -BCH_ERR_btree_node_read_err_must_retry,
751 				     c, ca, b, NULL,
752 				     bset_bad_seq,
753 				     "incorrect sequence number (wrong btree node)");
754 		}
755 
756 		btree_err_on(BTREE_NODE_ID(bn) != b->c.btree_id,
757 			     -BCH_ERR_btree_node_read_err_must_retry,
758 			     c, ca, b, i,
759 			     btree_node_bad_btree,
760 			     "incorrect btree id");
761 
762 		btree_err_on(BTREE_NODE_LEVEL(bn) != b->c.level,
763 			     -BCH_ERR_btree_node_read_err_must_retry,
764 			     c, ca, b, i,
765 			     btree_node_bad_level,
766 			     "incorrect level");
767 
768 		if (!write)
769 			compat_btree_node(b->c.level, b->c.btree_id, version,
770 					  BSET_BIG_ENDIAN(i), write, bn);
771 
772 		if (b->key.k.type == KEY_TYPE_btree_ptr_v2) {
773 			struct bch_btree_ptr_v2 *bp =
774 				&bkey_i_to_btree_ptr_v2(&b->key)->v;
775 
776 			if (BTREE_PTR_RANGE_UPDATED(bp)) {
777 				b->data->min_key = bp->min_key;
778 				b->data->max_key = b->key.k.p;
779 			}
780 
781 			btree_err_on(!bpos_eq(b->data->min_key, bp->min_key),
782 				     -BCH_ERR_btree_node_read_err_must_retry,
783 				     c, ca, b, NULL,
784 				     btree_node_bad_min_key,
785 				     "incorrect min_key: got %s should be %s",
786 				     (printbuf_reset(&buf1),
787 				      bch2_bpos_to_text(&buf1, bn->min_key), buf1.buf),
788 				     (printbuf_reset(&buf2),
789 				      bch2_bpos_to_text(&buf2, bp->min_key), buf2.buf));
790 		}
791 
792 		btree_err_on(!bpos_eq(bn->max_key, b->key.k.p),
793 			     -BCH_ERR_btree_node_read_err_must_retry,
794 			     c, ca, b, i,
795 			     btree_node_bad_max_key,
796 			     "incorrect max key %s",
797 			     (printbuf_reset(&buf1),
798 			      bch2_bpos_to_text(&buf1, bn->max_key), buf1.buf));
799 
800 		if (write)
801 			compat_btree_node(b->c.level, b->c.btree_id, version,
802 					  BSET_BIG_ENDIAN(i), write, bn);
803 
804 		btree_err_on(bch2_bkey_format_invalid(c, &bn->format, write, &buf1),
805 			     -BCH_ERR_btree_node_read_err_bad_node,
806 			     c, ca, b, i,
807 			     btree_node_bad_format,
808 			     "invalid bkey format: %s\n  %s", buf1.buf,
809 			     (printbuf_reset(&buf2),
810 			      bch2_bkey_format_to_text(&buf2, &bn->format), buf2.buf));
811 		printbuf_reset(&buf1);
812 
813 		compat_bformat(b->c.level, b->c.btree_id, version,
814 			       BSET_BIG_ENDIAN(i), write,
815 			       &bn->format);
816 	}
817 out:
818 fsck_err:
819 	printbuf_exit(&buf2);
820 	printbuf_exit(&buf1);
821 	return ret;
822 }
823 
824 static int bset_key_invalid(struct bch_fs *c, struct btree *b,
825 			    struct bkey_s_c k,
826 			    bool updated_range, int rw,
827 			    struct printbuf *err)
828 {
829 	return __bch2_bkey_invalid(c, k, btree_node_type(b), READ, err) ?:
830 		(!updated_range ? bch2_bkey_in_btree_node(c, b, k, err) : 0) ?:
831 		(rw == WRITE ? bch2_bkey_val_invalid(c, k, READ, err) : 0);
832 }
833 
834 static bool __bkey_valid(struct bch_fs *c, struct btree *b,
835 			 struct bset *i, struct bkey_packed *k)
836 {
837 	if (bkey_p_next(k) > vstruct_last(i))
838 		return false;
839 
840 	if (k->format > KEY_FORMAT_CURRENT)
841 		return false;
842 
843 	struct printbuf buf = PRINTBUF;
844 	struct bkey tmp;
845 	struct bkey_s u = __bkey_disassemble(b, k, &tmp);
846 	bool ret = __bch2_bkey_invalid(c, u.s_c, btree_node_type(b), READ, &buf);
847 	printbuf_exit(&buf);
848 	return ret;
849 }
850 
851 static int validate_bset_keys(struct bch_fs *c, struct btree *b,
852 			 struct bset *i, int write,
853 			 bool have_retry, bool *saw_error)
854 {
855 	unsigned version = le16_to_cpu(i->version);
856 	struct bkey_packed *k, *prev = NULL;
857 	struct printbuf buf = PRINTBUF;
858 	bool updated_range = b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
859 		BTREE_PTR_RANGE_UPDATED(&bkey_i_to_btree_ptr_v2(&b->key)->v);
860 	int ret = 0;
861 
862 	for (k = i->start;
863 	     k != vstruct_last(i);) {
864 		struct bkey_s u;
865 		struct bkey tmp;
866 		unsigned next_good_key;
867 
868 		if (btree_err_on(bkey_p_next(k) > vstruct_last(i),
869 				 -BCH_ERR_btree_node_read_err_fixable,
870 				 c, NULL, b, i,
871 				 btree_node_bkey_past_bset_end,
872 				 "key extends past end of bset")) {
873 			i->u64s = cpu_to_le16((u64 *) k - i->_data);
874 			break;
875 		}
876 
877 		if (btree_err_on(k->format > KEY_FORMAT_CURRENT,
878 				 -BCH_ERR_btree_node_read_err_fixable,
879 				 c, NULL, b, i,
880 				 btree_node_bkey_bad_format,
881 				 "invalid bkey format %u", k->format))
882 			goto drop_this_key;
883 
884 		/* XXX: validate k->u64s */
885 		if (!write)
886 			bch2_bkey_compat(b->c.level, b->c.btree_id, version,
887 				    BSET_BIG_ENDIAN(i), write,
888 				    &b->format, k);
889 
890 		u = __bkey_disassemble(b, k, &tmp);
891 
892 		printbuf_reset(&buf);
893 		if (bset_key_invalid(c, b, u.s_c, updated_range, write, &buf)) {
894 			printbuf_reset(&buf);
895 			bset_key_invalid(c, b, u.s_c, updated_range, write, &buf);
896 			prt_printf(&buf, "\n  ");
897 			bch2_bkey_val_to_text(&buf, c, u.s_c);
898 
899 			btree_err(-BCH_ERR_btree_node_read_err_fixable,
900 				  c, NULL, b, i,
901 				  btree_node_bad_bkey,
902 				  "invalid bkey: %s", buf.buf);
903 			goto drop_this_key;
904 		}
905 
906 		if (write)
907 			bch2_bkey_compat(b->c.level, b->c.btree_id, version,
908 				    BSET_BIG_ENDIAN(i), write,
909 				    &b->format, k);
910 
911 		if (prev && bkey_iter_cmp(b, prev, k) > 0) {
912 			struct bkey up = bkey_unpack_key(b, prev);
913 
914 			printbuf_reset(&buf);
915 			prt_printf(&buf, "keys out of order: ");
916 			bch2_bkey_to_text(&buf, &up);
917 			prt_printf(&buf, " > ");
918 			bch2_bkey_to_text(&buf, u.k);
919 
920 			if (btree_err(-BCH_ERR_btree_node_read_err_fixable,
921 				      c, NULL, b, i,
922 				      btree_node_bkey_out_of_order,
923 				      "%s", buf.buf))
924 				goto drop_this_key;
925 		}
926 
927 		prev = k;
928 		k = bkey_p_next(k);
929 		continue;
930 drop_this_key:
931 		next_good_key = k->u64s;
932 
933 		if (!next_good_key ||
934 		    (BSET_BIG_ENDIAN(i) == CPU_BIG_ENDIAN &&
935 		     version >= bcachefs_metadata_version_snapshot)) {
936 			/*
937 			 * only do scanning if bch2_bkey_compat() has nothing to
938 			 * do
939 			 */
940 
941 			if (!__bkey_valid(c, b, i, (void *) ((u64 *) k + next_good_key))) {
942 				for (next_good_key = 1;
943 				     next_good_key < (u64 *) vstruct_last(i) - (u64 *) k;
944 				     next_good_key++)
945 					if (__bkey_valid(c, b, i, (void *) ((u64 *) k + next_good_key)))
946 						goto got_good_key;
947 
948 			}
949 
950 			/*
951 			 * didn't find a good key, have to truncate the rest of
952 			 * the bset
953 			 */
954 			next_good_key = (u64 *) vstruct_last(i) - (u64 *) k;
955 		}
956 got_good_key:
957 		le16_add_cpu(&i->u64s, -next_good_key);
958 		memmove_u64s_down(k, bkey_p_next(k), (u64 *) vstruct_end(i) - (u64 *) k);
959 	}
960 fsck_err:
961 	printbuf_exit(&buf);
962 	return ret;
963 }
964 
965 int bch2_btree_node_read_done(struct bch_fs *c, struct bch_dev *ca,
966 			      struct btree *b, bool have_retry, bool *saw_error)
967 {
968 	struct btree_node_entry *bne;
969 	struct sort_iter *iter;
970 	struct btree_node *sorted;
971 	struct bkey_packed *k;
972 	struct bset *i;
973 	bool used_mempool, blacklisted;
974 	bool updated_range = b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
975 		BTREE_PTR_RANGE_UPDATED(&bkey_i_to_btree_ptr_v2(&b->key)->v);
976 	unsigned u64s;
977 	unsigned ptr_written = btree_ptr_sectors_written(&b->key);
978 	struct printbuf buf = PRINTBUF;
979 	int ret = 0, retry_read = 0, write = READ;
980 	u64 start_time = local_clock();
981 
982 	b->version_ondisk = U16_MAX;
983 	/* We might get called multiple times on read retry: */
984 	b->written = 0;
985 
986 	iter = mempool_alloc(&c->fill_iter, GFP_NOFS);
987 	sort_iter_init(iter, b, (btree_blocks(c) + 1) * 2);
988 
989 	if (bch2_meta_read_fault("btree"))
990 		btree_err(-BCH_ERR_btree_node_read_err_must_retry,
991 			  c, ca, b, NULL,
992 			  btree_node_fault_injected,
993 			  "dynamic fault");
994 
995 	btree_err_on(le64_to_cpu(b->data->magic) != bset_magic(c),
996 		     -BCH_ERR_btree_node_read_err_must_retry,
997 		     c, ca, b, NULL,
998 		     btree_node_bad_magic,
999 		     "bad magic: want %llx, got %llx",
1000 		     bset_magic(c), le64_to_cpu(b->data->magic));
1001 
1002 	if (b->key.k.type == KEY_TYPE_btree_ptr_v2) {
1003 		struct bch_btree_ptr_v2 *bp =
1004 			&bkey_i_to_btree_ptr_v2(&b->key)->v;
1005 
1006 		bch2_bpos_to_text(&buf, b->data->min_key);
1007 		prt_str(&buf, "-");
1008 		bch2_bpos_to_text(&buf, b->data->max_key);
1009 
1010 		btree_err_on(b->data->keys.seq != bp->seq,
1011 			     -BCH_ERR_btree_node_read_err_must_retry,
1012 			     c, ca, b, NULL,
1013 			     btree_node_bad_seq,
1014 			     "got wrong btree node (want %llx got %llx)\n"
1015 			     "got btree %s level %llu pos %s",
1016 			     bp->seq, b->data->keys.seq,
1017 			     bch2_btree_id_str(BTREE_NODE_ID(b->data)),
1018 			     BTREE_NODE_LEVEL(b->data),
1019 			     buf.buf);
1020 	} else {
1021 		btree_err_on(!b->data->keys.seq,
1022 			     -BCH_ERR_btree_node_read_err_must_retry,
1023 			     c, ca, b, NULL,
1024 			     btree_node_bad_seq,
1025 			     "bad btree header: seq 0");
1026 	}
1027 
1028 	while (b->written < (ptr_written ?: btree_sectors(c))) {
1029 		unsigned sectors;
1030 		struct nonce nonce;
1031 		bool first = !b->written;
1032 		bool csum_bad;
1033 
1034 		if (!b->written) {
1035 			i = &b->data->keys;
1036 
1037 			btree_err_on(!bch2_checksum_type_valid(c, BSET_CSUM_TYPE(i)),
1038 				     -BCH_ERR_btree_node_read_err_want_retry,
1039 				     c, ca, b, i,
1040 				     bset_unknown_csum,
1041 				     "unknown checksum type %llu", BSET_CSUM_TYPE(i));
1042 
1043 			nonce = btree_nonce(i, b->written << 9);
1044 
1045 			struct bch_csum csum = csum_vstruct(c, BSET_CSUM_TYPE(i), nonce, b->data);
1046 			csum_bad = bch2_crc_cmp(b->data->csum, csum);
1047 			if (csum_bad)
1048 				bch2_io_error(ca, BCH_MEMBER_ERROR_checksum);
1049 
1050 			btree_err_on(csum_bad,
1051 				     -BCH_ERR_btree_node_read_err_want_retry,
1052 				     c, ca, b, i,
1053 				     bset_bad_csum,
1054 				     "%s",
1055 				     (printbuf_reset(&buf),
1056 				      bch2_csum_err_msg(&buf, BSET_CSUM_TYPE(i), b->data->csum, csum),
1057 				      buf.buf));
1058 
1059 			ret = bset_encrypt(c, i, b->written << 9);
1060 			if (bch2_fs_fatal_err_on(ret, c,
1061 					"error decrypting btree node: %i", ret))
1062 				goto fsck_err;
1063 
1064 			btree_err_on(btree_node_type_is_extents(btree_node_type(b)) &&
1065 				     !BTREE_NODE_NEW_EXTENT_OVERWRITE(b->data),
1066 				     -BCH_ERR_btree_node_read_err_incompatible,
1067 				     c, NULL, b, NULL,
1068 				     btree_node_unsupported_version,
1069 				     "btree node does not have NEW_EXTENT_OVERWRITE set");
1070 
1071 			sectors = vstruct_sectors(b->data, c->block_bits);
1072 		} else {
1073 			bne = write_block(b);
1074 			i = &bne->keys;
1075 
1076 			if (i->seq != b->data->keys.seq)
1077 				break;
1078 
1079 			btree_err_on(!bch2_checksum_type_valid(c, BSET_CSUM_TYPE(i)),
1080 				     -BCH_ERR_btree_node_read_err_want_retry,
1081 				     c, ca, b, i,
1082 				     bset_unknown_csum,
1083 				     "unknown checksum type %llu", BSET_CSUM_TYPE(i));
1084 
1085 			nonce = btree_nonce(i, b->written << 9);
1086 			struct bch_csum csum = csum_vstruct(c, BSET_CSUM_TYPE(i), nonce, bne);
1087 			csum_bad = bch2_crc_cmp(bne->csum, csum);
1088 			if (csum_bad)
1089 				bch2_io_error(ca, BCH_MEMBER_ERROR_checksum);
1090 
1091 			btree_err_on(csum_bad,
1092 				     -BCH_ERR_btree_node_read_err_want_retry,
1093 				     c, ca, b, i,
1094 				     bset_bad_csum,
1095 				     "%s",
1096 				     (printbuf_reset(&buf),
1097 				      bch2_csum_err_msg(&buf, BSET_CSUM_TYPE(i), bne->csum, csum),
1098 				      buf.buf));
1099 
1100 			ret = bset_encrypt(c, i, b->written << 9);
1101 			if (bch2_fs_fatal_err_on(ret, c,
1102 					"error decrypting btree node: %i\n", ret))
1103 				goto fsck_err;
1104 
1105 			sectors = vstruct_sectors(bne, c->block_bits);
1106 		}
1107 
1108 		b->version_ondisk = min(b->version_ondisk,
1109 					le16_to_cpu(i->version));
1110 
1111 		ret = validate_bset(c, ca, b, i, b->written, sectors,
1112 				    READ, have_retry, saw_error);
1113 		if (ret)
1114 			goto fsck_err;
1115 
1116 		if (!b->written)
1117 			btree_node_set_format(b, b->data->format);
1118 
1119 		ret = validate_bset_keys(c, b, i, READ, have_retry, saw_error);
1120 		if (ret)
1121 			goto fsck_err;
1122 
1123 		SET_BSET_BIG_ENDIAN(i, CPU_BIG_ENDIAN);
1124 
1125 		blacklisted = bch2_journal_seq_is_blacklisted(c,
1126 					le64_to_cpu(i->journal_seq),
1127 					true);
1128 
1129 		btree_err_on(blacklisted && first,
1130 			     -BCH_ERR_btree_node_read_err_fixable,
1131 			     c, ca, b, i,
1132 			     bset_blacklisted_journal_seq,
1133 			     "first btree node bset has blacklisted journal seq (%llu)",
1134 			     le64_to_cpu(i->journal_seq));
1135 
1136 		btree_err_on(blacklisted && ptr_written,
1137 			     -BCH_ERR_btree_node_read_err_fixable,
1138 			     c, ca, b, i,
1139 			     first_bset_blacklisted_journal_seq,
1140 			     "found blacklisted bset (journal seq %llu) in btree node at offset %u-%u/%u",
1141 			     le64_to_cpu(i->journal_seq),
1142 			     b->written, b->written + sectors, ptr_written);
1143 
1144 		b->written += sectors;
1145 
1146 		if (blacklisted && !first)
1147 			continue;
1148 
1149 		sort_iter_add(iter,
1150 			      vstruct_idx(i, 0),
1151 			      vstruct_last(i));
1152 	}
1153 
1154 	if (ptr_written) {
1155 		btree_err_on(b->written < ptr_written,
1156 			     -BCH_ERR_btree_node_read_err_want_retry,
1157 			     c, ca, b, NULL,
1158 			     btree_node_data_missing,
1159 			     "btree node data missing: expected %u sectors, found %u",
1160 			     ptr_written, b->written);
1161 	} else {
1162 		for (bne = write_block(b);
1163 		     bset_byte_offset(b, bne) < btree_buf_bytes(b);
1164 		     bne = (void *) bne + block_bytes(c))
1165 			btree_err_on(bne->keys.seq == b->data->keys.seq &&
1166 				     !bch2_journal_seq_is_blacklisted(c,
1167 								      le64_to_cpu(bne->keys.journal_seq),
1168 								      true),
1169 				     -BCH_ERR_btree_node_read_err_want_retry,
1170 				     c, ca, b, NULL,
1171 				     btree_node_bset_after_end,
1172 				     "found bset signature after last bset");
1173 	}
1174 
1175 	sorted = btree_bounce_alloc(c, btree_buf_bytes(b), &used_mempool);
1176 	sorted->keys.u64s = 0;
1177 
1178 	set_btree_bset(b, b->set, &b->data->keys);
1179 
1180 	b->nr = bch2_key_sort_fix_overlapping(c, &sorted->keys, iter);
1181 
1182 	u64s = le16_to_cpu(sorted->keys.u64s);
1183 	*sorted = *b->data;
1184 	sorted->keys.u64s = cpu_to_le16(u64s);
1185 	swap(sorted, b->data);
1186 	set_btree_bset(b, b->set, &b->data->keys);
1187 	b->nsets = 1;
1188 
1189 	BUG_ON(b->nr.live_u64s != u64s);
1190 
1191 	btree_bounce_free(c, btree_buf_bytes(b), used_mempool, sorted);
1192 
1193 	if (updated_range)
1194 		bch2_btree_node_drop_keys_outside_node(b);
1195 
1196 	i = &b->data->keys;
1197 	for (k = i->start; k != vstruct_last(i);) {
1198 		struct bkey tmp;
1199 		struct bkey_s u = __bkey_disassemble(b, k, &tmp);
1200 
1201 		printbuf_reset(&buf);
1202 
1203 		if (bch2_bkey_val_invalid(c, u.s_c, READ, &buf) ||
1204 		    (bch2_inject_invalid_keys &&
1205 		     !bversion_cmp(u.k->version, MAX_VERSION))) {
1206 			printbuf_reset(&buf);
1207 
1208 			prt_printf(&buf, "invalid bkey: ");
1209 			bch2_bkey_val_invalid(c, u.s_c, READ, &buf);
1210 			prt_printf(&buf, "\n  ");
1211 			bch2_bkey_val_to_text(&buf, c, u.s_c);
1212 
1213 			btree_err(-BCH_ERR_btree_node_read_err_fixable,
1214 				  c, NULL, b, i,
1215 				  btree_node_bad_bkey,
1216 				  "%s", buf.buf);
1217 
1218 			btree_keys_account_key_drop(&b->nr, 0, k);
1219 
1220 			i->u64s = cpu_to_le16(le16_to_cpu(i->u64s) - k->u64s);
1221 			memmove_u64s_down(k, bkey_p_next(k),
1222 					  (u64 *) vstruct_end(i) - (u64 *) k);
1223 			set_btree_bset_end(b, b->set);
1224 			continue;
1225 		}
1226 
1227 		if (u.k->type == KEY_TYPE_btree_ptr_v2) {
1228 			struct bkey_s_btree_ptr_v2 bp = bkey_s_to_btree_ptr_v2(u);
1229 
1230 			bp.v->mem_ptr = 0;
1231 		}
1232 
1233 		k = bkey_p_next(k);
1234 	}
1235 
1236 	bch2_bset_build_aux_tree(b, b->set, false);
1237 
1238 	set_needs_whiteout(btree_bset_first(b), true);
1239 
1240 	btree_node_reset_sib_u64s(b);
1241 
1242 	bkey_for_each_ptr(bch2_bkey_ptrs(bkey_i_to_s(&b->key)), ptr) {
1243 		struct bch_dev *ca2 = bch_dev_bkey_exists(c, ptr->dev);
1244 
1245 		if (ca2->mi.state != BCH_MEMBER_STATE_rw)
1246 			set_btree_node_need_rewrite(b);
1247 	}
1248 
1249 	if (!ptr_written)
1250 		set_btree_node_need_rewrite(b);
1251 out:
1252 	mempool_free(iter, &c->fill_iter);
1253 	printbuf_exit(&buf);
1254 	bch2_time_stats_update(&c->times[BCH_TIME_btree_node_read_done], start_time);
1255 	return retry_read;
1256 fsck_err:
1257 	if (ret == -BCH_ERR_btree_node_read_err_want_retry ||
1258 	    ret == -BCH_ERR_btree_node_read_err_must_retry)
1259 		retry_read = 1;
1260 	else
1261 		set_btree_node_read_error(b);
1262 	goto out;
1263 }
1264 
1265 static void btree_node_read_work(struct work_struct *work)
1266 {
1267 	struct btree_read_bio *rb =
1268 		container_of(work, struct btree_read_bio, work);
1269 	struct bch_fs *c	= rb->c;
1270 	struct btree *b		= rb->b;
1271 	struct bch_dev *ca	= bch_dev_bkey_exists(c, rb->pick.ptr.dev);
1272 	struct bio *bio		= &rb->bio;
1273 	struct bch_io_failures failed = { .nr = 0 };
1274 	struct printbuf buf = PRINTBUF;
1275 	bool saw_error = false;
1276 	bool retry = false;
1277 	bool can_retry;
1278 
1279 	goto start;
1280 	while (1) {
1281 		retry = true;
1282 		bch_info(c, "retrying read");
1283 		ca = bch_dev_bkey_exists(c, rb->pick.ptr.dev);
1284 		rb->have_ioref		= bch2_dev_get_ioref(ca, READ);
1285 		bio_reset(bio, NULL, REQ_OP_READ|REQ_SYNC|REQ_META);
1286 		bio->bi_iter.bi_sector	= rb->pick.ptr.offset;
1287 		bio->bi_iter.bi_size	= btree_buf_bytes(b);
1288 
1289 		if (rb->have_ioref) {
1290 			bio_set_dev(bio, ca->disk_sb.bdev);
1291 			submit_bio_wait(bio);
1292 		} else {
1293 			bio->bi_status = BLK_STS_REMOVED;
1294 		}
1295 start:
1296 		printbuf_reset(&buf);
1297 		bch2_btree_pos_to_text(&buf, c, b);
1298 		bch2_dev_io_err_on(bio->bi_status, ca, BCH_MEMBER_ERROR_read,
1299 				   "btree read error %s for %s",
1300 				   bch2_blk_status_to_str(bio->bi_status), buf.buf);
1301 		if (rb->have_ioref)
1302 			percpu_ref_put(&ca->io_ref);
1303 		rb->have_ioref = false;
1304 
1305 		bch2_mark_io_failure(&failed, &rb->pick);
1306 
1307 		can_retry = bch2_bkey_pick_read_device(c,
1308 				bkey_i_to_s_c(&b->key),
1309 				&failed, &rb->pick) > 0;
1310 
1311 		if (!bio->bi_status &&
1312 		    !bch2_btree_node_read_done(c, ca, b, can_retry, &saw_error)) {
1313 			if (retry)
1314 				bch_info(c, "retry success");
1315 			break;
1316 		}
1317 
1318 		saw_error = true;
1319 
1320 		if (!can_retry) {
1321 			set_btree_node_read_error(b);
1322 			break;
1323 		}
1324 	}
1325 
1326 	bch2_time_stats_update(&c->times[BCH_TIME_btree_node_read],
1327 			       rb->start_time);
1328 	bio_put(&rb->bio);
1329 
1330 	if (saw_error && !btree_node_read_error(b)) {
1331 		printbuf_reset(&buf);
1332 		bch2_bpos_to_text(&buf, b->key.k.p);
1333 		bch_info(c, "%s: rewriting btree node at btree=%s level=%u %s due to error",
1334 			 __func__, bch2_btree_id_str(b->c.btree_id), b->c.level, buf.buf);
1335 
1336 		bch2_btree_node_rewrite_async(c, b);
1337 	}
1338 
1339 	printbuf_exit(&buf);
1340 	clear_btree_node_read_in_flight(b);
1341 	wake_up_bit(&b->flags, BTREE_NODE_read_in_flight);
1342 }
1343 
1344 static void btree_node_read_endio(struct bio *bio)
1345 {
1346 	struct btree_read_bio *rb =
1347 		container_of(bio, struct btree_read_bio, bio);
1348 	struct bch_fs *c	= rb->c;
1349 
1350 	if (rb->have_ioref) {
1351 		struct bch_dev *ca = bch_dev_bkey_exists(c, rb->pick.ptr.dev);
1352 
1353 		bch2_latency_acct(ca, rb->start_time, READ);
1354 	}
1355 
1356 	queue_work(c->io_complete_wq, &rb->work);
1357 }
1358 
1359 struct btree_node_read_all {
1360 	struct closure		cl;
1361 	struct bch_fs		*c;
1362 	struct btree		*b;
1363 	unsigned		nr;
1364 	void			*buf[BCH_REPLICAS_MAX];
1365 	struct bio		*bio[BCH_REPLICAS_MAX];
1366 	blk_status_t		err[BCH_REPLICAS_MAX];
1367 };
1368 
1369 static unsigned btree_node_sectors_written(struct bch_fs *c, void *data)
1370 {
1371 	struct btree_node *bn = data;
1372 	struct btree_node_entry *bne;
1373 	unsigned offset = 0;
1374 
1375 	if (le64_to_cpu(bn->magic) !=  bset_magic(c))
1376 		return 0;
1377 
1378 	while (offset < btree_sectors(c)) {
1379 		if (!offset) {
1380 			offset += vstruct_sectors(bn, c->block_bits);
1381 		} else {
1382 			bne = data + (offset << 9);
1383 			if (bne->keys.seq != bn->keys.seq)
1384 				break;
1385 			offset += vstruct_sectors(bne, c->block_bits);
1386 		}
1387 	}
1388 
1389 	return offset;
1390 }
1391 
1392 static bool btree_node_has_extra_bsets(struct bch_fs *c, unsigned offset, void *data)
1393 {
1394 	struct btree_node *bn = data;
1395 	struct btree_node_entry *bne;
1396 
1397 	if (!offset)
1398 		return false;
1399 
1400 	while (offset < btree_sectors(c)) {
1401 		bne = data + (offset << 9);
1402 		if (bne->keys.seq == bn->keys.seq)
1403 			return true;
1404 		offset++;
1405 	}
1406 
1407 	return false;
1408 	return offset;
1409 }
1410 
1411 static CLOSURE_CALLBACK(btree_node_read_all_replicas_done)
1412 {
1413 	closure_type(ra, struct btree_node_read_all, cl);
1414 	struct bch_fs *c = ra->c;
1415 	struct btree *b = ra->b;
1416 	struct printbuf buf = PRINTBUF;
1417 	bool dump_bset_maps = false;
1418 	bool have_retry = false;
1419 	int ret = 0, best = -1, write = READ;
1420 	unsigned i, written = 0, written2 = 0;
1421 	__le64 seq = b->key.k.type == KEY_TYPE_btree_ptr_v2
1422 		? bkey_i_to_btree_ptr_v2(&b->key)->v.seq : 0;
1423 	bool _saw_error = false, *saw_error = &_saw_error;
1424 
1425 	for (i = 0; i < ra->nr; i++) {
1426 		struct btree_node *bn = ra->buf[i];
1427 
1428 		if (ra->err[i])
1429 			continue;
1430 
1431 		if (le64_to_cpu(bn->magic) != bset_magic(c) ||
1432 		    (seq && seq != bn->keys.seq))
1433 			continue;
1434 
1435 		if (best < 0) {
1436 			best = i;
1437 			written = btree_node_sectors_written(c, bn);
1438 			continue;
1439 		}
1440 
1441 		written2 = btree_node_sectors_written(c, ra->buf[i]);
1442 		if (btree_err_on(written2 != written, -BCH_ERR_btree_node_read_err_fixable,
1443 				 c, NULL, b, NULL,
1444 				 btree_node_replicas_sectors_written_mismatch,
1445 				 "btree node sectors written mismatch: %u != %u",
1446 				 written, written2) ||
1447 		    btree_err_on(btree_node_has_extra_bsets(c, written2, ra->buf[i]),
1448 				 -BCH_ERR_btree_node_read_err_fixable,
1449 				 c, NULL, b, NULL,
1450 				 btree_node_bset_after_end,
1451 				 "found bset signature after last bset") ||
1452 		    btree_err_on(memcmp(ra->buf[best], ra->buf[i], written << 9),
1453 				 -BCH_ERR_btree_node_read_err_fixable,
1454 				 c, NULL, b, NULL,
1455 				 btree_node_replicas_data_mismatch,
1456 				 "btree node replicas content mismatch"))
1457 			dump_bset_maps = true;
1458 
1459 		if (written2 > written) {
1460 			written = written2;
1461 			best = i;
1462 		}
1463 	}
1464 fsck_err:
1465 	if (dump_bset_maps) {
1466 		for (i = 0; i < ra->nr; i++) {
1467 			struct btree_node *bn = ra->buf[i];
1468 			struct btree_node_entry *bne = NULL;
1469 			unsigned offset = 0, sectors;
1470 			bool gap = false;
1471 
1472 			if (ra->err[i])
1473 				continue;
1474 
1475 			printbuf_reset(&buf);
1476 
1477 			while (offset < btree_sectors(c)) {
1478 				if (!offset) {
1479 					sectors = vstruct_sectors(bn, c->block_bits);
1480 				} else {
1481 					bne = ra->buf[i] + (offset << 9);
1482 					if (bne->keys.seq != bn->keys.seq)
1483 						break;
1484 					sectors = vstruct_sectors(bne, c->block_bits);
1485 				}
1486 
1487 				prt_printf(&buf, " %u-%u", offset, offset + sectors);
1488 				if (bne && bch2_journal_seq_is_blacklisted(c,
1489 							le64_to_cpu(bne->keys.journal_seq), false))
1490 					prt_printf(&buf, "*");
1491 				offset += sectors;
1492 			}
1493 
1494 			while (offset < btree_sectors(c)) {
1495 				bne = ra->buf[i] + (offset << 9);
1496 				if (bne->keys.seq == bn->keys.seq) {
1497 					if (!gap)
1498 						prt_printf(&buf, " GAP");
1499 					gap = true;
1500 
1501 					sectors = vstruct_sectors(bne, c->block_bits);
1502 					prt_printf(&buf, " %u-%u", offset, offset + sectors);
1503 					if (bch2_journal_seq_is_blacklisted(c,
1504 							le64_to_cpu(bne->keys.journal_seq), false))
1505 						prt_printf(&buf, "*");
1506 				}
1507 				offset++;
1508 			}
1509 
1510 			bch_err(c, "replica %u:%s", i, buf.buf);
1511 		}
1512 	}
1513 
1514 	if (best >= 0) {
1515 		memcpy(b->data, ra->buf[best], btree_buf_bytes(b));
1516 		ret = bch2_btree_node_read_done(c, NULL, b, false, saw_error);
1517 	} else {
1518 		ret = -1;
1519 	}
1520 
1521 	if (ret)
1522 		set_btree_node_read_error(b);
1523 	else if (*saw_error)
1524 		bch2_btree_node_rewrite_async(c, b);
1525 
1526 	for (i = 0; i < ra->nr; i++) {
1527 		mempool_free(ra->buf[i], &c->btree_bounce_pool);
1528 		bio_put(ra->bio[i]);
1529 	}
1530 
1531 	closure_debug_destroy(&ra->cl);
1532 	kfree(ra);
1533 	printbuf_exit(&buf);
1534 
1535 	clear_btree_node_read_in_flight(b);
1536 	wake_up_bit(&b->flags, BTREE_NODE_read_in_flight);
1537 }
1538 
1539 static void btree_node_read_all_replicas_endio(struct bio *bio)
1540 {
1541 	struct btree_read_bio *rb =
1542 		container_of(bio, struct btree_read_bio, bio);
1543 	struct bch_fs *c	= rb->c;
1544 	struct btree_node_read_all *ra = rb->ra;
1545 
1546 	if (rb->have_ioref) {
1547 		struct bch_dev *ca = bch_dev_bkey_exists(c, rb->pick.ptr.dev);
1548 
1549 		bch2_latency_acct(ca, rb->start_time, READ);
1550 	}
1551 
1552 	ra->err[rb->idx] = bio->bi_status;
1553 	closure_put(&ra->cl);
1554 }
1555 
1556 /*
1557  * XXX This allocates multiple times from the same mempools, and can deadlock
1558  * under sufficient memory pressure (but is only a debug path)
1559  */
1560 static int btree_node_read_all_replicas(struct bch_fs *c, struct btree *b, bool sync)
1561 {
1562 	struct bkey_s_c k = bkey_i_to_s_c(&b->key);
1563 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1564 	const union bch_extent_entry *entry;
1565 	struct extent_ptr_decoded pick;
1566 	struct btree_node_read_all *ra;
1567 	unsigned i;
1568 
1569 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
1570 	if (!ra)
1571 		return -BCH_ERR_ENOMEM_btree_node_read_all_replicas;
1572 
1573 	closure_init(&ra->cl, NULL);
1574 	ra->c	= c;
1575 	ra->b	= b;
1576 	ra->nr	= bch2_bkey_nr_ptrs(k);
1577 
1578 	for (i = 0; i < ra->nr; i++) {
1579 		ra->buf[i] = mempool_alloc(&c->btree_bounce_pool, GFP_NOFS);
1580 		ra->bio[i] = bio_alloc_bioset(NULL,
1581 					      buf_pages(ra->buf[i], btree_buf_bytes(b)),
1582 					      REQ_OP_READ|REQ_SYNC|REQ_META,
1583 					      GFP_NOFS,
1584 					      &c->btree_bio);
1585 	}
1586 
1587 	i = 0;
1588 	bkey_for_each_ptr_decode(k.k, ptrs, pick, entry) {
1589 		struct bch_dev *ca = bch_dev_bkey_exists(c, pick.ptr.dev);
1590 		struct btree_read_bio *rb =
1591 			container_of(ra->bio[i], struct btree_read_bio, bio);
1592 		rb->c			= c;
1593 		rb->b			= b;
1594 		rb->ra			= ra;
1595 		rb->start_time		= local_clock();
1596 		rb->have_ioref		= bch2_dev_get_ioref(ca, READ);
1597 		rb->idx			= i;
1598 		rb->pick		= pick;
1599 		rb->bio.bi_iter.bi_sector = pick.ptr.offset;
1600 		rb->bio.bi_end_io	= btree_node_read_all_replicas_endio;
1601 		bch2_bio_map(&rb->bio, ra->buf[i], btree_buf_bytes(b));
1602 
1603 		if (rb->have_ioref) {
1604 			this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_btree],
1605 				     bio_sectors(&rb->bio));
1606 			bio_set_dev(&rb->bio, ca->disk_sb.bdev);
1607 
1608 			closure_get(&ra->cl);
1609 			submit_bio(&rb->bio);
1610 		} else {
1611 			ra->err[i] = BLK_STS_REMOVED;
1612 		}
1613 
1614 		i++;
1615 	}
1616 
1617 	if (sync) {
1618 		closure_sync(&ra->cl);
1619 		btree_node_read_all_replicas_done(&ra->cl.work);
1620 	} else {
1621 		continue_at(&ra->cl, btree_node_read_all_replicas_done,
1622 			    c->io_complete_wq);
1623 	}
1624 
1625 	return 0;
1626 }
1627 
1628 void bch2_btree_node_read(struct btree_trans *trans, struct btree *b,
1629 			  bool sync)
1630 {
1631 	struct bch_fs *c = trans->c;
1632 	struct extent_ptr_decoded pick;
1633 	struct btree_read_bio *rb;
1634 	struct bch_dev *ca;
1635 	struct bio *bio;
1636 	int ret;
1637 
1638 	trace_and_count(c, btree_node_read, trans, b);
1639 
1640 	if (bch2_verify_all_btree_replicas &&
1641 	    !btree_node_read_all_replicas(c, b, sync))
1642 		return;
1643 
1644 	ret = bch2_bkey_pick_read_device(c, bkey_i_to_s_c(&b->key),
1645 					 NULL, &pick);
1646 
1647 	if (ret <= 0) {
1648 		struct printbuf buf = PRINTBUF;
1649 
1650 		prt_str(&buf, "btree node read error: no device to read from\n at ");
1651 		bch2_btree_pos_to_text(&buf, c, b);
1652 		bch_err(c, "%s", buf.buf);
1653 
1654 		if (c->recovery_passes_explicit & BIT_ULL(BCH_RECOVERY_PASS_check_topology) &&
1655 		    c->curr_recovery_pass > BCH_RECOVERY_PASS_check_topology)
1656 			bch2_fatal_error(c);
1657 
1658 		set_btree_node_read_error(b);
1659 		clear_btree_node_read_in_flight(b);
1660 		wake_up_bit(&b->flags, BTREE_NODE_read_in_flight);
1661 		printbuf_exit(&buf);
1662 		return;
1663 	}
1664 
1665 	ca = bch_dev_bkey_exists(c, pick.ptr.dev);
1666 
1667 	bio = bio_alloc_bioset(NULL,
1668 			       buf_pages(b->data, btree_buf_bytes(b)),
1669 			       REQ_OP_READ|REQ_SYNC|REQ_META,
1670 			       GFP_NOFS,
1671 			       &c->btree_bio);
1672 	rb = container_of(bio, struct btree_read_bio, bio);
1673 	rb->c			= c;
1674 	rb->b			= b;
1675 	rb->ra			= NULL;
1676 	rb->start_time		= local_clock();
1677 	rb->have_ioref		= bch2_dev_get_ioref(ca, READ);
1678 	rb->pick		= pick;
1679 	INIT_WORK(&rb->work, btree_node_read_work);
1680 	bio->bi_iter.bi_sector	= pick.ptr.offset;
1681 	bio->bi_end_io		= btree_node_read_endio;
1682 	bch2_bio_map(bio, b->data, btree_buf_bytes(b));
1683 
1684 	if (rb->have_ioref) {
1685 		this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_btree],
1686 			     bio_sectors(bio));
1687 		bio_set_dev(bio, ca->disk_sb.bdev);
1688 
1689 		if (sync) {
1690 			submit_bio_wait(bio);
1691 			bch2_latency_acct(ca, rb->start_time, READ);
1692 			btree_node_read_work(&rb->work);
1693 		} else {
1694 			submit_bio(bio);
1695 		}
1696 	} else {
1697 		bio->bi_status = BLK_STS_REMOVED;
1698 
1699 		if (sync)
1700 			btree_node_read_work(&rb->work);
1701 		else
1702 			queue_work(c->io_complete_wq, &rb->work);
1703 	}
1704 }
1705 
1706 static int __bch2_btree_root_read(struct btree_trans *trans, enum btree_id id,
1707 				  const struct bkey_i *k, unsigned level)
1708 {
1709 	struct bch_fs *c = trans->c;
1710 	struct closure cl;
1711 	struct btree *b;
1712 	int ret;
1713 
1714 	closure_init_stack(&cl);
1715 
1716 	do {
1717 		ret = bch2_btree_cache_cannibalize_lock(trans, &cl);
1718 		closure_sync(&cl);
1719 	} while (ret);
1720 
1721 	b = bch2_btree_node_mem_alloc(trans, level != 0);
1722 	bch2_btree_cache_cannibalize_unlock(trans);
1723 
1724 	BUG_ON(IS_ERR(b));
1725 
1726 	bkey_copy(&b->key, k);
1727 	BUG_ON(bch2_btree_node_hash_insert(&c->btree_cache, b, level, id));
1728 
1729 	set_btree_node_read_in_flight(b);
1730 
1731 	bch2_btree_node_read(trans, b, true);
1732 
1733 	if (btree_node_read_error(b)) {
1734 		bch2_btree_node_hash_remove(&c->btree_cache, b);
1735 
1736 		mutex_lock(&c->btree_cache.lock);
1737 		list_move(&b->list, &c->btree_cache.freeable);
1738 		mutex_unlock(&c->btree_cache.lock);
1739 
1740 		ret = -EIO;
1741 		goto err;
1742 	}
1743 
1744 	bch2_btree_set_root_for_read(c, b);
1745 err:
1746 	six_unlock_write(&b->c.lock);
1747 	six_unlock_intent(&b->c.lock);
1748 
1749 	return ret;
1750 }
1751 
1752 int bch2_btree_root_read(struct bch_fs *c, enum btree_id id,
1753 			const struct bkey_i *k, unsigned level)
1754 {
1755 	return bch2_trans_run(c, __bch2_btree_root_read(trans, id, k, level));
1756 }
1757 
1758 static void bch2_btree_complete_write(struct bch_fs *c, struct btree *b,
1759 				      struct btree_write *w)
1760 {
1761 	unsigned long old, new, v = READ_ONCE(b->will_make_reachable);
1762 
1763 	do {
1764 		old = new = v;
1765 		if (!(old & 1))
1766 			break;
1767 
1768 		new &= ~1UL;
1769 	} while ((v = cmpxchg(&b->will_make_reachable, old, new)) != old);
1770 
1771 	if (old & 1)
1772 		closure_put(&((struct btree_update *) new)->cl);
1773 
1774 	bch2_journal_pin_drop(&c->journal, &w->journal);
1775 }
1776 
1777 static void __btree_node_write_done(struct bch_fs *c, struct btree *b)
1778 {
1779 	struct btree_write *w = btree_prev_write(b);
1780 	unsigned long old, new, v;
1781 	unsigned type = 0;
1782 
1783 	bch2_btree_complete_write(c, b, w);
1784 
1785 	v = READ_ONCE(b->flags);
1786 	do {
1787 		old = new = v;
1788 
1789 		if ((old & (1U << BTREE_NODE_dirty)) &&
1790 		    (old & (1U << BTREE_NODE_need_write)) &&
1791 		    !(old & (1U << BTREE_NODE_never_write)) &&
1792 		    !(old & (1U << BTREE_NODE_write_blocked)) &&
1793 		    !(old & (1U << BTREE_NODE_will_make_reachable))) {
1794 			new &= ~(1U << BTREE_NODE_dirty);
1795 			new &= ~(1U << BTREE_NODE_need_write);
1796 			new |=  (1U << BTREE_NODE_write_in_flight);
1797 			new |=  (1U << BTREE_NODE_write_in_flight_inner);
1798 			new |=  (1U << BTREE_NODE_just_written);
1799 			new ^=  (1U << BTREE_NODE_write_idx);
1800 
1801 			type = new & BTREE_WRITE_TYPE_MASK;
1802 			new &= ~BTREE_WRITE_TYPE_MASK;
1803 		} else {
1804 			new &= ~(1U << BTREE_NODE_write_in_flight);
1805 			new &= ~(1U << BTREE_NODE_write_in_flight_inner);
1806 		}
1807 	} while ((v = cmpxchg(&b->flags, old, new)) != old);
1808 
1809 	if (new & (1U << BTREE_NODE_write_in_flight))
1810 		__bch2_btree_node_write(c, b, BTREE_WRITE_ALREADY_STARTED|type);
1811 	else
1812 		wake_up_bit(&b->flags, BTREE_NODE_write_in_flight);
1813 }
1814 
1815 static void btree_node_write_done(struct bch_fs *c, struct btree *b)
1816 {
1817 	struct btree_trans *trans = bch2_trans_get(c);
1818 
1819 	btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_read);
1820 	__btree_node_write_done(c, b);
1821 	six_unlock_read(&b->c.lock);
1822 
1823 	bch2_trans_put(trans);
1824 }
1825 
1826 static void btree_node_write_work(struct work_struct *work)
1827 {
1828 	struct btree_write_bio *wbio =
1829 		container_of(work, struct btree_write_bio, work);
1830 	struct bch_fs *c	= wbio->wbio.c;
1831 	struct btree *b		= wbio->wbio.bio.bi_private;
1832 	struct bch_extent_ptr *ptr;
1833 	int ret = 0;
1834 
1835 	btree_bounce_free(c,
1836 		wbio->data_bytes,
1837 		wbio->wbio.used_mempool,
1838 		wbio->data);
1839 
1840 	bch2_bkey_drop_ptrs(bkey_i_to_s(&wbio->key), ptr,
1841 		bch2_dev_list_has_dev(wbio->wbio.failed, ptr->dev));
1842 
1843 	if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(&wbio->key))) {
1844 		ret = -BCH_ERR_btree_write_all_failed;
1845 		goto err;
1846 	}
1847 
1848 	if (wbio->wbio.first_btree_write) {
1849 		if (wbio->wbio.failed.nr) {
1850 
1851 		}
1852 	} else {
1853 		ret = bch2_trans_do(c, NULL, NULL, 0,
1854 			bch2_btree_node_update_key_get_iter(trans, b, &wbio->key,
1855 					BCH_WATERMARK_reclaim|
1856 					BCH_TRANS_COMMIT_journal_reclaim|
1857 					BCH_TRANS_COMMIT_no_enospc|
1858 					BCH_TRANS_COMMIT_no_check_rw,
1859 					!wbio->wbio.failed.nr));
1860 		if (ret)
1861 			goto err;
1862 	}
1863 out:
1864 	bio_put(&wbio->wbio.bio);
1865 	btree_node_write_done(c, b);
1866 	return;
1867 err:
1868 	set_btree_node_noevict(b);
1869 	if (!bch2_err_matches(ret, EROFS))
1870 		bch2_fs_fatal_error(c, "fatal error writing btree node: %s", bch2_err_str(ret));
1871 	goto out;
1872 }
1873 
1874 static void btree_node_write_endio(struct bio *bio)
1875 {
1876 	struct bch_write_bio *wbio	= to_wbio(bio);
1877 	struct bch_write_bio *parent	= wbio->split ? wbio->parent : NULL;
1878 	struct bch_write_bio *orig	= parent ?: wbio;
1879 	struct btree_write_bio *wb	= container_of(orig, struct btree_write_bio, wbio);
1880 	struct bch_fs *c		= wbio->c;
1881 	struct btree *b			= wbio->bio.bi_private;
1882 	struct bch_dev *ca		= bch_dev_bkey_exists(c, wbio->dev);
1883 	unsigned long flags;
1884 
1885 	if (wbio->have_ioref)
1886 		bch2_latency_acct(ca, wbio->submit_time, WRITE);
1887 
1888 	if (bch2_dev_io_err_on(bio->bi_status, ca, BCH_MEMBER_ERROR_write,
1889 			       "btree write error: %s",
1890 			       bch2_blk_status_to_str(bio->bi_status)) ||
1891 	    bch2_meta_write_fault("btree")) {
1892 		spin_lock_irqsave(&c->btree_write_error_lock, flags);
1893 		bch2_dev_list_add_dev(&orig->failed, wbio->dev);
1894 		spin_unlock_irqrestore(&c->btree_write_error_lock, flags);
1895 	}
1896 
1897 	if (wbio->have_ioref)
1898 		percpu_ref_put(&ca->io_ref);
1899 
1900 	if (parent) {
1901 		bio_put(bio);
1902 		bio_endio(&parent->bio);
1903 		return;
1904 	}
1905 
1906 	clear_btree_node_write_in_flight_inner(b);
1907 	wake_up_bit(&b->flags, BTREE_NODE_write_in_flight_inner);
1908 	INIT_WORK(&wb->work, btree_node_write_work);
1909 	queue_work(c->btree_io_complete_wq, &wb->work);
1910 }
1911 
1912 static int validate_bset_for_write(struct bch_fs *c, struct btree *b,
1913 				   struct bset *i, unsigned sectors)
1914 {
1915 	struct printbuf buf = PRINTBUF;
1916 	bool saw_error;
1917 	int ret;
1918 
1919 	ret = bch2_bkey_invalid(c, bkey_i_to_s_c(&b->key),
1920 				BKEY_TYPE_btree, WRITE, &buf);
1921 
1922 	if (ret)
1923 		bch2_fs_inconsistent(c, "invalid btree node key before write: %s", buf.buf);
1924 	printbuf_exit(&buf);
1925 	if (ret)
1926 		return ret;
1927 
1928 	ret = validate_bset_keys(c, b, i, WRITE, false, &saw_error) ?:
1929 		validate_bset(c, NULL, b, i, b->written, sectors, WRITE, false, &saw_error);
1930 	if (ret) {
1931 		bch2_inconsistent_error(c);
1932 		dump_stack();
1933 	}
1934 
1935 	return ret;
1936 }
1937 
1938 static void btree_write_submit(struct work_struct *work)
1939 {
1940 	struct btree_write_bio *wbio = container_of(work, struct btree_write_bio, work);
1941 	BKEY_PADDED_ONSTACK(k, BKEY_BTREE_PTR_VAL_U64s_MAX) tmp;
1942 
1943 	bkey_copy(&tmp.k, &wbio->key);
1944 
1945 	bkey_for_each_ptr(bch2_bkey_ptrs(bkey_i_to_s(&tmp.k)), ptr)
1946 		ptr->offset += wbio->sector_offset;
1947 
1948 	bch2_submit_wbio_replicas(&wbio->wbio, wbio->wbio.c, BCH_DATA_btree,
1949 				  &tmp.k, false);
1950 }
1951 
1952 void __bch2_btree_node_write(struct bch_fs *c, struct btree *b, unsigned flags)
1953 {
1954 	struct btree_write_bio *wbio;
1955 	struct bset_tree *t;
1956 	struct bset *i;
1957 	struct btree_node *bn = NULL;
1958 	struct btree_node_entry *bne = NULL;
1959 	struct sort_iter_stack sort_iter;
1960 	struct nonce nonce;
1961 	unsigned bytes_to_write, sectors_to_write, bytes, u64s;
1962 	u64 seq = 0;
1963 	bool used_mempool;
1964 	unsigned long old, new;
1965 	bool validate_before_checksum = false;
1966 	enum btree_write_type type = flags & BTREE_WRITE_TYPE_MASK;
1967 	void *data;
1968 	int ret;
1969 
1970 	if (flags & BTREE_WRITE_ALREADY_STARTED)
1971 		goto do_write;
1972 
1973 	/*
1974 	 * We may only have a read lock on the btree node - the dirty bit is our
1975 	 * "lock" against racing with other threads that may be trying to start
1976 	 * a write, we do a write iff we clear the dirty bit. Since setting the
1977 	 * dirty bit requires a write lock, we can't race with other threads
1978 	 * redirtying it:
1979 	 */
1980 	do {
1981 		old = new = READ_ONCE(b->flags);
1982 
1983 		if (!(old & (1 << BTREE_NODE_dirty)))
1984 			return;
1985 
1986 		if ((flags & BTREE_WRITE_ONLY_IF_NEED) &&
1987 		    !(old & (1 << BTREE_NODE_need_write)))
1988 			return;
1989 
1990 		if (old &
1991 		    ((1 << BTREE_NODE_never_write)|
1992 		     (1 << BTREE_NODE_write_blocked)))
1993 			return;
1994 
1995 		if (b->written &&
1996 		    (old & (1 << BTREE_NODE_will_make_reachable)))
1997 			return;
1998 
1999 		if (old & (1 << BTREE_NODE_write_in_flight))
2000 			return;
2001 
2002 		if (flags & BTREE_WRITE_ONLY_IF_NEED)
2003 			type = new & BTREE_WRITE_TYPE_MASK;
2004 		new &= ~BTREE_WRITE_TYPE_MASK;
2005 
2006 		new &= ~(1 << BTREE_NODE_dirty);
2007 		new &= ~(1 << BTREE_NODE_need_write);
2008 		new |=  (1 << BTREE_NODE_write_in_flight);
2009 		new |=  (1 << BTREE_NODE_write_in_flight_inner);
2010 		new |=  (1 << BTREE_NODE_just_written);
2011 		new ^=  (1 << BTREE_NODE_write_idx);
2012 	} while (cmpxchg_acquire(&b->flags, old, new) != old);
2013 
2014 	if (new & (1U << BTREE_NODE_need_write))
2015 		return;
2016 do_write:
2017 	BUG_ON((type == BTREE_WRITE_initial) != (b->written == 0));
2018 
2019 	atomic_dec(&c->btree_cache.dirty);
2020 
2021 	BUG_ON(btree_node_fake(b));
2022 	BUG_ON((b->will_make_reachable != 0) != !b->written);
2023 
2024 	BUG_ON(b->written >= btree_sectors(c));
2025 	BUG_ON(b->written & (block_sectors(c) - 1));
2026 	BUG_ON(bset_written(b, btree_bset_last(b)));
2027 	BUG_ON(le64_to_cpu(b->data->magic) != bset_magic(c));
2028 	BUG_ON(memcmp(&b->data->format, &b->format, sizeof(b->format)));
2029 
2030 	bch2_sort_whiteouts(c, b);
2031 
2032 	sort_iter_stack_init(&sort_iter, b);
2033 
2034 	bytes = !b->written
2035 		? sizeof(struct btree_node)
2036 		: sizeof(struct btree_node_entry);
2037 
2038 	bytes += b->whiteout_u64s * sizeof(u64);
2039 
2040 	for_each_bset(b, t) {
2041 		i = bset(b, t);
2042 
2043 		if (bset_written(b, i))
2044 			continue;
2045 
2046 		bytes += le16_to_cpu(i->u64s) * sizeof(u64);
2047 		sort_iter_add(&sort_iter.iter,
2048 			      btree_bkey_first(b, t),
2049 			      btree_bkey_last(b, t));
2050 		seq = max(seq, le64_to_cpu(i->journal_seq));
2051 	}
2052 
2053 	BUG_ON(b->written && !seq);
2054 
2055 	/* bch2_varint_decode may read up to 7 bytes past the end of the buffer: */
2056 	bytes += 8;
2057 
2058 	/* buffer must be a multiple of the block size */
2059 	bytes = round_up(bytes, block_bytes(c));
2060 
2061 	data = btree_bounce_alloc(c, bytes, &used_mempool);
2062 
2063 	if (!b->written) {
2064 		bn = data;
2065 		*bn = *b->data;
2066 		i = &bn->keys;
2067 	} else {
2068 		bne = data;
2069 		bne->keys = b->data->keys;
2070 		i = &bne->keys;
2071 	}
2072 
2073 	i->journal_seq	= cpu_to_le64(seq);
2074 	i->u64s		= 0;
2075 
2076 	sort_iter_add(&sort_iter.iter,
2077 		      unwritten_whiteouts_start(b),
2078 		      unwritten_whiteouts_end(b));
2079 	SET_BSET_SEPARATE_WHITEOUTS(i, false);
2080 
2081 	b->whiteout_u64s = 0;
2082 
2083 	u64s = bch2_sort_keys(i->start, &sort_iter.iter, false);
2084 	le16_add_cpu(&i->u64s, u64s);
2085 
2086 	BUG_ON(!b->written && i->u64s != b->data->keys.u64s);
2087 
2088 	set_needs_whiteout(i, false);
2089 
2090 	/* do we have data to write? */
2091 	if (b->written && !i->u64s)
2092 		goto nowrite;
2093 
2094 	bytes_to_write = vstruct_end(i) - data;
2095 	sectors_to_write = round_up(bytes_to_write, block_bytes(c)) >> 9;
2096 
2097 	if (!b->written &&
2098 	    b->key.k.type == KEY_TYPE_btree_ptr_v2)
2099 		BUG_ON(btree_ptr_sectors_written(&b->key) != sectors_to_write);
2100 
2101 	memset(data + bytes_to_write, 0,
2102 	       (sectors_to_write << 9) - bytes_to_write);
2103 
2104 	BUG_ON(b->written + sectors_to_write > btree_sectors(c));
2105 	BUG_ON(BSET_BIG_ENDIAN(i) != CPU_BIG_ENDIAN);
2106 	BUG_ON(i->seq != b->data->keys.seq);
2107 
2108 	i->version = cpu_to_le16(c->sb.version);
2109 	SET_BSET_OFFSET(i, b->written);
2110 	SET_BSET_CSUM_TYPE(i, bch2_meta_checksum_type(c));
2111 
2112 	if (bch2_csum_type_is_encryption(BSET_CSUM_TYPE(i)))
2113 		validate_before_checksum = true;
2114 
2115 	/* validate_bset will be modifying: */
2116 	if (le16_to_cpu(i->version) < bcachefs_metadata_version_current)
2117 		validate_before_checksum = true;
2118 
2119 	/* if we're going to be encrypting, check metadata validity first: */
2120 	if (validate_before_checksum &&
2121 	    validate_bset_for_write(c, b, i, sectors_to_write))
2122 		goto err;
2123 
2124 	ret = bset_encrypt(c, i, b->written << 9);
2125 	if (bch2_fs_fatal_err_on(ret, c,
2126 			"error encrypting btree node: %i\n", ret))
2127 		goto err;
2128 
2129 	nonce = btree_nonce(i, b->written << 9);
2130 
2131 	if (bn)
2132 		bn->csum = csum_vstruct(c, BSET_CSUM_TYPE(i), nonce, bn);
2133 	else
2134 		bne->csum = csum_vstruct(c, BSET_CSUM_TYPE(i), nonce, bne);
2135 
2136 	/* if we're not encrypting, check metadata after checksumming: */
2137 	if (!validate_before_checksum &&
2138 	    validate_bset_for_write(c, b, i, sectors_to_write))
2139 		goto err;
2140 
2141 	/*
2142 	 * We handle btree write errors by immediately halting the journal -
2143 	 * after we've done that, we can't issue any subsequent btree writes
2144 	 * because they might have pointers to new nodes that failed to write.
2145 	 *
2146 	 * Furthermore, there's no point in doing any more btree writes because
2147 	 * with the journal stopped, we're never going to update the journal to
2148 	 * reflect that those writes were done and the data flushed from the
2149 	 * journal:
2150 	 *
2151 	 * Also on journal error, the pending write may have updates that were
2152 	 * never journalled (interior nodes, see btree_update_nodes_written()) -
2153 	 * it's critical that we don't do the write in that case otherwise we
2154 	 * will have updates visible that weren't in the journal:
2155 	 *
2156 	 * Make sure to update b->written so bch2_btree_init_next() doesn't
2157 	 * break:
2158 	 */
2159 	if (bch2_journal_error(&c->journal) ||
2160 	    c->opts.nochanges)
2161 		goto err;
2162 
2163 	trace_and_count(c, btree_node_write, b, bytes_to_write, sectors_to_write);
2164 
2165 	wbio = container_of(bio_alloc_bioset(NULL,
2166 				buf_pages(data, sectors_to_write << 9),
2167 				REQ_OP_WRITE|REQ_META,
2168 				GFP_NOFS,
2169 				&c->btree_bio),
2170 			    struct btree_write_bio, wbio.bio);
2171 	wbio_init(&wbio->wbio.bio);
2172 	wbio->data			= data;
2173 	wbio->data_bytes		= bytes;
2174 	wbio->sector_offset		= b->written;
2175 	wbio->wbio.c			= c;
2176 	wbio->wbio.used_mempool		= used_mempool;
2177 	wbio->wbio.first_btree_write	= !b->written;
2178 	wbio->wbio.bio.bi_end_io	= btree_node_write_endio;
2179 	wbio->wbio.bio.bi_private	= b;
2180 
2181 	bch2_bio_map(&wbio->wbio.bio, data, sectors_to_write << 9);
2182 
2183 	bkey_copy(&wbio->key, &b->key);
2184 
2185 	b->written += sectors_to_write;
2186 
2187 	if (wbio->key.k.type == KEY_TYPE_btree_ptr_v2)
2188 		bkey_i_to_btree_ptr_v2(&wbio->key)->v.sectors_written =
2189 			cpu_to_le16(b->written);
2190 
2191 	atomic64_inc(&c->btree_write_stats[type].nr);
2192 	atomic64_add(bytes_to_write, &c->btree_write_stats[type].bytes);
2193 
2194 	INIT_WORK(&wbio->work, btree_write_submit);
2195 	queue_work(c->io_complete_wq, &wbio->work);
2196 	return;
2197 err:
2198 	set_btree_node_noevict(b);
2199 	b->written += sectors_to_write;
2200 nowrite:
2201 	btree_bounce_free(c, bytes, used_mempool, data);
2202 	__btree_node_write_done(c, b);
2203 }
2204 
2205 /*
2206  * Work that must be done with write lock held:
2207  */
2208 bool bch2_btree_post_write_cleanup(struct bch_fs *c, struct btree *b)
2209 {
2210 	bool invalidated_iter = false;
2211 	struct btree_node_entry *bne;
2212 	struct bset_tree *t;
2213 
2214 	if (!btree_node_just_written(b))
2215 		return false;
2216 
2217 	BUG_ON(b->whiteout_u64s);
2218 
2219 	clear_btree_node_just_written(b);
2220 
2221 	/*
2222 	 * Note: immediately after write, bset_written() doesn't work - the
2223 	 * amount of data we had to write after compaction might have been
2224 	 * smaller than the offset of the last bset.
2225 	 *
2226 	 * However, we know that all bsets have been written here, as long as
2227 	 * we're still holding the write lock:
2228 	 */
2229 
2230 	/*
2231 	 * XXX: decide if we really want to unconditionally sort down to a
2232 	 * single bset:
2233 	 */
2234 	if (b->nsets > 1) {
2235 		btree_node_sort(c, b, 0, b->nsets, true);
2236 		invalidated_iter = true;
2237 	} else {
2238 		invalidated_iter = bch2_drop_whiteouts(b, COMPACT_ALL);
2239 	}
2240 
2241 	for_each_bset(b, t)
2242 		set_needs_whiteout(bset(b, t), true);
2243 
2244 	bch2_btree_verify(c, b);
2245 
2246 	/*
2247 	 * If later we don't unconditionally sort down to a single bset, we have
2248 	 * to ensure this is still true:
2249 	 */
2250 	BUG_ON((void *) btree_bkey_last(b, bset_tree_last(b)) > write_block(b));
2251 
2252 	bne = want_new_bset(c, b);
2253 	if (bne)
2254 		bch2_bset_init_next(b, bne);
2255 
2256 	bch2_btree_build_aux_trees(b);
2257 
2258 	return invalidated_iter;
2259 }
2260 
2261 /*
2262  * Use this one if the node is intent locked:
2263  */
2264 void bch2_btree_node_write(struct bch_fs *c, struct btree *b,
2265 			   enum six_lock_type lock_type_held,
2266 			   unsigned flags)
2267 {
2268 	if (lock_type_held == SIX_LOCK_intent ||
2269 	    (lock_type_held == SIX_LOCK_read &&
2270 	     six_lock_tryupgrade(&b->c.lock))) {
2271 		__bch2_btree_node_write(c, b, flags);
2272 
2273 		/* don't cycle lock unnecessarily: */
2274 		if (btree_node_just_written(b) &&
2275 		    six_trylock_write(&b->c.lock)) {
2276 			bch2_btree_post_write_cleanup(c, b);
2277 			six_unlock_write(&b->c.lock);
2278 		}
2279 
2280 		if (lock_type_held == SIX_LOCK_read)
2281 			six_lock_downgrade(&b->c.lock);
2282 	} else {
2283 		__bch2_btree_node_write(c, b, flags);
2284 		if (lock_type_held == SIX_LOCK_write &&
2285 		    btree_node_just_written(b))
2286 			bch2_btree_post_write_cleanup(c, b);
2287 	}
2288 }
2289 
2290 static bool __bch2_btree_flush_all(struct bch_fs *c, unsigned flag)
2291 {
2292 	struct bucket_table *tbl;
2293 	struct rhash_head *pos;
2294 	struct btree *b;
2295 	unsigned i;
2296 	bool ret = false;
2297 restart:
2298 	rcu_read_lock();
2299 	for_each_cached_btree(b, c, tbl, i, pos)
2300 		if (test_bit(flag, &b->flags)) {
2301 			rcu_read_unlock();
2302 			wait_on_bit_io(&b->flags, flag, TASK_UNINTERRUPTIBLE);
2303 			ret = true;
2304 			goto restart;
2305 		}
2306 	rcu_read_unlock();
2307 
2308 	return ret;
2309 }
2310 
2311 bool bch2_btree_flush_all_reads(struct bch_fs *c)
2312 {
2313 	return __bch2_btree_flush_all(c, BTREE_NODE_read_in_flight);
2314 }
2315 
2316 bool bch2_btree_flush_all_writes(struct bch_fs *c)
2317 {
2318 	return __bch2_btree_flush_all(c, BTREE_NODE_write_in_flight);
2319 }
2320 
2321 static const char * const bch2_btree_write_types[] = {
2322 #define x(t, n) [n] = #t,
2323 	BCH_BTREE_WRITE_TYPES()
2324 	NULL
2325 };
2326 
2327 void bch2_btree_write_stats_to_text(struct printbuf *out, struct bch_fs *c)
2328 {
2329 	printbuf_tabstop_push(out, 20);
2330 	printbuf_tabstop_push(out, 10);
2331 
2332 	prt_tab(out);
2333 	prt_str(out, "nr");
2334 	prt_tab(out);
2335 	prt_str(out, "size");
2336 	prt_newline(out);
2337 
2338 	for (unsigned i = 0; i < BTREE_WRITE_TYPE_NR; i++) {
2339 		u64 nr		= atomic64_read(&c->btree_write_stats[i].nr);
2340 		u64 bytes	= atomic64_read(&c->btree_write_stats[i].bytes);
2341 
2342 		prt_printf(out, "%s:", bch2_btree_write_types[i]);
2343 		prt_tab(out);
2344 		prt_u64(out, nr);
2345 		prt_tab(out);
2346 		prt_human_readable_u64(out, nr ? div64_u64(bytes, nr) : 0);
2347 		prt_newline(out);
2348 	}
2349 }
2350