xref: /linux/fs/bcachefs/btree_gc.c (revision 8732594017d32132ca741f4ec4eec91211f5d10c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4  * Copyright (C) 2014 Datera Inc.
5  */
6 
7 #include "bcachefs.h"
8 #include "alloc_background.h"
9 #include "alloc_foreground.h"
10 #include "backpointers.h"
11 #include "bkey_methods.h"
12 #include "bkey_buf.h"
13 #include "btree_journal_iter.h"
14 #include "btree_key_cache.h"
15 #include "btree_locking.h"
16 #include "btree_node_scan.h"
17 #include "btree_update_interior.h"
18 #include "btree_io.h"
19 #include "btree_gc.h"
20 #include "buckets.h"
21 #include "clock.h"
22 #include "debug.h"
23 #include "ec.h"
24 #include "error.h"
25 #include "extents.h"
26 #include "journal.h"
27 #include "keylist.h"
28 #include "move.h"
29 #include "recovery_passes.h"
30 #include "reflink.h"
31 #include "replicas.h"
32 #include "super-io.h"
33 #include "trace.h"
34 
35 #include <linux/slab.h>
36 #include <linux/bitops.h>
37 #include <linux/freezer.h>
38 #include <linux/kthread.h>
39 #include <linux/preempt.h>
40 #include <linux/rcupdate.h>
41 #include <linux/sched/task.h>
42 
43 #define DROP_THIS_NODE		10
44 #define DROP_PREV_NODE		11
45 #define DID_FILL_FROM_SCAN	12
46 
47 static struct bkey_s unsafe_bkey_s_c_to_s(struct bkey_s_c k)
48 {
49 	return (struct bkey_s) {{{
50 		(struct bkey *) k.k,
51 		(struct bch_val *) k.v
52 	}}};
53 }
54 
55 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
56 {
57 	preempt_disable();
58 	write_seqcount_begin(&c->gc_pos_lock);
59 	c->gc_pos = new_pos;
60 	write_seqcount_end(&c->gc_pos_lock);
61 	preempt_enable();
62 }
63 
64 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
65 {
66 	BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) < 0);
67 	__gc_pos_set(c, new_pos);
68 }
69 
70 static void btree_ptr_to_v2(struct btree *b, struct bkey_i_btree_ptr_v2 *dst)
71 {
72 	switch (b->key.k.type) {
73 	case KEY_TYPE_btree_ptr: {
74 		struct bkey_i_btree_ptr *src = bkey_i_to_btree_ptr(&b->key);
75 
76 		dst->k.p		= src->k.p;
77 		dst->v.mem_ptr		= 0;
78 		dst->v.seq		= b->data->keys.seq;
79 		dst->v.sectors_written	= 0;
80 		dst->v.flags		= 0;
81 		dst->v.min_key		= b->data->min_key;
82 		set_bkey_val_bytes(&dst->k, sizeof(dst->v) + bkey_val_bytes(&src->k));
83 		memcpy(dst->v.start, src->v.start, bkey_val_bytes(&src->k));
84 		break;
85 	}
86 	case KEY_TYPE_btree_ptr_v2:
87 		bkey_copy(&dst->k_i, &b->key);
88 		break;
89 	default:
90 		BUG();
91 	}
92 }
93 
94 static int set_node_min(struct bch_fs *c, struct btree *b, struct bpos new_min)
95 {
96 	struct bkey_i_btree_ptr_v2 *new;
97 	int ret;
98 
99 	if (c->opts.verbose) {
100 		struct printbuf buf = PRINTBUF;
101 
102 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
103 		prt_str(&buf, " -> ");
104 		bch2_bpos_to_text(&buf, new_min);
105 
106 		bch_info(c, "%s(): %s", __func__, buf.buf);
107 		printbuf_exit(&buf);
108 	}
109 
110 	new = kmalloc_array(BKEY_BTREE_PTR_U64s_MAX, sizeof(u64), GFP_KERNEL);
111 	if (!new)
112 		return -BCH_ERR_ENOMEM_gc_repair_key;
113 
114 	btree_ptr_to_v2(b, new);
115 	b->data->min_key	= new_min;
116 	new->v.min_key		= new_min;
117 	SET_BTREE_PTR_RANGE_UPDATED(&new->v, true);
118 
119 	ret = bch2_journal_key_insert_take(c, b->c.btree_id, b->c.level + 1, &new->k_i);
120 	if (ret) {
121 		kfree(new);
122 		return ret;
123 	}
124 
125 	bch2_btree_node_drop_keys_outside_node(b);
126 	bkey_copy(&b->key, &new->k_i);
127 	return 0;
128 }
129 
130 static int set_node_max(struct bch_fs *c, struct btree *b, struct bpos new_max)
131 {
132 	struct bkey_i_btree_ptr_v2 *new;
133 	int ret;
134 
135 	if (c->opts.verbose) {
136 		struct printbuf buf = PRINTBUF;
137 
138 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
139 		prt_str(&buf, " -> ");
140 		bch2_bpos_to_text(&buf, new_max);
141 
142 		bch_info(c, "%s(): %s", __func__, buf.buf);
143 		printbuf_exit(&buf);
144 	}
145 
146 	ret = bch2_journal_key_delete(c, b->c.btree_id, b->c.level + 1, b->key.k.p);
147 	if (ret)
148 		return ret;
149 
150 	new = kmalloc_array(BKEY_BTREE_PTR_U64s_MAX, sizeof(u64), GFP_KERNEL);
151 	if (!new)
152 		return -BCH_ERR_ENOMEM_gc_repair_key;
153 
154 	btree_ptr_to_v2(b, new);
155 	b->data->max_key	= new_max;
156 	new->k.p		= new_max;
157 	SET_BTREE_PTR_RANGE_UPDATED(&new->v, true);
158 
159 	ret = bch2_journal_key_insert_take(c, b->c.btree_id, b->c.level + 1, &new->k_i);
160 	if (ret) {
161 		kfree(new);
162 		return ret;
163 	}
164 
165 	bch2_btree_node_drop_keys_outside_node(b);
166 
167 	mutex_lock(&c->btree_cache.lock);
168 	bch2_btree_node_hash_remove(&c->btree_cache, b);
169 
170 	bkey_copy(&b->key, &new->k_i);
171 	ret = __bch2_btree_node_hash_insert(&c->btree_cache, b);
172 	BUG_ON(ret);
173 	mutex_unlock(&c->btree_cache.lock);
174 	return 0;
175 }
176 
177 static int btree_check_node_boundaries(struct bch_fs *c, struct btree *b,
178 				       struct btree *prev, struct btree *cur,
179 				       struct bpos *pulled_from_scan)
180 {
181 	struct bpos expected_start = !prev
182 		? b->data->min_key
183 		: bpos_successor(prev->key.k.p);
184 	struct printbuf buf = PRINTBUF;
185 	int ret = 0;
186 
187 	BUG_ON(b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
188 	       !bpos_eq(bkey_i_to_btree_ptr_v2(&b->key)->v.min_key,
189 			b->data->min_key));
190 
191 	if (bpos_eq(expected_start, cur->data->min_key))
192 		return 0;
193 
194 	prt_printf(&buf, "  at btree %s level %u:\n  parent: ",
195 		   bch2_btree_id_str(b->c.btree_id), b->c.level);
196 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
197 
198 	if (prev) {
199 		prt_printf(&buf, "\n  prev: ");
200 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&prev->key));
201 	}
202 
203 	prt_str(&buf, "\n  next: ");
204 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&cur->key));
205 
206 	if (bpos_lt(expected_start, cur->data->min_key)) {				/* gap */
207 		if (b->c.level == 1 &&
208 		    bpos_lt(*pulled_from_scan, cur->data->min_key)) {
209 			ret = bch2_get_scanned_nodes(c, b->c.btree_id, 0,
210 						     expected_start,
211 						     bpos_predecessor(cur->data->min_key));
212 			if (ret)
213 				goto err;
214 
215 			*pulled_from_scan = cur->data->min_key;
216 			ret = DID_FILL_FROM_SCAN;
217 		} else {
218 			if (mustfix_fsck_err(c, btree_node_topology_bad_min_key,
219 					     "btree node with incorrect min_key%s", buf.buf))
220 				ret = set_node_min(c, cur, expected_start);
221 		}
222 	} else {									/* overlap */
223 		if (prev && BTREE_NODE_SEQ(cur->data) > BTREE_NODE_SEQ(prev->data)) {	/* cur overwrites prev */
224 			if (bpos_ge(prev->data->min_key, cur->data->min_key)) {		/* fully? */
225 				if (mustfix_fsck_err(c, btree_node_topology_overwritten_by_next_node,
226 						     "btree node overwritten by next node%s", buf.buf))
227 					ret = DROP_PREV_NODE;
228 			} else {
229 				if (mustfix_fsck_err(c, btree_node_topology_bad_max_key,
230 						     "btree node with incorrect max_key%s", buf.buf))
231 					ret = set_node_max(c, prev,
232 							   bpos_predecessor(cur->data->min_key));
233 			}
234 		} else {
235 			if (bpos_ge(expected_start, cur->data->max_key)) {		/* fully? */
236 				if (mustfix_fsck_err(c, btree_node_topology_overwritten_by_prev_node,
237 						     "btree node overwritten by prev node%s", buf.buf))
238 					ret = DROP_THIS_NODE;
239 			} else {
240 				if (mustfix_fsck_err(c, btree_node_topology_bad_min_key,
241 						     "btree node with incorrect min_key%s", buf.buf))
242 					ret = set_node_min(c, cur, expected_start);
243 			}
244 		}
245 	}
246 err:
247 fsck_err:
248 	printbuf_exit(&buf);
249 	return ret;
250 }
251 
252 static int btree_repair_node_end(struct bch_fs *c, struct btree *b,
253 				 struct btree *child, struct bpos *pulled_from_scan)
254 {
255 	struct printbuf buf = PRINTBUF;
256 	int ret = 0;
257 
258 	if (bpos_eq(child->key.k.p, b->key.k.p))
259 		return 0;
260 
261 	prt_printf(&buf, "at btree %s level %u:\n  parent: ",
262 		   bch2_btree_id_str(b->c.btree_id), b->c.level);
263 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
264 
265 	prt_str(&buf, "\n  child: ");
266 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&child->key));
267 
268 	if (mustfix_fsck_err(c, btree_node_topology_bad_max_key,
269 			     "btree node with incorrect max_key%s", buf.buf)) {
270 		if (b->c.level == 1 &&
271 		    bpos_lt(*pulled_from_scan, b->key.k.p)) {
272 			ret = bch2_get_scanned_nodes(c, b->c.btree_id, 0,
273 						bpos_successor(child->key.k.p), b->key.k.p);
274 			if (ret)
275 				goto err;
276 
277 			*pulled_from_scan = b->key.k.p;
278 			ret = DID_FILL_FROM_SCAN;
279 		} else {
280 			ret = set_node_max(c, child, b->key.k.p);
281 		}
282 	}
283 err:
284 fsck_err:
285 	printbuf_exit(&buf);
286 	return ret;
287 }
288 
289 static int bch2_btree_repair_topology_recurse(struct btree_trans *trans, struct btree *b,
290 					      struct bpos *pulled_from_scan)
291 {
292 	struct bch_fs *c = trans->c;
293 	struct btree_and_journal_iter iter;
294 	struct bkey_s_c k;
295 	struct bkey_buf prev_k, cur_k;
296 	struct btree *prev = NULL, *cur = NULL;
297 	bool have_child, new_pass = false;
298 	struct printbuf buf = PRINTBUF;
299 	int ret = 0;
300 
301 	if (!b->c.level)
302 		return 0;
303 
304 	bch2_bkey_buf_init(&prev_k);
305 	bch2_bkey_buf_init(&cur_k);
306 again:
307 	cur = prev = NULL;
308 	have_child = new_pass = false;
309 	bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
310 	iter.prefetch = true;
311 
312 	while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
313 		BUG_ON(bpos_lt(k.k->p, b->data->min_key));
314 		BUG_ON(bpos_gt(k.k->p, b->data->max_key));
315 
316 		bch2_btree_and_journal_iter_advance(&iter);
317 		bch2_bkey_buf_reassemble(&cur_k, c, k);
318 
319 		cur = bch2_btree_node_get_noiter(trans, cur_k.k,
320 					b->c.btree_id, b->c.level - 1,
321 					false);
322 		ret = PTR_ERR_OR_ZERO(cur);
323 
324 		printbuf_reset(&buf);
325 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(cur_k.k));
326 
327 		if (mustfix_fsck_err_on(bch2_err_matches(ret, EIO), c,
328 				btree_node_unreadable,
329 				"Topology repair: unreadable btree node at btree %s level %u:\n"
330 				"  %s",
331 				bch2_btree_id_str(b->c.btree_id),
332 				b->c.level - 1,
333 				buf.buf)) {
334 			bch2_btree_node_evict(trans, cur_k.k);
335 			cur = NULL;
336 			ret = bch2_journal_key_delete(c, b->c.btree_id,
337 						      b->c.level, cur_k.k->k.p);
338 			if (ret)
339 				break;
340 
341 			if (!btree_id_is_alloc(b->c.btree_id)) {
342 				ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_scan_for_btree_nodes);
343 				if (ret)
344 					break;
345 			}
346 			continue;
347 		}
348 
349 		bch_err_msg(c, ret, "getting btree node");
350 		if (ret)
351 			break;
352 
353 		if (bch2_btree_node_is_stale(c, cur)) {
354 			bch_info(c, "btree node %s older than nodes found by scanning", buf.buf);
355 			six_unlock_read(&cur->c.lock);
356 			bch2_btree_node_evict(trans, cur_k.k);
357 			ret = bch2_journal_key_delete(c, b->c.btree_id,
358 						      b->c.level, cur_k.k->k.p);
359 			cur = NULL;
360 			if (ret)
361 				break;
362 			continue;
363 		}
364 
365 		ret = btree_check_node_boundaries(c, b, prev, cur, pulled_from_scan);
366 		if (ret == DID_FILL_FROM_SCAN) {
367 			new_pass = true;
368 			ret = 0;
369 		}
370 
371 		if (ret == DROP_THIS_NODE) {
372 			six_unlock_read(&cur->c.lock);
373 			bch2_btree_node_evict(trans, cur_k.k);
374 			ret = bch2_journal_key_delete(c, b->c.btree_id,
375 						      b->c.level, cur_k.k->k.p);
376 			cur = NULL;
377 			if (ret)
378 				break;
379 			continue;
380 		}
381 
382 		if (prev)
383 			six_unlock_read(&prev->c.lock);
384 		prev = NULL;
385 
386 		if (ret == DROP_PREV_NODE) {
387 			bch_info(c, "dropped prev node");
388 			bch2_btree_node_evict(trans, prev_k.k);
389 			ret = bch2_journal_key_delete(c, b->c.btree_id,
390 						      b->c.level, prev_k.k->k.p);
391 			if (ret)
392 				break;
393 
394 			bch2_btree_and_journal_iter_exit(&iter);
395 			goto again;
396 		} else if (ret)
397 			break;
398 
399 		prev = cur;
400 		cur = NULL;
401 		bch2_bkey_buf_copy(&prev_k, c, cur_k.k);
402 	}
403 
404 	if (!ret && !IS_ERR_OR_NULL(prev)) {
405 		BUG_ON(cur);
406 		ret = btree_repair_node_end(c, b, prev, pulled_from_scan);
407 		if (ret == DID_FILL_FROM_SCAN) {
408 			new_pass = true;
409 			ret = 0;
410 		}
411 	}
412 
413 	if (!IS_ERR_OR_NULL(prev))
414 		six_unlock_read(&prev->c.lock);
415 	prev = NULL;
416 	if (!IS_ERR_OR_NULL(cur))
417 		six_unlock_read(&cur->c.lock);
418 	cur = NULL;
419 
420 	if (ret)
421 		goto err;
422 
423 	bch2_btree_and_journal_iter_exit(&iter);
424 
425 	if (new_pass)
426 		goto again;
427 
428 	bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
429 	iter.prefetch = true;
430 
431 	while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
432 		bch2_bkey_buf_reassemble(&cur_k, c, k);
433 		bch2_btree_and_journal_iter_advance(&iter);
434 
435 		cur = bch2_btree_node_get_noiter(trans, cur_k.k,
436 					b->c.btree_id, b->c.level - 1,
437 					false);
438 		ret = PTR_ERR_OR_ZERO(cur);
439 
440 		bch_err_msg(c, ret, "getting btree node");
441 		if (ret)
442 			goto err;
443 
444 		ret = bch2_btree_repair_topology_recurse(trans, cur, pulled_from_scan);
445 		six_unlock_read(&cur->c.lock);
446 		cur = NULL;
447 
448 		if (ret == DROP_THIS_NODE) {
449 			bch2_btree_node_evict(trans, cur_k.k);
450 			ret = bch2_journal_key_delete(c, b->c.btree_id,
451 						      b->c.level, cur_k.k->k.p);
452 			new_pass = true;
453 		}
454 
455 		if (ret)
456 			goto err;
457 
458 		have_child = true;
459 	}
460 
461 	printbuf_reset(&buf);
462 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
463 
464 	if (mustfix_fsck_err_on(!have_child, c,
465 			btree_node_topology_interior_node_empty,
466 			"empty interior btree node at btree %s level %u\n"
467 			"  %s",
468 			bch2_btree_id_str(b->c.btree_id),
469 			b->c.level, buf.buf))
470 		ret = DROP_THIS_NODE;
471 err:
472 fsck_err:
473 	if (!IS_ERR_OR_NULL(prev))
474 		six_unlock_read(&prev->c.lock);
475 	if (!IS_ERR_OR_NULL(cur))
476 		six_unlock_read(&cur->c.lock);
477 
478 	bch2_btree_and_journal_iter_exit(&iter);
479 
480 	if (!ret && new_pass)
481 		goto again;
482 
483 	BUG_ON(!ret && bch2_btree_node_check_topology(trans, b));
484 
485 	bch2_bkey_buf_exit(&prev_k, c);
486 	bch2_bkey_buf_exit(&cur_k, c);
487 	printbuf_exit(&buf);
488 	return ret;
489 }
490 
491 int bch2_check_topology(struct bch_fs *c)
492 {
493 	struct btree_trans *trans = bch2_trans_get(c);
494 	struct bpos pulled_from_scan = POS_MIN;
495 	int ret = 0;
496 
497 	for (unsigned i = 0; i < btree_id_nr_alive(c) && !ret; i++) {
498 		struct btree_root *r = bch2_btree_id_root(c, i);
499 		bool reconstructed_root = false;
500 
501 		if (r->error) {
502 			ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_scan_for_btree_nodes);
503 			if (ret)
504 				break;
505 reconstruct_root:
506 			bch_info(c, "btree root %s unreadable, must recover from scan", bch2_btree_id_str(i));
507 
508 			r->alive = false;
509 			r->error = 0;
510 
511 			if (!bch2_btree_has_scanned_nodes(c, i)) {
512 				mustfix_fsck_err(c, btree_root_unreadable_and_scan_found_nothing,
513 						 "no nodes found for btree %s, continue?", bch2_btree_id_str(i));
514 				bch2_btree_root_alloc_fake_trans(trans, i, 0);
515 			} else {
516 				bch2_btree_root_alloc_fake_trans(trans, i, 1);
517 				bch2_shoot_down_journal_keys(c, i, 1, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
518 				ret = bch2_get_scanned_nodes(c, i, 0, POS_MIN, SPOS_MAX);
519 				if (ret)
520 					break;
521 			}
522 
523 			reconstructed_root = true;
524 		}
525 
526 		struct btree *b = r->b;
527 
528 		btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_read);
529 		ret = bch2_btree_repair_topology_recurse(trans, b, &pulled_from_scan);
530 		six_unlock_read(&b->c.lock);
531 
532 		if (ret == DROP_THIS_NODE) {
533 			bch2_btree_node_hash_remove(&c->btree_cache, b);
534 			mutex_lock(&c->btree_cache.lock);
535 			list_move(&b->list, &c->btree_cache.freeable);
536 			mutex_unlock(&c->btree_cache.lock);
537 
538 			r->b = NULL;
539 
540 			if (!reconstructed_root)
541 				goto reconstruct_root;
542 
543 			bch_err(c, "empty btree root %s", bch2_btree_id_str(i));
544 			bch2_btree_root_alloc_fake_trans(trans, i, 0);
545 			r->alive = false;
546 			ret = 0;
547 		}
548 	}
549 fsck_err:
550 	bch2_trans_put(trans);
551 	return ret;
552 }
553 
554 /* marking of btree keys/nodes: */
555 
556 static int bch2_gc_mark_key(struct btree_trans *trans, enum btree_id btree_id,
557 			    unsigned level, struct btree **prev,
558 			    struct btree_iter *iter, struct bkey_s_c k,
559 			    bool initial)
560 {
561 	struct bch_fs *c = trans->c;
562 
563 	if (iter) {
564 		struct btree_path *path = btree_iter_path(trans, iter);
565 		struct btree *b = path_l(path)->b;
566 
567 		if (*prev != b) {
568 			int ret = bch2_btree_node_check_topology(trans, b);
569 			if (ret)
570 				return ret;
571 		}
572 		*prev = b;
573 	}
574 
575 	struct bkey deleted = KEY(0, 0, 0);
576 	struct bkey_s_c old = (struct bkey_s_c) { &deleted, NULL };
577 	struct printbuf buf = PRINTBUF;
578 	int ret = 0;
579 
580 	deleted.p = k.k->p;
581 
582 	if (initial) {
583 		BUG_ON(bch2_journal_seq_verify &&
584 		       k.k->version.lo > atomic64_read(&c->journal.seq));
585 
586 		if (fsck_err_on(k.k->version.lo > atomic64_read(&c->key_version), c,
587 				bkey_version_in_future,
588 				"key version number higher than recorded %llu\n  %s",
589 				atomic64_read(&c->key_version),
590 				(bch2_bkey_val_to_text(&buf, c, k), buf.buf)))
591 			atomic64_set(&c->key_version, k.k->version.lo);
592 	}
593 
594 	if (mustfix_fsck_err_on(level && !bch2_dev_btree_bitmap_marked(c, k),
595 				c, btree_bitmap_not_marked,
596 				"btree ptr not marked in member info btree allocated bitmap\n  %s",
597 				(printbuf_reset(&buf),
598 				 bch2_bkey_val_to_text(&buf, c, k),
599 				 buf.buf))) {
600 		mutex_lock(&c->sb_lock);
601 		bch2_dev_btree_bitmap_mark(c, k);
602 		bch2_write_super(c);
603 		mutex_unlock(&c->sb_lock);
604 	}
605 
606 	/*
607 	 * We require a commit before key_trigger() because
608 	 * key_trigger(BTREE_TRIGGER_GC) is not idempotant; we'll calculate the
609 	 * wrong result if we run it multiple times.
610 	 */
611 	unsigned flags = !iter ? BTREE_TRIGGER_is_root : 0;
612 
613 	ret = bch2_key_trigger(trans, btree_id, level, old, unsafe_bkey_s_c_to_s(k),
614 			       BTREE_TRIGGER_check_repair|flags);
615 	if (ret)
616 		goto out;
617 
618 	if (trans->nr_updates) {
619 		ret = bch2_trans_commit(trans, NULL, NULL, 0) ?:
620 			-BCH_ERR_transaction_restart_nested;
621 		goto out;
622 	}
623 
624 	ret = bch2_key_trigger(trans, btree_id, level, old, unsafe_bkey_s_c_to_s(k),
625 			       BTREE_TRIGGER_gc|flags);
626 out:
627 fsck_err:
628 	printbuf_exit(&buf);
629 	bch_err_fn(c, ret);
630 	return ret;
631 }
632 
633 static int bch2_gc_btree(struct btree_trans *trans, enum btree_id btree, bool initial)
634 {
635 	struct bch_fs *c = trans->c;
636 	int level = 0, target_depth = btree_node_type_needs_gc(__btree_node_type(0, btree)) ? 0 : 1;
637 	int ret = 0;
638 
639 	/* We need to make sure every leaf node is readable before going RW */
640 	if (initial)
641 		target_depth = 0;
642 
643 	/* root */
644 	mutex_lock(&c->btree_root_lock);
645 	struct btree *b = bch2_btree_id_root(c, btree)->b;
646 	if (!btree_node_fake(b)) {
647 		gc_pos_set(c, gc_pos_btree(btree, b->c.level + 1, SPOS_MAX));
648 		ret = lockrestart_do(trans,
649 			bch2_gc_mark_key(trans, b->c.btree_id, b->c.level + 1,
650 					 NULL, NULL, bkey_i_to_s_c(&b->key), initial));
651 		level = b->c.level;
652 	}
653 	mutex_unlock(&c->btree_root_lock);
654 
655 	if (ret)
656 		return ret;
657 
658 	for (; level >= target_depth; --level) {
659 		struct btree *prev = NULL;
660 		struct btree_iter iter;
661 		bch2_trans_node_iter_init(trans, &iter, btree, POS_MIN, 0, level,
662 					  BTREE_ITER_prefetch);
663 
664 		ret = for_each_btree_key_continue(trans, iter, 0, k, ({
665 			gc_pos_set(c, gc_pos_btree(btree, level, k.k->p));
666 			bch2_gc_mark_key(trans, btree, level, &prev, &iter, k, initial);
667 		}));
668 		if (ret)
669 			break;
670 	}
671 
672 	return ret;
673 }
674 
675 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
676 {
677 	return cmp_int(gc_btree_order(l), gc_btree_order(r));
678 }
679 
680 static int bch2_gc_btrees(struct bch_fs *c)
681 {
682 	struct btree_trans *trans = bch2_trans_get(c);
683 	enum btree_id ids[BTREE_ID_NR];
684 	unsigned i;
685 	int ret = 0;
686 
687 	for (i = 0; i < BTREE_ID_NR; i++)
688 		ids[i] = i;
689 	bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
690 
691 	for (i = 0; i < btree_id_nr_alive(c) && !ret; i++) {
692 		unsigned btree = i < BTREE_ID_NR ? ids[i] : i;
693 
694 		if (IS_ERR_OR_NULL(bch2_btree_id_root(c, btree)->b))
695 			continue;
696 
697 		ret = bch2_gc_btree(trans, btree, true);
698 
699 		if (mustfix_fsck_err_on(bch2_err_matches(ret, EIO),
700 					c, btree_node_read_error,
701 			       "btree node read error for %s",
702 			       bch2_btree_id_str(btree)))
703 			ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_check_topology);
704 	}
705 fsck_err:
706 	bch2_trans_put(trans);
707 	bch_err_fn(c, ret);
708 	return ret;
709 }
710 
711 static int bch2_mark_superblocks(struct bch_fs *c)
712 {
713 	mutex_lock(&c->sb_lock);
714 	gc_pos_set(c, gc_phase(GC_PHASE_sb));
715 
716 	int ret = bch2_trans_mark_dev_sbs_flags(c, BTREE_TRIGGER_gc);
717 	mutex_unlock(&c->sb_lock);
718 	return ret;
719 }
720 
721 static void bch2_gc_free(struct bch_fs *c)
722 {
723 	genradix_free(&c->reflink_gc_table);
724 	genradix_free(&c->gc_stripes);
725 
726 	for_each_member_device(c, ca) {
727 		kvfree(rcu_dereference_protected(ca->buckets_gc, 1));
728 		ca->buckets_gc = NULL;
729 
730 		free_percpu(ca->usage_gc);
731 		ca->usage_gc = NULL;
732 	}
733 
734 	free_percpu(c->usage_gc);
735 	c->usage_gc = NULL;
736 }
737 
738 static int bch2_gc_done(struct bch_fs *c)
739 {
740 	struct bch_dev *ca = NULL;
741 	struct printbuf buf = PRINTBUF;
742 	unsigned i;
743 	int ret = 0;
744 
745 	percpu_down_write(&c->mark_lock);
746 
747 #define copy_field(_err, _f, _msg, ...)						\
748 	if (fsck_err_on(dst->_f != src->_f, c, _err,				\
749 			_msg ": got %llu, should be %llu" , ##__VA_ARGS__,	\
750 			dst->_f, src->_f))					\
751 		dst->_f = src->_f
752 #define copy_dev_field(_err, _f, _msg, ...)					\
753 	copy_field(_err, _f, "dev %u has wrong " _msg, ca->dev_idx, ##__VA_ARGS__)
754 #define copy_fs_field(_err, _f, _msg, ...)					\
755 	copy_field(_err, _f, "fs has wrong " _msg, ##__VA_ARGS__)
756 
757 	for (i = 0; i < ARRAY_SIZE(c->usage); i++)
758 		bch2_fs_usage_acc_to_base(c, i);
759 
760 	__for_each_member_device(c, ca) {
761 		struct bch_dev_usage *dst = ca->usage_base;
762 		struct bch_dev_usage *src = (void *)
763 			bch2_acc_percpu_u64s((u64 __percpu *) ca->usage_gc,
764 					     dev_usage_u64s());
765 
766 		for (i = 0; i < BCH_DATA_NR; i++) {
767 			copy_dev_field(dev_usage_buckets_wrong,
768 				       d[i].buckets,	"%s buckets", bch2_data_type_str(i));
769 			copy_dev_field(dev_usage_sectors_wrong,
770 				       d[i].sectors,	"%s sectors", bch2_data_type_str(i));
771 			copy_dev_field(dev_usage_fragmented_wrong,
772 				       d[i].fragmented,	"%s fragmented", bch2_data_type_str(i));
773 		}
774 	}
775 
776 	{
777 		unsigned nr = fs_usage_u64s(c);
778 		struct bch_fs_usage *dst = c->usage_base;
779 		struct bch_fs_usage *src = (void *)
780 			bch2_acc_percpu_u64s((u64 __percpu *) c->usage_gc, nr);
781 
782 		copy_fs_field(fs_usage_hidden_wrong,
783 			      b.hidden,		"hidden");
784 		copy_fs_field(fs_usage_btree_wrong,
785 			      b.btree,		"btree");
786 
787 		copy_fs_field(fs_usage_data_wrong,
788 			      b.data,	"data");
789 		copy_fs_field(fs_usage_cached_wrong,
790 			      b.cached,	"cached");
791 		copy_fs_field(fs_usage_reserved_wrong,
792 			      b.reserved,	"reserved");
793 		copy_fs_field(fs_usage_nr_inodes_wrong,
794 			      b.nr_inodes,"nr_inodes");
795 
796 		for (i = 0; i < BCH_REPLICAS_MAX; i++)
797 			copy_fs_field(fs_usage_persistent_reserved_wrong,
798 				      persistent_reserved[i],
799 				      "persistent_reserved[%i]", i);
800 
801 		for (i = 0; i < c->replicas.nr; i++) {
802 			struct bch_replicas_entry_v1 *e =
803 				cpu_replicas_entry(&c->replicas, i);
804 
805 			printbuf_reset(&buf);
806 			bch2_replicas_entry_to_text(&buf, e);
807 
808 			copy_fs_field(fs_usage_replicas_wrong,
809 				      replicas[i], "%s", buf.buf);
810 		}
811 	}
812 
813 #undef copy_fs_field
814 #undef copy_dev_field
815 #undef copy_stripe_field
816 #undef copy_field
817 fsck_err:
818 	bch2_dev_put(ca);
819 	bch_err_fn(c, ret);
820 	percpu_up_write(&c->mark_lock);
821 	printbuf_exit(&buf);
822 	return ret;
823 }
824 
825 static int bch2_gc_start(struct bch_fs *c)
826 {
827 	BUG_ON(c->usage_gc);
828 
829 	c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
830 					 sizeof(u64), GFP_KERNEL);
831 	if (!c->usage_gc) {
832 		bch_err(c, "error allocating c->usage_gc");
833 		return -BCH_ERR_ENOMEM_gc_start;
834 	}
835 
836 	for_each_member_device(c, ca) {
837 		BUG_ON(ca->usage_gc);
838 
839 		ca->usage_gc = alloc_percpu(struct bch_dev_usage);
840 		if (!ca->usage_gc) {
841 			bch_err(c, "error allocating ca->usage_gc");
842 			bch2_dev_put(ca);
843 			return -BCH_ERR_ENOMEM_gc_start;
844 		}
845 
846 		this_cpu_write(ca->usage_gc->d[BCH_DATA_free].buckets,
847 			       ca->mi.nbuckets - ca->mi.first_bucket);
848 	}
849 
850 	return 0;
851 }
852 
853 /* returns true if not equal */
854 static inline bool bch2_alloc_v4_cmp(struct bch_alloc_v4 l,
855 				     struct bch_alloc_v4 r)
856 {
857 	return  l.gen != r.gen				||
858 		l.oldest_gen != r.oldest_gen		||
859 		l.data_type != r.data_type		||
860 		l.dirty_sectors	!= r.dirty_sectors	||
861 		l.cached_sectors != r.cached_sectors	 ||
862 		l.stripe_redundancy != r.stripe_redundancy ||
863 		l.stripe != r.stripe;
864 }
865 
866 static int bch2_alloc_write_key(struct btree_trans *trans,
867 				struct btree_iter *iter,
868 				struct bch_dev *ca,
869 				struct bkey_s_c k)
870 {
871 	struct bch_fs *c = trans->c;
872 	struct bkey_i_alloc_v4 *a;
873 	struct bch_alloc_v4 old_gc, gc, old_convert, new;
874 	const struct bch_alloc_v4 *old;
875 	int ret;
876 
877 	if (!bucket_valid(ca, k.k->p.offset))
878 		return 0;
879 
880 	old = bch2_alloc_to_v4(k, &old_convert);
881 	gc = new = *old;
882 
883 	percpu_down_read(&c->mark_lock);
884 	__bucket_m_to_alloc(&gc, *gc_bucket(ca, iter->pos.offset));
885 
886 	old_gc = gc;
887 
888 	if ((old->data_type == BCH_DATA_sb ||
889 	     old->data_type == BCH_DATA_journal) &&
890 	    !bch2_dev_is_online(ca)) {
891 		gc.data_type = old->data_type;
892 		gc.dirty_sectors = old->dirty_sectors;
893 	}
894 
895 	/*
896 	 * gc.data_type doesn't yet include need_discard & need_gc_gen states -
897 	 * fix that here:
898 	 */
899 	alloc_data_type_set(&gc, gc.data_type);
900 
901 	if (gc.data_type != old_gc.data_type ||
902 	    gc.dirty_sectors != old_gc.dirty_sectors)
903 		bch2_dev_usage_update(c, ca, &old_gc, &gc, 0, true);
904 	percpu_up_read(&c->mark_lock);
905 
906 	if (fsck_err_on(new.data_type != gc.data_type, c,
907 			alloc_key_data_type_wrong,
908 			"bucket %llu:%llu gen %u has wrong data_type"
909 			": got %s, should be %s",
910 			iter->pos.inode, iter->pos.offset,
911 			gc.gen,
912 			bch2_data_type_str(new.data_type),
913 			bch2_data_type_str(gc.data_type)))
914 		new.data_type = gc.data_type;
915 
916 #define copy_bucket_field(_errtype, _f)					\
917 	if (fsck_err_on(new._f != gc._f, c, _errtype,			\
918 			"bucket %llu:%llu gen %u data type %s has wrong " #_f	\
919 			": got %u, should be %u",			\
920 			iter->pos.inode, iter->pos.offset,		\
921 			gc.gen,						\
922 			bch2_data_type_str(gc.data_type),		\
923 			new._f, gc._f))					\
924 		new._f = gc._f;						\
925 
926 	copy_bucket_field(alloc_key_gen_wrong,
927 			  gen);
928 	copy_bucket_field(alloc_key_dirty_sectors_wrong,
929 			  dirty_sectors);
930 	copy_bucket_field(alloc_key_cached_sectors_wrong,
931 			  cached_sectors);
932 	copy_bucket_field(alloc_key_stripe_wrong,
933 			  stripe);
934 	copy_bucket_field(alloc_key_stripe_redundancy_wrong,
935 			  stripe_redundancy);
936 #undef copy_bucket_field
937 
938 	if (!bch2_alloc_v4_cmp(*old, new))
939 		return 0;
940 
941 	a = bch2_alloc_to_v4_mut(trans, k);
942 	ret = PTR_ERR_OR_ZERO(a);
943 	if (ret)
944 		return ret;
945 
946 	a->v = new;
947 
948 	/*
949 	 * The trigger normally makes sure this is set, but we're not running
950 	 * triggers:
951 	 */
952 	if (a->v.data_type == BCH_DATA_cached && !a->v.io_time[READ])
953 		a->v.io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
954 
955 	ret = bch2_trans_update(trans, iter, &a->k_i, BTREE_TRIGGER_norun);
956 fsck_err:
957 	return ret;
958 }
959 
960 static int bch2_gc_alloc_done(struct bch_fs *c)
961 {
962 	int ret = 0;
963 
964 	for_each_member_device(c, ca) {
965 		ret = bch2_trans_run(c,
966 			for_each_btree_key_upto_commit(trans, iter, BTREE_ID_alloc,
967 					POS(ca->dev_idx, ca->mi.first_bucket),
968 					POS(ca->dev_idx, ca->mi.nbuckets - 1),
969 					BTREE_ITER_slots|BTREE_ITER_prefetch, k,
970 					NULL, NULL, BCH_TRANS_COMMIT_lazy_rw,
971 				bch2_alloc_write_key(trans, &iter, ca, k)));
972 		if (ret) {
973 			bch2_dev_put(ca);
974 			break;
975 		}
976 	}
977 
978 	bch_err_fn(c, ret);
979 	return ret;
980 }
981 
982 static int bch2_gc_alloc_start(struct bch_fs *c)
983 {
984 	for_each_member_device(c, ca) {
985 		struct bucket_array *buckets = kvmalloc(sizeof(struct bucket_array) +
986 				ca->mi.nbuckets * sizeof(struct bucket),
987 				GFP_KERNEL|__GFP_ZERO);
988 		if (!buckets) {
989 			bch2_dev_put(ca);
990 			bch_err(c, "error allocating ca->buckets[gc]");
991 			return -BCH_ERR_ENOMEM_gc_alloc_start;
992 		}
993 
994 		buckets->first_bucket	= ca->mi.first_bucket;
995 		buckets->nbuckets	= ca->mi.nbuckets;
996 		buckets->nbuckets_minus_first =
997 			buckets->nbuckets - buckets->first_bucket;
998 		rcu_assign_pointer(ca->buckets_gc, buckets);
999 	}
1000 
1001 	struct bch_dev *ca = NULL;
1002 	int ret = bch2_trans_run(c,
1003 		for_each_btree_key(trans, iter, BTREE_ID_alloc, POS_MIN,
1004 					 BTREE_ITER_prefetch, k, ({
1005 			ca = bch2_dev_iterate(c, ca, k.k->p.inode);
1006 			if (!ca) {
1007 				bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
1008 				continue;
1009 			}
1010 
1011 			if (bucket_valid(ca, k.k->p.offset)) {
1012 				struct bch_alloc_v4 a_convert;
1013 				const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
1014 
1015 				struct bucket *g = gc_bucket(ca, k.k->p.offset);
1016 				g->gen_valid	= 1;
1017 				g->gen		= a->gen;
1018 			}
1019 			0;
1020 		})));
1021 	bch2_dev_put(ca);
1022 	bch_err_fn(c, ret);
1023 	return ret;
1024 }
1025 
1026 static int bch2_gc_write_reflink_key(struct btree_trans *trans,
1027 				     struct btree_iter *iter,
1028 				     struct bkey_s_c k,
1029 				     size_t *idx)
1030 {
1031 	struct bch_fs *c = trans->c;
1032 	const __le64 *refcount = bkey_refcount_c(k);
1033 	struct printbuf buf = PRINTBUF;
1034 	struct reflink_gc *r;
1035 	int ret = 0;
1036 
1037 	if (!refcount)
1038 		return 0;
1039 
1040 	while ((r = genradix_ptr(&c->reflink_gc_table, *idx)) &&
1041 	       r->offset < k.k->p.offset)
1042 		++*idx;
1043 
1044 	if (!r ||
1045 	    r->offset != k.k->p.offset ||
1046 	    r->size != k.k->size) {
1047 		bch_err(c, "unexpected inconsistency walking reflink table at gc finish");
1048 		return -EINVAL;
1049 	}
1050 
1051 	if (fsck_err_on(r->refcount != le64_to_cpu(*refcount), c,
1052 			reflink_v_refcount_wrong,
1053 			"reflink key has wrong refcount:\n"
1054 			"  %s\n"
1055 			"  should be %u",
1056 			(bch2_bkey_val_to_text(&buf, c, k), buf.buf),
1057 			r->refcount)) {
1058 		struct bkey_i *new = bch2_bkey_make_mut_noupdate(trans, k);
1059 		ret = PTR_ERR_OR_ZERO(new);
1060 		if (ret)
1061 			goto out;
1062 
1063 		if (!r->refcount)
1064 			new->k.type = KEY_TYPE_deleted;
1065 		else
1066 			*bkey_refcount(bkey_i_to_s(new)) = cpu_to_le64(r->refcount);
1067 		ret = bch2_trans_update(trans, iter, new, 0);
1068 	}
1069 out:
1070 fsck_err:
1071 	printbuf_exit(&buf);
1072 	return ret;
1073 }
1074 
1075 static int bch2_gc_reflink_done(struct bch_fs *c)
1076 {
1077 	size_t idx = 0;
1078 
1079 	int ret = bch2_trans_run(c,
1080 		for_each_btree_key_commit(trans, iter,
1081 				BTREE_ID_reflink, POS_MIN,
1082 				BTREE_ITER_prefetch, k,
1083 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1084 			bch2_gc_write_reflink_key(trans, &iter, k, &idx)));
1085 	c->reflink_gc_nr = 0;
1086 	return ret;
1087 }
1088 
1089 static int bch2_gc_reflink_start(struct bch_fs *c)
1090 {
1091 	c->reflink_gc_nr = 0;
1092 
1093 	int ret = bch2_trans_run(c,
1094 		for_each_btree_key(trans, iter, BTREE_ID_reflink, POS_MIN,
1095 				   BTREE_ITER_prefetch, k, ({
1096 			const __le64 *refcount = bkey_refcount_c(k);
1097 
1098 			if (!refcount)
1099 				continue;
1100 
1101 			struct reflink_gc *r = genradix_ptr_alloc(&c->reflink_gc_table,
1102 							c->reflink_gc_nr++, GFP_KERNEL);
1103 			if (!r) {
1104 				ret = -BCH_ERR_ENOMEM_gc_reflink_start;
1105 				break;
1106 			}
1107 
1108 			r->offset	= k.k->p.offset;
1109 			r->size		= k.k->size;
1110 			r->refcount	= 0;
1111 			0;
1112 		})));
1113 
1114 	bch_err_fn(c, ret);
1115 	return ret;
1116 }
1117 
1118 static int bch2_gc_write_stripes_key(struct btree_trans *trans,
1119 				     struct btree_iter *iter,
1120 				     struct bkey_s_c k)
1121 {
1122 	struct bch_fs *c = trans->c;
1123 	struct printbuf buf = PRINTBUF;
1124 	const struct bch_stripe *s;
1125 	struct gc_stripe *m;
1126 	bool bad = false;
1127 	unsigned i;
1128 	int ret = 0;
1129 
1130 	if (k.k->type != KEY_TYPE_stripe)
1131 		return 0;
1132 
1133 	s = bkey_s_c_to_stripe(k).v;
1134 	m = genradix_ptr(&c->gc_stripes, k.k->p.offset);
1135 
1136 	for (i = 0; i < s->nr_blocks; i++) {
1137 		u32 old = stripe_blockcount_get(s, i);
1138 		u32 new = (m ? m->block_sectors[i] : 0);
1139 
1140 		if (old != new) {
1141 			prt_printf(&buf, "stripe block %u has wrong sector count: got %u, should be %u\n",
1142 				   i, old, new);
1143 			bad = true;
1144 		}
1145 	}
1146 
1147 	if (bad)
1148 		bch2_bkey_val_to_text(&buf, c, k);
1149 
1150 	if (fsck_err_on(bad, c, stripe_sector_count_wrong,
1151 			"%s", buf.buf)) {
1152 		struct bkey_i_stripe *new;
1153 
1154 		new = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1155 		ret = PTR_ERR_OR_ZERO(new);
1156 		if (ret)
1157 			return ret;
1158 
1159 		bkey_reassemble(&new->k_i, k);
1160 
1161 		for (i = 0; i < new->v.nr_blocks; i++)
1162 			stripe_blockcount_set(&new->v, i, m ? m->block_sectors[i] : 0);
1163 
1164 		ret = bch2_trans_update(trans, iter, &new->k_i, 0);
1165 	}
1166 fsck_err:
1167 	printbuf_exit(&buf);
1168 	return ret;
1169 }
1170 
1171 static int bch2_gc_stripes_done(struct bch_fs *c)
1172 {
1173 	return bch2_trans_run(c,
1174 		for_each_btree_key_commit(trans, iter,
1175 				BTREE_ID_stripes, POS_MIN,
1176 				BTREE_ITER_prefetch, k,
1177 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1178 			bch2_gc_write_stripes_key(trans, &iter, k)));
1179 }
1180 
1181 /**
1182  * bch2_check_allocations - walk all references to buckets, and recompute them:
1183  *
1184  * @c:			filesystem object
1185  *
1186  * Returns: 0 on success, or standard errcode on failure
1187  *
1188  * Order matters here:
1189  *  - Concurrent GC relies on the fact that we have a total ordering for
1190  *    everything that GC walks - see  gc_will_visit_node(),
1191  *    gc_will_visit_root()
1192  *
1193  *  - also, references move around in the course of index updates and
1194  *    various other crap: everything needs to agree on the ordering
1195  *    references are allowed to move around in - e.g., we're allowed to
1196  *    start with a reference owned by an open_bucket (the allocator) and
1197  *    move it to the btree, but not the reverse.
1198  *
1199  *    This is necessary to ensure that gc doesn't miss references that
1200  *    move around - if references move backwards in the ordering GC
1201  *    uses, GC could skip past them
1202  */
1203 int bch2_check_allocations(struct bch_fs *c)
1204 {
1205 	int ret;
1206 
1207 	lockdep_assert_held(&c->state_lock);
1208 
1209 	down_write(&c->gc_lock);
1210 
1211 	bch2_btree_interior_updates_flush(c);
1212 
1213 	ret   = bch2_gc_start(c) ?:
1214 		bch2_gc_alloc_start(c) ?:
1215 		bch2_gc_reflink_start(c);
1216 	if (ret)
1217 		goto out;
1218 
1219 	gc_pos_set(c, gc_phase(GC_PHASE_start));
1220 
1221 	ret = bch2_mark_superblocks(c);
1222 	BUG_ON(ret);
1223 
1224 	ret = bch2_gc_btrees(c);
1225 	if (ret)
1226 		goto out;
1227 
1228 	c->gc_count++;
1229 
1230 	bch2_journal_block(&c->journal);
1231 out:
1232 	ret   = bch2_gc_alloc_done(c) ?:
1233 		bch2_gc_done(c) ?:
1234 		bch2_gc_stripes_done(c) ?:
1235 		bch2_gc_reflink_done(c);
1236 
1237 	bch2_journal_unblock(&c->journal);
1238 
1239 	percpu_down_write(&c->mark_lock);
1240 	/* Indicates that gc is no longer in progress: */
1241 	__gc_pos_set(c, gc_phase(GC_PHASE_not_running));
1242 
1243 	bch2_gc_free(c);
1244 	percpu_up_write(&c->mark_lock);
1245 
1246 	up_write(&c->gc_lock);
1247 
1248 	/*
1249 	 * At startup, allocations can happen directly instead of via the
1250 	 * allocator thread - issue wakeup in case they blocked on gc_lock:
1251 	 */
1252 	closure_wake_up(&c->freelist_wait);
1253 	bch_err_fn(c, ret);
1254 	return ret;
1255 }
1256 
1257 static int gc_btree_gens_key(struct btree_trans *trans,
1258 			     struct btree_iter *iter,
1259 			     struct bkey_s_c k)
1260 {
1261 	struct bch_fs *c = trans->c;
1262 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1263 	struct bkey_i *u;
1264 	int ret;
1265 
1266 	if (unlikely(test_bit(BCH_FS_going_ro, &c->flags)))
1267 		return -EROFS;
1268 
1269 	percpu_down_read(&c->mark_lock);
1270 	rcu_read_lock();
1271 	bkey_for_each_ptr(ptrs, ptr) {
1272 		struct bch_dev *ca = bch2_dev_rcu(c, ptr->dev);
1273 		if (!ca)
1274 			continue;
1275 
1276 		if (dev_ptr_stale(ca, ptr) > 16) {
1277 			rcu_read_unlock();
1278 			percpu_up_read(&c->mark_lock);
1279 			goto update;
1280 		}
1281 	}
1282 
1283 	bkey_for_each_ptr(ptrs, ptr) {
1284 		struct bch_dev *ca = bch2_dev_rcu(c, ptr->dev);
1285 		if (!ca)
1286 			continue;
1287 
1288 		u8 *gen = &ca->oldest_gen[PTR_BUCKET_NR(ca, ptr)];
1289 		if (gen_after(*gen, ptr->gen))
1290 			*gen = ptr->gen;
1291 	}
1292 	rcu_read_unlock();
1293 	percpu_up_read(&c->mark_lock);
1294 	return 0;
1295 update:
1296 	u = bch2_bkey_make_mut(trans, iter, &k, 0);
1297 	ret = PTR_ERR_OR_ZERO(u);
1298 	if (ret)
1299 		return ret;
1300 
1301 	bch2_extent_normalize(c, bkey_i_to_s(u));
1302 	return 0;
1303 }
1304 
1305 static int bch2_alloc_write_oldest_gen(struct btree_trans *trans, struct bch_dev *ca,
1306 				       struct btree_iter *iter, struct bkey_s_c k)
1307 {
1308 	struct bch_alloc_v4 a_convert;
1309 	const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
1310 	struct bkey_i_alloc_v4 *a_mut;
1311 	int ret;
1312 
1313 	if (a->oldest_gen == ca->oldest_gen[iter->pos.offset])
1314 		return 0;
1315 
1316 	a_mut = bch2_alloc_to_v4_mut(trans, k);
1317 	ret = PTR_ERR_OR_ZERO(a_mut);
1318 	if (ret)
1319 		return ret;
1320 
1321 	a_mut->v.oldest_gen = ca->oldest_gen[iter->pos.offset];
1322 	alloc_data_type_set(&a_mut->v, a_mut->v.data_type);
1323 
1324 	return bch2_trans_update(trans, iter, &a_mut->k_i, 0);
1325 }
1326 
1327 int bch2_gc_gens(struct bch_fs *c)
1328 {
1329 	u64 b, start_time = local_clock();
1330 	int ret;
1331 
1332 	/*
1333 	 * Ideally we would be using state_lock and not gc_lock here, but that
1334 	 * introduces a deadlock in the RO path - we currently take the state
1335 	 * lock at the start of going RO, thus the gc thread may get stuck:
1336 	 */
1337 	if (!mutex_trylock(&c->gc_gens_lock))
1338 		return 0;
1339 
1340 	trace_and_count(c, gc_gens_start, c);
1341 	down_read(&c->gc_lock);
1342 
1343 	for_each_member_device(c, ca) {
1344 		struct bucket_gens *gens = bucket_gens(ca);
1345 
1346 		BUG_ON(ca->oldest_gen);
1347 
1348 		ca->oldest_gen = kvmalloc(gens->nbuckets, GFP_KERNEL);
1349 		if (!ca->oldest_gen) {
1350 			bch2_dev_put(ca);
1351 			ret = -BCH_ERR_ENOMEM_gc_gens;
1352 			goto err;
1353 		}
1354 
1355 		for (b = gens->first_bucket;
1356 		     b < gens->nbuckets; b++)
1357 			ca->oldest_gen[b] = gens->b[b];
1358 	}
1359 
1360 	for (unsigned i = 0; i < BTREE_ID_NR; i++)
1361 		if (btree_type_has_ptrs(i)) {
1362 			c->gc_gens_btree = i;
1363 			c->gc_gens_pos = POS_MIN;
1364 
1365 			ret = bch2_trans_run(c,
1366 				for_each_btree_key_commit(trans, iter, i,
1367 						POS_MIN,
1368 						BTREE_ITER_prefetch|BTREE_ITER_all_snapshots,
1369 						k,
1370 						NULL, NULL,
1371 						BCH_TRANS_COMMIT_no_enospc,
1372 					gc_btree_gens_key(trans, &iter, k)));
1373 			if (ret)
1374 				goto err;
1375 		}
1376 
1377 	struct bch_dev *ca = NULL;
1378 	ret = bch2_trans_run(c,
1379 		for_each_btree_key_commit(trans, iter, BTREE_ID_alloc,
1380 				POS_MIN,
1381 				BTREE_ITER_prefetch,
1382 				k,
1383 				NULL, NULL,
1384 				BCH_TRANS_COMMIT_no_enospc, ({
1385 			ca = bch2_dev_iterate(c, ca, k.k->p.inode);
1386 			if (!ca) {
1387 				bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
1388 				continue;
1389 			}
1390 			bch2_alloc_write_oldest_gen(trans, ca, &iter, k);
1391 		})));
1392 	bch2_dev_put(ca);
1393 
1394 	if (ret)
1395 		goto err;
1396 
1397 	c->gc_gens_btree	= 0;
1398 	c->gc_gens_pos		= POS_MIN;
1399 
1400 	c->gc_count++;
1401 
1402 	bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
1403 	trace_and_count(c, gc_gens_end, c);
1404 err:
1405 	for_each_member_device(c, ca) {
1406 		kvfree(ca->oldest_gen);
1407 		ca->oldest_gen = NULL;
1408 	}
1409 
1410 	up_read(&c->gc_lock);
1411 	mutex_unlock(&c->gc_gens_lock);
1412 	if (!bch2_err_matches(ret, EROFS))
1413 		bch_err_fn(c, ret);
1414 	return ret;
1415 }
1416 
1417 static void bch2_gc_gens_work(struct work_struct *work)
1418 {
1419 	struct bch_fs *c = container_of(work, struct bch_fs, gc_gens_work);
1420 	bch2_gc_gens(c);
1421 	bch2_write_ref_put(c, BCH_WRITE_REF_gc_gens);
1422 }
1423 
1424 void bch2_gc_gens_async(struct bch_fs *c)
1425 {
1426 	if (bch2_write_ref_tryget(c, BCH_WRITE_REF_gc_gens) &&
1427 	    !queue_work(c->write_ref_wq, &c->gc_gens_work))
1428 		bch2_write_ref_put(c, BCH_WRITE_REF_gc_gens);
1429 }
1430 
1431 void bch2_fs_gc_init(struct bch_fs *c)
1432 {
1433 	seqcount_init(&c->gc_pos_lock);
1434 
1435 	INIT_WORK(&c->gc_gens_work, bch2_gc_gens_work);
1436 }
1437