xref: /linux/fs/bcachefs/btree_gc.c (revision 173b0b5b0e865348684c02bd9cb1d22b5d46e458)
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 bool should_restart_for_topology_repair(struct bch_fs *c)
56 {
57 	return c->opts.fix_errors != FSCK_FIX_no &&
58 		!(c->recovery_passes_complete & BIT_ULL(BCH_RECOVERY_PASS_check_topology));
59 }
60 
61 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
62 {
63 	preempt_disable();
64 	write_seqcount_begin(&c->gc_pos_lock);
65 	c->gc_pos = new_pos;
66 	write_seqcount_end(&c->gc_pos_lock);
67 	preempt_enable();
68 }
69 
70 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
71 {
72 	BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
73 	__gc_pos_set(c, new_pos);
74 }
75 
76 static void btree_ptr_to_v2(struct btree *b, struct bkey_i_btree_ptr_v2 *dst)
77 {
78 	switch (b->key.k.type) {
79 	case KEY_TYPE_btree_ptr: {
80 		struct bkey_i_btree_ptr *src = bkey_i_to_btree_ptr(&b->key);
81 
82 		dst->k.p		= src->k.p;
83 		dst->v.mem_ptr		= 0;
84 		dst->v.seq		= b->data->keys.seq;
85 		dst->v.sectors_written	= 0;
86 		dst->v.flags		= 0;
87 		dst->v.min_key		= b->data->min_key;
88 		set_bkey_val_bytes(&dst->k, sizeof(dst->v) + bkey_val_bytes(&src->k));
89 		memcpy(dst->v.start, src->v.start, bkey_val_bytes(&src->k));
90 		break;
91 	}
92 	case KEY_TYPE_btree_ptr_v2:
93 		bkey_copy(&dst->k_i, &b->key);
94 		break;
95 	default:
96 		BUG();
97 	}
98 }
99 
100 static void bch2_btree_node_update_key_early(struct btree_trans *trans,
101 					     enum btree_id btree, unsigned level,
102 					     struct bkey_s_c old, struct bkey_i *new)
103 {
104 	struct bch_fs *c = trans->c;
105 	struct btree *b;
106 	struct bkey_buf tmp;
107 	int ret;
108 
109 	bch2_bkey_buf_init(&tmp);
110 	bch2_bkey_buf_reassemble(&tmp, c, old);
111 
112 	b = bch2_btree_node_get_noiter(trans, tmp.k, btree, level, true);
113 	if (!IS_ERR_OR_NULL(b)) {
114 		mutex_lock(&c->btree_cache.lock);
115 
116 		bch2_btree_node_hash_remove(&c->btree_cache, b);
117 
118 		bkey_copy(&b->key, new);
119 		ret = __bch2_btree_node_hash_insert(&c->btree_cache, b);
120 		BUG_ON(ret);
121 
122 		mutex_unlock(&c->btree_cache.lock);
123 		six_unlock_read(&b->c.lock);
124 	}
125 
126 	bch2_bkey_buf_exit(&tmp, c);
127 }
128 
129 static int set_node_min(struct bch_fs *c, struct btree *b, struct bpos new_min)
130 {
131 	struct bkey_i_btree_ptr_v2 *new;
132 	int ret;
133 
134 	if (c->opts.verbose) {
135 		struct printbuf buf = PRINTBUF;
136 
137 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
138 		prt_str(&buf, " -> ");
139 		bch2_bpos_to_text(&buf, new_min);
140 
141 		bch_info(c, "%s(): %s", __func__, buf.buf);
142 		printbuf_exit(&buf);
143 	}
144 
145 	new = kmalloc_array(BKEY_BTREE_PTR_U64s_MAX, sizeof(u64), GFP_KERNEL);
146 	if (!new)
147 		return -BCH_ERR_ENOMEM_gc_repair_key;
148 
149 	btree_ptr_to_v2(b, new);
150 	b->data->min_key	= new_min;
151 	new->v.min_key		= new_min;
152 	SET_BTREE_PTR_RANGE_UPDATED(&new->v, true);
153 
154 	ret = bch2_journal_key_insert_take(c, b->c.btree_id, b->c.level + 1, &new->k_i);
155 	if (ret) {
156 		kfree(new);
157 		return ret;
158 	}
159 
160 	bch2_btree_node_drop_keys_outside_node(b);
161 	bkey_copy(&b->key, &new->k_i);
162 	return 0;
163 }
164 
165 static int set_node_max(struct bch_fs *c, struct btree *b, struct bpos new_max)
166 {
167 	struct bkey_i_btree_ptr_v2 *new;
168 	int ret;
169 
170 	if (c->opts.verbose) {
171 		struct printbuf buf = PRINTBUF;
172 
173 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
174 		prt_str(&buf, " -> ");
175 		bch2_bpos_to_text(&buf, new_max);
176 
177 		bch_info(c, "%s(): %s", __func__, buf.buf);
178 		printbuf_exit(&buf);
179 	}
180 
181 	ret = bch2_journal_key_delete(c, b->c.btree_id, b->c.level + 1, b->key.k.p);
182 	if (ret)
183 		return ret;
184 
185 	new = kmalloc_array(BKEY_BTREE_PTR_U64s_MAX, sizeof(u64), GFP_KERNEL);
186 	if (!new)
187 		return -BCH_ERR_ENOMEM_gc_repair_key;
188 
189 	btree_ptr_to_v2(b, new);
190 	b->data->max_key	= new_max;
191 	new->k.p		= new_max;
192 	SET_BTREE_PTR_RANGE_UPDATED(&new->v, true);
193 
194 	ret = bch2_journal_key_insert_take(c, b->c.btree_id, b->c.level + 1, &new->k_i);
195 	if (ret) {
196 		kfree(new);
197 		return ret;
198 	}
199 
200 	bch2_btree_node_drop_keys_outside_node(b);
201 
202 	mutex_lock(&c->btree_cache.lock);
203 	bch2_btree_node_hash_remove(&c->btree_cache, b);
204 
205 	bkey_copy(&b->key, &new->k_i);
206 	ret = __bch2_btree_node_hash_insert(&c->btree_cache, b);
207 	BUG_ON(ret);
208 	mutex_unlock(&c->btree_cache.lock);
209 	return 0;
210 }
211 
212 static int btree_check_node_boundaries(struct bch_fs *c, struct btree *b,
213 				       struct btree *prev, struct btree *cur,
214 				       struct bpos *pulled_from_scan)
215 {
216 	struct bpos expected_start = !prev
217 		? b->data->min_key
218 		: bpos_successor(prev->key.k.p);
219 	struct printbuf buf = PRINTBUF;
220 	int ret = 0;
221 
222 	BUG_ON(b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
223 	       !bpos_eq(bkey_i_to_btree_ptr_v2(&b->key)->v.min_key,
224 			b->data->min_key));
225 
226 	if (bpos_eq(expected_start, cur->data->min_key))
227 		return 0;
228 
229 	prt_printf(&buf, "  at btree %s level %u:\n  parent: ",
230 		   bch2_btree_id_str(b->c.btree_id), b->c.level);
231 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
232 
233 	if (prev) {
234 		prt_printf(&buf, "\n  prev: ");
235 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&prev->key));
236 	}
237 
238 	prt_str(&buf, "\n  next: ");
239 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&cur->key));
240 
241 	if (bpos_lt(expected_start, cur->data->min_key)) {				/* gap */
242 		if (b->c.level == 1 &&
243 		    bpos_lt(*pulled_from_scan, cur->data->min_key)) {
244 			ret = bch2_get_scanned_nodes(c, b->c.btree_id, 0,
245 						     expected_start,
246 						     bpos_predecessor(cur->data->min_key));
247 			if (ret)
248 				goto err;
249 
250 			*pulled_from_scan = cur->data->min_key;
251 			ret = DID_FILL_FROM_SCAN;
252 		} else {
253 			if (mustfix_fsck_err(c, btree_node_topology_bad_min_key,
254 					     "btree node with incorrect min_key%s", buf.buf))
255 				ret = set_node_min(c, cur, expected_start);
256 		}
257 	} else {									/* overlap */
258 		if (prev && BTREE_NODE_SEQ(cur->data) > BTREE_NODE_SEQ(prev->data)) {	/* cur overwrites prev */
259 			if (bpos_ge(prev->data->min_key, cur->data->min_key)) {		/* fully? */
260 				if (mustfix_fsck_err(c, btree_node_topology_overwritten_by_next_node,
261 						     "btree node overwritten by next node%s", buf.buf))
262 					ret = DROP_PREV_NODE;
263 			} else {
264 				if (mustfix_fsck_err(c, btree_node_topology_bad_max_key,
265 						     "btree node with incorrect max_key%s", buf.buf))
266 					ret = set_node_max(c, prev,
267 							   bpos_predecessor(cur->data->min_key));
268 			}
269 		} else {
270 			if (bpos_ge(expected_start, cur->data->max_key)) {		/* fully? */
271 				if (mustfix_fsck_err(c, btree_node_topology_overwritten_by_prev_node,
272 						     "btree node overwritten by prev node%s", buf.buf))
273 					ret = DROP_THIS_NODE;
274 			} else {
275 				if (mustfix_fsck_err(c, btree_node_topology_bad_min_key,
276 						     "btree node with incorrect min_key%s", buf.buf))
277 					ret = set_node_min(c, cur, expected_start);
278 			}
279 		}
280 	}
281 err:
282 fsck_err:
283 	printbuf_exit(&buf);
284 	return ret;
285 }
286 
287 static int btree_repair_node_end(struct bch_fs *c, struct btree *b,
288 				 struct btree *child, struct bpos *pulled_from_scan)
289 {
290 	struct printbuf buf = PRINTBUF;
291 	int ret = 0;
292 
293 	if (bpos_eq(child->key.k.p, b->key.k.p))
294 		return 0;
295 
296 	prt_printf(&buf, "at btree %s level %u:\n  parent: ",
297 		   bch2_btree_id_str(b->c.btree_id), b->c.level);
298 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
299 
300 	prt_str(&buf, "\n  child: ");
301 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&child->key));
302 
303 	if (mustfix_fsck_err(c, btree_node_topology_bad_max_key,
304 			     "btree node with incorrect max_key%s", buf.buf)) {
305 		if (b->c.level == 1 &&
306 		    bpos_lt(*pulled_from_scan, b->key.k.p)) {
307 			ret = bch2_get_scanned_nodes(c, b->c.btree_id, 0,
308 						bpos_successor(child->key.k.p), b->key.k.p);
309 			if (ret)
310 				goto err;
311 
312 			*pulled_from_scan = b->key.k.p;
313 			ret = DID_FILL_FROM_SCAN;
314 		} else {
315 			ret = set_node_max(c, child, b->key.k.p);
316 		}
317 	}
318 err:
319 fsck_err:
320 	printbuf_exit(&buf);
321 	return ret;
322 }
323 
324 static int bch2_btree_repair_topology_recurse(struct btree_trans *trans, struct btree *b,
325 					      struct bpos *pulled_from_scan)
326 {
327 	struct bch_fs *c = trans->c;
328 	struct btree_and_journal_iter iter;
329 	struct bkey_s_c k;
330 	struct bkey_buf prev_k, cur_k;
331 	struct btree *prev = NULL, *cur = NULL;
332 	bool have_child, new_pass = false;
333 	struct printbuf buf = PRINTBUF;
334 	int ret = 0;
335 
336 	if (!b->c.level)
337 		return 0;
338 
339 	bch2_bkey_buf_init(&prev_k);
340 	bch2_bkey_buf_init(&cur_k);
341 again:
342 	cur = prev = NULL;
343 	have_child = new_pass = false;
344 	bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
345 	iter.prefetch = true;
346 
347 	while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
348 		BUG_ON(bpos_lt(k.k->p, b->data->min_key));
349 		BUG_ON(bpos_gt(k.k->p, b->data->max_key));
350 
351 		bch2_btree_and_journal_iter_advance(&iter);
352 		bch2_bkey_buf_reassemble(&cur_k, c, k);
353 
354 		cur = bch2_btree_node_get_noiter(trans, cur_k.k,
355 					b->c.btree_id, b->c.level - 1,
356 					false);
357 		ret = PTR_ERR_OR_ZERO(cur);
358 
359 		printbuf_reset(&buf);
360 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(cur_k.k));
361 
362 		if (mustfix_fsck_err_on(bch2_err_matches(ret, EIO), c,
363 				btree_node_unreadable,
364 				"Topology repair: unreadable btree node at btree %s level %u:\n"
365 				"  %s",
366 				bch2_btree_id_str(b->c.btree_id),
367 				b->c.level - 1,
368 				buf.buf)) {
369 			bch2_btree_node_evict(trans, cur_k.k);
370 			cur = NULL;
371 			ret = bch2_journal_key_delete(c, b->c.btree_id,
372 						      b->c.level, cur_k.k->k.p);
373 			if (ret)
374 				break;
375 
376 			if (!btree_id_is_alloc(b->c.btree_id)) {
377 				ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_scan_for_btree_nodes);
378 				if (ret)
379 					break;
380 			}
381 			continue;
382 		}
383 
384 		bch_err_msg(c, ret, "getting btree node");
385 		if (ret)
386 			break;
387 
388 		if (bch2_btree_node_is_stale(c, cur)) {
389 			bch_info(c, "btree node %s older than nodes found by scanning", buf.buf);
390 			six_unlock_read(&cur->c.lock);
391 			bch2_btree_node_evict(trans, cur_k.k);
392 			ret = bch2_journal_key_delete(c, b->c.btree_id,
393 						      b->c.level, cur_k.k->k.p);
394 			cur = NULL;
395 			if (ret)
396 				break;
397 			continue;
398 		}
399 
400 		ret = btree_check_node_boundaries(c, b, prev, cur, pulled_from_scan);
401 		if (ret == DID_FILL_FROM_SCAN) {
402 			new_pass = true;
403 			ret = 0;
404 		}
405 
406 		if (ret == DROP_THIS_NODE) {
407 			six_unlock_read(&cur->c.lock);
408 			bch2_btree_node_evict(trans, cur_k.k);
409 			ret = bch2_journal_key_delete(c, b->c.btree_id,
410 						      b->c.level, cur_k.k->k.p);
411 			cur = NULL;
412 			if (ret)
413 				break;
414 			continue;
415 		}
416 
417 		if (prev)
418 			six_unlock_read(&prev->c.lock);
419 		prev = NULL;
420 
421 		if (ret == DROP_PREV_NODE) {
422 			bch_info(c, "dropped prev node");
423 			bch2_btree_node_evict(trans, prev_k.k);
424 			ret = bch2_journal_key_delete(c, b->c.btree_id,
425 						      b->c.level, prev_k.k->k.p);
426 			if (ret)
427 				break;
428 
429 			bch2_btree_and_journal_iter_exit(&iter);
430 			goto again;
431 		} else if (ret)
432 			break;
433 
434 		prev = cur;
435 		cur = NULL;
436 		bch2_bkey_buf_copy(&prev_k, c, cur_k.k);
437 	}
438 
439 	if (!ret && !IS_ERR_OR_NULL(prev)) {
440 		BUG_ON(cur);
441 		ret = btree_repair_node_end(c, b, prev, pulled_from_scan);
442 		if (ret == DID_FILL_FROM_SCAN) {
443 			new_pass = true;
444 			ret = 0;
445 		}
446 	}
447 
448 	if (!IS_ERR_OR_NULL(prev))
449 		six_unlock_read(&prev->c.lock);
450 	prev = NULL;
451 	if (!IS_ERR_OR_NULL(cur))
452 		six_unlock_read(&cur->c.lock);
453 	cur = NULL;
454 
455 	if (ret)
456 		goto err;
457 
458 	bch2_btree_and_journal_iter_exit(&iter);
459 
460 	if (new_pass)
461 		goto again;
462 
463 	bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
464 	iter.prefetch = true;
465 
466 	while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
467 		bch2_bkey_buf_reassemble(&cur_k, c, k);
468 		bch2_btree_and_journal_iter_advance(&iter);
469 
470 		cur = bch2_btree_node_get_noiter(trans, cur_k.k,
471 					b->c.btree_id, b->c.level - 1,
472 					false);
473 		ret = PTR_ERR_OR_ZERO(cur);
474 
475 		bch_err_msg(c, ret, "getting btree node");
476 		if (ret)
477 			goto err;
478 
479 		ret = bch2_btree_repair_topology_recurse(trans, cur, pulled_from_scan);
480 		six_unlock_read(&cur->c.lock);
481 		cur = NULL;
482 
483 		if (ret == DROP_THIS_NODE) {
484 			bch2_btree_node_evict(trans, cur_k.k);
485 			ret = bch2_journal_key_delete(c, b->c.btree_id,
486 						      b->c.level, cur_k.k->k.p);
487 			new_pass = true;
488 		}
489 
490 		if (ret)
491 			goto err;
492 
493 		have_child = true;
494 	}
495 
496 	printbuf_reset(&buf);
497 	bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
498 
499 	if (mustfix_fsck_err_on(!have_child, c,
500 			btree_node_topology_interior_node_empty,
501 			"empty interior btree node at btree %s level %u\n"
502 			"  %s",
503 			bch2_btree_id_str(b->c.btree_id),
504 			b->c.level, buf.buf))
505 		ret = DROP_THIS_NODE;
506 err:
507 fsck_err:
508 	if (!IS_ERR_OR_NULL(prev))
509 		six_unlock_read(&prev->c.lock);
510 	if (!IS_ERR_OR_NULL(cur))
511 		six_unlock_read(&cur->c.lock);
512 
513 	bch2_btree_and_journal_iter_exit(&iter);
514 
515 	if (!ret && new_pass)
516 		goto again;
517 
518 	BUG_ON(!ret && bch2_btree_node_check_topology(trans, b));
519 
520 	bch2_bkey_buf_exit(&prev_k, c);
521 	bch2_bkey_buf_exit(&cur_k, c);
522 	printbuf_exit(&buf);
523 	return ret;
524 }
525 
526 int bch2_check_topology(struct bch_fs *c)
527 {
528 	struct btree_trans *trans = bch2_trans_get(c);
529 	struct bpos pulled_from_scan = POS_MIN;
530 	int ret = 0;
531 
532 	for (unsigned i = 0; i < btree_id_nr_alive(c) && !ret; i++) {
533 		struct btree_root *r = bch2_btree_id_root(c, i);
534 		bool reconstructed_root = false;
535 
536 		if (r->error) {
537 			ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_scan_for_btree_nodes);
538 			if (ret)
539 				break;
540 reconstruct_root:
541 			bch_info(c, "btree root %s unreadable, must recover from scan", bch2_btree_id_str(i));
542 
543 			r->alive = false;
544 			r->error = 0;
545 
546 			if (!bch2_btree_has_scanned_nodes(c, i)) {
547 				mustfix_fsck_err(c, btree_root_unreadable_and_scan_found_nothing,
548 						 "no nodes found for btree %s, continue?", bch2_btree_id_str(i));
549 				bch2_btree_root_alloc_fake(c, i, 0);
550 			} else {
551 				bch2_btree_root_alloc_fake(c, i, 1);
552 				bch2_shoot_down_journal_keys(c, i, 1, BTREE_MAX_DEPTH, POS_MIN, SPOS_MAX);
553 				ret = bch2_get_scanned_nodes(c, i, 0, POS_MIN, SPOS_MAX);
554 				if (ret)
555 					break;
556 			}
557 
558 			reconstructed_root = true;
559 		}
560 
561 		struct btree *b = r->b;
562 
563 		btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_read);
564 		ret = bch2_btree_repair_topology_recurse(trans, b, &pulled_from_scan);
565 		six_unlock_read(&b->c.lock);
566 
567 		if (ret == DROP_THIS_NODE) {
568 			bch2_btree_node_hash_remove(&c->btree_cache, b);
569 			mutex_lock(&c->btree_cache.lock);
570 			list_move(&b->list, &c->btree_cache.freeable);
571 			mutex_unlock(&c->btree_cache.lock);
572 
573 			r->b = NULL;
574 
575 			if (!reconstructed_root)
576 				goto reconstruct_root;
577 
578 			bch_err(c, "empty btree root %s", bch2_btree_id_str(i));
579 			bch2_btree_root_alloc_fake(c, i, 0);
580 			r->alive = false;
581 			ret = 0;
582 		}
583 	}
584 fsck_err:
585 	bch2_trans_put(trans);
586 	return ret;
587 }
588 
589 static int bch2_check_fix_ptrs(struct btree_trans *trans, enum btree_id btree_id,
590 			       unsigned level, bool is_root,
591 			       struct bkey_s_c *k)
592 {
593 	struct bch_fs *c = trans->c;
594 	struct bkey_ptrs_c ptrs_c = bch2_bkey_ptrs_c(*k);
595 	const union bch_extent_entry *entry_c;
596 	struct extent_ptr_decoded p = { 0 };
597 	bool do_update = false;
598 	struct printbuf buf = PRINTBUF;
599 	int ret = 0;
600 
601 	/*
602 	 * XXX
603 	 * use check_bucket_ref here
604 	 */
605 	bkey_for_each_ptr_decode(k->k, ptrs_c, p, entry_c) {
606 		struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
607 		struct bucket *g = PTR_GC_BUCKET(ca, &p.ptr);
608 		enum bch_data_type data_type = bch2_bkey_ptr_data_type(*k, p, entry_c);
609 
610 		if (fsck_err_on(!g->gen_valid,
611 				c, ptr_to_missing_alloc_key,
612 				"bucket %u:%zu data type %s ptr gen %u missing in alloc btree\n"
613 				"while marking %s",
614 				p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr),
615 				bch2_data_type_str(ptr_data_type(k->k, &p.ptr)),
616 				p.ptr.gen,
617 				(printbuf_reset(&buf),
618 				 bch2_bkey_val_to_text(&buf, c, *k), buf.buf))) {
619 			if (!p.ptr.cached) {
620 				g->gen_valid		= true;
621 				g->gen			= p.ptr.gen;
622 			} else {
623 				do_update = true;
624 			}
625 		}
626 
627 		if (fsck_err_on(gen_cmp(p.ptr.gen, g->gen) > 0,
628 				c, ptr_gen_newer_than_bucket_gen,
629 				"bucket %u:%zu data type %s ptr gen in the future: %u > %u\n"
630 				"while marking %s",
631 				p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr),
632 				bch2_data_type_str(ptr_data_type(k->k, &p.ptr)),
633 				p.ptr.gen, g->gen,
634 				(printbuf_reset(&buf),
635 				 bch2_bkey_val_to_text(&buf, c, *k), buf.buf))) {
636 			if (!p.ptr.cached) {
637 				g->gen_valid		= true;
638 				g->gen			= p.ptr.gen;
639 				g->data_type		= 0;
640 				g->dirty_sectors	= 0;
641 				g->cached_sectors	= 0;
642 				set_bit(BCH_FS_need_another_gc, &c->flags);
643 			} else {
644 				do_update = true;
645 			}
646 		}
647 
648 		if (fsck_err_on(gen_cmp(g->gen, p.ptr.gen) > BUCKET_GC_GEN_MAX,
649 				c, ptr_gen_newer_than_bucket_gen,
650 				"bucket %u:%zu gen %u data type %s: ptr gen %u too stale\n"
651 				"while marking %s",
652 				p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr), g->gen,
653 				bch2_data_type_str(ptr_data_type(k->k, &p.ptr)),
654 				p.ptr.gen,
655 				(printbuf_reset(&buf),
656 				 bch2_bkey_val_to_text(&buf, c, *k), buf.buf)))
657 			do_update = true;
658 
659 		if (fsck_err_on(!p.ptr.cached && gen_cmp(p.ptr.gen, g->gen) < 0,
660 				c, stale_dirty_ptr,
661 				"bucket %u:%zu data type %s stale dirty ptr: %u < %u\n"
662 				"while marking %s",
663 				p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr),
664 				bch2_data_type_str(ptr_data_type(k->k, &p.ptr)),
665 				p.ptr.gen, g->gen,
666 				(printbuf_reset(&buf),
667 				 bch2_bkey_val_to_text(&buf, c, *k), buf.buf)))
668 			do_update = true;
669 
670 		if (data_type != BCH_DATA_btree && p.ptr.gen != g->gen)
671 			continue;
672 
673 		if (fsck_err_on(bucket_data_type(g->data_type) &&
674 				bucket_data_type(g->data_type) !=
675 				bucket_data_type(data_type), c,
676 				ptr_bucket_data_type_mismatch,
677 				"bucket %u:%zu different types of data in same bucket: %s, %s\n"
678 				"while marking %s",
679 				p.ptr.dev, PTR_BUCKET_NR(ca, &p.ptr),
680 				bch2_data_type_str(g->data_type),
681 				bch2_data_type_str(data_type),
682 				(printbuf_reset(&buf),
683 				 bch2_bkey_val_to_text(&buf, c, *k), buf.buf))) {
684 			if (data_type == BCH_DATA_btree) {
685 				g->data_type	= data_type;
686 				set_bit(BCH_FS_need_another_gc, &c->flags);
687 			} else {
688 				do_update = true;
689 			}
690 		}
691 
692 		if (p.has_ec) {
693 			struct gc_stripe *m = genradix_ptr(&c->gc_stripes, p.ec.idx);
694 
695 			if (fsck_err_on(!m || !m->alive, c,
696 					ptr_to_missing_stripe,
697 					"pointer to nonexistent stripe %llu\n"
698 					"while marking %s",
699 					(u64) p.ec.idx,
700 					(printbuf_reset(&buf),
701 					 bch2_bkey_val_to_text(&buf, c, *k), buf.buf)))
702 				do_update = true;
703 
704 			if (fsck_err_on(m && m->alive && !bch2_ptr_matches_stripe_m(m, p), c,
705 					ptr_to_incorrect_stripe,
706 					"pointer does not match stripe %llu\n"
707 					"while marking %s",
708 					(u64) p.ec.idx,
709 					(printbuf_reset(&buf),
710 					 bch2_bkey_val_to_text(&buf, c, *k), buf.buf)))
711 				do_update = true;
712 		}
713 	}
714 
715 	if (do_update) {
716 		if (is_root) {
717 			bch_err(c, "cannot update btree roots yet");
718 			ret = -EINVAL;
719 			goto err;
720 		}
721 
722 		struct bkey_i *new = kmalloc(bkey_bytes(k->k), GFP_KERNEL);
723 		if (!new) {
724 			ret = -BCH_ERR_ENOMEM_gc_repair_key;
725 			bch_err_msg(c, ret, "allocating new key");
726 			goto err;
727 		}
728 
729 		bkey_reassemble(new, *k);
730 
731 		if (level) {
732 			/*
733 			 * We don't want to drop btree node pointers - if the
734 			 * btree node isn't there anymore, the read path will
735 			 * sort it out:
736 			 */
737 			struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
738 			bkey_for_each_ptr(ptrs, ptr) {
739 				struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
740 				struct bucket *g = PTR_GC_BUCKET(ca, ptr);
741 
742 				ptr->gen = g->gen;
743 			}
744 		} else {
745 			struct bkey_ptrs ptrs;
746 			union bch_extent_entry *entry;
747 restart_drop_ptrs:
748 			ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
749 			bkey_for_each_ptr_decode(bkey_i_to_s(new).k, ptrs, p, entry) {
750 				struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
751 				struct bucket *g = PTR_GC_BUCKET(ca, &p.ptr);
752 				enum bch_data_type data_type = bch2_bkey_ptr_data_type(bkey_i_to_s_c(new), p, entry);
753 
754 				if ((p.ptr.cached &&
755 				     (!g->gen_valid || gen_cmp(p.ptr.gen, g->gen) > 0)) ||
756 				    (!p.ptr.cached &&
757 				     gen_cmp(p.ptr.gen, g->gen) < 0) ||
758 				    gen_cmp(g->gen, p.ptr.gen) > BUCKET_GC_GEN_MAX ||
759 				    (g->data_type &&
760 				     g->data_type != data_type)) {
761 					bch2_bkey_drop_ptr(bkey_i_to_s(new), &entry->ptr);
762 					goto restart_drop_ptrs;
763 				}
764 			}
765 again:
766 			ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
767 			bkey_extent_entry_for_each(ptrs, entry) {
768 				if (extent_entry_type(entry) == BCH_EXTENT_ENTRY_stripe_ptr) {
769 					struct gc_stripe *m = genradix_ptr(&c->gc_stripes,
770 									entry->stripe_ptr.idx);
771 					union bch_extent_entry *next_ptr;
772 
773 					bkey_extent_entry_for_each_from(ptrs, next_ptr, entry)
774 						if (extent_entry_type(next_ptr) == BCH_EXTENT_ENTRY_ptr)
775 							goto found;
776 					next_ptr = NULL;
777 found:
778 					if (!next_ptr) {
779 						bch_err(c, "aieee, found stripe ptr with no data ptr");
780 						continue;
781 					}
782 
783 					if (!m || !m->alive ||
784 					    !__bch2_ptr_matches_stripe(&m->ptrs[entry->stripe_ptr.block],
785 								       &next_ptr->ptr,
786 								       m->sectors)) {
787 						bch2_bkey_extent_entry_drop(new, entry);
788 						goto again;
789 					}
790 				}
791 			}
792 		}
793 
794 		if (level)
795 			bch2_btree_node_update_key_early(trans, btree_id, level - 1, *k, new);
796 
797 		if (0) {
798 			printbuf_reset(&buf);
799 			bch2_bkey_val_to_text(&buf, c, *k);
800 			bch_info(c, "updated %s", buf.buf);
801 
802 			printbuf_reset(&buf);
803 			bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(new));
804 			bch_info(c, "new key %s", buf.buf);
805 		}
806 
807 		ret = bch2_journal_key_insert_take(c, btree_id, level, new);
808 		if (ret) {
809 			kfree(new);
810 			goto err;
811 		}
812 
813 		*k = bkey_i_to_s_c(new);
814 	}
815 err:
816 fsck_err:
817 	printbuf_exit(&buf);
818 	return ret;
819 }
820 
821 /* marking of btree keys/nodes: */
822 
823 static int bch2_gc_mark_key(struct btree_trans *trans, enum btree_id btree_id,
824 			    unsigned level, bool is_root,
825 			    struct bkey_s_c *k,
826 			    bool initial)
827 {
828 	struct bch_fs *c = trans->c;
829 	struct bkey deleted = KEY(0, 0, 0);
830 	struct bkey_s_c old = (struct bkey_s_c) { &deleted, NULL };
831 	struct printbuf buf = PRINTBUF;
832 	int ret = 0;
833 
834 	deleted.p = k->k->p;
835 
836 	if (initial) {
837 		BUG_ON(bch2_journal_seq_verify &&
838 		       k->k->version.lo > atomic64_read(&c->journal.seq));
839 
840 		if (fsck_err_on(k->k->version.lo > atomic64_read(&c->key_version), c,
841 				bkey_version_in_future,
842 				"key version number higher than recorded: %llu > %llu",
843 				k->k->version.lo,
844 				atomic64_read(&c->key_version)))
845 			atomic64_set(&c->key_version, k->k->version.lo);
846 	}
847 
848 	ret = bch2_check_fix_ptrs(trans, btree_id, level, is_root, k);
849 	if (ret)
850 		goto err;
851 
852 	if (mustfix_fsck_err_on(level && !bch2_dev_btree_bitmap_marked(c, *k),
853 				c, btree_bitmap_not_marked,
854 				"btree ptr not marked in member info btree allocated bitmap\n  %s",
855 				(bch2_bkey_val_to_text(&buf, c, *k),
856 				 buf.buf))) {
857 		mutex_lock(&c->sb_lock);
858 		bch2_dev_btree_bitmap_mark(c, *k);
859 		bch2_write_super(c);
860 		mutex_unlock(&c->sb_lock);
861 	}
862 
863 	ret = commit_do(trans, NULL, NULL, 0,
864 			bch2_key_trigger(trans, btree_id, level, old,
865 					 unsafe_bkey_s_c_to_s(*k), BTREE_TRIGGER_GC));
866 fsck_err:
867 err:
868 	printbuf_exit(&buf);
869 	bch_err_fn(c, ret);
870 	return ret;
871 }
872 
873 static int btree_gc_mark_node(struct btree_trans *trans, struct btree *b, bool initial)
874 {
875 	struct btree_node_iter iter;
876 	struct bkey unpacked;
877 	struct bkey_s_c k;
878 	int ret = 0;
879 
880 	ret = bch2_btree_node_check_topology(trans, b);
881 	if (ret)
882 		return ret;
883 
884 	if (!btree_node_type_needs_gc(btree_node_type(b)))
885 		return 0;
886 
887 	bch2_btree_node_iter_init_from_start(&iter, b);
888 
889 	while ((k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked)).k) {
890 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level, false,
891 				       &k, initial);
892 		if (ret)
893 			return ret;
894 
895 		bch2_btree_node_iter_advance(&iter, b);
896 	}
897 
898 	return 0;
899 }
900 
901 static int bch2_gc_btree(struct btree_trans *trans, enum btree_id btree_id,
902 			 bool initial, bool metadata_only)
903 {
904 	struct bch_fs *c = trans->c;
905 	struct btree_iter iter;
906 	struct btree *b;
907 	unsigned depth = metadata_only ? 1 : 0;
908 	int ret = 0;
909 
910 	gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
911 
912 	__for_each_btree_node(trans, iter, btree_id, POS_MIN,
913 			      0, depth, BTREE_ITER_PREFETCH, b, ret) {
914 		bch2_verify_btree_nr_keys(b);
915 
916 		gc_pos_set(c, gc_pos_btree_node(b));
917 
918 		ret = btree_gc_mark_node(trans, b, initial);
919 		if (ret)
920 			break;
921 	}
922 	bch2_trans_iter_exit(trans, &iter);
923 
924 	if (ret)
925 		return ret;
926 
927 	mutex_lock(&c->btree_root_lock);
928 	b = bch2_btree_id_root(c, btree_id)->b;
929 	if (!btree_node_fake(b)) {
930 		struct bkey_s_c k = bkey_i_to_s_c(&b->key);
931 
932 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level + 1,
933 				       true, &k, initial);
934 	}
935 	gc_pos_set(c, gc_pos_btree_root(b->c.btree_id));
936 	mutex_unlock(&c->btree_root_lock);
937 
938 	return ret;
939 }
940 
941 static int bch2_gc_btree_init_recurse(struct btree_trans *trans, struct btree *b,
942 				      unsigned target_depth)
943 {
944 	struct bch_fs *c = trans->c;
945 	struct btree_and_journal_iter iter;
946 	struct bkey_s_c k;
947 	struct bkey_buf cur;
948 	struct printbuf buf = PRINTBUF;
949 	int ret = 0;
950 
951 	ret = bch2_btree_node_check_topology(trans, b);
952 	if (ret)
953 		return ret;
954 
955 	bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
956 	bch2_bkey_buf_init(&cur);
957 
958 	while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
959 		BUG_ON(bpos_lt(k.k->p, b->data->min_key));
960 		BUG_ON(bpos_gt(k.k->p, b->data->max_key));
961 
962 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level,
963 				       false, &k, true);
964 		if (ret)
965 			goto fsck_err;
966 
967 		bch2_btree_and_journal_iter_advance(&iter);
968 	}
969 
970 	if (b->c.level > target_depth) {
971 		bch2_btree_and_journal_iter_exit(&iter);
972 		bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
973 		iter.prefetch = true;
974 
975 		while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
976 			struct btree *child;
977 
978 			bch2_bkey_buf_reassemble(&cur, c, k);
979 			bch2_btree_and_journal_iter_advance(&iter);
980 
981 			child = bch2_btree_node_get_noiter(trans, cur.k,
982 						b->c.btree_id, b->c.level - 1,
983 						false);
984 			ret = PTR_ERR_OR_ZERO(child);
985 
986 			if (bch2_err_matches(ret, EIO)) {
987 				bch2_topology_error(c);
988 
989 				if (__fsck_err(c,
990 					  FSCK_CAN_FIX|
991 					  FSCK_CAN_IGNORE|
992 					  FSCK_NO_RATELIMIT,
993 					  btree_node_read_error,
994 					  "Unreadable btree node at btree %s level %u:\n"
995 					  "  %s",
996 					  bch2_btree_id_str(b->c.btree_id),
997 					  b->c.level - 1,
998 					  (printbuf_reset(&buf),
999 					   bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(cur.k)), buf.buf)) &&
1000 				    should_restart_for_topology_repair(c)) {
1001 					bch_info(c, "Halting mark and sweep to start topology repair pass");
1002 					ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_check_topology);
1003 					goto fsck_err;
1004 				} else {
1005 					/* Continue marking when opted to not
1006 					 * fix the error: */
1007 					ret = 0;
1008 					set_bit(BCH_FS_initial_gc_unfixed, &c->flags);
1009 					continue;
1010 				}
1011 			} else if (ret) {
1012 				bch_err_msg(c, ret, "getting btree node");
1013 				break;
1014 			}
1015 
1016 			ret = bch2_gc_btree_init_recurse(trans, child,
1017 							 target_depth);
1018 			six_unlock_read(&child->c.lock);
1019 
1020 			if (ret)
1021 				break;
1022 		}
1023 	}
1024 fsck_err:
1025 	bch2_bkey_buf_exit(&cur, c);
1026 	bch2_btree_and_journal_iter_exit(&iter);
1027 	printbuf_exit(&buf);
1028 	return ret;
1029 }
1030 
1031 static int bch2_gc_btree_init(struct btree_trans *trans,
1032 			      enum btree_id btree_id,
1033 			      bool metadata_only)
1034 {
1035 	struct bch_fs *c = trans->c;
1036 	struct btree *b;
1037 	unsigned target_depth = metadata_only ? 1 : 0;
1038 	struct printbuf buf = PRINTBUF;
1039 	int ret = 0;
1040 
1041 	b = bch2_btree_id_root(c, btree_id)->b;
1042 
1043 	six_lock_read(&b->c.lock, NULL, NULL);
1044 	printbuf_reset(&buf);
1045 	bch2_bpos_to_text(&buf, b->data->min_key);
1046 	if (mustfix_fsck_err_on(!bpos_eq(b->data->min_key, POS_MIN), c,
1047 				btree_root_bad_min_key,
1048 			"btree root with incorrect min_key: %s", buf.buf)) {
1049 		bch_err(c, "repair unimplemented");
1050 		ret = -BCH_ERR_fsck_repair_unimplemented;
1051 		goto fsck_err;
1052 	}
1053 
1054 	printbuf_reset(&buf);
1055 	bch2_bpos_to_text(&buf, b->data->max_key);
1056 	if (mustfix_fsck_err_on(!bpos_eq(b->data->max_key, SPOS_MAX), c,
1057 				btree_root_bad_max_key,
1058 			"btree root with incorrect max_key: %s", buf.buf)) {
1059 		bch_err(c, "repair unimplemented");
1060 		ret = -BCH_ERR_fsck_repair_unimplemented;
1061 		goto fsck_err;
1062 	}
1063 
1064 	if (b->c.level >= target_depth)
1065 		ret = bch2_gc_btree_init_recurse(trans, b, target_depth);
1066 
1067 	if (!ret) {
1068 		struct bkey_s_c k = bkey_i_to_s_c(&b->key);
1069 
1070 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level + 1, true,
1071 				       &k, true);
1072 	}
1073 fsck_err:
1074 	six_unlock_read(&b->c.lock);
1075 
1076 	bch_err_fn(c, ret);
1077 	printbuf_exit(&buf);
1078 	return ret;
1079 }
1080 
1081 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
1082 {
1083 	return  (int) btree_id_to_gc_phase(l) -
1084 		(int) btree_id_to_gc_phase(r);
1085 }
1086 
1087 static int bch2_gc_btrees(struct bch_fs *c, bool initial, bool metadata_only)
1088 {
1089 	struct btree_trans *trans = bch2_trans_get(c);
1090 	enum btree_id ids[BTREE_ID_NR];
1091 	unsigned i;
1092 	int ret = 0;
1093 
1094 	for (i = 0; i < BTREE_ID_NR; i++)
1095 		ids[i] = i;
1096 	bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
1097 
1098 	for (i = 0; i < BTREE_ID_NR && !ret; i++)
1099 		ret = initial
1100 			? bch2_gc_btree_init(trans, ids[i], metadata_only)
1101 			: bch2_gc_btree(trans, ids[i], initial, metadata_only);
1102 
1103 	for (i = BTREE_ID_NR; i < btree_id_nr_alive(c) && !ret; i++) {
1104 		if (!bch2_btree_id_root(c, i)->alive)
1105 			continue;
1106 
1107 		ret = initial
1108 			? bch2_gc_btree_init(trans, i, metadata_only)
1109 			: bch2_gc_btree(trans, i, initial, metadata_only);
1110 	}
1111 
1112 	bch2_trans_put(trans);
1113 	bch_err_fn(c, ret);
1114 	return ret;
1115 }
1116 
1117 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
1118 				  u64 start, u64 end,
1119 				  enum bch_data_type type,
1120 				  unsigned flags)
1121 {
1122 	u64 b = sector_to_bucket(ca, start);
1123 
1124 	do {
1125 		unsigned sectors =
1126 			min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
1127 
1128 		bch2_mark_metadata_bucket(c, ca, b, type, sectors,
1129 					  gc_phase(GC_PHASE_SB), flags);
1130 		b++;
1131 		start += sectors;
1132 	} while (start < end);
1133 }
1134 
1135 static void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
1136 				     unsigned flags)
1137 {
1138 	struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
1139 	unsigned i;
1140 	u64 b;
1141 
1142 	for (i = 0; i < layout->nr_superblocks; i++) {
1143 		u64 offset = le64_to_cpu(layout->sb_offset[i]);
1144 
1145 		if (offset == BCH_SB_SECTOR)
1146 			mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
1147 					      BCH_DATA_sb, flags);
1148 
1149 		mark_metadata_sectors(c, ca, offset,
1150 				      offset + (1 << layout->sb_max_size_bits),
1151 				      BCH_DATA_sb, flags);
1152 	}
1153 
1154 	for (i = 0; i < ca->journal.nr; i++) {
1155 		b = ca->journal.buckets[i];
1156 		bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_journal,
1157 					  ca->mi.bucket_size,
1158 					  gc_phase(GC_PHASE_SB), flags);
1159 	}
1160 }
1161 
1162 static void bch2_mark_superblocks(struct bch_fs *c)
1163 {
1164 	mutex_lock(&c->sb_lock);
1165 	gc_pos_set(c, gc_phase(GC_PHASE_SB));
1166 
1167 	for_each_online_member(c, ca)
1168 		bch2_mark_dev_superblock(c, ca, BTREE_TRIGGER_GC);
1169 	mutex_unlock(&c->sb_lock);
1170 }
1171 
1172 #if 0
1173 /* Also see bch2_pending_btree_node_free_insert_done() */
1174 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
1175 {
1176 	struct btree_update *as;
1177 	struct pending_btree_node_free *d;
1178 
1179 	mutex_lock(&c->btree_interior_update_lock);
1180 	gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
1181 
1182 	for_each_pending_btree_node_free(c, as, d)
1183 		if (d->index_update_done)
1184 			bch2_mark_key(c, bkey_i_to_s_c(&d->key), BTREE_TRIGGER_GC);
1185 
1186 	mutex_unlock(&c->btree_interior_update_lock);
1187 }
1188 #endif
1189 
1190 static void bch2_gc_free(struct bch_fs *c)
1191 {
1192 	genradix_free(&c->reflink_gc_table);
1193 	genradix_free(&c->gc_stripes);
1194 
1195 	for_each_member_device(c, ca) {
1196 		kvfree(rcu_dereference_protected(ca->buckets_gc, 1));
1197 		ca->buckets_gc = NULL;
1198 
1199 		free_percpu(ca->usage_gc);
1200 		ca->usage_gc = NULL;
1201 	}
1202 
1203 	free_percpu(c->usage_gc);
1204 	c->usage_gc = NULL;
1205 }
1206 
1207 static int bch2_gc_done(struct bch_fs *c,
1208 			bool initial, bool metadata_only)
1209 {
1210 	struct bch_dev *ca = NULL;
1211 	struct printbuf buf = PRINTBUF;
1212 	bool verify = !metadata_only &&
1213 		!c->opts.reconstruct_alloc &&
1214 		(!initial || (c->sb.compat & (1ULL << BCH_COMPAT_alloc_info)));
1215 	unsigned i;
1216 	int ret = 0;
1217 
1218 	percpu_down_write(&c->mark_lock);
1219 
1220 #define copy_field(_err, _f, _msg, ...)					\
1221 	if (dst->_f != src->_f &&					\
1222 	    (!verify ||							\
1223 	     fsck_err(c, _err, _msg ": got %llu, should be %llu"	\
1224 		      , ##__VA_ARGS__, dst->_f, src->_f)))		\
1225 		dst->_f = src->_f
1226 #define copy_dev_field(_err, _f, _msg, ...)				\
1227 	copy_field(_err, _f, "dev %u has wrong " _msg, ca->dev_idx, ##__VA_ARGS__)
1228 #define copy_fs_field(_err, _f, _msg, ...)				\
1229 	copy_field(_err, _f, "fs has wrong " _msg, ##__VA_ARGS__)
1230 
1231 	for (i = 0; i < ARRAY_SIZE(c->usage); i++)
1232 		bch2_fs_usage_acc_to_base(c, i);
1233 
1234 	__for_each_member_device(c, ca) {
1235 		struct bch_dev_usage *dst = ca->usage_base;
1236 		struct bch_dev_usage *src = (void *)
1237 			bch2_acc_percpu_u64s((u64 __percpu *) ca->usage_gc,
1238 					     dev_usage_u64s());
1239 
1240 		for (i = 0; i < BCH_DATA_NR; i++) {
1241 			copy_dev_field(dev_usage_buckets_wrong,
1242 				       d[i].buckets,	"%s buckets", bch2_data_type_str(i));
1243 			copy_dev_field(dev_usage_sectors_wrong,
1244 				       d[i].sectors,	"%s sectors", bch2_data_type_str(i));
1245 			copy_dev_field(dev_usage_fragmented_wrong,
1246 				       d[i].fragmented,	"%s fragmented", bch2_data_type_str(i));
1247 		}
1248 	}
1249 
1250 	{
1251 		unsigned nr = fs_usage_u64s(c);
1252 		struct bch_fs_usage *dst = c->usage_base;
1253 		struct bch_fs_usage *src = (void *)
1254 			bch2_acc_percpu_u64s((u64 __percpu *) c->usage_gc, nr);
1255 
1256 		copy_fs_field(fs_usage_hidden_wrong,
1257 			      b.hidden,		"hidden");
1258 		copy_fs_field(fs_usage_btree_wrong,
1259 			      b.btree,		"btree");
1260 
1261 		if (!metadata_only) {
1262 			copy_fs_field(fs_usage_data_wrong,
1263 				      b.data,	"data");
1264 			copy_fs_field(fs_usage_cached_wrong,
1265 				      b.cached,	"cached");
1266 			copy_fs_field(fs_usage_reserved_wrong,
1267 				      b.reserved,	"reserved");
1268 			copy_fs_field(fs_usage_nr_inodes_wrong,
1269 				      b.nr_inodes,"nr_inodes");
1270 
1271 			for (i = 0; i < BCH_REPLICAS_MAX; i++)
1272 				copy_fs_field(fs_usage_persistent_reserved_wrong,
1273 					      persistent_reserved[i],
1274 					      "persistent_reserved[%i]", i);
1275 		}
1276 
1277 		for (i = 0; i < c->replicas.nr; i++) {
1278 			struct bch_replicas_entry_v1 *e =
1279 				cpu_replicas_entry(&c->replicas, i);
1280 
1281 			if (metadata_only &&
1282 			    (e->data_type == BCH_DATA_user ||
1283 			     e->data_type == BCH_DATA_cached))
1284 				continue;
1285 
1286 			printbuf_reset(&buf);
1287 			bch2_replicas_entry_to_text(&buf, e);
1288 
1289 			copy_fs_field(fs_usage_replicas_wrong,
1290 				      replicas[i], "%s", buf.buf);
1291 		}
1292 	}
1293 
1294 #undef copy_fs_field
1295 #undef copy_dev_field
1296 #undef copy_stripe_field
1297 #undef copy_field
1298 fsck_err:
1299 	if (ca)
1300 		percpu_ref_put(&ca->ref);
1301 	bch_err_fn(c, ret);
1302 
1303 	percpu_up_write(&c->mark_lock);
1304 	printbuf_exit(&buf);
1305 	return ret;
1306 }
1307 
1308 static int bch2_gc_start(struct bch_fs *c)
1309 {
1310 	BUG_ON(c->usage_gc);
1311 
1312 	c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
1313 					 sizeof(u64), GFP_KERNEL);
1314 	if (!c->usage_gc) {
1315 		bch_err(c, "error allocating c->usage_gc");
1316 		return -BCH_ERR_ENOMEM_gc_start;
1317 	}
1318 
1319 	for_each_member_device(c, ca) {
1320 		BUG_ON(ca->usage_gc);
1321 
1322 		ca->usage_gc = alloc_percpu(struct bch_dev_usage);
1323 		if (!ca->usage_gc) {
1324 			bch_err(c, "error allocating ca->usage_gc");
1325 			percpu_ref_put(&ca->ref);
1326 			return -BCH_ERR_ENOMEM_gc_start;
1327 		}
1328 
1329 		this_cpu_write(ca->usage_gc->d[BCH_DATA_free].buckets,
1330 			       ca->mi.nbuckets - ca->mi.first_bucket);
1331 	}
1332 
1333 	return 0;
1334 }
1335 
1336 static int bch2_gc_reset(struct bch_fs *c)
1337 {
1338 	for_each_member_device(c, ca) {
1339 		free_percpu(ca->usage_gc);
1340 		ca->usage_gc = NULL;
1341 	}
1342 
1343 	free_percpu(c->usage_gc);
1344 	c->usage_gc = NULL;
1345 
1346 	return bch2_gc_start(c);
1347 }
1348 
1349 /* returns true if not equal */
1350 static inline bool bch2_alloc_v4_cmp(struct bch_alloc_v4 l,
1351 				     struct bch_alloc_v4 r)
1352 {
1353 	return  l.gen != r.gen				||
1354 		l.oldest_gen != r.oldest_gen		||
1355 		l.data_type != r.data_type		||
1356 		l.dirty_sectors	!= r.dirty_sectors	||
1357 		l.cached_sectors != r.cached_sectors	 ||
1358 		l.stripe_redundancy != r.stripe_redundancy ||
1359 		l.stripe != r.stripe;
1360 }
1361 
1362 static int bch2_alloc_write_key(struct btree_trans *trans,
1363 				struct btree_iter *iter,
1364 				struct bkey_s_c k,
1365 				bool metadata_only)
1366 {
1367 	struct bch_fs *c = trans->c;
1368 	struct bch_dev *ca = bch_dev_bkey_exists(c, iter->pos.inode);
1369 	struct bucket old_gc, gc, *b;
1370 	struct bkey_i_alloc_v4 *a;
1371 	struct bch_alloc_v4 old_convert, new;
1372 	const struct bch_alloc_v4 *old;
1373 	int ret;
1374 
1375 	old = bch2_alloc_to_v4(k, &old_convert);
1376 	new = *old;
1377 
1378 	percpu_down_read(&c->mark_lock);
1379 	b = gc_bucket(ca, iter->pos.offset);
1380 	old_gc = *b;
1381 
1382 	if ((old->data_type == BCH_DATA_sb ||
1383 	     old->data_type == BCH_DATA_journal) &&
1384 	    !bch2_dev_is_online(ca)) {
1385 		b->data_type = old->data_type;
1386 		b->dirty_sectors = old->dirty_sectors;
1387 	}
1388 
1389 	/*
1390 	 * b->data_type doesn't yet include need_discard & need_gc_gen states -
1391 	 * fix that here:
1392 	 */
1393 	b->data_type = __alloc_data_type(b->dirty_sectors,
1394 					 b->cached_sectors,
1395 					 b->stripe,
1396 					 *old,
1397 					 b->data_type);
1398 	gc = *b;
1399 
1400 	if (gc.data_type != old_gc.data_type ||
1401 	    gc.dirty_sectors != old_gc.dirty_sectors)
1402 		bch2_dev_usage_update_m(c, ca, &old_gc, &gc);
1403 	percpu_up_read(&c->mark_lock);
1404 
1405 	if (metadata_only &&
1406 	    gc.data_type != BCH_DATA_sb &&
1407 	    gc.data_type != BCH_DATA_journal &&
1408 	    gc.data_type != BCH_DATA_btree)
1409 		return 0;
1410 
1411 	if (gen_after(old->gen, gc.gen))
1412 		return 0;
1413 
1414 	if (fsck_err_on(new.data_type != gc.data_type, c,
1415 			alloc_key_data_type_wrong,
1416 			"bucket %llu:%llu gen %u has wrong data_type"
1417 			": got %s, should be %s",
1418 			iter->pos.inode, iter->pos.offset,
1419 			gc.gen,
1420 			bch2_data_type_str(new.data_type),
1421 			bch2_data_type_str(gc.data_type)))
1422 		new.data_type = gc.data_type;
1423 
1424 #define copy_bucket_field(_errtype, _f)					\
1425 	if (fsck_err_on(new._f != gc._f, c, _errtype,			\
1426 			"bucket %llu:%llu gen %u data type %s has wrong " #_f	\
1427 			": got %u, should be %u",			\
1428 			iter->pos.inode, iter->pos.offset,		\
1429 			gc.gen,						\
1430 			bch2_data_type_str(gc.data_type),		\
1431 			new._f, gc._f))					\
1432 		new._f = gc._f;						\
1433 
1434 	copy_bucket_field(alloc_key_gen_wrong,
1435 			  gen);
1436 	copy_bucket_field(alloc_key_dirty_sectors_wrong,
1437 			  dirty_sectors);
1438 	copy_bucket_field(alloc_key_cached_sectors_wrong,
1439 			  cached_sectors);
1440 	copy_bucket_field(alloc_key_stripe_wrong,
1441 			  stripe);
1442 	copy_bucket_field(alloc_key_stripe_redundancy_wrong,
1443 			  stripe_redundancy);
1444 #undef copy_bucket_field
1445 
1446 	if (!bch2_alloc_v4_cmp(*old, new))
1447 		return 0;
1448 
1449 	a = bch2_alloc_to_v4_mut(trans, k);
1450 	ret = PTR_ERR_OR_ZERO(a);
1451 	if (ret)
1452 		return ret;
1453 
1454 	a->v = new;
1455 
1456 	/*
1457 	 * The trigger normally makes sure this is set, but we're not running
1458 	 * triggers:
1459 	 */
1460 	if (a->v.data_type == BCH_DATA_cached && !a->v.io_time[READ])
1461 		a->v.io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
1462 
1463 	ret = bch2_trans_update(trans, iter, &a->k_i, BTREE_TRIGGER_NORUN);
1464 fsck_err:
1465 	return ret;
1466 }
1467 
1468 static int bch2_gc_alloc_done(struct bch_fs *c, bool metadata_only)
1469 {
1470 	int ret = 0;
1471 
1472 	for_each_member_device(c, ca) {
1473 		ret = bch2_trans_run(c,
1474 			for_each_btree_key_upto_commit(trans, iter, BTREE_ID_alloc,
1475 					POS(ca->dev_idx, ca->mi.first_bucket),
1476 					POS(ca->dev_idx, ca->mi.nbuckets - 1),
1477 					BTREE_ITER_SLOTS|BTREE_ITER_PREFETCH, k,
1478 					NULL, NULL, BCH_TRANS_COMMIT_lazy_rw,
1479 				bch2_alloc_write_key(trans, &iter, k, metadata_only)));
1480 		if (ret) {
1481 			percpu_ref_put(&ca->ref);
1482 			break;
1483 		}
1484 	}
1485 
1486 	bch_err_fn(c, ret);
1487 	return ret;
1488 }
1489 
1490 static int bch2_gc_alloc_start(struct bch_fs *c, bool metadata_only)
1491 {
1492 	for_each_member_device(c, ca) {
1493 		struct bucket_array *buckets = kvmalloc(sizeof(struct bucket_array) +
1494 				ca->mi.nbuckets * sizeof(struct bucket),
1495 				GFP_KERNEL|__GFP_ZERO);
1496 		if (!buckets) {
1497 			percpu_ref_put(&ca->ref);
1498 			bch_err(c, "error allocating ca->buckets[gc]");
1499 			return -BCH_ERR_ENOMEM_gc_alloc_start;
1500 		}
1501 
1502 		buckets->first_bucket	= ca->mi.first_bucket;
1503 		buckets->nbuckets	= ca->mi.nbuckets;
1504 		rcu_assign_pointer(ca->buckets_gc, buckets);
1505 	}
1506 
1507 	int ret = bch2_trans_run(c,
1508 		for_each_btree_key(trans, iter, BTREE_ID_alloc, POS_MIN,
1509 					 BTREE_ITER_PREFETCH, k, ({
1510 			struct bch_dev *ca = bch_dev_bkey_exists(c, k.k->p.inode);
1511 			struct bucket *g = gc_bucket(ca, k.k->p.offset);
1512 
1513 			struct bch_alloc_v4 a_convert;
1514 			const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
1515 
1516 			g->gen_valid	= 1;
1517 			g->gen		= a->gen;
1518 
1519 			if (metadata_only &&
1520 			    (a->data_type == BCH_DATA_user ||
1521 			     a->data_type == BCH_DATA_cached ||
1522 			     a->data_type == BCH_DATA_parity)) {
1523 				g->data_type		= a->data_type;
1524 				g->dirty_sectors	= a->dirty_sectors;
1525 				g->cached_sectors	= a->cached_sectors;
1526 				g->stripe		= a->stripe;
1527 				g->stripe_redundancy	= a->stripe_redundancy;
1528 			}
1529 
1530 			0;
1531 		})));
1532 	bch_err_fn(c, ret);
1533 	return ret;
1534 }
1535 
1536 static void bch2_gc_alloc_reset(struct bch_fs *c, bool metadata_only)
1537 {
1538 	for_each_member_device(c, ca) {
1539 		struct bucket_array *buckets = gc_bucket_array(ca);
1540 		struct bucket *g;
1541 
1542 		for_each_bucket(g, buckets) {
1543 			if (metadata_only &&
1544 			    (g->data_type == BCH_DATA_user ||
1545 			     g->data_type == BCH_DATA_cached ||
1546 			     g->data_type == BCH_DATA_parity))
1547 				continue;
1548 			g->data_type = 0;
1549 			g->dirty_sectors = 0;
1550 			g->cached_sectors = 0;
1551 		}
1552 	}
1553 }
1554 
1555 static int bch2_gc_write_reflink_key(struct btree_trans *trans,
1556 				     struct btree_iter *iter,
1557 				     struct bkey_s_c k,
1558 				     size_t *idx)
1559 {
1560 	struct bch_fs *c = trans->c;
1561 	const __le64 *refcount = bkey_refcount_c(k);
1562 	struct printbuf buf = PRINTBUF;
1563 	struct reflink_gc *r;
1564 	int ret = 0;
1565 
1566 	if (!refcount)
1567 		return 0;
1568 
1569 	while ((r = genradix_ptr(&c->reflink_gc_table, *idx)) &&
1570 	       r->offset < k.k->p.offset)
1571 		++*idx;
1572 
1573 	if (!r ||
1574 	    r->offset != k.k->p.offset ||
1575 	    r->size != k.k->size) {
1576 		bch_err(c, "unexpected inconsistency walking reflink table at gc finish");
1577 		return -EINVAL;
1578 	}
1579 
1580 	if (fsck_err_on(r->refcount != le64_to_cpu(*refcount), c,
1581 			reflink_v_refcount_wrong,
1582 			"reflink key has wrong refcount:\n"
1583 			"  %s\n"
1584 			"  should be %u",
1585 			(bch2_bkey_val_to_text(&buf, c, k), buf.buf),
1586 			r->refcount)) {
1587 		struct bkey_i *new = bch2_bkey_make_mut_noupdate(trans, k);
1588 		ret = PTR_ERR_OR_ZERO(new);
1589 		if (ret)
1590 			return ret;
1591 
1592 		if (!r->refcount)
1593 			new->k.type = KEY_TYPE_deleted;
1594 		else
1595 			*bkey_refcount(bkey_i_to_s(new)) = cpu_to_le64(r->refcount);
1596 		ret = bch2_trans_update(trans, iter, new, 0);
1597 	}
1598 fsck_err:
1599 	printbuf_exit(&buf);
1600 	return ret;
1601 }
1602 
1603 static int bch2_gc_reflink_done(struct bch_fs *c, bool metadata_only)
1604 {
1605 	size_t idx = 0;
1606 
1607 	if (metadata_only)
1608 		return 0;
1609 
1610 	int ret = bch2_trans_run(c,
1611 		for_each_btree_key_commit(trans, iter,
1612 				BTREE_ID_reflink, POS_MIN,
1613 				BTREE_ITER_PREFETCH, k,
1614 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1615 			bch2_gc_write_reflink_key(trans, &iter, k, &idx)));
1616 	c->reflink_gc_nr = 0;
1617 	return ret;
1618 }
1619 
1620 static int bch2_gc_reflink_start(struct bch_fs *c,
1621 				 bool metadata_only)
1622 {
1623 
1624 	if (metadata_only)
1625 		return 0;
1626 
1627 	c->reflink_gc_nr = 0;
1628 
1629 	int ret = bch2_trans_run(c,
1630 		for_each_btree_key(trans, iter, BTREE_ID_reflink, POS_MIN,
1631 				   BTREE_ITER_PREFETCH, k, ({
1632 			const __le64 *refcount = bkey_refcount_c(k);
1633 
1634 			if (!refcount)
1635 				continue;
1636 
1637 			struct reflink_gc *r = genradix_ptr_alloc(&c->reflink_gc_table,
1638 							c->reflink_gc_nr++, GFP_KERNEL);
1639 			if (!r) {
1640 				ret = -BCH_ERR_ENOMEM_gc_reflink_start;
1641 				break;
1642 			}
1643 
1644 			r->offset	= k.k->p.offset;
1645 			r->size		= k.k->size;
1646 			r->refcount	= 0;
1647 			0;
1648 		})));
1649 
1650 	bch_err_fn(c, ret);
1651 	return ret;
1652 }
1653 
1654 static void bch2_gc_reflink_reset(struct bch_fs *c, bool metadata_only)
1655 {
1656 	struct genradix_iter iter;
1657 	struct reflink_gc *r;
1658 
1659 	genradix_for_each(&c->reflink_gc_table, iter, r)
1660 		r->refcount = 0;
1661 }
1662 
1663 static int bch2_gc_write_stripes_key(struct btree_trans *trans,
1664 				     struct btree_iter *iter,
1665 				     struct bkey_s_c k)
1666 {
1667 	struct bch_fs *c = trans->c;
1668 	struct printbuf buf = PRINTBUF;
1669 	const struct bch_stripe *s;
1670 	struct gc_stripe *m;
1671 	bool bad = false;
1672 	unsigned i;
1673 	int ret = 0;
1674 
1675 	if (k.k->type != KEY_TYPE_stripe)
1676 		return 0;
1677 
1678 	s = bkey_s_c_to_stripe(k).v;
1679 	m = genradix_ptr(&c->gc_stripes, k.k->p.offset);
1680 
1681 	for (i = 0; i < s->nr_blocks; i++) {
1682 		u32 old = stripe_blockcount_get(s, i);
1683 		u32 new = (m ? m->block_sectors[i] : 0);
1684 
1685 		if (old != new) {
1686 			prt_printf(&buf, "stripe block %u has wrong sector count: got %u, should be %u\n",
1687 				   i, old, new);
1688 			bad = true;
1689 		}
1690 	}
1691 
1692 	if (bad)
1693 		bch2_bkey_val_to_text(&buf, c, k);
1694 
1695 	if (fsck_err_on(bad, c, stripe_sector_count_wrong,
1696 			"%s", buf.buf)) {
1697 		struct bkey_i_stripe *new;
1698 
1699 		new = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1700 		ret = PTR_ERR_OR_ZERO(new);
1701 		if (ret)
1702 			return ret;
1703 
1704 		bkey_reassemble(&new->k_i, k);
1705 
1706 		for (i = 0; i < new->v.nr_blocks; i++)
1707 			stripe_blockcount_set(&new->v, i, m ? m->block_sectors[i] : 0);
1708 
1709 		ret = bch2_trans_update(trans, iter, &new->k_i, 0);
1710 	}
1711 fsck_err:
1712 	printbuf_exit(&buf);
1713 	return ret;
1714 }
1715 
1716 static int bch2_gc_stripes_done(struct bch_fs *c, bool metadata_only)
1717 {
1718 	if (metadata_only)
1719 		return 0;
1720 
1721 	return bch2_trans_run(c,
1722 		for_each_btree_key_commit(trans, iter,
1723 				BTREE_ID_stripes, POS_MIN,
1724 				BTREE_ITER_PREFETCH, k,
1725 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1726 			bch2_gc_write_stripes_key(trans, &iter, k)));
1727 }
1728 
1729 static void bch2_gc_stripes_reset(struct bch_fs *c, bool metadata_only)
1730 {
1731 	genradix_free(&c->gc_stripes);
1732 }
1733 
1734 /**
1735  * bch2_gc - walk _all_ references to buckets, and recompute them:
1736  *
1737  * @c:			filesystem object
1738  * @initial:		are we in recovery?
1739  * @metadata_only:	are we just checking metadata references, or everything?
1740  *
1741  * Returns: 0 on success, or standard errcode on failure
1742  *
1743  * Order matters here:
1744  *  - Concurrent GC relies on the fact that we have a total ordering for
1745  *    everything that GC walks - see  gc_will_visit_node(),
1746  *    gc_will_visit_root()
1747  *
1748  *  - also, references move around in the course of index updates and
1749  *    various other crap: everything needs to agree on the ordering
1750  *    references are allowed to move around in - e.g., we're allowed to
1751  *    start with a reference owned by an open_bucket (the allocator) and
1752  *    move it to the btree, but not the reverse.
1753  *
1754  *    This is necessary to ensure that gc doesn't miss references that
1755  *    move around - if references move backwards in the ordering GC
1756  *    uses, GC could skip past them
1757  */
1758 int bch2_gc(struct bch_fs *c, bool initial, bool metadata_only)
1759 {
1760 	unsigned iter = 0;
1761 	int ret;
1762 
1763 	lockdep_assert_held(&c->state_lock);
1764 
1765 	down_write(&c->gc_lock);
1766 
1767 	bch2_btree_interior_updates_flush(c);
1768 
1769 	ret   = bch2_gc_start(c) ?:
1770 		bch2_gc_alloc_start(c, metadata_only) ?:
1771 		bch2_gc_reflink_start(c, metadata_only);
1772 	if (ret)
1773 		goto out;
1774 again:
1775 	gc_pos_set(c, gc_phase(GC_PHASE_START));
1776 
1777 	bch2_mark_superblocks(c);
1778 
1779 	ret = bch2_gc_btrees(c, initial, metadata_only);
1780 
1781 	if (ret)
1782 		goto out;
1783 
1784 #if 0
1785 	bch2_mark_pending_btree_node_frees(c);
1786 #endif
1787 	c->gc_count++;
1788 
1789 	if (test_bit(BCH_FS_need_another_gc, &c->flags) ||
1790 	    (!iter && bch2_test_restart_gc)) {
1791 		if (iter++ > 2) {
1792 			bch_info(c, "Unable to fix bucket gens, looping");
1793 			ret = -EINVAL;
1794 			goto out;
1795 		}
1796 
1797 		/*
1798 		 * XXX: make sure gens we fixed got saved
1799 		 */
1800 		bch_info(c, "Second GC pass needed, restarting:");
1801 		clear_bit(BCH_FS_need_another_gc, &c->flags);
1802 		__gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
1803 
1804 		bch2_gc_stripes_reset(c, metadata_only);
1805 		bch2_gc_alloc_reset(c, metadata_only);
1806 		bch2_gc_reflink_reset(c, metadata_only);
1807 		ret = bch2_gc_reset(c);
1808 		if (ret)
1809 			goto out;
1810 
1811 		/* flush fsck errors, reset counters */
1812 		bch2_flush_fsck_errs(c);
1813 		goto again;
1814 	}
1815 out:
1816 	if (!ret) {
1817 		bch2_journal_block(&c->journal);
1818 
1819 		ret   = bch2_gc_alloc_done(c, metadata_only) ?:
1820 			bch2_gc_done(c, initial, metadata_only) ?:
1821 			bch2_gc_stripes_done(c, metadata_only) ?:
1822 			bch2_gc_reflink_done(c, metadata_only);
1823 
1824 		bch2_journal_unblock(&c->journal);
1825 	}
1826 
1827 	percpu_down_write(&c->mark_lock);
1828 	/* Indicates that gc is no longer in progress: */
1829 	__gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
1830 
1831 	bch2_gc_free(c);
1832 	percpu_up_write(&c->mark_lock);
1833 
1834 	up_write(&c->gc_lock);
1835 
1836 	/*
1837 	 * At startup, allocations can happen directly instead of via the
1838 	 * allocator thread - issue wakeup in case they blocked on gc_lock:
1839 	 */
1840 	closure_wake_up(&c->freelist_wait);
1841 	bch_err_fn(c, ret);
1842 	return ret;
1843 }
1844 
1845 static int gc_btree_gens_key(struct btree_trans *trans,
1846 			     struct btree_iter *iter,
1847 			     struct bkey_s_c k)
1848 {
1849 	struct bch_fs *c = trans->c;
1850 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1851 	struct bkey_i *u;
1852 	int ret;
1853 
1854 	percpu_down_read(&c->mark_lock);
1855 	bkey_for_each_ptr(ptrs, ptr) {
1856 		struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
1857 
1858 		if (ptr_stale(ca, ptr) > 16) {
1859 			percpu_up_read(&c->mark_lock);
1860 			goto update;
1861 		}
1862 	}
1863 
1864 	bkey_for_each_ptr(ptrs, ptr) {
1865 		struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
1866 		u8 *gen = &ca->oldest_gen[PTR_BUCKET_NR(ca, ptr)];
1867 
1868 		if (gen_after(*gen, ptr->gen))
1869 			*gen = ptr->gen;
1870 	}
1871 	percpu_up_read(&c->mark_lock);
1872 	return 0;
1873 update:
1874 	u = bch2_bkey_make_mut(trans, iter, &k, 0);
1875 	ret = PTR_ERR_OR_ZERO(u);
1876 	if (ret)
1877 		return ret;
1878 
1879 	bch2_extent_normalize(c, bkey_i_to_s(u));
1880 	return 0;
1881 }
1882 
1883 static int bch2_alloc_write_oldest_gen(struct btree_trans *trans, struct btree_iter *iter,
1884 				       struct bkey_s_c k)
1885 {
1886 	struct bch_dev *ca = bch_dev_bkey_exists(trans->c, iter->pos.inode);
1887 	struct bch_alloc_v4 a_convert;
1888 	const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
1889 	struct bkey_i_alloc_v4 *a_mut;
1890 	int ret;
1891 
1892 	if (a->oldest_gen == ca->oldest_gen[iter->pos.offset])
1893 		return 0;
1894 
1895 	a_mut = bch2_alloc_to_v4_mut(trans, k);
1896 	ret = PTR_ERR_OR_ZERO(a_mut);
1897 	if (ret)
1898 		return ret;
1899 
1900 	a_mut->v.oldest_gen = ca->oldest_gen[iter->pos.offset];
1901 	a_mut->v.data_type = alloc_data_type(a_mut->v, a_mut->v.data_type);
1902 
1903 	return bch2_trans_update(trans, iter, &a_mut->k_i, 0);
1904 }
1905 
1906 int bch2_gc_gens(struct bch_fs *c)
1907 {
1908 	u64 b, start_time = local_clock();
1909 	int ret;
1910 
1911 	/*
1912 	 * Ideally we would be using state_lock and not gc_lock here, but that
1913 	 * introduces a deadlock in the RO path - we currently take the state
1914 	 * lock at the start of going RO, thus the gc thread may get stuck:
1915 	 */
1916 	if (!mutex_trylock(&c->gc_gens_lock))
1917 		return 0;
1918 
1919 	trace_and_count(c, gc_gens_start, c);
1920 	down_read(&c->gc_lock);
1921 
1922 	for_each_member_device(c, ca) {
1923 		struct bucket_gens *gens = bucket_gens(ca);
1924 
1925 		BUG_ON(ca->oldest_gen);
1926 
1927 		ca->oldest_gen = kvmalloc(gens->nbuckets, GFP_KERNEL);
1928 		if (!ca->oldest_gen) {
1929 			percpu_ref_put(&ca->ref);
1930 			ret = -BCH_ERR_ENOMEM_gc_gens;
1931 			goto err;
1932 		}
1933 
1934 		for (b = gens->first_bucket;
1935 		     b < gens->nbuckets; b++)
1936 			ca->oldest_gen[b] = gens->b[b];
1937 	}
1938 
1939 	for (unsigned i = 0; i < BTREE_ID_NR; i++)
1940 		if (btree_type_has_ptrs(i)) {
1941 			c->gc_gens_btree = i;
1942 			c->gc_gens_pos = POS_MIN;
1943 
1944 			ret = bch2_trans_run(c,
1945 				for_each_btree_key_commit(trans, iter, i,
1946 						POS_MIN,
1947 						BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1948 						k,
1949 						NULL, NULL,
1950 						BCH_TRANS_COMMIT_no_enospc,
1951 					gc_btree_gens_key(trans, &iter, k)));
1952 			if (ret)
1953 				goto err;
1954 		}
1955 
1956 	ret = bch2_trans_run(c,
1957 		for_each_btree_key_commit(trans, iter, BTREE_ID_alloc,
1958 				POS_MIN,
1959 				BTREE_ITER_PREFETCH,
1960 				k,
1961 				NULL, NULL,
1962 				BCH_TRANS_COMMIT_no_enospc,
1963 			bch2_alloc_write_oldest_gen(trans, &iter, k)));
1964 	if (ret)
1965 		goto err;
1966 
1967 	c->gc_gens_btree	= 0;
1968 	c->gc_gens_pos		= POS_MIN;
1969 
1970 	c->gc_count++;
1971 
1972 	bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
1973 	trace_and_count(c, gc_gens_end, c);
1974 err:
1975 	for_each_member_device(c, ca) {
1976 		kvfree(ca->oldest_gen);
1977 		ca->oldest_gen = NULL;
1978 	}
1979 
1980 	up_read(&c->gc_lock);
1981 	mutex_unlock(&c->gc_gens_lock);
1982 	if (!bch2_err_matches(ret, EROFS))
1983 		bch_err_fn(c, ret);
1984 	return ret;
1985 }
1986 
1987 static int bch2_gc_thread(void *arg)
1988 {
1989 	struct bch_fs *c = arg;
1990 	struct io_clock *clock = &c->io_clock[WRITE];
1991 	unsigned long last = atomic64_read(&clock->now);
1992 	unsigned last_kick = atomic_read(&c->kick_gc);
1993 
1994 	set_freezable();
1995 
1996 	while (1) {
1997 		while (1) {
1998 			set_current_state(TASK_INTERRUPTIBLE);
1999 
2000 			if (kthread_should_stop()) {
2001 				__set_current_state(TASK_RUNNING);
2002 				return 0;
2003 			}
2004 
2005 			if (atomic_read(&c->kick_gc) != last_kick)
2006 				break;
2007 
2008 			if (c->btree_gc_periodic) {
2009 				unsigned long next = last + c->capacity / 16;
2010 
2011 				if (atomic64_read(&clock->now) >= next)
2012 					break;
2013 
2014 				bch2_io_clock_schedule_timeout(clock, next);
2015 			} else {
2016 				schedule();
2017 			}
2018 
2019 			try_to_freeze();
2020 		}
2021 		__set_current_state(TASK_RUNNING);
2022 
2023 		last = atomic64_read(&clock->now);
2024 		last_kick = atomic_read(&c->kick_gc);
2025 
2026 		/*
2027 		 * Full gc is currently incompatible with btree key cache:
2028 		 */
2029 #if 0
2030 		ret = bch2_gc(c, false, false);
2031 #else
2032 		bch2_gc_gens(c);
2033 #endif
2034 		debug_check_no_locks_held();
2035 	}
2036 
2037 	return 0;
2038 }
2039 
2040 void bch2_gc_thread_stop(struct bch_fs *c)
2041 {
2042 	struct task_struct *p;
2043 
2044 	p = c->gc_thread;
2045 	c->gc_thread = NULL;
2046 
2047 	if (p) {
2048 		kthread_stop(p);
2049 		put_task_struct(p);
2050 	}
2051 }
2052 
2053 int bch2_gc_thread_start(struct bch_fs *c)
2054 {
2055 	struct task_struct *p;
2056 
2057 	if (c->gc_thread)
2058 		return 0;
2059 
2060 	p = kthread_create(bch2_gc_thread, c, "bch-gc/%s", c->name);
2061 	if (IS_ERR(p)) {
2062 		bch_err_fn(c, PTR_ERR(p));
2063 		return PTR_ERR(p);
2064 	}
2065 
2066 	get_task_struct(p);
2067 	c->gc_thread = p;
2068 	wake_up_process(p);
2069 	return 0;
2070 }
2071