xref: /linux/fs/bcachefs/btree_gc.c (revision 53ed0af4964229595b60594b35334d006d411ef0)
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 	int ret = 0;
832 
833 	deleted.p = k->k->p;
834 
835 	if (initial) {
836 		BUG_ON(bch2_journal_seq_verify &&
837 		       k->k->version.lo > atomic64_read(&c->journal.seq));
838 
839 		if (fsck_err_on(k->k->version.lo > atomic64_read(&c->key_version), c,
840 				bkey_version_in_future,
841 				"key version number higher than recorded: %llu > %llu",
842 				k->k->version.lo,
843 				atomic64_read(&c->key_version)))
844 			atomic64_set(&c->key_version, k->k->version.lo);
845 	}
846 
847 	ret = bch2_check_fix_ptrs(trans, btree_id, level, is_root, k);
848 	if (ret)
849 		goto err;
850 
851 	ret = commit_do(trans, NULL, NULL, 0,
852 			bch2_key_trigger(trans, btree_id, level, old,
853 					 unsafe_bkey_s_c_to_s(*k), BTREE_TRIGGER_GC));
854 fsck_err:
855 err:
856 	bch_err_fn(c, ret);
857 	return ret;
858 }
859 
860 static int btree_gc_mark_node(struct btree_trans *trans, struct btree *b, bool initial)
861 {
862 	struct btree_node_iter iter;
863 	struct bkey unpacked;
864 	struct bkey_s_c k;
865 	int ret = 0;
866 
867 	ret = bch2_btree_node_check_topology(trans, b);
868 	if (ret)
869 		return ret;
870 
871 	if (!btree_node_type_needs_gc(btree_node_type(b)))
872 		return 0;
873 
874 	bch2_btree_node_iter_init_from_start(&iter, b);
875 
876 	while ((k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked)).k) {
877 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level, false,
878 				       &k, initial);
879 		if (ret)
880 			return ret;
881 
882 		bch2_btree_node_iter_advance(&iter, b);
883 	}
884 
885 	return 0;
886 }
887 
888 static int bch2_gc_btree(struct btree_trans *trans, enum btree_id btree_id,
889 			 bool initial, bool metadata_only)
890 {
891 	struct bch_fs *c = trans->c;
892 	struct btree_iter iter;
893 	struct btree *b;
894 	unsigned depth = metadata_only ? 1 : 0;
895 	int ret = 0;
896 
897 	gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
898 
899 	__for_each_btree_node(trans, iter, btree_id, POS_MIN,
900 			      0, depth, BTREE_ITER_PREFETCH, b, ret) {
901 		bch2_verify_btree_nr_keys(b);
902 
903 		gc_pos_set(c, gc_pos_btree_node(b));
904 
905 		ret = btree_gc_mark_node(trans, b, initial);
906 		if (ret)
907 			break;
908 	}
909 	bch2_trans_iter_exit(trans, &iter);
910 
911 	if (ret)
912 		return ret;
913 
914 	mutex_lock(&c->btree_root_lock);
915 	b = bch2_btree_id_root(c, btree_id)->b;
916 	if (!btree_node_fake(b)) {
917 		struct bkey_s_c k = bkey_i_to_s_c(&b->key);
918 
919 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level + 1,
920 				       true, &k, initial);
921 	}
922 	gc_pos_set(c, gc_pos_btree_root(b->c.btree_id));
923 	mutex_unlock(&c->btree_root_lock);
924 
925 	return ret;
926 }
927 
928 static int bch2_gc_btree_init_recurse(struct btree_trans *trans, struct btree *b,
929 				      unsigned target_depth)
930 {
931 	struct bch_fs *c = trans->c;
932 	struct btree_and_journal_iter iter;
933 	struct bkey_s_c k;
934 	struct bkey_buf cur;
935 	struct printbuf buf = PRINTBUF;
936 	int ret = 0;
937 
938 	ret = bch2_btree_node_check_topology(trans, b);
939 	if (ret)
940 		return ret;
941 
942 	bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
943 	bch2_bkey_buf_init(&cur);
944 
945 	while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
946 		BUG_ON(bpos_lt(k.k->p, b->data->min_key));
947 		BUG_ON(bpos_gt(k.k->p, b->data->max_key));
948 
949 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level,
950 				       false, &k, true);
951 		if (ret)
952 			goto fsck_err;
953 
954 		bch2_btree_and_journal_iter_advance(&iter);
955 	}
956 
957 	if (b->c.level > target_depth) {
958 		bch2_btree_and_journal_iter_exit(&iter);
959 		bch2_btree_and_journal_iter_init_node_iter(trans, &iter, b);
960 		iter.prefetch = true;
961 
962 		while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
963 			struct btree *child;
964 
965 			bch2_bkey_buf_reassemble(&cur, c, k);
966 			bch2_btree_and_journal_iter_advance(&iter);
967 
968 			child = bch2_btree_node_get_noiter(trans, cur.k,
969 						b->c.btree_id, b->c.level - 1,
970 						false);
971 			ret = PTR_ERR_OR_ZERO(child);
972 
973 			if (bch2_err_matches(ret, EIO)) {
974 				bch2_topology_error(c);
975 
976 				if (__fsck_err(c,
977 					  FSCK_CAN_FIX|
978 					  FSCK_CAN_IGNORE|
979 					  FSCK_NO_RATELIMIT,
980 					  btree_node_read_error,
981 					  "Unreadable btree node at btree %s level %u:\n"
982 					  "  %s",
983 					  bch2_btree_id_str(b->c.btree_id),
984 					  b->c.level - 1,
985 					  (printbuf_reset(&buf),
986 					   bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(cur.k)), buf.buf)) &&
987 				    should_restart_for_topology_repair(c)) {
988 					bch_info(c, "Halting mark and sweep to start topology repair pass");
989 					ret = bch2_run_explicit_recovery_pass(c, BCH_RECOVERY_PASS_check_topology);
990 					goto fsck_err;
991 				} else {
992 					/* Continue marking when opted to not
993 					 * fix the error: */
994 					ret = 0;
995 					set_bit(BCH_FS_initial_gc_unfixed, &c->flags);
996 					continue;
997 				}
998 			} else if (ret) {
999 				bch_err_msg(c, ret, "getting btree node");
1000 				break;
1001 			}
1002 
1003 			ret = bch2_gc_btree_init_recurse(trans, child,
1004 							 target_depth);
1005 			six_unlock_read(&child->c.lock);
1006 
1007 			if (ret)
1008 				break;
1009 		}
1010 	}
1011 fsck_err:
1012 	bch2_bkey_buf_exit(&cur, c);
1013 	bch2_btree_and_journal_iter_exit(&iter);
1014 	printbuf_exit(&buf);
1015 	return ret;
1016 }
1017 
1018 static int bch2_gc_btree_init(struct btree_trans *trans,
1019 			      enum btree_id btree_id,
1020 			      bool metadata_only)
1021 {
1022 	struct bch_fs *c = trans->c;
1023 	struct btree *b;
1024 	unsigned target_depth = metadata_only ? 1 : 0;
1025 	struct printbuf buf = PRINTBUF;
1026 	int ret = 0;
1027 
1028 	b = bch2_btree_id_root(c, btree_id)->b;
1029 
1030 	six_lock_read(&b->c.lock, NULL, NULL);
1031 	printbuf_reset(&buf);
1032 	bch2_bpos_to_text(&buf, b->data->min_key);
1033 	if (mustfix_fsck_err_on(!bpos_eq(b->data->min_key, POS_MIN), c,
1034 				btree_root_bad_min_key,
1035 			"btree root with incorrect min_key: %s", buf.buf)) {
1036 		bch_err(c, "repair unimplemented");
1037 		ret = -BCH_ERR_fsck_repair_unimplemented;
1038 		goto fsck_err;
1039 	}
1040 
1041 	printbuf_reset(&buf);
1042 	bch2_bpos_to_text(&buf, b->data->max_key);
1043 	if (mustfix_fsck_err_on(!bpos_eq(b->data->max_key, SPOS_MAX), c,
1044 				btree_root_bad_max_key,
1045 			"btree root with incorrect max_key: %s", buf.buf)) {
1046 		bch_err(c, "repair unimplemented");
1047 		ret = -BCH_ERR_fsck_repair_unimplemented;
1048 		goto fsck_err;
1049 	}
1050 
1051 	if (b->c.level >= target_depth)
1052 		ret = bch2_gc_btree_init_recurse(trans, b, target_depth);
1053 
1054 	if (!ret) {
1055 		struct bkey_s_c k = bkey_i_to_s_c(&b->key);
1056 
1057 		ret = bch2_gc_mark_key(trans, b->c.btree_id, b->c.level + 1, true,
1058 				       &k, true);
1059 	}
1060 fsck_err:
1061 	six_unlock_read(&b->c.lock);
1062 
1063 	bch_err_fn(c, ret);
1064 	printbuf_exit(&buf);
1065 	return ret;
1066 }
1067 
1068 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
1069 {
1070 	return  (int) btree_id_to_gc_phase(l) -
1071 		(int) btree_id_to_gc_phase(r);
1072 }
1073 
1074 static int bch2_gc_btrees(struct bch_fs *c, bool initial, bool metadata_only)
1075 {
1076 	struct btree_trans *trans = bch2_trans_get(c);
1077 	enum btree_id ids[BTREE_ID_NR];
1078 	unsigned i;
1079 	int ret = 0;
1080 
1081 	for (i = 0; i < BTREE_ID_NR; i++)
1082 		ids[i] = i;
1083 	bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
1084 
1085 	for (i = 0; i < BTREE_ID_NR && !ret; i++)
1086 		ret = initial
1087 			? bch2_gc_btree_init(trans, ids[i], metadata_only)
1088 			: bch2_gc_btree(trans, ids[i], initial, metadata_only);
1089 
1090 	for (i = BTREE_ID_NR; i < btree_id_nr_alive(c) && !ret; i++) {
1091 		if (!bch2_btree_id_root(c, i)->alive)
1092 			continue;
1093 
1094 		ret = initial
1095 			? bch2_gc_btree_init(trans, i, metadata_only)
1096 			: bch2_gc_btree(trans, i, initial, metadata_only);
1097 	}
1098 
1099 	bch2_trans_put(trans);
1100 	bch_err_fn(c, ret);
1101 	return ret;
1102 }
1103 
1104 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
1105 				  u64 start, u64 end,
1106 				  enum bch_data_type type,
1107 				  unsigned flags)
1108 {
1109 	u64 b = sector_to_bucket(ca, start);
1110 
1111 	do {
1112 		unsigned sectors =
1113 			min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
1114 
1115 		bch2_mark_metadata_bucket(c, ca, b, type, sectors,
1116 					  gc_phase(GC_PHASE_SB), flags);
1117 		b++;
1118 		start += sectors;
1119 	} while (start < end);
1120 }
1121 
1122 static void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
1123 				     unsigned flags)
1124 {
1125 	struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
1126 	unsigned i;
1127 	u64 b;
1128 
1129 	for (i = 0; i < layout->nr_superblocks; i++) {
1130 		u64 offset = le64_to_cpu(layout->sb_offset[i]);
1131 
1132 		if (offset == BCH_SB_SECTOR)
1133 			mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
1134 					      BCH_DATA_sb, flags);
1135 
1136 		mark_metadata_sectors(c, ca, offset,
1137 				      offset + (1 << layout->sb_max_size_bits),
1138 				      BCH_DATA_sb, flags);
1139 	}
1140 
1141 	for (i = 0; i < ca->journal.nr; i++) {
1142 		b = ca->journal.buckets[i];
1143 		bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_journal,
1144 					  ca->mi.bucket_size,
1145 					  gc_phase(GC_PHASE_SB), flags);
1146 	}
1147 }
1148 
1149 static void bch2_mark_superblocks(struct bch_fs *c)
1150 {
1151 	mutex_lock(&c->sb_lock);
1152 	gc_pos_set(c, gc_phase(GC_PHASE_SB));
1153 
1154 	for_each_online_member(c, ca)
1155 		bch2_mark_dev_superblock(c, ca, BTREE_TRIGGER_GC);
1156 	mutex_unlock(&c->sb_lock);
1157 }
1158 
1159 #if 0
1160 /* Also see bch2_pending_btree_node_free_insert_done() */
1161 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
1162 {
1163 	struct btree_update *as;
1164 	struct pending_btree_node_free *d;
1165 
1166 	mutex_lock(&c->btree_interior_update_lock);
1167 	gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
1168 
1169 	for_each_pending_btree_node_free(c, as, d)
1170 		if (d->index_update_done)
1171 			bch2_mark_key(c, bkey_i_to_s_c(&d->key), BTREE_TRIGGER_GC);
1172 
1173 	mutex_unlock(&c->btree_interior_update_lock);
1174 }
1175 #endif
1176 
1177 static void bch2_gc_free(struct bch_fs *c)
1178 {
1179 	genradix_free(&c->reflink_gc_table);
1180 	genradix_free(&c->gc_stripes);
1181 
1182 	for_each_member_device(c, ca) {
1183 		kvfree(rcu_dereference_protected(ca->buckets_gc, 1));
1184 		ca->buckets_gc = NULL;
1185 
1186 		free_percpu(ca->usage_gc);
1187 		ca->usage_gc = NULL;
1188 	}
1189 
1190 	free_percpu(c->usage_gc);
1191 	c->usage_gc = NULL;
1192 }
1193 
1194 static int bch2_gc_done(struct bch_fs *c,
1195 			bool initial, bool metadata_only)
1196 {
1197 	struct bch_dev *ca = NULL;
1198 	struct printbuf buf = PRINTBUF;
1199 	bool verify = !metadata_only &&
1200 		!c->opts.reconstruct_alloc &&
1201 		(!initial || (c->sb.compat & (1ULL << BCH_COMPAT_alloc_info)));
1202 	unsigned i;
1203 	int ret = 0;
1204 
1205 	percpu_down_write(&c->mark_lock);
1206 
1207 #define copy_field(_err, _f, _msg, ...)					\
1208 	if (dst->_f != src->_f &&					\
1209 	    (!verify ||							\
1210 	     fsck_err(c, _err, _msg ": got %llu, should be %llu"	\
1211 		      , ##__VA_ARGS__, dst->_f, src->_f)))		\
1212 		dst->_f = src->_f
1213 #define copy_dev_field(_err, _f, _msg, ...)				\
1214 	copy_field(_err, _f, "dev %u has wrong " _msg, ca->dev_idx, ##__VA_ARGS__)
1215 #define copy_fs_field(_err, _f, _msg, ...)				\
1216 	copy_field(_err, _f, "fs has wrong " _msg, ##__VA_ARGS__)
1217 
1218 	for (i = 0; i < ARRAY_SIZE(c->usage); i++)
1219 		bch2_fs_usage_acc_to_base(c, i);
1220 
1221 	__for_each_member_device(c, ca) {
1222 		struct bch_dev_usage *dst = ca->usage_base;
1223 		struct bch_dev_usage *src = (void *)
1224 			bch2_acc_percpu_u64s((u64 __percpu *) ca->usage_gc,
1225 					     dev_usage_u64s());
1226 
1227 		for (i = 0; i < BCH_DATA_NR; i++) {
1228 			copy_dev_field(dev_usage_buckets_wrong,
1229 				       d[i].buckets,	"%s buckets", bch2_data_type_str(i));
1230 			copy_dev_field(dev_usage_sectors_wrong,
1231 				       d[i].sectors,	"%s sectors", bch2_data_type_str(i));
1232 			copy_dev_field(dev_usage_fragmented_wrong,
1233 				       d[i].fragmented,	"%s fragmented", bch2_data_type_str(i));
1234 		}
1235 	}
1236 
1237 	{
1238 		unsigned nr = fs_usage_u64s(c);
1239 		struct bch_fs_usage *dst = c->usage_base;
1240 		struct bch_fs_usage *src = (void *)
1241 			bch2_acc_percpu_u64s((u64 __percpu *) c->usage_gc, nr);
1242 
1243 		copy_fs_field(fs_usage_hidden_wrong,
1244 			      b.hidden,		"hidden");
1245 		copy_fs_field(fs_usage_btree_wrong,
1246 			      b.btree,		"btree");
1247 
1248 		if (!metadata_only) {
1249 			copy_fs_field(fs_usage_data_wrong,
1250 				      b.data,	"data");
1251 			copy_fs_field(fs_usage_cached_wrong,
1252 				      b.cached,	"cached");
1253 			copy_fs_field(fs_usage_reserved_wrong,
1254 				      b.reserved,	"reserved");
1255 			copy_fs_field(fs_usage_nr_inodes_wrong,
1256 				      b.nr_inodes,"nr_inodes");
1257 
1258 			for (i = 0; i < BCH_REPLICAS_MAX; i++)
1259 				copy_fs_field(fs_usage_persistent_reserved_wrong,
1260 					      persistent_reserved[i],
1261 					      "persistent_reserved[%i]", i);
1262 		}
1263 
1264 		for (i = 0; i < c->replicas.nr; i++) {
1265 			struct bch_replicas_entry_v1 *e =
1266 				cpu_replicas_entry(&c->replicas, i);
1267 
1268 			if (metadata_only &&
1269 			    (e->data_type == BCH_DATA_user ||
1270 			     e->data_type == BCH_DATA_cached))
1271 				continue;
1272 
1273 			printbuf_reset(&buf);
1274 			bch2_replicas_entry_to_text(&buf, e);
1275 
1276 			copy_fs_field(fs_usage_replicas_wrong,
1277 				      replicas[i], "%s", buf.buf);
1278 		}
1279 	}
1280 
1281 #undef copy_fs_field
1282 #undef copy_dev_field
1283 #undef copy_stripe_field
1284 #undef copy_field
1285 fsck_err:
1286 	if (ca)
1287 		percpu_ref_put(&ca->ref);
1288 	bch_err_fn(c, ret);
1289 
1290 	percpu_up_write(&c->mark_lock);
1291 	printbuf_exit(&buf);
1292 	return ret;
1293 }
1294 
1295 static int bch2_gc_start(struct bch_fs *c)
1296 {
1297 	BUG_ON(c->usage_gc);
1298 
1299 	c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
1300 					 sizeof(u64), GFP_KERNEL);
1301 	if (!c->usage_gc) {
1302 		bch_err(c, "error allocating c->usage_gc");
1303 		return -BCH_ERR_ENOMEM_gc_start;
1304 	}
1305 
1306 	for_each_member_device(c, ca) {
1307 		BUG_ON(ca->usage_gc);
1308 
1309 		ca->usage_gc = alloc_percpu(struct bch_dev_usage);
1310 		if (!ca->usage_gc) {
1311 			bch_err(c, "error allocating ca->usage_gc");
1312 			percpu_ref_put(&ca->ref);
1313 			return -BCH_ERR_ENOMEM_gc_start;
1314 		}
1315 
1316 		this_cpu_write(ca->usage_gc->d[BCH_DATA_free].buckets,
1317 			       ca->mi.nbuckets - ca->mi.first_bucket);
1318 	}
1319 
1320 	return 0;
1321 }
1322 
1323 static int bch2_gc_reset(struct bch_fs *c)
1324 {
1325 	for_each_member_device(c, ca) {
1326 		free_percpu(ca->usage_gc);
1327 		ca->usage_gc = NULL;
1328 	}
1329 
1330 	free_percpu(c->usage_gc);
1331 	c->usage_gc = NULL;
1332 
1333 	return bch2_gc_start(c);
1334 }
1335 
1336 /* returns true if not equal */
1337 static inline bool bch2_alloc_v4_cmp(struct bch_alloc_v4 l,
1338 				     struct bch_alloc_v4 r)
1339 {
1340 	return  l.gen != r.gen				||
1341 		l.oldest_gen != r.oldest_gen		||
1342 		l.data_type != r.data_type		||
1343 		l.dirty_sectors	!= r.dirty_sectors	||
1344 		l.cached_sectors != r.cached_sectors	 ||
1345 		l.stripe_redundancy != r.stripe_redundancy ||
1346 		l.stripe != r.stripe;
1347 }
1348 
1349 static int bch2_alloc_write_key(struct btree_trans *trans,
1350 				struct btree_iter *iter,
1351 				struct bkey_s_c k,
1352 				bool metadata_only)
1353 {
1354 	struct bch_fs *c = trans->c;
1355 	struct bch_dev *ca = bch_dev_bkey_exists(c, iter->pos.inode);
1356 	struct bucket old_gc, gc, *b;
1357 	struct bkey_i_alloc_v4 *a;
1358 	struct bch_alloc_v4 old_convert, new;
1359 	const struct bch_alloc_v4 *old;
1360 	int ret;
1361 
1362 	old = bch2_alloc_to_v4(k, &old_convert);
1363 	new = *old;
1364 
1365 	percpu_down_read(&c->mark_lock);
1366 	b = gc_bucket(ca, iter->pos.offset);
1367 	old_gc = *b;
1368 
1369 	if ((old->data_type == BCH_DATA_sb ||
1370 	     old->data_type == BCH_DATA_journal) &&
1371 	    !bch2_dev_is_online(ca)) {
1372 		b->data_type = old->data_type;
1373 		b->dirty_sectors = old->dirty_sectors;
1374 	}
1375 
1376 	/*
1377 	 * b->data_type doesn't yet include need_discard & need_gc_gen states -
1378 	 * fix that here:
1379 	 */
1380 	b->data_type = __alloc_data_type(b->dirty_sectors,
1381 					 b->cached_sectors,
1382 					 b->stripe,
1383 					 *old,
1384 					 b->data_type);
1385 	gc = *b;
1386 
1387 	if (gc.data_type != old_gc.data_type ||
1388 	    gc.dirty_sectors != old_gc.dirty_sectors)
1389 		bch2_dev_usage_update_m(c, ca, &old_gc, &gc);
1390 	percpu_up_read(&c->mark_lock);
1391 
1392 	if (metadata_only &&
1393 	    gc.data_type != BCH_DATA_sb &&
1394 	    gc.data_type != BCH_DATA_journal &&
1395 	    gc.data_type != BCH_DATA_btree)
1396 		return 0;
1397 
1398 	if (gen_after(old->gen, gc.gen))
1399 		return 0;
1400 
1401 	if (fsck_err_on(new.data_type != gc.data_type, c,
1402 			alloc_key_data_type_wrong,
1403 			"bucket %llu:%llu gen %u has wrong data_type"
1404 			": got %s, should be %s",
1405 			iter->pos.inode, iter->pos.offset,
1406 			gc.gen,
1407 			bch2_data_type_str(new.data_type),
1408 			bch2_data_type_str(gc.data_type)))
1409 		new.data_type = gc.data_type;
1410 
1411 #define copy_bucket_field(_errtype, _f)					\
1412 	if (fsck_err_on(new._f != gc._f, c, _errtype,			\
1413 			"bucket %llu:%llu gen %u data type %s has wrong " #_f	\
1414 			": got %u, should be %u",			\
1415 			iter->pos.inode, iter->pos.offset,		\
1416 			gc.gen,						\
1417 			bch2_data_type_str(gc.data_type),		\
1418 			new._f, gc._f))					\
1419 		new._f = gc._f;						\
1420 
1421 	copy_bucket_field(alloc_key_gen_wrong,
1422 			  gen);
1423 	copy_bucket_field(alloc_key_dirty_sectors_wrong,
1424 			  dirty_sectors);
1425 	copy_bucket_field(alloc_key_cached_sectors_wrong,
1426 			  cached_sectors);
1427 	copy_bucket_field(alloc_key_stripe_wrong,
1428 			  stripe);
1429 	copy_bucket_field(alloc_key_stripe_redundancy_wrong,
1430 			  stripe_redundancy);
1431 #undef copy_bucket_field
1432 
1433 	if (!bch2_alloc_v4_cmp(*old, new))
1434 		return 0;
1435 
1436 	a = bch2_alloc_to_v4_mut(trans, k);
1437 	ret = PTR_ERR_OR_ZERO(a);
1438 	if (ret)
1439 		return ret;
1440 
1441 	a->v = new;
1442 
1443 	/*
1444 	 * The trigger normally makes sure this is set, but we're not running
1445 	 * triggers:
1446 	 */
1447 	if (a->v.data_type == BCH_DATA_cached && !a->v.io_time[READ])
1448 		a->v.io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
1449 
1450 	ret = bch2_trans_update(trans, iter, &a->k_i, BTREE_TRIGGER_NORUN);
1451 fsck_err:
1452 	return ret;
1453 }
1454 
1455 static int bch2_gc_alloc_done(struct bch_fs *c, bool metadata_only)
1456 {
1457 	int ret = 0;
1458 
1459 	for_each_member_device(c, ca) {
1460 		ret = bch2_trans_run(c,
1461 			for_each_btree_key_upto_commit(trans, iter, BTREE_ID_alloc,
1462 					POS(ca->dev_idx, ca->mi.first_bucket),
1463 					POS(ca->dev_idx, ca->mi.nbuckets - 1),
1464 					BTREE_ITER_SLOTS|BTREE_ITER_PREFETCH, k,
1465 					NULL, NULL, BCH_TRANS_COMMIT_lazy_rw,
1466 				bch2_alloc_write_key(trans, &iter, k, metadata_only)));
1467 		if (ret) {
1468 			percpu_ref_put(&ca->ref);
1469 			break;
1470 		}
1471 	}
1472 
1473 	bch_err_fn(c, ret);
1474 	return ret;
1475 }
1476 
1477 static int bch2_gc_alloc_start(struct bch_fs *c, bool metadata_only)
1478 {
1479 	for_each_member_device(c, ca) {
1480 		struct bucket_array *buckets = kvmalloc(sizeof(struct bucket_array) +
1481 				ca->mi.nbuckets * sizeof(struct bucket),
1482 				GFP_KERNEL|__GFP_ZERO);
1483 		if (!buckets) {
1484 			percpu_ref_put(&ca->ref);
1485 			bch_err(c, "error allocating ca->buckets[gc]");
1486 			return -BCH_ERR_ENOMEM_gc_alloc_start;
1487 		}
1488 
1489 		buckets->first_bucket	= ca->mi.first_bucket;
1490 		buckets->nbuckets	= ca->mi.nbuckets;
1491 		rcu_assign_pointer(ca->buckets_gc, buckets);
1492 	}
1493 
1494 	int ret = bch2_trans_run(c,
1495 		for_each_btree_key(trans, iter, BTREE_ID_alloc, POS_MIN,
1496 					 BTREE_ITER_PREFETCH, k, ({
1497 			struct bch_dev *ca = bch_dev_bkey_exists(c, k.k->p.inode);
1498 			struct bucket *g = gc_bucket(ca, k.k->p.offset);
1499 
1500 			struct bch_alloc_v4 a_convert;
1501 			const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
1502 
1503 			g->gen_valid	= 1;
1504 			g->gen		= a->gen;
1505 
1506 			if (metadata_only &&
1507 			    (a->data_type == BCH_DATA_user ||
1508 			     a->data_type == BCH_DATA_cached ||
1509 			     a->data_type == BCH_DATA_parity)) {
1510 				g->data_type		= a->data_type;
1511 				g->dirty_sectors	= a->dirty_sectors;
1512 				g->cached_sectors	= a->cached_sectors;
1513 				g->stripe		= a->stripe;
1514 				g->stripe_redundancy	= a->stripe_redundancy;
1515 			}
1516 
1517 			0;
1518 		})));
1519 	bch_err_fn(c, ret);
1520 	return ret;
1521 }
1522 
1523 static void bch2_gc_alloc_reset(struct bch_fs *c, bool metadata_only)
1524 {
1525 	for_each_member_device(c, ca) {
1526 		struct bucket_array *buckets = gc_bucket_array(ca);
1527 		struct bucket *g;
1528 
1529 		for_each_bucket(g, buckets) {
1530 			if (metadata_only &&
1531 			    (g->data_type == BCH_DATA_user ||
1532 			     g->data_type == BCH_DATA_cached ||
1533 			     g->data_type == BCH_DATA_parity))
1534 				continue;
1535 			g->data_type = 0;
1536 			g->dirty_sectors = 0;
1537 			g->cached_sectors = 0;
1538 		}
1539 	}
1540 }
1541 
1542 static int bch2_gc_write_reflink_key(struct btree_trans *trans,
1543 				     struct btree_iter *iter,
1544 				     struct bkey_s_c k,
1545 				     size_t *idx)
1546 {
1547 	struct bch_fs *c = trans->c;
1548 	const __le64 *refcount = bkey_refcount_c(k);
1549 	struct printbuf buf = PRINTBUF;
1550 	struct reflink_gc *r;
1551 	int ret = 0;
1552 
1553 	if (!refcount)
1554 		return 0;
1555 
1556 	while ((r = genradix_ptr(&c->reflink_gc_table, *idx)) &&
1557 	       r->offset < k.k->p.offset)
1558 		++*idx;
1559 
1560 	if (!r ||
1561 	    r->offset != k.k->p.offset ||
1562 	    r->size != k.k->size) {
1563 		bch_err(c, "unexpected inconsistency walking reflink table at gc finish");
1564 		return -EINVAL;
1565 	}
1566 
1567 	if (fsck_err_on(r->refcount != le64_to_cpu(*refcount), c,
1568 			reflink_v_refcount_wrong,
1569 			"reflink key has wrong refcount:\n"
1570 			"  %s\n"
1571 			"  should be %u",
1572 			(bch2_bkey_val_to_text(&buf, c, k), buf.buf),
1573 			r->refcount)) {
1574 		struct bkey_i *new = bch2_bkey_make_mut_noupdate(trans, k);
1575 		ret = PTR_ERR_OR_ZERO(new);
1576 		if (ret)
1577 			return ret;
1578 
1579 		if (!r->refcount)
1580 			new->k.type = KEY_TYPE_deleted;
1581 		else
1582 			*bkey_refcount(bkey_i_to_s(new)) = cpu_to_le64(r->refcount);
1583 		ret = bch2_trans_update(trans, iter, new, 0);
1584 	}
1585 fsck_err:
1586 	printbuf_exit(&buf);
1587 	return ret;
1588 }
1589 
1590 static int bch2_gc_reflink_done(struct bch_fs *c, bool metadata_only)
1591 {
1592 	size_t idx = 0;
1593 
1594 	if (metadata_only)
1595 		return 0;
1596 
1597 	int ret = bch2_trans_run(c,
1598 		for_each_btree_key_commit(trans, iter,
1599 				BTREE_ID_reflink, POS_MIN,
1600 				BTREE_ITER_PREFETCH, k,
1601 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1602 			bch2_gc_write_reflink_key(trans, &iter, k, &idx)));
1603 	c->reflink_gc_nr = 0;
1604 	return ret;
1605 }
1606 
1607 static int bch2_gc_reflink_start(struct bch_fs *c,
1608 				 bool metadata_only)
1609 {
1610 
1611 	if (metadata_only)
1612 		return 0;
1613 
1614 	c->reflink_gc_nr = 0;
1615 
1616 	int ret = bch2_trans_run(c,
1617 		for_each_btree_key(trans, iter, BTREE_ID_reflink, POS_MIN,
1618 				   BTREE_ITER_PREFETCH, k, ({
1619 			const __le64 *refcount = bkey_refcount_c(k);
1620 
1621 			if (!refcount)
1622 				continue;
1623 
1624 			struct reflink_gc *r = genradix_ptr_alloc(&c->reflink_gc_table,
1625 							c->reflink_gc_nr++, GFP_KERNEL);
1626 			if (!r) {
1627 				ret = -BCH_ERR_ENOMEM_gc_reflink_start;
1628 				break;
1629 			}
1630 
1631 			r->offset	= k.k->p.offset;
1632 			r->size		= k.k->size;
1633 			r->refcount	= 0;
1634 			0;
1635 		})));
1636 
1637 	bch_err_fn(c, ret);
1638 	return ret;
1639 }
1640 
1641 static void bch2_gc_reflink_reset(struct bch_fs *c, bool metadata_only)
1642 {
1643 	struct genradix_iter iter;
1644 	struct reflink_gc *r;
1645 
1646 	genradix_for_each(&c->reflink_gc_table, iter, r)
1647 		r->refcount = 0;
1648 }
1649 
1650 static int bch2_gc_write_stripes_key(struct btree_trans *trans,
1651 				     struct btree_iter *iter,
1652 				     struct bkey_s_c k)
1653 {
1654 	struct bch_fs *c = trans->c;
1655 	struct printbuf buf = PRINTBUF;
1656 	const struct bch_stripe *s;
1657 	struct gc_stripe *m;
1658 	bool bad = false;
1659 	unsigned i;
1660 	int ret = 0;
1661 
1662 	if (k.k->type != KEY_TYPE_stripe)
1663 		return 0;
1664 
1665 	s = bkey_s_c_to_stripe(k).v;
1666 	m = genradix_ptr(&c->gc_stripes, k.k->p.offset);
1667 
1668 	for (i = 0; i < s->nr_blocks; i++) {
1669 		u32 old = stripe_blockcount_get(s, i);
1670 		u32 new = (m ? m->block_sectors[i] : 0);
1671 
1672 		if (old != new) {
1673 			prt_printf(&buf, "stripe block %u has wrong sector count: got %u, should be %u\n",
1674 				   i, old, new);
1675 			bad = true;
1676 		}
1677 	}
1678 
1679 	if (bad)
1680 		bch2_bkey_val_to_text(&buf, c, k);
1681 
1682 	if (fsck_err_on(bad, c, stripe_sector_count_wrong,
1683 			"%s", buf.buf)) {
1684 		struct bkey_i_stripe *new;
1685 
1686 		new = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1687 		ret = PTR_ERR_OR_ZERO(new);
1688 		if (ret)
1689 			return ret;
1690 
1691 		bkey_reassemble(&new->k_i, k);
1692 
1693 		for (i = 0; i < new->v.nr_blocks; i++)
1694 			stripe_blockcount_set(&new->v, i, m ? m->block_sectors[i] : 0);
1695 
1696 		ret = bch2_trans_update(trans, iter, &new->k_i, 0);
1697 	}
1698 fsck_err:
1699 	printbuf_exit(&buf);
1700 	return ret;
1701 }
1702 
1703 static int bch2_gc_stripes_done(struct bch_fs *c, bool metadata_only)
1704 {
1705 	if (metadata_only)
1706 		return 0;
1707 
1708 	return bch2_trans_run(c,
1709 		for_each_btree_key_commit(trans, iter,
1710 				BTREE_ID_stripes, POS_MIN,
1711 				BTREE_ITER_PREFETCH, k,
1712 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1713 			bch2_gc_write_stripes_key(trans, &iter, k)));
1714 }
1715 
1716 static void bch2_gc_stripes_reset(struct bch_fs *c, bool metadata_only)
1717 {
1718 	genradix_free(&c->gc_stripes);
1719 }
1720 
1721 /**
1722  * bch2_gc - walk _all_ references to buckets, and recompute them:
1723  *
1724  * @c:			filesystem object
1725  * @initial:		are we in recovery?
1726  * @metadata_only:	are we just checking metadata references, or everything?
1727  *
1728  * Returns: 0 on success, or standard errcode on failure
1729  *
1730  * Order matters here:
1731  *  - Concurrent GC relies on the fact that we have a total ordering for
1732  *    everything that GC walks - see  gc_will_visit_node(),
1733  *    gc_will_visit_root()
1734  *
1735  *  - also, references move around in the course of index updates and
1736  *    various other crap: everything needs to agree on the ordering
1737  *    references are allowed to move around in - e.g., we're allowed to
1738  *    start with a reference owned by an open_bucket (the allocator) and
1739  *    move it to the btree, but not the reverse.
1740  *
1741  *    This is necessary to ensure that gc doesn't miss references that
1742  *    move around - if references move backwards in the ordering GC
1743  *    uses, GC could skip past them
1744  */
1745 int bch2_gc(struct bch_fs *c, bool initial, bool metadata_only)
1746 {
1747 	unsigned iter = 0;
1748 	int ret;
1749 
1750 	lockdep_assert_held(&c->state_lock);
1751 
1752 	down_write(&c->gc_lock);
1753 
1754 	bch2_btree_interior_updates_flush(c);
1755 
1756 	ret   = bch2_gc_start(c) ?:
1757 		bch2_gc_alloc_start(c, metadata_only) ?:
1758 		bch2_gc_reflink_start(c, metadata_only);
1759 	if (ret)
1760 		goto out;
1761 again:
1762 	gc_pos_set(c, gc_phase(GC_PHASE_START));
1763 
1764 	bch2_mark_superblocks(c);
1765 
1766 	ret = bch2_gc_btrees(c, initial, metadata_only);
1767 
1768 	if (ret)
1769 		goto out;
1770 
1771 #if 0
1772 	bch2_mark_pending_btree_node_frees(c);
1773 #endif
1774 	c->gc_count++;
1775 
1776 	if (test_bit(BCH_FS_need_another_gc, &c->flags) ||
1777 	    (!iter && bch2_test_restart_gc)) {
1778 		if (iter++ > 2) {
1779 			bch_info(c, "Unable to fix bucket gens, looping");
1780 			ret = -EINVAL;
1781 			goto out;
1782 		}
1783 
1784 		/*
1785 		 * XXX: make sure gens we fixed got saved
1786 		 */
1787 		bch_info(c, "Second GC pass needed, restarting:");
1788 		clear_bit(BCH_FS_need_another_gc, &c->flags);
1789 		__gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
1790 
1791 		bch2_gc_stripes_reset(c, metadata_only);
1792 		bch2_gc_alloc_reset(c, metadata_only);
1793 		bch2_gc_reflink_reset(c, metadata_only);
1794 		ret = bch2_gc_reset(c);
1795 		if (ret)
1796 			goto out;
1797 
1798 		/* flush fsck errors, reset counters */
1799 		bch2_flush_fsck_errs(c);
1800 		goto again;
1801 	}
1802 out:
1803 	if (!ret) {
1804 		bch2_journal_block(&c->journal);
1805 
1806 		ret   = bch2_gc_alloc_done(c, metadata_only) ?:
1807 			bch2_gc_done(c, initial, metadata_only) ?:
1808 			bch2_gc_stripes_done(c, metadata_only) ?:
1809 			bch2_gc_reflink_done(c, metadata_only);
1810 
1811 		bch2_journal_unblock(&c->journal);
1812 	}
1813 
1814 	percpu_down_write(&c->mark_lock);
1815 	/* Indicates that gc is no longer in progress: */
1816 	__gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
1817 
1818 	bch2_gc_free(c);
1819 	percpu_up_write(&c->mark_lock);
1820 
1821 	up_write(&c->gc_lock);
1822 
1823 	/*
1824 	 * At startup, allocations can happen directly instead of via the
1825 	 * allocator thread - issue wakeup in case they blocked on gc_lock:
1826 	 */
1827 	closure_wake_up(&c->freelist_wait);
1828 	bch_err_fn(c, ret);
1829 	return ret;
1830 }
1831 
1832 static int gc_btree_gens_key(struct btree_trans *trans,
1833 			     struct btree_iter *iter,
1834 			     struct bkey_s_c k)
1835 {
1836 	struct bch_fs *c = trans->c;
1837 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1838 	struct bkey_i *u;
1839 	int ret;
1840 
1841 	percpu_down_read(&c->mark_lock);
1842 	bkey_for_each_ptr(ptrs, ptr) {
1843 		struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
1844 
1845 		if (ptr_stale(ca, ptr) > 16) {
1846 			percpu_up_read(&c->mark_lock);
1847 			goto update;
1848 		}
1849 	}
1850 
1851 	bkey_for_each_ptr(ptrs, ptr) {
1852 		struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
1853 		u8 *gen = &ca->oldest_gen[PTR_BUCKET_NR(ca, ptr)];
1854 
1855 		if (gen_after(*gen, ptr->gen))
1856 			*gen = ptr->gen;
1857 	}
1858 	percpu_up_read(&c->mark_lock);
1859 	return 0;
1860 update:
1861 	u = bch2_bkey_make_mut(trans, iter, &k, 0);
1862 	ret = PTR_ERR_OR_ZERO(u);
1863 	if (ret)
1864 		return ret;
1865 
1866 	bch2_extent_normalize(c, bkey_i_to_s(u));
1867 	return 0;
1868 }
1869 
1870 static int bch2_alloc_write_oldest_gen(struct btree_trans *trans, struct btree_iter *iter,
1871 				       struct bkey_s_c k)
1872 {
1873 	struct bch_dev *ca = bch_dev_bkey_exists(trans->c, iter->pos.inode);
1874 	struct bch_alloc_v4 a_convert;
1875 	const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
1876 	struct bkey_i_alloc_v4 *a_mut;
1877 	int ret;
1878 
1879 	if (a->oldest_gen == ca->oldest_gen[iter->pos.offset])
1880 		return 0;
1881 
1882 	a_mut = bch2_alloc_to_v4_mut(trans, k);
1883 	ret = PTR_ERR_OR_ZERO(a_mut);
1884 	if (ret)
1885 		return ret;
1886 
1887 	a_mut->v.oldest_gen = ca->oldest_gen[iter->pos.offset];
1888 	a_mut->v.data_type = alloc_data_type(a_mut->v, a_mut->v.data_type);
1889 
1890 	return bch2_trans_update(trans, iter, &a_mut->k_i, 0);
1891 }
1892 
1893 int bch2_gc_gens(struct bch_fs *c)
1894 {
1895 	u64 b, start_time = local_clock();
1896 	int ret;
1897 
1898 	/*
1899 	 * Ideally we would be using state_lock and not gc_lock here, but that
1900 	 * introduces a deadlock in the RO path - we currently take the state
1901 	 * lock at the start of going RO, thus the gc thread may get stuck:
1902 	 */
1903 	if (!mutex_trylock(&c->gc_gens_lock))
1904 		return 0;
1905 
1906 	trace_and_count(c, gc_gens_start, c);
1907 	down_read(&c->gc_lock);
1908 
1909 	for_each_member_device(c, ca) {
1910 		struct bucket_gens *gens = bucket_gens(ca);
1911 
1912 		BUG_ON(ca->oldest_gen);
1913 
1914 		ca->oldest_gen = kvmalloc(gens->nbuckets, GFP_KERNEL);
1915 		if (!ca->oldest_gen) {
1916 			percpu_ref_put(&ca->ref);
1917 			ret = -BCH_ERR_ENOMEM_gc_gens;
1918 			goto err;
1919 		}
1920 
1921 		for (b = gens->first_bucket;
1922 		     b < gens->nbuckets; b++)
1923 			ca->oldest_gen[b] = gens->b[b];
1924 	}
1925 
1926 	for (unsigned i = 0; i < BTREE_ID_NR; i++)
1927 		if (btree_type_has_ptrs(i)) {
1928 			c->gc_gens_btree = i;
1929 			c->gc_gens_pos = POS_MIN;
1930 
1931 			ret = bch2_trans_run(c,
1932 				for_each_btree_key_commit(trans, iter, i,
1933 						POS_MIN,
1934 						BTREE_ITER_PREFETCH|BTREE_ITER_ALL_SNAPSHOTS,
1935 						k,
1936 						NULL, NULL,
1937 						BCH_TRANS_COMMIT_no_enospc,
1938 					gc_btree_gens_key(trans, &iter, k)));
1939 			if (ret)
1940 				goto err;
1941 		}
1942 
1943 	ret = bch2_trans_run(c,
1944 		for_each_btree_key_commit(trans, iter, BTREE_ID_alloc,
1945 				POS_MIN,
1946 				BTREE_ITER_PREFETCH,
1947 				k,
1948 				NULL, NULL,
1949 				BCH_TRANS_COMMIT_no_enospc,
1950 			bch2_alloc_write_oldest_gen(trans, &iter, k)));
1951 	if (ret)
1952 		goto err;
1953 
1954 	c->gc_gens_btree	= 0;
1955 	c->gc_gens_pos		= POS_MIN;
1956 
1957 	c->gc_count++;
1958 
1959 	bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
1960 	trace_and_count(c, gc_gens_end, c);
1961 err:
1962 	for_each_member_device(c, ca) {
1963 		kvfree(ca->oldest_gen);
1964 		ca->oldest_gen = NULL;
1965 	}
1966 
1967 	up_read(&c->gc_lock);
1968 	mutex_unlock(&c->gc_gens_lock);
1969 	if (!bch2_err_matches(ret, EROFS))
1970 		bch_err_fn(c, ret);
1971 	return ret;
1972 }
1973 
1974 static int bch2_gc_thread(void *arg)
1975 {
1976 	struct bch_fs *c = arg;
1977 	struct io_clock *clock = &c->io_clock[WRITE];
1978 	unsigned long last = atomic64_read(&clock->now);
1979 	unsigned last_kick = atomic_read(&c->kick_gc);
1980 
1981 	set_freezable();
1982 
1983 	while (1) {
1984 		while (1) {
1985 			set_current_state(TASK_INTERRUPTIBLE);
1986 
1987 			if (kthread_should_stop()) {
1988 				__set_current_state(TASK_RUNNING);
1989 				return 0;
1990 			}
1991 
1992 			if (atomic_read(&c->kick_gc) != last_kick)
1993 				break;
1994 
1995 			if (c->btree_gc_periodic) {
1996 				unsigned long next = last + c->capacity / 16;
1997 
1998 				if (atomic64_read(&clock->now) >= next)
1999 					break;
2000 
2001 				bch2_io_clock_schedule_timeout(clock, next);
2002 			} else {
2003 				schedule();
2004 			}
2005 
2006 			try_to_freeze();
2007 		}
2008 		__set_current_state(TASK_RUNNING);
2009 
2010 		last = atomic64_read(&clock->now);
2011 		last_kick = atomic_read(&c->kick_gc);
2012 
2013 		/*
2014 		 * Full gc is currently incompatible with btree key cache:
2015 		 */
2016 #if 0
2017 		ret = bch2_gc(c, false, false);
2018 #else
2019 		bch2_gc_gens(c);
2020 #endif
2021 		debug_check_no_locks_held();
2022 	}
2023 
2024 	return 0;
2025 }
2026 
2027 void bch2_gc_thread_stop(struct bch_fs *c)
2028 {
2029 	struct task_struct *p;
2030 
2031 	p = c->gc_thread;
2032 	c->gc_thread = NULL;
2033 
2034 	if (p) {
2035 		kthread_stop(p);
2036 		put_task_struct(p);
2037 	}
2038 }
2039 
2040 int bch2_gc_thread_start(struct bch_fs *c)
2041 {
2042 	struct task_struct *p;
2043 
2044 	if (c->gc_thread)
2045 		return 0;
2046 
2047 	p = kthread_create(bch2_gc_thread, c, "bch-gc/%s", c->name);
2048 	if (IS_ERR(p)) {
2049 		bch_err_fn(c, PTR_ERR(p));
2050 		return PTR_ERR(p);
2051 	}
2052 
2053 	get_task_struct(p);
2054 	c->gc_thread = p;
2055 	wake_up_process(p);
2056 	return 0;
2057 }
2058