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, false), 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 bch2_stripes_heap_insert(c, dst, dst_iter.pos);
623 genradix_iter_advance(&dst_iter, &c->stripes[0]);
624 genradix_iter_advance(&src_iter, &c->stripes[1]);
628 for_each_member_device(ca, c, i) {
629 struct bucket_array *dst = __bucket_array(ca, 0);
630 struct bucket_array *src = __bucket_array(ca, 1);
633 for (b = 0; b < src->nbuckets; b++) {
634 copy_bucket_field(gen);
635 copy_bucket_field(data_type);
636 copy_bucket_field(owned_by_allocator);
637 copy_bucket_field(stripe);
638 copy_bucket_field(dirty_sectors);
639 copy_bucket_field(cached_sectors);
641 dst->b[b].oldest_gen = src->b[b].oldest_gen;
645 bch2_fs_usage_acc_to_base(c, 0);
646 bch2_fs_usage_acc_to_base(c, 1);
648 bch2_dev_usage_from_buckets(c);
651 unsigned nr = fs_usage_u64s(c);
652 struct bch_fs_usage *dst = c->usage_base;
653 struct bch_fs_usage *src = (void *)
654 bch2_acc_percpu_u64s((void *) c->usage_gc, nr);
656 copy_fs_field(hidden, "hidden");
657 copy_fs_field(btree, "btree");
659 if (!metadata_only) {
660 copy_fs_field(data, "data");
661 copy_fs_field(cached, "cached");
662 copy_fs_field(reserved, "reserved");
663 copy_fs_field(nr_inodes,"nr_inodes");
665 for (i = 0; i < BCH_REPLICAS_MAX; i++)
666 copy_fs_field(persistent_reserved[i],
667 "persistent_reserved[%i]", i);
670 for (i = 0; i < c->replicas.nr; i++) {
671 struct bch_replicas_entry *e =
672 cpu_replicas_entry(&c->replicas, i);
676 (e->data_type == BCH_DATA_USER ||
677 e->data_type == BCH_DATA_CACHED))
680 bch2_replicas_entry_to_text(&PBUF(buf), e);
682 copy_fs_field(replicas[i], "%s", buf);
687 #undef copy_dev_field
688 #undef copy_bucket_field
689 #undef copy_stripe_field
695 static int bch2_gc_start(struct bch_fs *c,
704 c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
705 sizeof(u64), GFP_KERNEL);
707 bch_err(c, "error allocating c->usage_gc");
711 for_each_member_device(ca, c, i) {
712 BUG_ON(ca->buckets[1]);
713 BUG_ON(ca->usage[1]);
715 ca->buckets[1] = kvpmalloc(sizeof(struct bucket_array) +
716 ca->mi.nbuckets * sizeof(struct bucket),
717 GFP_KERNEL|__GFP_ZERO);
718 if (!ca->buckets[1]) {
719 percpu_ref_put(&ca->ref);
720 bch_err(c, "error allocating ca->buckets[gc]");
724 ca->usage[1] = alloc_percpu(struct bch_dev_usage);
726 bch_err(c, "error allocating ca->usage[gc]");
727 percpu_ref_put(&ca->ref);
732 ret = bch2_ec_mem_alloc(c, true);
734 bch_err(c, "error allocating ec gc mem");
738 percpu_down_write(&c->mark_lock);
741 * indicate to stripe code that we need to allocate for the gc stripes
744 gc_pos_set(c, gc_phase(GC_PHASE_START));
746 for_each_member_device(ca, c, i) {
747 struct bucket_array *dst = __bucket_array(ca, 1);
748 struct bucket_array *src = __bucket_array(ca, 0);
751 dst->first_bucket = src->first_bucket;
752 dst->nbuckets = src->nbuckets;
754 for (b = 0; b < src->nbuckets; b++) {
755 struct bucket *d = &dst->b[b];
756 struct bucket *s = &src->b[b];
758 d->_mark.gen = dst->b[b].oldest_gen = s->mark.gen;
759 d->gen_valid = s->gen_valid;
762 (s->mark.data_type == BCH_DATA_USER ||
763 s->mark.data_type == BCH_DATA_CACHED)) {
765 d->_mark.owned_by_allocator = 0;
770 percpu_up_write(&c->mark_lock);
776 * bch2_gc - walk _all_ references to buckets, and recompute them:
778 * Order matters here:
779 * - Concurrent GC relies on the fact that we have a total ordering for
780 * everything that GC walks - see gc_will_visit_node(),
781 * gc_will_visit_root()
783 * - also, references move around in the course of index updates and
784 * various other crap: everything needs to agree on the ordering
785 * references are allowed to move around in - e.g., we're allowed to
786 * start with a reference owned by an open_bucket (the allocator) and
787 * move it to the btree, but not the reverse.
789 * This is necessary to ensure that gc doesn't miss references that
790 * move around - if references move backwards in the ordering GC
791 * uses, GC could skip past them
793 int bch2_gc(struct bch_fs *c, struct journal_keys *journal_keys,
794 bool initial, bool metadata_only)
797 u64 start_time = local_clock();
798 unsigned i, iter = 0;
801 lockdep_assert_held(&c->state_lock);
804 down_write(&c->gc_lock);
806 /* flush interior btree updates: */
807 closure_wait_event(&c->btree_interior_update_wait,
808 !bch2_btree_interior_updates_nr_pending(c));
810 ret = bch2_gc_start(c, metadata_only);
814 bch2_mark_superblocks(c);
816 ret = bch2_gc_btrees(c, journal_keys, initial, metadata_only);
821 bch2_mark_pending_btree_node_frees(c);
823 bch2_mark_allocator_buckets(c);
828 (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
829 (!iter && test_restart_gc(c)))) {
831 * XXX: make sure gens we fixed got saved
834 bch_info(c, "Fixed gens, restarting mark and sweep:");
835 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
836 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
838 percpu_down_write(&c->mark_lock);
840 percpu_up_write(&c->mark_lock);
841 /* flush fsck errors, reset counters */
842 bch2_flush_fsck_errs(c);
847 bch_info(c, "Unable to fix bucket gens, looping");
852 bch2_journal_block(&c->journal);
854 percpu_down_write(&c->mark_lock);
855 ret = bch2_gc_done(c, initial, metadata_only);
857 bch2_journal_unblock(&c->journal);
859 percpu_down_write(&c->mark_lock);
862 /* Indicates that gc is no longer in progress: */
863 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
866 percpu_up_write(&c->mark_lock);
868 up_write(&c->gc_lock);
871 bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
874 * Wake up allocator in case it was waiting for buckets
875 * because of not being able to inc gens
877 for_each_member_device(ca, c, i)
878 bch2_wake_allocator(ca);
881 * At startup, allocations can happen directly instead of via the
882 * allocator thread - issue wakeup in case they blocked on gc_lock:
884 closure_wake_up(&c->freelist_wait);
889 * For recalculating oldest gen, we only need to walk keys in leaf nodes; btree
890 * node pointers currently never have cached pointers that can become stale:
892 static int bch2_gc_btree_gens(struct bch_fs *c, enum btree_id id)
894 struct btree_trans trans;
895 struct btree_iter *iter;
899 bch2_trans_init(&trans, c, 0, 0);
901 for_each_btree_key(&trans, iter, id, POS_MIN, BTREE_ITER_PREFETCH, k, ret) {
902 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
903 const struct bch_extent_ptr *ptr;
905 bkey_for_each_ptr(ptrs, ptr) {
906 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
907 struct bucket *g = PTR_BUCKET(ca, ptr, false);
909 if (gen_after(g->gc_gen, ptr->gen))
910 g->gc_gen = ptr->gen;
912 if (gen_after(g->mark.gen, ptr->gen) > 32) {
913 /* rewrite btree node */
919 bch2_trans_exit(&trans);
923 int bch2_gc_gens(struct bch_fs *c)
929 down_read(&c->state_lock);
931 for_each_member_device(ca, c, i) {
932 struct bucket_array *buckets = bucket_array(ca);
935 for_each_bucket(g, buckets)
936 g->gc_gen = g->mark.gen;
939 for (i = 0; i < BTREE_ID_NR; i++)
940 if (btree_node_type_needs_gc(i)) {
941 ret = bch2_gc_btree_gens(c, i);
946 for_each_member_device(ca, c, i) {
947 struct bucket_array *buckets = bucket_array(ca);
950 for_each_bucket(g, buckets)
951 g->oldest_gen = g->gc_gen;
954 up_read(&c->state_lock);
958 /* Btree coalescing */
960 static void recalc_packed_keys(struct btree *b)
962 struct bset *i = btree_bset_first(b);
963 struct bkey_packed *k;
965 memset(&b->nr, 0, sizeof(b->nr));
967 BUG_ON(b->nsets != 1);
969 vstruct_for_each(i, k)
970 btree_keys_account_key_add(&b->nr, 0, k);
973 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
974 struct btree *old_nodes[GC_MERGE_NODES])
976 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
977 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
978 unsigned blocks = btree_blocks(c) * 2 / 3;
979 struct btree *new_nodes[GC_MERGE_NODES];
980 struct btree_update *as;
981 struct keylist keylist;
982 struct bkey_format_state format_state;
983 struct bkey_format new_format;
985 memset(new_nodes, 0, sizeof(new_nodes));
986 bch2_keylist_init(&keylist, NULL);
988 /* Count keys that are not deleted */
989 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
990 u64s += old_nodes[i]->nr.live_u64s;
992 nr_old_nodes = nr_new_nodes = i;
994 /* Check if all keys in @old_nodes could fit in one fewer node */
995 if (nr_old_nodes <= 1 ||
996 __vstruct_blocks(struct btree_node, c->block_bits,
997 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
1000 /* Find a format that all keys in @old_nodes can pack into */
1001 bch2_bkey_format_init(&format_state);
1003 for (i = 0; i < nr_old_nodes; i++)
1004 __bch2_btree_calc_format(&format_state, old_nodes[i]);
1006 new_format = bch2_bkey_format_done(&format_state);
1008 /* Check if repacking would make any nodes too big to fit */
1009 for (i = 0; i < nr_old_nodes; i++)
1010 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
1011 trace_btree_gc_coalesce_fail(c,
1012 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
1016 if (bch2_keylist_realloc(&keylist, NULL, 0,
1017 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
1018 trace_btree_gc_coalesce_fail(c,
1019 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
1023 as = bch2_btree_update_start(iter->trans, iter->btree_id,
1024 btree_update_reserve_required(c, parent) + nr_old_nodes,
1025 BTREE_INSERT_NOFAIL|
1026 BTREE_INSERT_USE_RESERVE,
1029 trace_btree_gc_coalesce_fail(c,
1030 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
1031 bch2_keylist_free(&keylist, NULL);
1035 trace_btree_gc_coalesce(c, old_nodes[0]);
1037 for (i = 0; i < nr_old_nodes; i++)
1038 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
1040 /* Repack everything with @new_format and sort down to one bset */
1041 for (i = 0; i < nr_old_nodes; i++)
1043 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
1047 * Conceptually we concatenate the nodes together and slice them
1048 * up at different boundaries.
1050 for (i = nr_new_nodes - 1; i > 0; --i) {
1051 struct btree *n1 = new_nodes[i];
1052 struct btree *n2 = new_nodes[i - 1];
1054 struct bset *s1 = btree_bset_first(n1);
1055 struct bset *s2 = btree_bset_first(n2);
1056 struct bkey_packed *k, *last = NULL;
1058 /* Calculate how many keys from @n2 we could fit inside @n1 */
1062 k < vstruct_last(s2) &&
1063 vstruct_blocks_plus(n1->data, c->block_bits,
1064 u64s + k->u64s) <= blocks;
1065 k = bkey_next_skip_noops(k, vstruct_last(s2))) {
1070 if (u64s == le16_to_cpu(s2->u64s)) {
1071 /* n2 fits entirely in n1 */
1072 n1->key.k.p = n1->data->max_key = n2->data->max_key;
1074 memcpy_u64s(vstruct_last(s1),
1076 le16_to_cpu(s2->u64s));
1077 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
1079 set_btree_bset_end(n1, n1->set);
1081 six_unlock_write(&n2->c.lock);
1082 bch2_btree_node_free_never_inserted(c, n2);
1083 six_unlock_intent(&n2->c.lock);
1085 memmove(new_nodes + i - 1,
1087 sizeof(new_nodes[0]) * (nr_new_nodes - i));
1088 new_nodes[--nr_new_nodes] = NULL;
1090 /* move part of n2 into n1 */
1091 n1->key.k.p = n1->data->max_key =
1092 bkey_unpack_pos(n1, last);
1094 n2->data->min_key = bkey_successor(n1->data->max_key);
1096 memcpy_u64s(vstruct_last(s1),
1098 le16_add_cpu(&s1->u64s, u64s);
1101 vstruct_idx(s2, u64s),
1102 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
1103 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
1105 set_btree_bset_end(n1, n1->set);
1106 set_btree_bset_end(n2, n2->set);
1110 for (i = 0; i < nr_new_nodes; i++) {
1111 struct btree *n = new_nodes[i];
1113 recalc_packed_keys(n);
1114 btree_node_reset_sib_u64s(n);
1116 bch2_btree_build_aux_trees(n);
1118 bch2_btree_update_add_new_node(as, n);
1119 six_unlock_write(&n->c.lock);
1121 bch2_btree_node_write(c, n, SIX_LOCK_intent);
1125 * The keys for the old nodes get deleted. We don't want to insert keys
1126 * that compare equal to the keys for the new nodes we'll also be
1127 * inserting - we can't because keys on a keylist must be strictly
1128 * greater than the previous keys, and we also don't need to since the
1129 * key for the new node will serve the same purpose (overwriting the key
1130 * for the old node).
1132 for (i = 0; i < nr_old_nodes; i++) {
1133 struct bkey_i delete;
1136 for (j = 0; j < nr_new_nodes; j++)
1137 if (!bkey_cmp(old_nodes[i]->key.k.p,
1138 new_nodes[j]->key.k.p))
1141 bkey_init(&delete.k);
1142 delete.k.p = old_nodes[i]->key.k.p;
1143 bch2_keylist_add_in_order(&keylist, &delete);
1149 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
1150 * does the lookup once and thus expects the keys to be in sorted order
1151 * so we have to make sure the new keys are correctly ordered with
1152 * respect to the deleted keys added in the previous loop
1154 for (i = 0; i < nr_new_nodes; i++)
1155 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
1157 /* Insert the newly coalesced nodes */
1158 bch2_btree_insert_node(as, parent, iter, &keylist, 0);
1160 BUG_ON(!bch2_keylist_empty(&keylist));
1162 BUG_ON(iter->l[old_nodes[0]->c.level].b != old_nodes[0]);
1164 bch2_btree_iter_node_replace(iter, new_nodes[0]);
1166 for (i = 0; i < nr_new_nodes; i++)
1167 bch2_btree_update_get_open_buckets(as, new_nodes[i]);
1169 /* Free the old nodes and update our sliding window */
1170 for (i = 0; i < nr_old_nodes; i++) {
1171 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
1174 * the index update might have triggered a split, in which case
1175 * the nodes we coalesced - the new nodes we just created -
1176 * might not be sibling nodes anymore - don't add them to the
1177 * sliding window (except the first):
1180 old_nodes[i] = new_nodes[i];
1182 old_nodes[i] = NULL;
1186 for (i = 0; i < nr_new_nodes; i++)
1187 six_unlock_intent(&new_nodes[i]->c.lock);
1189 bch2_btree_update_done(as);
1190 bch2_keylist_free(&keylist, NULL);
1193 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
1195 struct btree_trans trans;
1196 struct btree_iter *iter;
1198 bool kthread = (current->flags & PF_KTHREAD) != 0;
1201 /* Sliding window of adjacent btree nodes */
1202 struct btree *merge[GC_MERGE_NODES];
1203 u32 lock_seq[GC_MERGE_NODES];
1205 bch2_trans_init(&trans, c, 0, 0);
1208 * XXX: We don't have a good way of positively matching on sibling nodes
1209 * that have the same parent - this code works by handling the cases
1210 * where they might not have the same parent, and is thus fragile. Ugh.
1212 * Perhaps redo this to use multiple linked iterators?
1214 memset(merge, 0, sizeof(merge));
1216 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1218 BTREE_ITER_PREFETCH, b) {
1219 memmove(merge + 1, merge,
1220 sizeof(merge) - sizeof(merge[0]));
1221 memmove(lock_seq + 1, lock_seq,
1222 sizeof(lock_seq) - sizeof(lock_seq[0]));
1226 for (i = 1; i < GC_MERGE_NODES; i++) {
1228 !six_relock_intent(&merge[i]->c.lock, lock_seq[i]))
1231 if (merge[i]->c.level != merge[0]->c.level) {
1232 six_unlock_intent(&merge[i]->c.lock);
1236 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
1238 bch2_coalesce_nodes(c, iter, merge);
1240 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
1241 lock_seq[i] = merge[i]->c.lock.state.seq;
1242 six_unlock_intent(&merge[i]->c.lock);
1245 lock_seq[0] = merge[0]->c.lock.state.seq;
1247 if (kthread && kthread_should_stop()) {
1248 bch2_trans_exit(&trans);
1252 bch2_trans_cond_resched(&trans);
1255 * If the parent node wasn't relocked, it might have been split
1256 * and the nodes in our sliding window might not have the same
1257 * parent anymore - blow away the sliding window:
1259 if (btree_iter_node(iter, iter->level + 1) &&
1260 !btree_node_intent_locked(iter, iter->level + 1))
1261 memset(merge + 1, 0,
1262 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
1264 return bch2_trans_exit(&trans);
1268 * bch_coalesce - coalesce adjacent nodes with low occupancy
1270 void bch2_coalesce(struct bch_fs *c)
1274 down_read(&c->gc_lock);
1275 trace_gc_coalesce_start(c);
1277 for (id = 0; id < BTREE_ID_NR; id++) {
1278 int ret = c->btree_roots[id].b
1279 ? bch2_coalesce_btree(c, id)
1283 if (ret != -ESHUTDOWN)
1284 bch_err(c, "btree coalescing failed: %d", ret);
1289 trace_gc_coalesce_end(c);
1290 up_read(&c->gc_lock);
1293 static int bch2_gc_thread(void *arg)
1295 struct bch_fs *c = arg;
1296 struct io_clock *clock = &c->io_clock[WRITE];
1297 unsigned long last = atomic_long_read(&clock->now);
1298 unsigned last_kick = atomic_read(&c->kick_gc);
1305 set_current_state(TASK_INTERRUPTIBLE);
1307 if (kthread_should_stop()) {
1308 __set_current_state(TASK_RUNNING);
1312 if (atomic_read(&c->kick_gc) != last_kick)
1315 if (c->btree_gc_periodic) {
1316 unsigned long next = last + c->capacity / 16;
1318 if (atomic_long_read(&clock->now) >= next)
1321 bch2_io_clock_schedule_timeout(clock, next);
1328 __set_current_state(TASK_RUNNING);
1330 last = atomic_long_read(&clock->now);
1331 last_kick = atomic_read(&c->kick_gc);
1334 * Full gc is currently incompatible with btree key cache:
1337 ret = bch2_gc(c, NULL, false, false);
1339 ret = bch2_gc_gens(c);
1342 bch_err(c, "btree gc failed: %i", ret);
1344 debug_check_no_locks_held();
1350 void bch2_gc_thread_stop(struct bch_fs *c)
1352 struct task_struct *p;
1355 c->gc_thread = NULL;
1363 int bch2_gc_thread_start(struct bch_fs *c)
1365 struct task_struct *p;
1367 BUG_ON(c->gc_thread);
1369 p = kthread_create(bch2_gc_thread, c, "bch_gc");