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->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->level > target_depth) {
300 child = bch2_btree_node_get_noiter(c, &tmp.k,
301 b->btree_id, b->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->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->lock);
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->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->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;
803 down_write(&c->gc_lock);
805 /* flush interior btree updates: */
806 closure_wait_event(&c->btree_interior_update_wait,
807 !bch2_btree_interior_updates_nr_pending(c));
809 ret = bch2_gc_start(c, metadata_only);
813 bch2_mark_superblocks(c);
815 ret = bch2_gc_btrees(c, journal_keys, initial, metadata_only);
820 bch2_mark_pending_btree_node_frees(c);
822 bch2_mark_allocator_buckets(c);
827 (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
828 (!iter && test_restart_gc(c)))) {
830 * XXX: make sure gens we fixed got saved
833 bch_info(c, "Fixed gens, restarting mark and sweep:");
834 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
835 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
837 percpu_down_write(&c->mark_lock);
839 percpu_up_write(&c->mark_lock);
840 /* flush fsck errors, reset counters */
841 bch2_flush_fsck_errs(c);
846 bch_info(c, "Unable to fix bucket gens, looping");
851 bch2_journal_block(&c->journal);
853 percpu_down_write(&c->mark_lock);
854 ret = bch2_gc_done(c, initial, metadata_only);
856 bch2_journal_unblock(&c->journal);
858 percpu_down_write(&c->mark_lock);
861 /* Indicates that gc is no longer in progress: */
862 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
865 percpu_up_write(&c->mark_lock);
867 up_write(&c->gc_lock);
870 bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
873 * Wake up allocator in case it was waiting for buckets
874 * because of not being able to inc gens
876 for_each_member_device(ca, c, i)
877 bch2_wake_allocator(ca);
880 * At startup, allocations can happen directly instead of via the
881 * allocator thread - issue wakeup in case they blocked on gc_lock:
883 closure_wake_up(&c->freelist_wait);
887 /* Btree coalescing */
889 static void recalc_packed_keys(struct btree *b)
891 struct bset *i = btree_bset_first(b);
892 struct bkey_packed *k;
894 memset(&b->nr, 0, sizeof(b->nr));
896 BUG_ON(b->nsets != 1);
898 vstruct_for_each(i, k)
899 btree_keys_account_key_add(&b->nr, 0, k);
902 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
903 struct btree *old_nodes[GC_MERGE_NODES])
905 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
906 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
907 unsigned blocks = btree_blocks(c) * 2 / 3;
908 struct btree *new_nodes[GC_MERGE_NODES];
909 struct btree_update *as;
910 struct keylist keylist;
911 struct bkey_format_state format_state;
912 struct bkey_format new_format;
914 memset(new_nodes, 0, sizeof(new_nodes));
915 bch2_keylist_init(&keylist, NULL);
917 /* Count keys that are not deleted */
918 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
919 u64s += old_nodes[i]->nr.live_u64s;
921 nr_old_nodes = nr_new_nodes = i;
923 /* Check if all keys in @old_nodes could fit in one fewer node */
924 if (nr_old_nodes <= 1 ||
925 __vstruct_blocks(struct btree_node, c->block_bits,
926 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
929 /* Find a format that all keys in @old_nodes can pack into */
930 bch2_bkey_format_init(&format_state);
932 for (i = 0; i < nr_old_nodes; i++)
933 __bch2_btree_calc_format(&format_state, old_nodes[i]);
935 new_format = bch2_bkey_format_done(&format_state);
937 /* Check if repacking would make any nodes too big to fit */
938 for (i = 0; i < nr_old_nodes; i++)
939 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
940 trace_btree_gc_coalesce_fail(c,
941 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
945 if (bch2_keylist_realloc(&keylist, NULL, 0,
946 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
947 trace_btree_gc_coalesce_fail(c,
948 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
952 as = bch2_btree_update_start(iter->trans, iter->btree_id,
953 btree_update_reserve_required(c, parent) + nr_old_nodes,
955 BTREE_INSERT_USE_RESERVE,
958 trace_btree_gc_coalesce_fail(c,
959 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
960 bch2_keylist_free(&keylist, NULL);
964 trace_btree_gc_coalesce(c, old_nodes[0]);
966 for (i = 0; i < nr_old_nodes; i++)
967 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
969 /* Repack everything with @new_format and sort down to one bset */
970 for (i = 0; i < nr_old_nodes; i++)
972 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
976 * Conceptually we concatenate the nodes together and slice them
977 * up at different boundaries.
979 for (i = nr_new_nodes - 1; i > 0; --i) {
980 struct btree *n1 = new_nodes[i];
981 struct btree *n2 = new_nodes[i - 1];
983 struct bset *s1 = btree_bset_first(n1);
984 struct bset *s2 = btree_bset_first(n2);
985 struct bkey_packed *k, *last = NULL;
987 /* Calculate how many keys from @n2 we could fit inside @n1 */
991 k < vstruct_last(s2) &&
992 vstruct_blocks_plus(n1->data, c->block_bits,
993 u64s + k->u64s) <= blocks;
994 k = bkey_next_skip_noops(k, vstruct_last(s2))) {
999 if (u64s == le16_to_cpu(s2->u64s)) {
1000 /* n2 fits entirely in n1 */
1001 n1->key.k.p = n1->data->max_key = n2->data->max_key;
1003 memcpy_u64s(vstruct_last(s1),
1005 le16_to_cpu(s2->u64s));
1006 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
1008 set_btree_bset_end(n1, n1->set);
1010 six_unlock_write(&n2->lock);
1011 bch2_btree_node_free_never_inserted(c, n2);
1012 six_unlock_intent(&n2->lock);
1014 memmove(new_nodes + i - 1,
1016 sizeof(new_nodes[0]) * (nr_new_nodes - i));
1017 new_nodes[--nr_new_nodes] = NULL;
1019 /* move part of n2 into n1 */
1020 n1->key.k.p = n1->data->max_key =
1021 bkey_unpack_pos(n1, last);
1023 n2->data->min_key = bkey_successor(n1->data->max_key);
1025 memcpy_u64s(vstruct_last(s1),
1027 le16_add_cpu(&s1->u64s, u64s);
1030 vstruct_idx(s2, u64s),
1031 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
1032 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
1034 set_btree_bset_end(n1, n1->set);
1035 set_btree_bset_end(n2, n2->set);
1039 for (i = 0; i < nr_new_nodes; i++) {
1040 struct btree *n = new_nodes[i];
1042 recalc_packed_keys(n);
1043 btree_node_reset_sib_u64s(n);
1045 bch2_btree_build_aux_trees(n);
1047 bch2_btree_update_add_new_node(as, n);
1048 six_unlock_write(&n->lock);
1050 bch2_btree_node_write(c, n, SIX_LOCK_intent);
1054 * The keys for the old nodes get deleted. We don't want to insert keys
1055 * that compare equal to the keys for the new nodes we'll also be
1056 * inserting - we can't because keys on a keylist must be strictly
1057 * greater than the previous keys, and we also don't need to since the
1058 * key for the new node will serve the same purpose (overwriting the key
1059 * for the old node).
1061 for (i = 0; i < nr_old_nodes; i++) {
1062 struct bkey_i delete;
1065 for (j = 0; j < nr_new_nodes; j++)
1066 if (!bkey_cmp(old_nodes[i]->key.k.p,
1067 new_nodes[j]->key.k.p))
1070 bkey_init(&delete.k);
1071 delete.k.p = old_nodes[i]->key.k.p;
1072 bch2_keylist_add_in_order(&keylist, &delete);
1078 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
1079 * does the lookup once and thus expects the keys to be in sorted order
1080 * so we have to make sure the new keys are correctly ordered with
1081 * respect to the deleted keys added in the previous loop
1083 for (i = 0; i < nr_new_nodes; i++)
1084 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
1086 /* Insert the newly coalesced nodes */
1087 bch2_btree_insert_node(as, parent, iter, &keylist, 0);
1089 BUG_ON(!bch2_keylist_empty(&keylist));
1091 BUG_ON(iter->l[old_nodes[0]->level].b != old_nodes[0]);
1093 bch2_btree_iter_node_replace(iter, new_nodes[0]);
1095 for (i = 0; i < nr_new_nodes; i++)
1096 bch2_btree_update_get_open_buckets(as, new_nodes[i]);
1098 /* Free the old nodes and update our sliding window */
1099 for (i = 0; i < nr_old_nodes; i++) {
1100 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
1103 * the index update might have triggered a split, in which case
1104 * the nodes we coalesced - the new nodes we just created -
1105 * might not be sibling nodes anymore - don't add them to the
1106 * sliding window (except the first):
1109 old_nodes[i] = new_nodes[i];
1111 old_nodes[i] = NULL;
1115 for (i = 0; i < nr_new_nodes; i++)
1116 six_unlock_intent(&new_nodes[i]->lock);
1118 bch2_btree_update_done(as);
1119 bch2_keylist_free(&keylist, NULL);
1122 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
1124 struct btree_trans trans;
1125 struct btree_iter *iter;
1127 bool kthread = (current->flags & PF_KTHREAD) != 0;
1130 /* Sliding window of adjacent btree nodes */
1131 struct btree *merge[GC_MERGE_NODES];
1132 u32 lock_seq[GC_MERGE_NODES];
1134 bch2_trans_init(&trans, c, 0, 0);
1137 * XXX: We don't have a good way of positively matching on sibling nodes
1138 * that have the same parent - this code works by handling the cases
1139 * where they might not have the same parent, and is thus fragile. Ugh.
1141 * Perhaps redo this to use multiple linked iterators?
1143 memset(merge, 0, sizeof(merge));
1145 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1147 BTREE_ITER_PREFETCH, b) {
1148 memmove(merge + 1, merge,
1149 sizeof(merge) - sizeof(merge[0]));
1150 memmove(lock_seq + 1, lock_seq,
1151 sizeof(lock_seq) - sizeof(lock_seq[0]));
1155 for (i = 1; i < GC_MERGE_NODES; i++) {
1157 !six_relock_intent(&merge[i]->lock, lock_seq[i]))
1160 if (merge[i]->level != merge[0]->level) {
1161 six_unlock_intent(&merge[i]->lock);
1165 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
1167 bch2_coalesce_nodes(c, iter, merge);
1169 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
1170 lock_seq[i] = merge[i]->lock.state.seq;
1171 six_unlock_intent(&merge[i]->lock);
1174 lock_seq[0] = merge[0]->lock.state.seq;
1176 if (kthread && kthread_should_stop()) {
1177 bch2_trans_exit(&trans);
1181 bch2_trans_cond_resched(&trans);
1184 * If the parent node wasn't relocked, it might have been split
1185 * and the nodes in our sliding window might not have the same
1186 * parent anymore - blow away the sliding window:
1188 if (btree_iter_node(iter, iter->level + 1) &&
1189 !btree_node_intent_locked(iter, iter->level + 1))
1190 memset(merge + 1, 0,
1191 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
1193 return bch2_trans_exit(&trans);
1197 * bch_coalesce - coalesce adjacent nodes with low occupancy
1199 void bch2_coalesce(struct bch_fs *c)
1203 down_read(&c->gc_lock);
1204 trace_gc_coalesce_start(c);
1206 for (id = 0; id < BTREE_ID_NR; id++) {
1207 int ret = c->btree_roots[id].b
1208 ? bch2_coalesce_btree(c, id)
1212 if (ret != -ESHUTDOWN)
1213 bch_err(c, "btree coalescing failed: %d", ret);
1218 trace_gc_coalesce_end(c);
1219 up_read(&c->gc_lock);
1222 static int bch2_gc_thread(void *arg)
1224 struct bch_fs *c = arg;
1225 struct io_clock *clock = &c->io_clock[WRITE];
1226 unsigned long last = atomic_long_read(&clock->now);
1227 unsigned last_kick = atomic_read(&c->kick_gc);
1234 set_current_state(TASK_INTERRUPTIBLE);
1236 if (kthread_should_stop()) {
1237 __set_current_state(TASK_RUNNING);
1241 if (atomic_read(&c->kick_gc) != last_kick)
1244 if (c->btree_gc_periodic) {
1245 unsigned long next = last + c->capacity / 16;
1247 if (atomic_long_read(&clock->now) >= next)
1250 bch2_io_clock_schedule_timeout(clock, next);
1257 __set_current_state(TASK_RUNNING);
1259 last = atomic_long_read(&clock->now);
1260 last_kick = atomic_read(&c->kick_gc);
1262 ret = bch2_gc(c, NULL, false, false);
1264 bch_err(c, "btree gc failed: %i", ret);
1266 debug_check_no_locks_held();
1272 void bch2_gc_thread_stop(struct bch_fs *c)
1274 struct task_struct *p;
1277 c->gc_thread = NULL;
1285 int bch2_gc_thread_start(struct bch_fs *c)
1287 struct task_struct *p;
1289 BUG_ON(c->gc_thread);
1291 p = kthread_create(bch2_gc_thread, c, "bch_gc");