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 "bkey_on_stack.h"
12 #include "btree_locking.h"
13 #include "btree_update_interior.h"
29 #include <linux/slab.h>
30 #include <linux/bitops.h>
31 #include <linux/freezer.h>
32 #include <linux/kthread.h>
33 #include <linux/preempt.h>
34 #include <linux/rcupdate.h>
35 #include <linux/sched/task.h>
36 #include <trace/events/bcachefs.h>
38 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
41 write_seqcount_begin(&c->gc_pos_lock);
43 write_seqcount_end(&c->gc_pos_lock);
47 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
49 BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
50 __gc_pos_set(c, new_pos);
53 static int bch2_gc_check_topology(struct bch_fs *c,
55 struct bpos *expected_start,
56 struct bpos expected_end,
61 if (k.k->type == KEY_TYPE_btree_ptr_v2) {
62 struct bkey_s_c_btree_ptr_v2 bp = bkey_s_c_to_btree_ptr_v2(k);
64 if (fsck_err_on(bkey_cmp(*expected_start, bp.v->min_key), c,
65 "btree node with incorrect min_key: got %llu:%llu, should be %llu:%llu",
68 expected_start->inode,
69 expected_start->offset)) {
74 *expected_start = bkey_cmp(k.k->p, POS_MAX)
75 ? bkey_successor(k.k->p)
78 if (fsck_err_on(is_last &&
79 bkey_cmp(k.k->p, expected_end), c,
80 "btree node with incorrect max_key: got %llu:%llu, should be %llu:%llu",
84 expected_end.offset)) {
91 /* marking of btree keys/nodes: */
93 static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
94 u8 *max_stale, bool initial)
96 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
97 const struct bch_extent_ptr *ptr;
100 (initial ? BTREE_TRIGGER_NOATOMIC : 0);
104 BUG_ON(journal_seq_verify(c) &&
105 k.k->version.lo > journal_cur_seq(&c->journal));
107 /* XXX change to fsck check */
108 if (fsck_err_on(k.k->version.lo > atomic64_read(&c->key_version), c,
109 "key version number higher than recorded: %llu > %llu",
111 atomic64_read(&c->key_version)))
112 atomic64_set(&c->key_version, k.k->version.lo);
114 if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
115 fsck_err_on(!bch2_bkey_replicas_marked(c, k), c,
116 "superblock not marked as containing replicas (type %u)",
118 ret = bch2_mark_bkey_replicas(c, k);
123 bkey_for_each_ptr(ptrs, ptr) {
124 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
125 struct bucket *g = PTR_BUCKET(ca, ptr, true);
126 struct bucket *g2 = PTR_BUCKET(ca, ptr, false);
128 if (mustfix_fsck_err_on(!g->gen_valid, c,
129 "bucket %u:%zu data type %s ptr gen %u missing in alloc btree",
130 ptr->dev, PTR_BUCKET_NR(ca, ptr),
131 bch2_data_types[ptr_data_type(k.k, ptr)],
133 g2->_mark.gen = g->_mark.gen = ptr->gen;
134 g2->gen_valid = g->gen_valid = true;
137 if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
138 "bucket %u:%zu data type %s ptr gen in the future: %u > %u",
139 ptr->dev, PTR_BUCKET_NR(ca, ptr),
140 bch2_data_types[ptr_data_type(k.k, ptr)],
141 ptr->gen, g->mark.gen)) {
142 g2->_mark.gen = g->_mark.gen = ptr->gen;
143 g2->gen_valid = g->gen_valid = true;
144 g2->_mark.data_type = 0;
145 g2->_mark.dirty_sectors = 0;
146 g2->_mark.cached_sectors = 0;
147 set_bit(BCH_FS_FIXED_GENS, &c->flags);
152 bkey_for_each_ptr(ptrs, ptr) {
153 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
154 struct bucket *g = PTR_BUCKET(ca, ptr, true);
156 if (gen_after(g->oldest_gen, ptr->gen))
157 g->oldest_gen = ptr->gen;
159 *max_stale = max(*max_stale, ptr_stale(ca, ptr));
162 bch2_mark_key(c, k, 0, k.k->size, NULL, 0, flags);
167 static int btree_gc_mark_node(struct bch_fs *c, struct btree *b, u8 *max_stale,
170 struct bpos next_node_start = b->data->min_key;
171 struct btree_node_iter iter;
172 struct bkey unpacked;
178 if (!btree_node_type_needs_gc(btree_node_type(b)))
181 bch2_btree_node_iter_init_from_start(&iter, b);
183 while ((k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked)).k) {
184 bch2_bkey_debugcheck(c, b, k);
186 ret = bch2_gc_mark_key(c, k, max_stale, initial);
190 bch2_btree_node_iter_advance(&iter, b);
193 ret = bch2_gc_check_topology(c, k,
196 bch2_btree_node_iter_end(&iter));
205 static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id,
206 bool initial, bool metadata_only)
208 struct btree_trans trans;
209 struct btree_iter *iter;
211 unsigned depth = metadata_only ? 1
212 : expensive_debug_checks(c) ? 0
213 : !btree_node_type_needs_gc(btree_id) ? 1
218 bch2_trans_init(&trans, c, 0, 0);
220 gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
222 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
223 0, depth, BTREE_ITER_PREFETCH, b) {
224 bch2_verify_btree_nr_keys(b);
226 gc_pos_set(c, gc_pos_btree_node(b));
228 ret = btree_gc_mark_node(c, b, &max_stale, initial);
234 bch2_btree_node_rewrite(c, iter,
236 BTREE_INSERT_USE_RESERVE|
238 BTREE_INSERT_GC_LOCK_HELD);
239 else if (!btree_gc_rewrite_disabled(c) &&
240 (btree_gc_always_rewrite(c) || max_stale > 16))
241 bch2_btree_node_rewrite(c, iter,
244 BTREE_INSERT_GC_LOCK_HELD);
247 bch2_trans_cond_resched(&trans);
249 ret = bch2_trans_exit(&trans) ?: ret;
253 mutex_lock(&c->btree_root_lock);
254 b = c->btree_roots[btree_id].b;
255 if (!btree_node_fake(b))
256 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
257 &max_stale, initial);
258 gc_pos_set(c, gc_pos_btree_root(b->c.btree_id));
259 mutex_unlock(&c->btree_root_lock);
264 static int bch2_gc_btree_init_recurse(struct bch_fs *c, struct btree *b,
265 struct journal_keys *journal_keys,
266 unsigned target_depth)
268 struct btree_and_journal_iter iter;
270 struct bpos next_node_start = b->data->min_key;
274 bch2_btree_and_journal_iter_init_node_iter(&iter, journal_keys, b);
276 while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
277 bch2_bkey_debugcheck(c, b, k);
279 BUG_ON(bkey_cmp(k.k->p, b->data->min_key) < 0);
280 BUG_ON(bkey_cmp(k.k->p, b->data->max_key) > 0);
282 ret = bch2_gc_mark_key(c, k, &max_stale, true);
290 bkey_reassemble(&tmp.k, k);
291 k = bkey_i_to_s_c(&tmp.k);
293 bch2_btree_and_journal_iter_advance(&iter);
295 ret = bch2_gc_check_topology(c, k,
298 !bch2_btree_and_journal_iter_peek(&iter).k);
302 if (b->c.level > target_depth) {
303 child = bch2_btree_node_get_noiter(c, &tmp.k,
304 b->c.btree_id, b->c.level - 1);
305 ret = PTR_ERR_OR_ZERO(child);
309 ret = bch2_gc_btree_init_recurse(c, child,
310 journal_keys, target_depth);
311 six_unlock_read(&child->c.lock);
317 bch2_btree_and_journal_iter_advance(&iter);
324 static int bch2_gc_btree_init(struct bch_fs *c,
325 struct journal_keys *journal_keys,
326 enum btree_id btree_id,
330 unsigned target_depth = metadata_only ? 1
331 : expensive_debug_checks(c) ? 0
332 : !btree_node_type_needs_gc(btree_id) ? 1
337 b = c->btree_roots[btree_id].b;
339 if (btree_node_fake(b))
342 six_lock_read(&b->c.lock, NULL, NULL);
343 if (fsck_err_on(bkey_cmp(b->data->min_key, POS_MIN), c,
344 "btree root with incorrect min_key: %llu:%llu",
345 b->data->min_key.inode,
346 b->data->min_key.offset)) {
350 if (fsck_err_on(bkey_cmp(b->data->max_key, POS_MAX), c,
351 "btree root with incorrect min_key: %llu:%llu",
352 b->data->max_key.inode,
353 b->data->max_key.offset)) {
357 if (b->c.level >= target_depth)
358 ret = bch2_gc_btree_init_recurse(c, b,
359 journal_keys, target_depth);
362 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
365 six_unlock_read(&b->c.lock);
370 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
372 return (int) btree_id_to_gc_phase(l) -
373 (int) btree_id_to_gc_phase(r);
376 static int bch2_gc_btrees(struct bch_fs *c, struct journal_keys *journal_keys,
377 bool initial, bool metadata_only)
379 enum btree_id ids[BTREE_ID_NR];
382 for (i = 0; i < BTREE_ID_NR; i++)
384 bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
386 for (i = 0; i < BTREE_ID_NR; i++) {
387 enum btree_id id = ids[i];
389 ? bch2_gc_btree_init(c, journal_keys,
391 : bch2_gc_btree(c, id, initial, metadata_only);
399 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
401 enum bch_data_type type,
404 u64 b = sector_to_bucket(ca, start);
408 min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
410 bch2_mark_metadata_bucket(c, ca, b, type, sectors,
411 gc_phase(GC_PHASE_SB), flags);
414 } while (start < end);
417 void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
420 struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
425 * This conditional is kind of gross, but we may be called from the
426 * device add path, before the new device has actually been added to the
427 * running filesystem:
430 lockdep_assert_held(&c->sb_lock);
431 percpu_down_read(&c->mark_lock);
434 for (i = 0; i < layout->nr_superblocks; i++) {
435 u64 offset = le64_to_cpu(layout->sb_offset[i]);
437 if (offset == BCH_SB_SECTOR)
438 mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
441 mark_metadata_sectors(c, ca, offset,
442 offset + (1 << layout->sb_max_size_bits),
446 for (i = 0; i < ca->journal.nr; i++) {
447 b = ca->journal.buckets[i];
448 bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_journal,
450 gc_phase(GC_PHASE_SB), flags);
454 percpu_up_read(&c->mark_lock);
457 static void bch2_mark_superblocks(struct bch_fs *c)
462 mutex_lock(&c->sb_lock);
463 gc_pos_set(c, gc_phase(GC_PHASE_SB));
465 for_each_online_member(ca, c, i)
466 bch2_mark_dev_superblock(c, ca, BTREE_TRIGGER_GC);
467 mutex_unlock(&c->sb_lock);
471 /* Also see bch2_pending_btree_node_free_insert_done() */
472 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
474 struct btree_update *as;
475 struct pending_btree_node_free *d;
477 mutex_lock(&c->btree_interior_update_lock);
478 gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
480 for_each_pending_btree_node_free(c, as, d)
481 if (d->index_update_done)
482 bch2_mark_key(c, bkey_i_to_s_c(&d->key),
486 mutex_unlock(&c->btree_interior_update_lock);
490 static void bch2_mark_allocator_buckets(struct bch_fs *c)
493 struct open_bucket *ob;
497 percpu_down_read(&c->mark_lock);
499 spin_lock(&c->freelist_lock);
500 gc_pos_set(c, gc_pos_alloc(c, NULL));
502 for_each_member_device(ca, c, ci) {
503 fifo_for_each_entry(i, &ca->free_inc, iter)
504 bch2_mark_alloc_bucket(c, ca, i, true,
505 gc_pos_alloc(c, NULL),
510 for (j = 0; j < RESERVE_NR; j++)
511 fifo_for_each_entry(i, &ca->free[j], iter)
512 bch2_mark_alloc_bucket(c, ca, i, true,
513 gc_pos_alloc(c, NULL),
517 spin_unlock(&c->freelist_lock);
519 for (ob = c->open_buckets;
520 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
522 spin_lock(&ob->lock);
524 gc_pos_set(c, gc_pos_alloc(c, ob));
525 ca = bch_dev_bkey_exists(c, ob->ptr.dev);
526 bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
530 spin_unlock(&ob->lock);
533 percpu_up_read(&c->mark_lock);
536 static void bch2_gc_free(struct bch_fs *c)
541 genradix_free(&c->stripes[1]);
543 for_each_member_device(ca, c, i) {
544 kvpfree(rcu_dereference_protected(ca->buckets[1], 1),
545 sizeof(struct bucket_array) +
546 ca->mi.nbuckets * sizeof(struct bucket));
547 ca->buckets[1] = NULL;
549 free_percpu(ca->usage[1]);
553 free_percpu(c->usage_gc);
557 static int bch2_gc_done(struct bch_fs *c,
558 bool initial, bool metadata_only)
561 bool verify = !metadata_only &&
563 (c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)));
567 #define copy_field(_f, _msg, ...) \
568 if (dst->_f != src->_f) { \
570 fsck_err(c, _msg ": got %llu, should be %llu" \
571 , ##__VA_ARGS__, dst->_f, src->_f); \
575 #define copy_stripe_field(_f, _msg, ...) \
576 if (dst->_f != src->_f) { \
578 fsck_err(c, "stripe %zu has wrong "_msg \
579 ": got %u, should be %u", \
580 dst_iter.pos, ##__VA_ARGS__, \
586 #define copy_bucket_field(_f) \
587 if (dst->b[b].mark._f != src->b[b].mark._f) { \
589 fsck_err(c, "bucket %u:%zu gen %u data type %s has wrong " #_f \
590 ": got %u, should be %u", i, b, \
591 dst->b[b].mark.gen, \
592 bch2_data_types[dst->b[b].mark.data_type],\
593 dst->b[b].mark._f, src->b[b].mark._f); \
594 dst->b[b]._mark._f = src->b[b].mark._f; \
597 #define copy_dev_field(_f, _msg, ...) \
598 copy_field(_f, "dev %u has wrong " _msg, i, ##__VA_ARGS__)
599 #define copy_fs_field(_f, _msg, ...) \
600 copy_field(_f, "fs has wrong " _msg, ##__VA_ARGS__)
602 if (!metadata_only) {
603 struct genradix_iter dst_iter = genradix_iter_init(&c->stripes[0], 0);
604 struct genradix_iter src_iter = genradix_iter_init(&c->stripes[1], 0);
605 struct stripe *dst, *src;
608 c->ec_stripes_heap.used = 0;
610 while ((dst = genradix_iter_peek(&dst_iter, &c->stripes[0])) &&
611 (src = genradix_iter_peek(&src_iter, &c->stripes[1]))) {
612 BUG_ON(src_iter.pos != dst_iter.pos);
614 copy_stripe_field(alive, "alive");
615 copy_stripe_field(sectors, "sectors");
616 copy_stripe_field(algorithm, "algorithm");
617 copy_stripe_field(nr_blocks, "nr_blocks");
618 copy_stripe_field(nr_redundant, "nr_redundant");
619 copy_stripe_field(blocks_nonempty,
622 for (i = 0; i < ARRAY_SIZE(dst->block_sectors); i++)
623 copy_stripe_field(block_sectors[i],
624 "block_sectors[%u]", i);
627 spin_lock(&c->ec_stripes_heap_lock);
628 bch2_stripes_heap_insert(c, dst, dst_iter.pos);
629 spin_unlock(&c->ec_stripes_heap_lock);
632 genradix_iter_advance(&dst_iter, &c->stripes[0]);
633 genradix_iter_advance(&src_iter, &c->stripes[1]);
637 for_each_member_device(ca, c, i) {
638 struct bucket_array *dst = __bucket_array(ca, 0);
639 struct bucket_array *src = __bucket_array(ca, 1);
642 for (b = 0; b < src->nbuckets; b++) {
643 copy_bucket_field(gen);
644 copy_bucket_field(data_type);
645 copy_bucket_field(owned_by_allocator);
646 copy_bucket_field(stripe);
647 copy_bucket_field(dirty_sectors);
648 copy_bucket_field(cached_sectors);
650 dst->b[b].oldest_gen = src->b[b].oldest_gen;
654 bch2_fs_usage_acc_to_base(c, 0);
655 bch2_fs_usage_acc_to_base(c, 1);
657 bch2_dev_usage_from_buckets(c);
660 unsigned nr = fs_usage_u64s(c);
661 struct bch_fs_usage *dst = c->usage_base;
662 struct bch_fs_usage *src = (void *)
663 bch2_acc_percpu_u64s((void *) c->usage_gc, nr);
665 copy_fs_field(hidden, "hidden");
666 copy_fs_field(btree, "btree");
668 if (!metadata_only) {
669 copy_fs_field(data, "data");
670 copy_fs_field(cached, "cached");
671 copy_fs_field(reserved, "reserved");
672 copy_fs_field(nr_inodes,"nr_inodes");
674 for (i = 0; i < BCH_REPLICAS_MAX; i++)
675 copy_fs_field(persistent_reserved[i],
676 "persistent_reserved[%i]", i);
679 for (i = 0; i < c->replicas.nr; i++) {
680 struct bch_replicas_entry *e =
681 cpu_replicas_entry(&c->replicas, i);
685 (e->data_type == BCH_DATA_user ||
686 e->data_type == BCH_DATA_cached))
689 bch2_replicas_entry_to_text(&PBUF(buf), e);
691 copy_fs_field(replicas[i], "%s", buf);
696 #undef copy_dev_field
697 #undef copy_bucket_field
698 #undef copy_stripe_field
704 static int bch2_gc_start(struct bch_fs *c,
713 c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
714 sizeof(u64), GFP_KERNEL);
716 bch_err(c, "error allocating c->usage_gc");
720 for_each_member_device(ca, c, i) {
721 BUG_ON(ca->buckets[1]);
722 BUG_ON(ca->usage[1]);
724 ca->buckets[1] = kvpmalloc(sizeof(struct bucket_array) +
725 ca->mi.nbuckets * sizeof(struct bucket),
726 GFP_KERNEL|__GFP_ZERO);
727 if (!ca->buckets[1]) {
728 percpu_ref_put(&ca->ref);
729 bch_err(c, "error allocating ca->buckets[gc]");
733 ca->usage[1] = alloc_percpu(struct bch_dev_usage);
735 bch_err(c, "error allocating ca->usage[gc]");
736 percpu_ref_put(&ca->ref);
741 ret = bch2_ec_mem_alloc(c, true);
743 bch_err(c, "error allocating ec gc mem");
747 percpu_down_write(&c->mark_lock);
750 * indicate to stripe code that we need to allocate for the gc stripes
753 gc_pos_set(c, gc_phase(GC_PHASE_START));
755 for_each_member_device(ca, c, i) {
756 struct bucket_array *dst = __bucket_array(ca, 1);
757 struct bucket_array *src = __bucket_array(ca, 0);
760 dst->first_bucket = src->first_bucket;
761 dst->nbuckets = src->nbuckets;
763 for (b = 0; b < src->nbuckets; b++) {
764 struct bucket *d = &dst->b[b];
765 struct bucket *s = &src->b[b];
767 d->_mark.gen = dst->b[b].oldest_gen = s->mark.gen;
768 d->gen_valid = s->gen_valid;
771 (s->mark.data_type == BCH_DATA_user ||
772 s->mark.data_type == BCH_DATA_cached)) {
774 d->_mark.owned_by_allocator = 0;
779 percpu_up_write(&c->mark_lock);
785 * bch2_gc - walk _all_ references to buckets, and recompute them:
787 * Order matters here:
788 * - Concurrent GC relies on the fact that we have a total ordering for
789 * everything that GC walks - see gc_will_visit_node(),
790 * gc_will_visit_root()
792 * - also, references move around in the course of index updates and
793 * various other crap: everything needs to agree on the ordering
794 * references are allowed to move around in - e.g., we're allowed to
795 * start with a reference owned by an open_bucket (the allocator) and
796 * move it to the btree, but not the reverse.
798 * This is necessary to ensure that gc doesn't miss references that
799 * move around - if references move backwards in the ordering GC
800 * uses, GC could skip past them
802 int bch2_gc(struct bch_fs *c, struct journal_keys *journal_keys,
803 bool initial, bool metadata_only)
806 u64 start_time = local_clock();
807 unsigned i, iter = 0;
810 lockdep_assert_held(&c->state_lock);
813 down_write(&c->gc_lock);
815 /* flush interior btree updates: */
816 closure_wait_event(&c->btree_interior_update_wait,
817 !bch2_btree_interior_updates_nr_pending(c));
819 ret = bch2_gc_start(c, metadata_only);
823 bch2_mark_superblocks(c);
825 ret = bch2_gc_btrees(c, journal_keys, initial, metadata_only);
830 bch2_mark_pending_btree_node_frees(c);
832 bch2_mark_allocator_buckets(c);
837 (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
838 (!iter && test_restart_gc(c)))) {
840 * XXX: make sure gens we fixed got saved
843 bch_info(c, "Fixed gens, restarting mark and sweep:");
844 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
845 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
847 percpu_down_write(&c->mark_lock);
849 percpu_up_write(&c->mark_lock);
850 /* flush fsck errors, reset counters */
851 bch2_flush_fsck_errs(c);
856 bch_info(c, "Unable to fix bucket gens, looping");
861 bch2_journal_block(&c->journal);
863 percpu_down_write(&c->mark_lock);
864 ret = bch2_gc_done(c, initial, metadata_only);
866 bch2_journal_unblock(&c->journal);
868 percpu_down_write(&c->mark_lock);
871 /* Indicates that gc is no longer in progress: */
872 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
875 percpu_up_write(&c->mark_lock);
877 up_write(&c->gc_lock);
880 bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
883 * Wake up allocator in case it was waiting for buckets
884 * because of not being able to inc gens
886 for_each_member_device(ca, c, i)
887 bch2_wake_allocator(ca);
890 * At startup, allocations can happen directly instead of via the
891 * allocator thread - issue wakeup in case they blocked on gc_lock:
893 closure_wake_up(&c->freelist_wait);
897 static bool gc_btree_gens_key(struct bch_fs *c, struct bkey_s_c k)
899 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
900 const struct bch_extent_ptr *ptr;
902 percpu_down_read(&c->mark_lock);
903 bkey_for_each_ptr(ptrs, ptr) {
904 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
905 struct bucket *g = PTR_BUCKET(ca, ptr, false);
907 if (gen_after(g->mark.gen, ptr->gen) > 16) {
908 percpu_up_read(&c->mark_lock);
913 bkey_for_each_ptr(ptrs, ptr) {
914 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
915 struct bucket *g = PTR_BUCKET(ca, ptr, false);
917 if (gen_after(g->gc_gen, ptr->gen))
918 g->gc_gen = ptr->gen;
920 percpu_up_read(&c->mark_lock);
926 * For recalculating oldest gen, we only need to walk keys in leaf nodes; btree
927 * node pointers currently never have cached pointers that can become stale:
929 static int bch2_gc_btree_gens(struct bch_fs *c, enum btree_id btree_id)
931 struct btree_trans trans;
932 struct btree_iter *iter;
934 struct bkey_on_stack sk;
937 bkey_on_stack_init(&sk);
938 bch2_trans_init(&trans, c, 0, 0);
940 iter = bch2_trans_get_iter(&trans, btree_id, POS_MIN,
941 BTREE_ITER_PREFETCH);
943 while ((k = bch2_btree_iter_peek(iter)).k &&
944 !(ret = bkey_err(k))) {
945 if (gc_btree_gens_key(c, k)) {
946 bkey_on_stack_reassemble(&sk, c, k);
947 bch2_extent_normalize(c, bkey_i_to_s(sk.k));
949 bch2_btree_iter_set_pos(iter, bkey_start_pos(&sk.k->k));
951 bch2_trans_update(&trans, iter, sk.k, 0);
953 ret = bch2_trans_commit(&trans, NULL, NULL,
954 BTREE_INSERT_NOFAIL);
962 bch2_btree_iter_next(iter);
965 bch2_trans_exit(&trans);
966 bkey_on_stack_exit(&sk, c);
971 int bch2_gc_gens(struct bch_fs *c)
974 struct bucket_array *buckets;
980 * Ideally we would be using state_lock and not gc_lock here, but that
981 * introduces a deadlock in the RO path - we currently take the state
982 * lock at the start of going RO, thus the gc thread may get stuck:
984 down_read(&c->gc_lock);
986 for_each_member_device(ca, c, i) {
987 down_read(&ca->bucket_lock);
988 buckets = bucket_array(ca);
990 for_each_bucket(g, buckets)
991 g->gc_gen = g->mark.gen;
992 up_read(&ca->bucket_lock);
995 for (i = 0; i < BTREE_ID_NR; i++)
996 if (btree_node_type_needs_gc(i)) {
997 ret = bch2_gc_btree_gens(c, i);
999 bch_err(c, "error recalculating oldest_gen: %i", ret);
1004 for_each_member_device(ca, c, i) {
1005 down_read(&ca->bucket_lock);
1006 buckets = bucket_array(ca);
1008 for_each_bucket(g, buckets)
1009 g->oldest_gen = g->gc_gen;
1010 up_read(&ca->bucket_lock);
1015 up_read(&c->gc_lock);
1019 /* Btree coalescing */
1021 static void recalc_packed_keys(struct btree *b)
1023 struct bset *i = btree_bset_first(b);
1024 struct bkey_packed *k;
1026 memset(&b->nr, 0, sizeof(b->nr));
1028 BUG_ON(b->nsets != 1);
1030 vstruct_for_each(i, k)
1031 btree_keys_account_key_add(&b->nr, 0, k);
1034 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
1035 struct btree *old_nodes[GC_MERGE_NODES])
1037 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
1038 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
1039 unsigned blocks = btree_blocks(c) * 2 / 3;
1040 struct btree *new_nodes[GC_MERGE_NODES];
1041 struct btree_update *as;
1042 struct keylist keylist;
1043 struct bkey_format_state format_state;
1044 struct bkey_format new_format;
1046 memset(new_nodes, 0, sizeof(new_nodes));
1047 bch2_keylist_init(&keylist, NULL);
1049 /* Count keys that are not deleted */
1050 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
1051 u64s += old_nodes[i]->nr.live_u64s;
1053 nr_old_nodes = nr_new_nodes = i;
1055 /* Check if all keys in @old_nodes could fit in one fewer node */
1056 if (nr_old_nodes <= 1 ||
1057 __vstruct_blocks(struct btree_node, c->block_bits,
1058 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
1061 /* Find a format that all keys in @old_nodes can pack into */
1062 bch2_bkey_format_init(&format_state);
1064 for (i = 0; i < nr_old_nodes; i++)
1065 __bch2_btree_calc_format(&format_state, old_nodes[i]);
1067 new_format = bch2_bkey_format_done(&format_state);
1069 /* Check if repacking would make any nodes too big to fit */
1070 for (i = 0; i < nr_old_nodes; i++)
1071 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
1072 trace_btree_gc_coalesce_fail(c,
1073 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
1077 if (bch2_keylist_realloc(&keylist, NULL, 0,
1078 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
1079 trace_btree_gc_coalesce_fail(c,
1080 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
1084 as = bch2_btree_update_start(iter->trans, iter->btree_id,
1085 btree_update_reserve_required(c, parent) + nr_old_nodes,
1086 BTREE_INSERT_NOFAIL|
1087 BTREE_INSERT_USE_RESERVE,
1090 trace_btree_gc_coalesce_fail(c,
1091 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
1092 bch2_keylist_free(&keylist, NULL);
1096 trace_btree_gc_coalesce(c, old_nodes[0]);
1098 for (i = 0; i < nr_old_nodes; i++)
1099 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
1101 /* Repack everything with @new_format and sort down to one bset */
1102 for (i = 0; i < nr_old_nodes; i++)
1104 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
1108 * Conceptually we concatenate the nodes together and slice them
1109 * up at different boundaries.
1111 for (i = nr_new_nodes - 1; i > 0; --i) {
1112 struct btree *n1 = new_nodes[i];
1113 struct btree *n2 = new_nodes[i - 1];
1115 struct bset *s1 = btree_bset_first(n1);
1116 struct bset *s2 = btree_bset_first(n2);
1117 struct bkey_packed *k, *last = NULL;
1119 /* Calculate how many keys from @n2 we could fit inside @n1 */
1123 k < vstruct_last(s2) &&
1124 vstruct_blocks_plus(n1->data, c->block_bits,
1125 u64s + k->u64s) <= blocks;
1126 k = bkey_next_skip_noops(k, vstruct_last(s2))) {
1131 if (u64s == le16_to_cpu(s2->u64s)) {
1132 /* n2 fits entirely in n1 */
1133 n1->key.k.p = n1->data->max_key = n2->data->max_key;
1135 memcpy_u64s(vstruct_last(s1),
1137 le16_to_cpu(s2->u64s));
1138 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
1140 set_btree_bset_end(n1, n1->set);
1142 six_unlock_write(&n2->c.lock);
1143 bch2_btree_node_free_never_inserted(c, n2);
1144 six_unlock_intent(&n2->c.lock);
1146 memmove(new_nodes + i - 1,
1148 sizeof(new_nodes[0]) * (nr_new_nodes - i));
1149 new_nodes[--nr_new_nodes] = NULL;
1151 /* move part of n2 into n1 */
1152 n1->key.k.p = n1->data->max_key =
1153 bkey_unpack_pos(n1, last);
1155 n2->data->min_key = bkey_successor(n1->data->max_key);
1157 memcpy_u64s(vstruct_last(s1),
1159 le16_add_cpu(&s1->u64s, u64s);
1162 vstruct_idx(s2, u64s),
1163 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
1164 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
1166 set_btree_bset_end(n1, n1->set);
1167 set_btree_bset_end(n2, n2->set);
1171 for (i = 0; i < nr_new_nodes; i++) {
1172 struct btree *n = new_nodes[i];
1174 recalc_packed_keys(n);
1175 btree_node_reset_sib_u64s(n);
1177 bch2_btree_build_aux_trees(n);
1179 bch2_btree_update_add_new_node(as, n);
1180 six_unlock_write(&n->c.lock);
1182 bch2_btree_node_write(c, n, SIX_LOCK_intent);
1186 * The keys for the old nodes get deleted. We don't want to insert keys
1187 * that compare equal to the keys for the new nodes we'll also be
1188 * inserting - we can't because keys on a keylist must be strictly
1189 * greater than the previous keys, and we also don't need to since the
1190 * key for the new node will serve the same purpose (overwriting the key
1191 * for the old node).
1193 for (i = 0; i < nr_old_nodes; i++) {
1194 struct bkey_i delete;
1197 for (j = 0; j < nr_new_nodes; j++)
1198 if (!bkey_cmp(old_nodes[i]->key.k.p,
1199 new_nodes[j]->key.k.p))
1202 bkey_init(&delete.k);
1203 delete.k.p = old_nodes[i]->key.k.p;
1204 bch2_keylist_add_in_order(&keylist, &delete);
1210 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
1211 * does the lookup once and thus expects the keys to be in sorted order
1212 * so we have to make sure the new keys are correctly ordered with
1213 * respect to the deleted keys added in the previous loop
1215 for (i = 0; i < nr_new_nodes; i++)
1216 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
1218 /* Insert the newly coalesced nodes */
1219 bch2_btree_insert_node(as, parent, iter, &keylist, 0);
1221 BUG_ON(!bch2_keylist_empty(&keylist));
1223 BUG_ON(iter->l[old_nodes[0]->c.level].b != old_nodes[0]);
1225 bch2_btree_iter_node_replace(iter, new_nodes[0]);
1227 for (i = 0; i < nr_new_nodes; i++)
1228 bch2_btree_update_get_open_buckets(as, new_nodes[i]);
1230 /* Free the old nodes and update our sliding window */
1231 for (i = 0; i < nr_old_nodes; i++) {
1232 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
1235 * the index update might have triggered a split, in which case
1236 * the nodes we coalesced - the new nodes we just created -
1237 * might not be sibling nodes anymore - don't add them to the
1238 * sliding window (except the first):
1241 old_nodes[i] = new_nodes[i];
1243 old_nodes[i] = NULL;
1247 for (i = 0; i < nr_new_nodes; i++)
1248 six_unlock_intent(&new_nodes[i]->c.lock);
1250 bch2_btree_update_done(as);
1251 bch2_keylist_free(&keylist, NULL);
1254 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
1256 struct btree_trans trans;
1257 struct btree_iter *iter;
1259 bool kthread = (current->flags & PF_KTHREAD) != 0;
1262 /* Sliding window of adjacent btree nodes */
1263 struct btree *merge[GC_MERGE_NODES];
1264 u32 lock_seq[GC_MERGE_NODES];
1266 bch2_trans_init(&trans, c, 0, 0);
1269 * XXX: We don't have a good way of positively matching on sibling nodes
1270 * that have the same parent - this code works by handling the cases
1271 * where they might not have the same parent, and is thus fragile. Ugh.
1273 * Perhaps redo this to use multiple linked iterators?
1275 memset(merge, 0, sizeof(merge));
1277 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1279 BTREE_ITER_PREFETCH, b) {
1280 memmove(merge + 1, merge,
1281 sizeof(merge) - sizeof(merge[0]));
1282 memmove(lock_seq + 1, lock_seq,
1283 sizeof(lock_seq) - sizeof(lock_seq[0]));
1287 for (i = 1; i < GC_MERGE_NODES; i++) {
1289 !six_relock_intent(&merge[i]->c.lock, lock_seq[i]))
1292 if (merge[i]->c.level != merge[0]->c.level) {
1293 six_unlock_intent(&merge[i]->c.lock);
1297 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
1299 bch2_coalesce_nodes(c, iter, merge);
1301 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
1302 lock_seq[i] = merge[i]->c.lock.state.seq;
1303 six_unlock_intent(&merge[i]->c.lock);
1306 lock_seq[0] = merge[0]->c.lock.state.seq;
1308 if (kthread && kthread_should_stop()) {
1309 bch2_trans_exit(&trans);
1313 bch2_trans_cond_resched(&trans);
1316 * If the parent node wasn't relocked, it might have been split
1317 * and the nodes in our sliding window might not have the same
1318 * parent anymore - blow away the sliding window:
1320 if (btree_iter_node(iter, iter->level + 1) &&
1321 !btree_node_intent_locked(iter, iter->level + 1))
1322 memset(merge + 1, 0,
1323 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
1325 return bch2_trans_exit(&trans);
1329 * bch_coalesce - coalesce adjacent nodes with low occupancy
1331 void bch2_coalesce(struct bch_fs *c)
1335 down_read(&c->gc_lock);
1336 trace_gc_coalesce_start(c);
1338 for (id = 0; id < BTREE_ID_NR; id++) {
1339 int ret = c->btree_roots[id].b
1340 ? bch2_coalesce_btree(c, id)
1344 if (ret != -ESHUTDOWN)
1345 bch_err(c, "btree coalescing failed: %d", ret);
1350 trace_gc_coalesce_end(c);
1351 up_read(&c->gc_lock);
1354 static int bch2_gc_thread(void *arg)
1356 struct bch_fs *c = arg;
1357 struct io_clock *clock = &c->io_clock[WRITE];
1358 unsigned long last = atomic_long_read(&clock->now);
1359 unsigned last_kick = atomic_read(&c->kick_gc);
1366 set_current_state(TASK_INTERRUPTIBLE);
1368 if (kthread_should_stop()) {
1369 __set_current_state(TASK_RUNNING);
1373 if (atomic_read(&c->kick_gc) != last_kick)
1376 if (c->btree_gc_periodic) {
1377 unsigned long next = last + c->capacity / 16;
1379 if (atomic_long_read(&clock->now) >= next)
1382 bch2_io_clock_schedule_timeout(clock, next);
1389 __set_current_state(TASK_RUNNING);
1391 last = atomic_long_read(&clock->now);
1392 last_kick = atomic_read(&c->kick_gc);
1395 * Full gc is currently incompatible with btree key cache:
1398 ret = bch2_gc(c, NULL, false, false);
1400 ret = bch2_gc_gens(c);
1403 bch_err(c, "btree gc failed: %i", ret);
1405 debug_check_no_locks_held();
1411 void bch2_gc_thread_stop(struct bch_fs *c)
1413 struct task_struct *p;
1416 c->gc_thread = NULL;
1424 int bch2_gc_thread_start(struct bch_fs *c)
1426 struct task_struct *p;
1428 BUG_ON(c->gc_thread);
1430 p = kthread_create(bch2_gc_thread, c, "bch_gc");