1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4 * Copyright (C) 2014 Datera Inc.
8 #include "alloc_background.h"
9 #include "alloc_foreground.h"
10 #include "bkey_methods.h"
11 #include "btree_locking.h"
12 #include "btree_update_interior.h"
28 #include <linux/slab.h>
29 #include <linux/bitops.h>
30 #include <linux/freezer.h>
31 #include <linux/kthread.h>
32 #include <linux/preempt.h>
33 #include <linux/rcupdate.h>
34 #include <linux/sched/task.h>
35 #include <trace/events/bcachefs.h>
37 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
39 write_seqcount_begin(&c->gc_pos_lock);
41 write_seqcount_end(&c->gc_pos_lock);
44 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
46 BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
47 __gc_pos_set(c, new_pos);
50 static int bch2_gc_check_topology(struct bch_fs *c,
52 struct bpos *expected_start,
53 struct bpos expected_end,
58 if (k.k->type == KEY_TYPE_btree_ptr_v2) {
59 struct bkey_s_c_btree_ptr_v2 bp = bkey_s_c_to_btree_ptr_v2(k);
61 if (fsck_err_on(bkey_cmp(*expected_start, bp.v->min_key), c,
62 "btree node with incorrect min_key: got %llu:%llu, should be %llu:%llu",
65 expected_start->inode,
66 expected_start->offset)) {
71 *expected_start = bkey_cmp(k.k->p, POS_MAX)
72 ? bkey_successor(k.k->p)
75 if (fsck_err_on(is_last &&
76 bkey_cmp(k.k->p, expected_end), c,
77 "btree node with incorrect max_key: got %llu:%llu, should be %llu:%llu",
81 expected_end.offset)) {
88 /* marking of btree keys/nodes: */
90 static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
91 u8 *max_stale, bool initial)
93 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
94 const struct bch_extent_ptr *ptr;
97 (initial ? BTREE_TRIGGER_NOATOMIC : 0);
101 BUG_ON(journal_seq_verify(c) &&
102 k.k->version.lo > journal_cur_seq(&c->journal));
104 /* XXX change to fsck check */
105 if (fsck_err_on(k.k->version.lo > atomic64_read(&c->key_version), c,
106 "key version number higher than recorded: %llu > %llu",
108 atomic64_read(&c->key_version)))
109 atomic64_set(&c->key_version, k.k->version.lo);
111 if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
112 fsck_err_on(!bch2_bkey_replicas_marked(c, k), c,
113 "superblock not marked as containing replicas (type %u)",
115 ret = bch2_mark_bkey_replicas(c, k);
120 bkey_for_each_ptr(ptrs, ptr) {
121 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
122 struct bucket *g = PTR_BUCKET(ca, ptr, true);
123 struct bucket *g2 = PTR_BUCKET(ca, ptr, false);
125 if (mustfix_fsck_err_on(!g->gen_valid, c,
126 "bucket %u:%zu data type %s ptr gen %u missing in alloc btree",
127 ptr->dev, PTR_BUCKET_NR(ca, ptr),
128 bch2_data_types[ptr_data_type(k.k, ptr)],
130 g2->_mark.gen = g->_mark.gen = ptr->gen;
131 g2->gen_valid = g->gen_valid = true;
134 if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
135 "bucket %u:%zu data type %s ptr gen in the future: %u > %u",
136 ptr->dev, PTR_BUCKET_NR(ca, ptr),
137 bch2_data_types[ptr_data_type(k.k, ptr)],
138 ptr->gen, g->mark.gen)) {
139 g2->_mark.gen = g->_mark.gen = ptr->gen;
140 g2->gen_valid = g->gen_valid = true;
141 g2->_mark.data_type = 0;
142 g2->_mark.dirty_sectors = 0;
143 g2->_mark.cached_sectors = 0;
144 set_bit(BCH_FS_FIXED_GENS, &c->flags);
149 bkey_for_each_ptr(ptrs, ptr) {
150 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
151 struct bucket *g = PTR_BUCKET(ca, ptr, true);
153 if (gen_after(g->oldest_gen, ptr->gen))
154 g->oldest_gen = ptr->gen;
156 *max_stale = max(*max_stale, ptr_stale(ca, ptr));
159 bch2_mark_key(c, k, 0, k.k->size, NULL, 0, flags);
164 static int btree_gc_mark_node(struct bch_fs *c, struct btree *b, u8 *max_stale,
167 struct bpos next_node_start = b->data->min_key;
168 struct btree_node_iter iter;
169 struct bkey unpacked;
175 if (!btree_node_type_needs_gc(btree_node_type(b)))
178 bch2_btree_node_iter_init_from_start(&iter, b);
180 while ((k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked)).k) {
181 bch2_bkey_debugcheck(c, b, k);
183 ret = bch2_gc_mark_key(c, k, max_stale, initial);
187 bch2_btree_node_iter_advance(&iter, b);
190 ret = bch2_gc_check_topology(c, k,
193 bch2_btree_node_iter_end(&iter));
202 static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id,
203 bool initial, bool metadata_only)
205 struct btree_trans trans;
206 struct btree_iter *iter;
208 unsigned depth = metadata_only ? 1
209 : expensive_debug_checks(c) ? 0
210 : !btree_node_type_needs_gc(btree_id) ? 1
215 bch2_trans_init(&trans, c, 0, 0);
217 gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
219 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
220 0, depth, BTREE_ITER_PREFETCH, b) {
221 bch2_verify_btree_nr_keys(b);
223 gc_pos_set(c, gc_pos_btree_node(b));
225 ret = btree_gc_mark_node(c, b, &max_stale, initial);
231 bch2_btree_node_rewrite(c, iter,
233 BTREE_INSERT_USE_RESERVE|
235 BTREE_INSERT_GC_LOCK_HELD);
236 else if (!btree_gc_rewrite_disabled(c) &&
237 (btree_gc_always_rewrite(c) || max_stale > 16))
238 bch2_btree_node_rewrite(c, iter,
241 BTREE_INSERT_GC_LOCK_HELD);
244 bch2_trans_cond_resched(&trans);
246 ret = bch2_trans_exit(&trans) ?: ret;
250 mutex_lock(&c->btree_root_lock);
251 b = c->btree_roots[btree_id].b;
252 if (!btree_node_fake(b))
253 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
254 &max_stale, initial);
255 gc_pos_set(c, gc_pos_btree_root(b->c.btree_id));
256 mutex_unlock(&c->btree_root_lock);
261 static int bch2_gc_btree_init_recurse(struct bch_fs *c, struct btree *b,
262 struct journal_keys *journal_keys,
263 unsigned target_depth)
265 struct btree_and_journal_iter iter;
267 struct bpos next_node_start = b->data->min_key;
271 bch2_btree_and_journal_iter_init_node_iter(&iter, journal_keys, b);
273 while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
274 bch2_bkey_debugcheck(c, b, k);
276 BUG_ON(bkey_cmp(k.k->p, b->data->min_key) < 0);
277 BUG_ON(bkey_cmp(k.k->p, b->data->max_key) > 0);
279 ret = bch2_gc_mark_key(c, k, &max_stale, true);
287 bkey_reassemble(&tmp.k, k);
288 k = bkey_i_to_s_c(&tmp.k);
290 bch2_btree_and_journal_iter_advance(&iter);
292 ret = bch2_gc_check_topology(c, k,
295 !bch2_btree_and_journal_iter_peek(&iter).k);
299 if (b->c.level > target_depth) {
300 child = bch2_btree_node_get_noiter(c, &tmp.k,
301 b->c.btree_id, b->c.level - 1);
302 ret = PTR_ERR_OR_ZERO(child);
306 ret = bch2_gc_btree_init_recurse(c, child,
307 journal_keys, target_depth);
308 six_unlock_read(&child->c.lock);
314 bch2_btree_and_journal_iter_advance(&iter);
321 static int bch2_gc_btree_init(struct bch_fs *c,
322 struct journal_keys *journal_keys,
323 enum btree_id btree_id,
327 unsigned target_depth = metadata_only ? 1
328 : expensive_debug_checks(c) ? 0
329 : !btree_node_type_needs_gc(btree_id) ? 1
334 b = c->btree_roots[btree_id].b;
336 if (btree_node_fake(b))
339 six_lock_read(&b->c.lock, NULL, NULL);
340 if (fsck_err_on(bkey_cmp(b->data->min_key, POS_MIN), c,
341 "btree root with incorrect min_key: %llu:%llu",
342 b->data->min_key.inode,
343 b->data->min_key.offset)) {
347 if (fsck_err_on(bkey_cmp(b->data->max_key, POS_MAX), c,
348 "btree root with incorrect min_key: %llu:%llu",
349 b->data->max_key.inode,
350 b->data->max_key.offset)) {
354 if (b->c.level >= target_depth)
355 ret = bch2_gc_btree_init_recurse(c, b,
356 journal_keys, target_depth);
359 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
362 six_unlock_read(&b->c.lock);
367 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
369 return (int) btree_id_to_gc_phase(l) -
370 (int) btree_id_to_gc_phase(r);
373 static int bch2_gc_btrees(struct bch_fs *c, struct journal_keys *journal_keys,
374 bool initial, bool metadata_only)
376 enum btree_id ids[BTREE_ID_NR];
379 for (i = 0; i < BTREE_ID_NR; i++)
381 bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
383 for (i = 0; i < BTREE_ID_NR; i++) {
384 enum btree_id id = ids[i];
386 ? bch2_gc_btree_init(c, journal_keys,
388 : bch2_gc_btree(c, id, initial, metadata_only);
396 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
398 enum bch_data_type type,
401 u64 b = sector_to_bucket(ca, start);
405 min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
407 bch2_mark_metadata_bucket(c, ca, b, type, sectors,
408 gc_phase(GC_PHASE_SB), flags);
411 } while (start < end);
414 void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
417 struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
422 * This conditional is kind of gross, but we may be called from the
423 * device add path, before the new device has actually been added to the
424 * running filesystem:
427 lockdep_assert_held(&c->sb_lock);
428 percpu_down_read(&c->mark_lock);
431 for (i = 0; i < layout->nr_superblocks; i++) {
432 u64 offset = le64_to_cpu(layout->sb_offset[i]);
434 if (offset == BCH_SB_SECTOR)
435 mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
438 mark_metadata_sectors(c, ca, offset,
439 offset + (1 << layout->sb_max_size_bits),
443 for (i = 0; i < ca->journal.nr; i++) {
444 b = ca->journal.buckets[i];
445 bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_journal,
447 gc_phase(GC_PHASE_SB), flags);
451 percpu_up_read(&c->mark_lock);
454 static void bch2_mark_superblocks(struct bch_fs *c)
459 mutex_lock(&c->sb_lock);
460 gc_pos_set(c, gc_phase(GC_PHASE_SB));
462 for_each_online_member(ca, c, i)
463 bch2_mark_dev_superblock(c, ca, BTREE_TRIGGER_GC);
464 mutex_unlock(&c->sb_lock);
468 /* Also see bch2_pending_btree_node_free_insert_done() */
469 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
471 struct btree_update *as;
472 struct pending_btree_node_free *d;
474 mutex_lock(&c->btree_interior_update_lock);
475 gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
477 for_each_pending_btree_node_free(c, as, d)
478 if (d->index_update_done)
479 bch2_mark_key(c, bkey_i_to_s_c(&d->key),
483 mutex_unlock(&c->btree_interior_update_lock);
487 static void bch2_mark_allocator_buckets(struct bch_fs *c)
490 struct open_bucket *ob;
494 percpu_down_read(&c->mark_lock);
496 spin_lock(&c->freelist_lock);
497 gc_pos_set(c, gc_pos_alloc(c, NULL));
499 for_each_member_device(ca, c, ci) {
500 fifo_for_each_entry(i, &ca->free_inc, iter)
501 bch2_mark_alloc_bucket(c, ca, i, true,
502 gc_pos_alloc(c, NULL),
507 for (j = 0; j < RESERVE_NR; j++)
508 fifo_for_each_entry(i, &ca->free[j], iter)
509 bch2_mark_alloc_bucket(c, ca, i, true,
510 gc_pos_alloc(c, NULL),
514 spin_unlock(&c->freelist_lock);
516 for (ob = c->open_buckets;
517 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
519 spin_lock(&ob->lock);
521 gc_pos_set(c, gc_pos_alloc(c, ob));
522 ca = bch_dev_bkey_exists(c, ob->ptr.dev);
523 bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
527 spin_unlock(&ob->lock);
530 percpu_up_read(&c->mark_lock);
533 static void bch2_gc_free(struct bch_fs *c)
538 genradix_free(&c->stripes[1]);
540 for_each_member_device(ca, c, i) {
541 kvpfree(rcu_dereference_protected(ca->buckets[1], 1),
542 sizeof(struct bucket_array) +
543 ca->mi.nbuckets * sizeof(struct bucket));
544 ca->buckets[1] = NULL;
546 free_percpu(ca->usage[1]);
550 free_percpu(c->usage_gc);
554 static int bch2_gc_done(struct bch_fs *c,
555 bool initial, bool metadata_only)
558 bool verify = !metadata_only &&
560 (c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)));
564 #define copy_field(_f, _msg, ...) \
565 if (dst->_f != src->_f) { \
567 fsck_err(c, _msg ": got %llu, should be %llu" \
568 , ##__VA_ARGS__, dst->_f, src->_f); \
571 #define copy_stripe_field(_f, _msg, ...) \
572 if (dst->_f != src->_f) { \
574 fsck_err(c, "stripe %zu has wrong "_msg \
575 ": got %u, should be %u", \
576 dst_iter.pos, ##__VA_ARGS__, \
581 #define copy_bucket_field(_f) \
582 if (dst->b[b].mark._f != src->b[b].mark._f) { \
584 fsck_err(c, "bucket %u:%zu gen %u data type %s has wrong " #_f \
585 ": got %u, should be %u", i, b, \
586 dst->b[b].mark.gen, \
587 bch2_data_types[dst->b[b].mark.data_type],\
588 dst->b[b].mark._f, src->b[b].mark._f); \
589 dst->b[b]._mark._f = src->b[b].mark._f; \
591 #define copy_dev_field(_f, _msg, ...) \
592 copy_field(_f, "dev %u has wrong " _msg, i, ##__VA_ARGS__)
593 #define copy_fs_field(_f, _msg, ...) \
594 copy_field(_f, "fs has wrong " _msg, ##__VA_ARGS__)
596 if (!metadata_only) {
597 struct genradix_iter dst_iter = genradix_iter_init(&c->stripes[0], 0);
598 struct genradix_iter src_iter = genradix_iter_init(&c->stripes[1], 0);
599 struct stripe *dst, *src;
602 c->ec_stripes_heap.used = 0;
604 while ((dst = genradix_iter_peek(&dst_iter, &c->stripes[0])) &&
605 (src = genradix_iter_peek(&src_iter, &c->stripes[1]))) {
606 BUG_ON(src_iter.pos != dst_iter.pos);
608 copy_stripe_field(alive, "alive");
609 copy_stripe_field(sectors, "sectors");
610 copy_stripe_field(algorithm, "algorithm");
611 copy_stripe_field(nr_blocks, "nr_blocks");
612 copy_stripe_field(nr_redundant, "nr_redundant");
613 copy_stripe_field(blocks_nonempty,
616 for (i = 0; i < ARRAY_SIZE(dst->block_sectors); i++)
617 copy_stripe_field(block_sectors[i],
618 "block_sectors[%u]", i);
621 spin_lock(&c->ec_stripes_heap_lock);
622 bch2_stripes_heap_insert(c, dst, dst_iter.pos);
623 spin_unlock(&c->ec_stripes_heap_lock);
626 genradix_iter_advance(&dst_iter, &c->stripes[0]);
627 genradix_iter_advance(&src_iter, &c->stripes[1]);
631 for_each_member_device(ca, c, i) {
632 struct bucket_array *dst = __bucket_array(ca, 0);
633 struct bucket_array *src = __bucket_array(ca, 1);
636 for (b = 0; b < src->nbuckets; b++) {
637 copy_bucket_field(gen);
638 copy_bucket_field(data_type);
639 copy_bucket_field(owned_by_allocator);
640 copy_bucket_field(stripe);
641 copy_bucket_field(dirty_sectors);
642 copy_bucket_field(cached_sectors);
644 dst->b[b].oldest_gen = src->b[b].oldest_gen;
648 bch2_fs_usage_acc_to_base(c, 0);
649 bch2_fs_usage_acc_to_base(c, 1);
651 bch2_dev_usage_from_buckets(c);
654 unsigned nr = fs_usage_u64s(c);
655 struct bch_fs_usage *dst = c->usage_base;
656 struct bch_fs_usage *src = (void *)
657 bch2_acc_percpu_u64s((void *) c->usage_gc, nr);
659 copy_fs_field(hidden, "hidden");
660 copy_fs_field(btree, "btree");
662 if (!metadata_only) {
663 copy_fs_field(data, "data");
664 copy_fs_field(cached, "cached");
665 copy_fs_field(reserved, "reserved");
666 copy_fs_field(nr_inodes,"nr_inodes");
668 for (i = 0; i < BCH_REPLICAS_MAX; i++)
669 copy_fs_field(persistent_reserved[i],
670 "persistent_reserved[%i]", i);
673 for (i = 0; i < c->replicas.nr; i++) {
674 struct bch_replicas_entry *e =
675 cpu_replicas_entry(&c->replicas, i);
679 (e->data_type == BCH_DATA_user ||
680 e->data_type == BCH_DATA_cached))
683 bch2_replicas_entry_to_text(&PBUF(buf), e);
685 copy_fs_field(replicas[i], "%s", buf);
690 #undef copy_dev_field
691 #undef copy_bucket_field
692 #undef copy_stripe_field
698 static int bch2_gc_start(struct bch_fs *c,
707 c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
708 sizeof(u64), GFP_KERNEL);
710 bch_err(c, "error allocating c->usage_gc");
714 for_each_member_device(ca, c, i) {
715 BUG_ON(ca->buckets[1]);
716 BUG_ON(ca->usage[1]);
718 ca->buckets[1] = kvpmalloc(sizeof(struct bucket_array) +
719 ca->mi.nbuckets * sizeof(struct bucket),
720 GFP_KERNEL|__GFP_ZERO);
721 if (!ca->buckets[1]) {
722 percpu_ref_put(&ca->ref);
723 bch_err(c, "error allocating ca->buckets[gc]");
727 ca->usage[1] = alloc_percpu(struct bch_dev_usage);
729 bch_err(c, "error allocating ca->usage[gc]");
730 percpu_ref_put(&ca->ref);
735 ret = bch2_ec_mem_alloc(c, true);
737 bch_err(c, "error allocating ec gc mem");
741 percpu_down_write(&c->mark_lock);
744 * indicate to stripe code that we need to allocate for the gc stripes
747 gc_pos_set(c, gc_phase(GC_PHASE_START));
749 for_each_member_device(ca, c, i) {
750 struct bucket_array *dst = __bucket_array(ca, 1);
751 struct bucket_array *src = __bucket_array(ca, 0);
754 dst->first_bucket = src->first_bucket;
755 dst->nbuckets = src->nbuckets;
757 for (b = 0; b < src->nbuckets; b++) {
758 struct bucket *d = &dst->b[b];
759 struct bucket *s = &src->b[b];
761 d->_mark.gen = dst->b[b].oldest_gen = s->mark.gen;
762 d->gen_valid = s->gen_valid;
765 (s->mark.data_type == BCH_DATA_user ||
766 s->mark.data_type == BCH_DATA_cached)) {
768 d->_mark.owned_by_allocator = 0;
773 percpu_up_write(&c->mark_lock);
779 * bch2_gc - walk _all_ references to buckets, and recompute them:
781 * Order matters here:
782 * - Concurrent GC relies on the fact that we have a total ordering for
783 * everything that GC walks - see gc_will_visit_node(),
784 * gc_will_visit_root()
786 * - also, references move around in the course of index updates and
787 * various other crap: everything needs to agree on the ordering
788 * references are allowed to move around in - e.g., we're allowed to
789 * start with a reference owned by an open_bucket (the allocator) and
790 * move it to the btree, but not the reverse.
792 * This is necessary to ensure that gc doesn't miss references that
793 * move around - if references move backwards in the ordering GC
794 * uses, GC could skip past them
796 int bch2_gc(struct bch_fs *c, struct journal_keys *journal_keys,
797 bool initial, bool metadata_only)
800 u64 start_time = local_clock();
801 unsigned i, iter = 0;
804 lockdep_assert_held(&c->state_lock);
807 down_write(&c->gc_lock);
809 /* flush interior btree updates: */
810 closure_wait_event(&c->btree_interior_update_wait,
811 !bch2_btree_interior_updates_nr_pending(c));
813 ret = bch2_gc_start(c, metadata_only);
817 bch2_mark_superblocks(c);
819 ret = bch2_gc_btrees(c, journal_keys, initial, metadata_only);
824 bch2_mark_pending_btree_node_frees(c);
826 bch2_mark_allocator_buckets(c);
831 (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
832 (!iter && test_restart_gc(c)))) {
834 * XXX: make sure gens we fixed got saved
837 bch_info(c, "Fixed gens, restarting mark and sweep:");
838 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
839 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
841 percpu_down_write(&c->mark_lock);
843 percpu_up_write(&c->mark_lock);
844 /* flush fsck errors, reset counters */
845 bch2_flush_fsck_errs(c);
850 bch_info(c, "Unable to fix bucket gens, looping");
855 bch2_journal_block(&c->journal);
857 percpu_down_write(&c->mark_lock);
858 ret = bch2_gc_done(c, initial, metadata_only);
860 bch2_journal_unblock(&c->journal);
862 percpu_down_write(&c->mark_lock);
865 /* Indicates that gc is no longer in progress: */
866 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
869 percpu_up_write(&c->mark_lock);
871 up_write(&c->gc_lock);
874 bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
877 * Wake up allocator in case it was waiting for buckets
878 * because of not being able to inc gens
880 for_each_member_device(ca, c, i)
881 bch2_wake_allocator(ca);
884 * At startup, allocations can happen directly instead of via the
885 * allocator thread - issue wakeup in case they blocked on gc_lock:
887 closure_wake_up(&c->freelist_wait);
892 * For recalculating oldest gen, we only need to walk keys in leaf nodes; btree
893 * node pointers currently never have cached pointers that can become stale:
895 static int bch2_gc_btree_gens(struct bch_fs *c, enum btree_id id)
897 struct btree_trans trans;
898 struct btree_iter *iter;
902 bch2_trans_init(&trans, c, 0, 0);
904 for_each_btree_key(&trans, iter, id, POS_MIN, BTREE_ITER_PREFETCH, k, ret) {
905 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
906 const struct bch_extent_ptr *ptr;
908 percpu_down_read(&c->mark_lock);
909 bkey_for_each_ptr(ptrs, ptr) {
910 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
911 struct bucket *g = PTR_BUCKET(ca, ptr, false);
913 if (gen_after(g->gc_gen, ptr->gen))
914 g->gc_gen = ptr->gen;
916 if (gen_after(g->mark.gen, ptr->gen) > 32) {
917 /* rewrite btree node */
921 percpu_up_read(&c->mark_lock);
924 bch2_trans_exit(&trans);
928 int bch2_gc_gens(struct bch_fs *c)
931 struct bucket_array *buckets;
937 * Ideally we would be using state_lock and not gc_lock here, but that
938 * introduces a deadlock in the RO path - we currently take the state
939 * lock at the start of going RO, thus the gc thread may get stuck:
941 down_read(&c->gc_lock);
943 for_each_member_device(ca, c, i) {
944 down_read(&ca->bucket_lock);
945 buckets = bucket_array(ca);
947 for_each_bucket(g, buckets)
948 g->gc_gen = g->mark.gen;
949 up_read(&ca->bucket_lock);
952 for (i = 0; i < BTREE_ID_NR; i++)
953 if (btree_node_type_needs_gc(i)) {
954 ret = bch2_gc_btree_gens(c, i);
956 bch_err(c, "error recalculating oldest_gen: %i", ret);
961 for_each_member_device(ca, c, i) {
962 down_read(&ca->bucket_lock);
963 buckets = bucket_array(ca);
965 for_each_bucket(g, buckets)
966 g->oldest_gen = g->gc_gen;
967 up_read(&ca->bucket_lock);
972 up_read(&c->gc_lock);
976 /* Btree coalescing */
978 static void recalc_packed_keys(struct btree *b)
980 struct bset *i = btree_bset_first(b);
981 struct bkey_packed *k;
983 memset(&b->nr, 0, sizeof(b->nr));
985 BUG_ON(b->nsets != 1);
987 vstruct_for_each(i, k)
988 btree_keys_account_key_add(&b->nr, 0, k);
991 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
992 struct btree *old_nodes[GC_MERGE_NODES])
994 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
995 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
996 unsigned blocks = btree_blocks(c) * 2 / 3;
997 struct btree *new_nodes[GC_MERGE_NODES];
998 struct btree_update *as;
999 struct keylist keylist;
1000 struct bkey_format_state format_state;
1001 struct bkey_format new_format;
1003 memset(new_nodes, 0, sizeof(new_nodes));
1004 bch2_keylist_init(&keylist, NULL);
1006 /* Count keys that are not deleted */
1007 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
1008 u64s += old_nodes[i]->nr.live_u64s;
1010 nr_old_nodes = nr_new_nodes = i;
1012 /* Check if all keys in @old_nodes could fit in one fewer node */
1013 if (nr_old_nodes <= 1 ||
1014 __vstruct_blocks(struct btree_node, c->block_bits,
1015 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
1018 /* Find a format that all keys in @old_nodes can pack into */
1019 bch2_bkey_format_init(&format_state);
1021 for (i = 0; i < nr_old_nodes; i++)
1022 __bch2_btree_calc_format(&format_state, old_nodes[i]);
1024 new_format = bch2_bkey_format_done(&format_state);
1026 /* Check if repacking would make any nodes too big to fit */
1027 for (i = 0; i < nr_old_nodes; i++)
1028 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
1029 trace_btree_gc_coalesce_fail(c,
1030 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
1034 if (bch2_keylist_realloc(&keylist, NULL, 0,
1035 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
1036 trace_btree_gc_coalesce_fail(c,
1037 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
1041 as = bch2_btree_update_start(iter->trans, iter->btree_id,
1042 btree_update_reserve_required(c, parent) + nr_old_nodes,
1043 BTREE_INSERT_NOFAIL|
1044 BTREE_INSERT_USE_RESERVE,
1047 trace_btree_gc_coalesce_fail(c,
1048 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
1049 bch2_keylist_free(&keylist, NULL);
1053 trace_btree_gc_coalesce(c, old_nodes[0]);
1055 for (i = 0; i < nr_old_nodes; i++)
1056 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
1058 /* Repack everything with @new_format and sort down to one bset */
1059 for (i = 0; i < nr_old_nodes; i++)
1061 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
1065 * Conceptually we concatenate the nodes together and slice them
1066 * up at different boundaries.
1068 for (i = nr_new_nodes - 1; i > 0; --i) {
1069 struct btree *n1 = new_nodes[i];
1070 struct btree *n2 = new_nodes[i - 1];
1072 struct bset *s1 = btree_bset_first(n1);
1073 struct bset *s2 = btree_bset_first(n2);
1074 struct bkey_packed *k, *last = NULL;
1076 /* Calculate how many keys from @n2 we could fit inside @n1 */
1080 k < vstruct_last(s2) &&
1081 vstruct_blocks_plus(n1->data, c->block_bits,
1082 u64s + k->u64s) <= blocks;
1083 k = bkey_next_skip_noops(k, vstruct_last(s2))) {
1088 if (u64s == le16_to_cpu(s2->u64s)) {
1089 /* n2 fits entirely in n1 */
1090 n1->key.k.p = n1->data->max_key = n2->data->max_key;
1092 memcpy_u64s(vstruct_last(s1),
1094 le16_to_cpu(s2->u64s));
1095 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
1097 set_btree_bset_end(n1, n1->set);
1099 six_unlock_write(&n2->c.lock);
1100 bch2_btree_node_free_never_inserted(c, n2);
1101 six_unlock_intent(&n2->c.lock);
1103 memmove(new_nodes + i - 1,
1105 sizeof(new_nodes[0]) * (nr_new_nodes - i));
1106 new_nodes[--nr_new_nodes] = NULL;
1108 /* move part of n2 into n1 */
1109 n1->key.k.p = n1->data->max_key =
1110 bkey_unpack_pos(n1, last);
1112 n2->data->min_key = bkey_successor(n1->data->max_key);
1114 memcpy_u64s(vstruct_last(s1),
1116 le16_add_cpu(&s1->u64s, u64s);
1119 vstruct_idx(s2, u64s),
1120 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
1121 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
1123 set_btree_bset_end(n1, n1->set);
1124 set_btree_bset_end(n2, n2->set);
1128 for (i = 0; i < nr_new_nodes; i++) {
1129 struct btree *n = new_nodes[i];
1131 recalc_packed_keys(n);
1132 btree_node_reset_sib_u64s(n);
1134 bch2_btree_build_aux_trees(n);
1136 bch2_btree_update_add_new_node(as, n);
1137 six_unlock_write(&n->c.lock);
1139 bch2_btree_node_write(c, n, SIX_LOCK_intent);
1143 * The keys for the old nodes get deleted. We don't want to insert keys
1144 * that compare equal to the keys for the new nodes we'll also be
1145 * inserting - we can't because keys on a keylist must be strictly
1146 * greater than the previous keys, and we also don't need to since the
1147 * key for the new node will serve the same purpose (overwriting the key
1148 * for the old node).
1150 for (i = 0; i < nr_old_nodes; i++) {
1151 struct bkey_i delete;
1154 for (j = 0; j < nr_new_nodes; j++)
1155 if (!bkey_cmp(old_nodes[i]->key.k.p,
1156 new_nodes[j]->key.k.p))
1159 bkey_init(&delete.k);
1160 delete.k.p = old_nodes[i]->key.k.p;
1161 bch2_keylist_add_in_order(&keylist, &delete);
1167 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
1168 * does the lookup once and thus expects the keys to be in sorted order
1169 * so we have to make sure the new keys are correctly ordered with
1170 * respect to the deleted keys added in the previous loop
1172 for (i = 0; i < nr_new_nodes; i++)
1173 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
1175 /* Insert the newly coalesced nodes */
1176 bch2_btree_insert_node(as, parent, iter, &keylist, 0);
1178 BUG_ON(!bch2_keylist_empty(&keylist));
1180 BUG_ON(iter->l[old_nodes[0]->c.level].b != old_nodes[0]);
1182 bch2_btree_iter_node_replace(iter, new_nodes[0]);
1184 for (i = 0; i < nr_new_nodes; i++)
1185 bch2_btree_update_get_open_buckets(as, new_nodes[i]);
1187 /* Free the old nodes and update our sliding window */
1188 for (i = 0; i < nr_old_nodes; i++) {
1189 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
1192 * the index update might have triggered a split, in which case
1193 * the nodes we coalesced - the new nodes we just created -
1194 * might not be sibling nodes anymore - don't add them to the
1195 * sliding window (except the first):
1198 old_nodes[i] = new_nodes[i];
1200 old_nodes[i] = NULL;
1204 for (i = 0; i < nr_new_nodes; i++)
1205 six_unlock_intent(&new_nodes[i]->c.lock);
1207 bch2_btree_update_done(as);
1208 bch2_keylist_free(&keylist, NULL);
1211 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
1213 struct btree_trans trans;
1214 struct btree_iter *iter;
1216 bool kthread = (current->flags & PF_KTHREAD) != 0;
1219 /* Sliding window of adjacent btree nodes */
1220 struct btree *merge[GC_MERGE_NODES];
1221 u32 lock_seq[GC_MERGE_NODES];
1223 bch2_trans_init(&trans, c, 0, 0);
1226 * XXX: We don't have a good way of positively matching on sibling nodes
1227 * that have the same parent - this code works by handling the cases
1228 * where they might not have the same parent, and is thus fragile. Ugh.
1230 * Perhaps redo this to use multiple linked iterators?
1232 memset(merge, 0, sizeof(merge));
1234 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1236 BTREE_ITER_PREFETCH, b) {
1237 memmove(merge + 1, merge,
1238 sizeof(merge) - sizeof(merge[0]));
1239 memmove(lock_seq + 1, lock_seq,
1240 sizeof(lock_seq) - sizeof(lock_seq[0]));
1244 for (i = 1; i < GC_MERGE_NODES; i++) {
1246 !six_relock_intent(&merge[i]->c.lock, lock_seq[i]))
1249 if (merge[i]->c.level != merge[0]->c.level) {
1250 six_unlock_intent(&merge[i]->c.lock);
1254 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
1256 bch2_coalesce_nodes(c, iter, merge);
1258 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
1259 lock_seq[i] = merge[i]->c.lock.state.seq;
1260 six_unlock_intent(&merge[i]->c.lock);
1263 lock_seq[0] = merge[0]->c.lock.state.seq;
1265 if (kthread && kthread_should_stop()) {
1266 bch2_trans_exit(&trans);
1270 bch2_trans_cond_resched(&trans);
1273 * If the parent node wasn't relocked, it might have been split
1274 * and the nodes in our sliding window might not have the same
1275 * parent anymore - blow away the sliding window:
1277 if (btree_iter_node(iter, iter->level + 1) &&
1278 !btree_node_intent_locked(iter, iter->level + 1))
1279 memset(merge + 1, 0,
1280 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
1282 return bch2_trans_exit(&trans);
1286 * bch_coalesce - coalesce adjacent nodes with low occupancy
1288 void bch2_coalesce(struct bch_fs *c)
1292 down_read(&c->gc_lock);
1293 trace_gc_coalesce_start(c);
1295 for (id = 0; id < BTREE_ID_NR; id++) {
1296 int ret = c->btree_roots[id].b
1297 ? bch2_coalesce_btree(c, id)
1301 if (ret != -ESHUTDOWN)
1302 bch_err(c, "btree coalescing failed: %d", ret);
1307 trace_gc_coalesce_end(c);
1308 up_read(&c->gc_lock);
1311 static int bch2_gc_thread(void *arg)
1313 struct bch_fs *c = arg;
1314 struct io_clock *clock = &c->io_clock[WRITE];
1315 unsigned long last = atomic_long_read(&clock->now);
1316 unsigned last_kick = atomic_read(&c->kick_gc);
1323 set_current_state(TASK_INTERRUPTIBLE);
1325 if (kthread_should_stop()) {
1326 __set_current_state(TASK_RUNNING);
1330 if (atomic_read(&c->kick_gc) != last_kick)
1333 if (c->btree_gc_periodic) {
1334 unsigned long next = last + c->capacity / 16;
1336 if (atomic_long_read(&clock->now) >= next)
1339 bch2_io_clock_schedule_timeout(clock, next);
1346 __set_current_state(TASK_RUNNING);
1348 last = atomic_long_read(&clock->now);
1349 last_kick = atomic_read(&c->kick_gc);
1352 * Full gc is currently incompatible with btree key cache:
1355 ret = bch2_gc(c, NULL, false, false);
1357 ret = bch2_gc_gens(c);
1360 bch_err(c, "btree gc failed: %i", ret);
1362 debug_check_no_locks_held();
1368 void bch2_gc_thread_stop(struct bch_fs *c)
1370 struct task_struct *p;
1373 c->gc_thread = NULL;
1381 int bch2_gc_thread_start(struct bch_fs *c)
1383 struct task_struct *p;
1385 BUG_ON(c->gc_thread);
1387 p = kthread_create(bch2_gc_thread, c, "bch_gc");