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