2 * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
3 * Copyright (C) 2014 Datera Inc.
7 #include "alloc_background.h"
8 #include "alloc_foreground.h"
9 #include "bkey_methods.h"
10 #include "btree_locking.h"
11 #include "btree_update_interior.h"
20 #include "journal_io.h"
26 #include <linux/slab.h>
27 #include <linux/bitops.h>
28 #include <linux/freezer.h>
29 #include <linux/kthread.h>
30 #include <linux/preempt.h>
31 #include <linux/rcupdate.h>
32 #include <linux/sched/task.h>
33 #include <trace/events/bcachefs.h>
35 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
37 write_seqcount_begin(&c->gc_pos_lock);
39 write_seqcount_end(&c->gc_pos_lock);
42 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
44 BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
45 __gc_pos_set(c, new_pos);
48 /* range_checks - for validating min/max pos of each btree node: */
58 static void btree_node_range_checks_init(struct range_checks *r, unsigned depth)
62 for (i = 0; i < BTREE_MAX_DEPTH; i++)
63 r->l[i].min = r->l[i].max = POS_MIN;
67 static void btree_node_range_checks(struct bch_fs *c, struct btree *b,
68 struct range_checks *r)
70 struct range_level *l = &r->l[b->level];
72 struct bpos expected_min = bkey_cmp(l->min, l->max)
73 ? btree_type_successor(b->btree_id, l->max)
76 bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, expected_min), c,
77 "btree node has incorrect min key: %llu:%llu != %llu:%llu",
78 b->data->min_key.inode,
79 b->data->min_key.offset,
83 l->max = b->data->max_key;
85 if (b->level > r->depth) {
86 l = &r->l[b->level - 1];
88 bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, l->min), c,
89 "btree node min doesn't match min of child nodes: %llu:%llu != %llu:%llu",
90 b->data->min_key.inode,
91 b->data->min_key.offset,
95 bch2_fs_inconsistent_on(bkey_cmp(b->data->max_key, l->max), c,
96 "btree node max doesn't match max of child nodes: %llu:%llu != %llu:%llu",
97 b->data->max_key.inode,
98 b->data->max_key.offset,
102 if (bkey_cmp(b->data->max_key, POS_MAX))
104 btree_type_successor(b->btree_id,
109 /* marking of btree keys/nodes: */
111 static bool bkey_type_needs_gc(enum bkey_type type)
114 case BKEY_TYPE_BTREE:
115 case BKEY_TYPE_EXTENTS:
122 static void ptr_gen_recalc_oldest(struct bch_fs *c,
123 const struct bch_extent_ptr *ptr,
126 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
127 size_t b = PTR_BUCKET_NR(ca, ptr);
129 if (gen_after(ca->oldest_gens[b], ptr->gen))
130 ca->oldest_gens[b] = ptr->gen;
132 *max_stale = max(*max_stale, ptr_stale(ca, ptr));
135 static u8 ptr_gens_recalc_oldest(struct bch_fs *c,
139 const struct bch_extent_ptr *ptr;
143 case BKEY_TYPE_BTREE:
144 case BKEY_TYPE_EXTENTS:
147 case BCH_EXTENT_CACHED: {
148 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
150 extent_for_each_ptr(e, ptr)
151 ptr_gen_recalc_oldest(c, ptr, &max_stale);
163 static int ptr_gen_check(struct bch_fs *c,
165 const struct bch_extent_ptr *ptr)
167 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
168 size_t b = PTR_BUCKET_NR(ca, ptr);
169 struct bucket *g = PTR_BUCKET(ca, ptr);
172 if (mustfix_fsck_err_on(!g->mark.gen_valid, c,
173 "found ptr with missing gen in alloc btree,\n"
176 g->_mark.gen = ptr->gen;
177 g->_mark.gen_valid = 1;
178 set_bit(b, ca->buckets_dirty);
181 if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
182 "%u ptr gen in the future: %u > %u",
183 type, ptr->gen, g->mark.gen)) {
184 g->_mark.gen = ptr->gen;
185 g->_mark.gen_valid = 1;
186 set_bit(b, ca->buckets_dirty);
187 set_bit(BCH_FS_FIXED_GENS, &c->flags);
193 static int ptr_gens_check(struct bch_fs *c, enum bkey_type type,
196 const struct bch_extent_ptr *ptr;
200 case BKEY_TYPE_BTREE:
201 case BKEY_TYPE_EXTENTS:
204 case BCH_EXTENT_CACHED: {
205 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
207 extent_for_each_ptr(e, ptr) {
208 ret = ptr_gen_check(c, type, ptr);
225 * For runtime mark and sweep:
227 static int bch2_gc_mark_key(struct bch_fs *c, enum bkey_type type,
228 struct bkey_s_c k, bool initial)
230 struct gc_pos pos = { 0 };
232 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
233 BCH_BUCKET_MARK_GC_LOCK_HELD|
234 (initial ? BCH_BUCKET_MARK_NOATOMIC : 0);
238 BUG_ON(journal_seq_verify(c) &&
239 k.k->version.lo > journal_cur_seq(&c->journal));
241 if (k.k->version.lo > atomic64_read(&c->key_version))
242 atomic64_set(&c->key_version, k.k->version.lo);
244 if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
245 fsck_err_on(!bch2_bkey_replicas_marked(c, type, k,
247 "superblock not marked as containing replicas (type %u)",
249 ret = bch2_mark_bkey_replicas(c, type, k);
254 ret = ptr_gens_check(c, type, k);
259 bch2_mark_key(c, type, k, true, k.k->size, pos, NULL, 0, flags);
261 ret = ptr_gens_recalc_oldest(c, type, k);
266 static int btree_gc_mark_node(struct bch_fs *c, struct btree *b,
269 enum bkey_type type = btree_node_type(b);
270 struct btree_node_iter iter;
271 struct bkey unpacked;
276 if (!bkey_type_needs_gc(type))
279 for_each_btree_node_key_unpack(b, k, &iter,
281 bch2_bkey_debugcheck(c, b, k);
283 ret = bch2_gc_mark_key(c, type, k, initial);
287 stale = max_t(u8, stale, ret);
293 static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id,
296 struct btree_iter iter;
298 struct range_checks r;
299 unsigned depth = bkey_type_needs_gc(btree_id) ? 0 : 1;
303 gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
305 if (!c->btree_roots[btree_id].b)
309 * if expensive_debug_checks is on, run range_checks on all leaf nodes:
311 * and on startup, we have to read every btree node (XXX: only if it was
312 * an unclean shutdown)
314 if (initial || expensive_debug_checks(c))
317 btree_node_range_checks_init(&r, depth);
319 __for_each_btree_node(&iter, c, btree_id, POS_MIN,
320 0, depth, BTREE_ITER_PREFETCH, b) {
321 btree_node_range_checks(c, b, &r);
323 bch2_verify_btree_nr_keys(b);
325 max_stale = btree_gc_mark_node(c, b, initial);
327 gc_pos_set(c, gc_pos_btree_node(b));
331 bch2_btree_node_rewrite(c, &iter,
333 BTREE_INSERT_USE_RESERVE|
335 BTREE_INSERT_GC_LOCK_HELD);
336 else if (!btree_gc_rewrite_disabled(c) &&
337 (btree_gc_always_rewrite(c) || max_stale > 16))
338 bch2_btree_node_rewrite(c, &iter,
341 BTREE_INSERT_GC_LOCK_HELD);
344 bch2_btree_iter_cond_resched(&iter);
346 ret = bch2_btree_iter_unlock(&iter);
350 mutex_lock(&c->btree_root_lock);
352 b = c->btree_roots[btree_id].b;
353 if (!btree_node_fake(b))
354 bch2_gc_mark_key(c, BKEY_TYPE_BTREE,
355 bkey_i_to_s_c(&b->key), initial);
356 gc_pos_set(c, gc_pos_btree_root(b->btree_id));
358 mutex_unlock(&c->btree_root_lock);
362 static int bch2_gc_btrees(struct bch_fs *c, struct list_head *journal,
367 for (i = 0; i < BTREE_ID_NR; i++) {
368 enum bkey_type type = bkey_type(0, i);
370 int ret = bch2_gc_btree(c, i, initial);
374 if (journal && bkey_type_needs_gc(type)) {
375 struct bkey_i *k, *n;
376 struct jset_entry *j;
377 struct journal_replay *r;
380 list_for_each_entry(r, journal, list)
381 for_each_jset_key(k, n, j, &r->j) {
382 if (type == bkey_type(j->level, j->btree_id)) {
383 ret = bch2_gc_mark_key(c, type,
384 bkey_i_to_s_c(k), initial);
395 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
397 enum bch_data_type type,
400 u64 b = sector_to_bucket(ca, start);
404 min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
406 bch2_mark_metadata_bucket(c, ca, b, type, sectors,
407 gc_phase(GC_PHASE_SB), flags);
410 } while (start < end);
413 void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
416 struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
421 * This conditional is kind of gross, but we may be called from the
422 * device add path, before the new device has actually been added to the
423 * running filesystem:
426 lockdep_assert_held(&c->sb_lock);
427 percpu_down_read_preempt_disable(&c->usage_lock);
432 for (i = 0; i < layout->nr_superblocks; i++) {
433 u64 offset = le64_to_cpu(layout->sb_offset[i]);
435 if (offset == BCH_SB_SECTOR)
436 mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
439 mark_metadata_sectors(c, ca, offset,
440 offset + (1 << layout->sb_max_size_bits),
445 spin_lock(&c->journal.lock);
447 for (i = 0; i < ca->journal.nr; i++) {
448 b = ca->journal.buckets[i];
449 bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_JOURNAL,
451 gc_phase(GC_PHASE_SB), flags);
455 percpu_up_read_preempt_enable(&c->usage_lock);
456 spin_unlock(&c->journal.lock);
462 static void bch2_mark_superblocks(struct bch_fs *c)
467 mutex_lock(&c->sb_lock);
468 gc_pos_set(c, gc_phase(GC_PHASE_SB));
470 for_each_online_member(ca, c, i)
471 bch2_mark_dev_superblock(c, ca,
472 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
473 BCH_BUCKET_MARK_GC_LOCK_HELD);
474 mutex_unlock(&c->sb_lock);
477 /* Also see bch2_pending_btree_node_free_insert_done() */
478 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
480 struct gc_pos pos = { 0 };
481 struct bch_fs_usage stats = { 0 };
482 struct btree_update *as;
483 struct pending_btree_node_free *d;
485 mutex_lock(&c->btree_interior_update_lock);
486 gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
488 for_each_pending_btree_node_free(c, as, d)
489 if (d->index_update_done)
490 bch2_mark_key(c, BKEY_TYPE_BTREE,
491 bkey_i_to_s_c(&d->key),
494 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
495 BCH_BUCKET_MARK_GC_LOCK_HELD);
497 * Don't apply stats - pending deletes aren't tracked in
501 mutex_unlock(&c->btree_interior_update_lock);
504 static void bch2_mark_allocator_buckets(struct bch_fs *c)
507 struct open_bucket *ob;
511 percpu_down_read_preempt_disable(&c->usage_lock);
513 spin_lock(&c->freelist_lock);
514 gc_pos_set(c, gc_pos_alloc(c, NULL));
516 for_each_member_device(ca, c, ci) {
517 fifo_for_each_entry(i, &ca->free_inc, iter)
518 bch2_mark_alloc_bucket(c, ca, i, true,
519 gc_pos_alloc(c, NULL),
520 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
521 BCH_BUCKET_MARK_GC_LOCK_HELD);
525 for (j = 0; j < RESERVE_NR; j++)
526 fifo_for_each_entry(i, &ca->free[j], iter)
527 bch2_mark_alloc_bucket(c, ca, i, true,
528 gc_pos_alloc(c, NULL),
529 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
530 BCH_BUCKET_MARK_GC_LOCK_HELD);
533 spin_unlock(&c->freelist_lock);
535 for (ob = c->open_buckets;
536 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
538 spin_lock(&ob->lock);
540 gc_pos_set(c, gc_pos_alloc(c, ob));
541 ca = bch_dev_bkey_exists(c, ob->ptr.dev);
542 bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
544 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
545 BCH_BUCKET_MARK_GC_LOCK_HELD);
547 spin_unlock(&ob->lock);
550 percpu_up_read_preempt_enable(&c->usage_lock);
553 static void bch2_gc_start(struct bch_fs *c)
556 struct bucket_array *buckets;
557 struct bucket_mark new;
562 percpu_down_write(&c->usage_lock);
565 * Indicates to buckets code that gc is now in progress - done under
566 * usage_lock to avoid racing with bch2_mark_key():
568 __gc_pos_set(c, gc_phase(GC_PHASE_START));
570 /* Save a copy of the existing bucket stats while we recompute them: */
571 for_each_member_device(ca, c, i) {
572 ca->usage_cached = __bch2_dev_usage_read(ca);
573 for_each_possible_cpu(cpu) {
574 struct bch_dev_usage *p =
575 per_cpu_ptr(ca->usage_percpu, cpu);
576 memset(p, 0, sizeof(*p));
580 c->usage_cached = __bch2_fs_usage_read(c);
581 for_each_possible_cpu(cpu) {
582 struct bch_fs_usage *p =
583 per_cpu_ptr(c->usage_percpu, cpu);
585 memset(p->replicas, 0, sizeof(p->replicas));
586 memset(p->buckets, 0, sizeof(p->buckets));
589 percpu_up_write(&c->usage_lock);
591 /* Clear bucket marks: */
592 for_each_member_device(ca, c, i) {
593 down_read(&ca->bucket_lock);
594 buckets = bucket_array(ca);
596 for (b = buckets->first_bucket; b < buckets->nbuckets; b++) {
597 bucket_cmpxchg(buckets->b + b, new, ({
598 new.owned_by_allocator = 0;
600 new.cached_sectors = 0;
601 new.dirty_sectors = 0;
603 ca->oldest_gens[b] = new.gen;
605 up_read(&ca->bucket_lock);
610 * bch_gc - recompute bucket marks and oldest_gen, rewrite btree nodes
612 void bch2_gc(struct bch_fs *c)
615 u64 start_time = local_clock();
620 * Walk _all_ references to buckets, and recompute them:
622 * Order matters here:
623 * - Concurrent GC relies on the fact that we have a total ordering for
624 * everything that GC walks - see gc_will_visit_node(),
625 * gc_will_visit_root()
627 * - also, references move around in the course of index updates and
628 * various other crap: everything needs to agree on the ordering
629 * references are allowed to move around in - e.g., we're allowed to
630 * start with a reference owned by an open_bucket (the allocator) and
631 * move it to the btree, but not the reverse.
633 * This is necessary to ensure that gc doesn't miss references that
634 * move around - if references move backwards in the ordering GC
635 * uses, GC could skip past them
640 * Do this before taking gc_lock - bch2_disk_reservation_get() blocks on
641 * gc_lock if sectors_available goes to 0:
643 bch2_recalc_sectors_available(c);
645 down_write(&c->gc_lock);
646 if (test_bit(BCH_FS_GC_FAILURE, &c->flags))
651 bch2_mark_superblocks(c);
653 ret = bch2_gc_btrees(c, NULL, false);
655 bch_err(c, "btree gc failed: %d", ret);
656 set_bit(BCH_FS_GC_FAILURE, &c->flags);
660 bch2_mark_pending_btree_node_frees(c);
661 bch2_mark_allocator_buckets(c);
663 /* Indicates that gc is no longer in progress: */
664 gc_pos_set(c, gc_phase(GC_PHASE_DONE));
667 up_write(&c->gc_lock);
669 bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
672 * Wake up allocator in case it was waiting for buckets
673 * because of not being able to inc gens
675 for_each_member_device(ca, c, i)
676 bch2_wake_allocator(ca);
679 * At startup, allocations can happen directly instead of via the
680 * allocator thread - issue wakeup in case they blocked on gc_lock:
682 closure_wake_up(&c->freelist_wait);
685 /* Btree coalescing */
687 static void recalc_packed_keys(struct btree *b)
689 struct bset *i = btree_bset_first(b);
690 struct bkey_packed *k;
692 memset(&b->nr, 0, sizeof(b->nr));
694 BUG_ON(b->nsets != 1);
696 vstruct_for_each(i, k)
697 btree_keys_account_key_add(&b->nr, 0, k);
700 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
701 struct btree *old_nodes[GC_MERGE_NODES])
703 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
704 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
705 unsigned blocks = btree_blocks(c) * 2 / 3;
706 struct btree *new_nodes[GC_MERGE_NODES];
707 struct btree_update *as;
708 struct keylist keylist;
709 struct bkey_format_state format_state;
710 struct bkey_format new_format;
712 memset(new_nodes, 0, sizeof(new_nodes));
713 bch2_keylist_init(&keylist, NULL);
715 /* Count keys that are not deleted */
716 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
717 u64s += old_nodes[i]->nr.live_u64s;
719 nr_old_nodes = nr_new_nodes = i;
721 /* Check if all keys in @old_nodes could fit in one fewer node */
722 if (nr_old_nodes <= 1 ||
723 __vstruct_blocks(struct btree_node, c->block_bits,
724 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
727 /* Find a format that all keys in @old_nodes can pack into */
728 bch2_bkey_format_init(&format_state);
730 for (i = 0; i < nr_old_nodes; i++)
731 __bch2_btree_calc_format(&format_state, old_nodes[i]);
733 new_format = bch2_bkey_format_done(&format_state);
735 /* Check if repacking would make any nodes too big to fit */
736 for (i = 0; i < nr_old_nodes; i++)
737 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
738 trace_btree_gc_coalesce_fail(c,
739 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
743 if (bch2_keylist_realloc(&keylist, NULL, 0,
744 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
745 trace_btree_gc_coalesce_fail(c,
746 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
750 as = bch2_btree_update_start(c, iter->btree_id,
751 btree_update_reserve_required(c, parent) + nr_old_nodes,
753 BTREE_INSERT_USE_RESERVE,
756 trace_btree_gc_coalesce_fail(c,
757 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
758 bch2_keylist_free(&keylist, NULL);
762 trace_btree_gc_coalesce(c, old_nodes[0]);
764 for (i = 0; i < nr_old_nodes; i++)
765 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
767 /* Repack everything with @new_format and sort down to one bset */
768 for (i = 0; i < nr_old_nodes; i++)
770 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
774 * Conceptually we concatenate the nodes together and slice them
775 * up at different boundaries.
777 for (i = nr_new_nodes - 1; i > 0; --i) {
778 struct btree *n1 = new_nodes[i];
779 struct btree *n2 = new_nodes[i - 1];
781 struct bset *s1 = btree_bset_first(n1);
782 struct bset *s2 = btree_bset_first(n2);
783 struct bkey_packed *k, *last = NULL;
785 /* Calculate how many keys from @n2 we could fit inside @n1 */
789 k < vstruct_last(s2) &&
790 vstruct_blocks_plus(n1->data, c->block_bits,
791 u64s + k->u64s) <= blocks;
797 if (u64s == le16_to_cpu(s2->u64s)) {
798 /* n2 fits entirely in n1 */
799 n1->key.k.p = n1->data->max_key = n2->data->max_key;
801 memcpy_u64s(vstruct_last(s1),
803 le16_to_cpu(s2->u64s));
804 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
806 set_btree_bset_end(n1, n1->set);
808 six_unlock_write(&n2->lock);
809 bch2_btree_node_free_never_inserted(c, n2);
810 six_unlock_intent(&n2->lock);
812 memmove(new_nodes + i - 1,
814 sizeof(new_nodes[0]) * (nr_new_nodes - i));
815 new_nodes[--nr_new_nodes] = NULL;
817 /* move part of n2 into n1 */
818 n1->key.k.p = n1->data->max_key =
819 bkey_unpack_pos(n1, last);
822 btree_type_successor(iter->btree_id,
825 memcpy_u64s(vstruct_last(s1),
827 le16_add_cpu(&s1->u64s, u64s);
830 vstruct_idx(s2, u64s),
831 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
832 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
834 set_btree_bset_end(n1, n1->set);
835 set_btree_bset_end(n2, n2->set);
839 for (i = 0; i < nr_new_nodes; i++) {
840 struct btree *n = new_nodes[i];
842 recalc_packed_keys(n);
843 btree_node_reset_sib_u64s(n);
845 bch2_btree_build_aux_trees(n);
846 six_unlock_write(&n->lock);
848 bch2_btree_node_write(c, n, SIX_LOCK_intent);
852 * The keys for the old nodes get deleted. We don't want to insert keys
853 * that compare equal to the keys for the new nodes we'll also be
854 * inserting - we can't because keys on a keylist must be strictly
855 * greater than the previous keys, and we also don't need to since the
856 * key for the new node will serve the same purpose (overwriting the key
859 for (i = 0; i < nr_old_nodes; i++) {
860 struct bkey_i delete;
863 for (j = 0; j < nr_new_nodes; j++)
864 if (!bkey_cmp(old_nodes[i]->key.k.p,
865 new_nodes[j]->key.k.p))
868 bkey_init(&delete.k);
869 delete.k.p = old_nodes[i]->key.k.p;
870 bch2_keylist_add_in_order(&keylist, &delete);
876 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
877 * does the lookup once and thus expects the keys to be in sorted order
878 * so we have to make sure the new keys are correctly ordered with
879 * respect to the deleted keys added in the previous loop
881 for (i = 0; i < nr_new_nodes; i++)
882 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
884 /* Insert the newly coalesced nodes */
885 bch2_btree_insert_node(as, parent, iter, &keylist, 0);
887 BUG_ON(!bch2_keylist_empty(&keylist));
889 BUG_ON(iter->l[old_nodes[0]->level].b != old_nodes[0]);
891 bch2_btree_iter_node_replace(iter, new_nodes[0]);
893 for (i = 0; i < nr_new_nodes; i++)
894 bch2_open_buckets_put(c, &new_nodes[i]->ob);
896 /* Free the old nodes and update our sliding window */
897 for (i = 0; i < nr_old_nodes; i++) {
898 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
899 six_unlock_intent(&old_nodes[i]->lock);
902 * the index update might have triggered a split, in which case
903 * the nodes we coalesced - the new nodes we just created -
904 * might not be sibling nodes anymore - don't add them to the
905 * sliding window (except the first):
908 old_nodes[i] = new_nodes[i];
912 six_unlock_intent(&new_nodes[i]->lock);
916 bch2_btree_update_done(as);
917 bch2_keylist_free(&keylist, NULL);
920 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
922 struct btree_iter iter;
924 bool kthread = (current->flags & PF_KTHREAD) != 0;
927 /* Sliding window of adjacent btree nodes */
928 struct btree *merge[GC_MERGE_NODES];
929 u32 lock_seq[GC_MERGE_NODES];
932 * XXX: We don't have a good way of positively matching on sibling nodes
933 * that have the same parent - this code works by handling the cases
934 * where they might not have the same parent, and is thus fragile. Ugh.
936 * Perhaps redo this to use multiple linked iterators?
938 memset(merge, 0, sizeof(merge));
940 __for_each_btree_node(&iter, c, btree_id, POS_MIN,
942 BTREE_ITER_PREFETCH, b) {
943 memmove(merge + 1, merge,
944 sizeof(merge) - sizeof(merge[0]));
945 memmove(lock_seq + 1, lock_seq,
946 sizeof(lock_seq) - sizeof(lock_seq[0]));
950 for (i = 1; i < GC_MERGE_NODES; i++) {
952 !six_relock_intent(&merge[i]->lock, lock_seq[i]))
955 if (merge[i]->level != merge[0]->level) {
956 six_unlock_intent(&merge[i]->lock);
960 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
962 bch2_coalesce_nodes(c, &iter, merge);
964 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
965 lock_seq[i] = merge[i]->lock.state.seq;
966 six_unlock_intent(&merge[i]->lock);
969 lock_seq[0] = merge[0]->lock.state.seq;
971 if (kthread && kthread_should_stop()) {
972 bch2_btree_iter_unlock(&iter);
976 bch2_btree_iter_cond_resched(&iter);
979 * If the parent node wasn't relocked, it might have been split
980 * and the nodes in our sliding window might not have the same
981 * parent anymore - blow away the sliding window:
983 if (btree_iter_node(&iter, iter.level + 1) &&
984 !btree_node_intent_locked(&iter, iter.level + 1))
986 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
988 return bch2_btree_iter_unlock(&iter);
992 * bch_coalesce - coalesce adjacent nodes with low occupancy
994 void bch2_coalesce(struct bch_fs *c)
998 if (test_bit(BCH_FS_GC_FAILURE, &c->flags))
1001 down_read(&c->gc_lock);
1002 trace_gc_coalesce_start(c);
1004 for (id = 0; id < BTREE_ID_NR; id++) {
1005 int ret = c->btree_roots[id].b
1006 ? bch2_coalesce_btree(c, id)
1010 if (ret != -ESHUTDOWN)
1011 bch_err(c, "btree coalescing failed: %d", ret);
1012 set_bit(BCH_FS_GC_FAILURE, &c->flags);
1017 trace_gc_coalesce_end(c);
1018 up_read(&c->gc_lock);
1021 static int bch2_gc_thread(void *arg)
1023 struct bch_fs *c = arg;
1024 struct io_clock *clock = &c->io_clock[WRITE];
1025 unsigned long last = atomic_long_read(&clock->now);
1026 unsigned last_kick = atomic_read(&c->kick_gc);
1032 set_current_state(TASK_INTERRUPTIBLE);
1034 if (kthread_should_stop()) {
1035 __set_current_state(TASK_RUNNING);
1039 if (atomic_read(&c->kick_gc) != last_kick)
1042 if (c->btree_gc_periodic) {
1043 unsigned long next = last + c->capacity / 16;
1045 if (atomic_long_read(&clock->now) >= next)
1048 bch2_io_clock_schedule_timeout(clock, next);
1055 __set_current_state(TASK_RUNNING);
1057 last = atomic_long_read(&clock->now);
1058 last_kick = atomic_read(&c->kick_gc);
1062 debug_check_no_locks_held();
1068 void bch2_gc_thread_stop(struct bch_fs *c)
1070 struct task_struct *p;
1073 c->gc_thread = NULL;
1081 int bch2_gc_thread_start(struct bch_fs *c)
1083 struct task_struct *p;
1085 BUG_ON(c->gc_thread);
1087 p = kthread_create(bch2_gc_thread, c, "bch_gc");
1097 /* Initial GC computes bucket marks during startup */
1099 int bch2_initial_gc(struct bch_fs *c, struct list_head *journal)
1104 down_write(&c->gc_lock);
1108 bch2_mark_superblocks(c);
1110 ret = bch2_gc_btrees(c, journal, true);
1114 if (test_bit(BCH_FS_FIXED_GENS, &c->flags)) {
1116 bch_info(c, "Unable to fix bucket gens, looping");
1121 bch_info(c, "Fixed gens, restarting initial mark and sweep:");
1122 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
1127 * Skip past versions that might have possibly been used (as nonces),
1128 * but hadn't had their pointers written:
1130 if (c->sb.encryption_type)
1131 atomic64_add(1 << 16, &c->key_version);
1133 gc_pos_set(c, gc_phase(GC_PHASE_DONE));
1134 set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
1136 up_write(&c->gc_lock);