2 * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
3 * Copyright (C) 2014 Datera Inc.
8 #include "bkey_methods.h"
9 #include "btree_locking.h"
10 #include "btree_update_interior.h"
23 #include <linux/slab.h>
24 #include <linux/bitops.h>
25 #include <linux/freezer.h>
26 #include <linux/kthread.h>
27 #include <linux/preempt.h>
28 #include <linux/rcupdate.h>
29 #include <trace/events/bcachefs.h>
39 static void btree_node_range_checks_init(struct range_checks *r, unsigned depth)
43 for (i = 0; i < BTREE_MAX_DEPTH; i++)
44 r->l[i].min = r->l[i].max = POS_MIN;
48 static void btree_node_range_checks(struct bch_fs *c, struct btree *b,
49 struct range_checks *r)
51 struct range_level *l = &r->l[b->level];
53 struct bpos expected_min = bkey_cmp(l->min, l->max)
54 ? btree_type_successor(b->btree_id, l->max)
57 bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, expected_min), c,
58 "btree node has incorrect min key: %llu:%llu != %llu:%llu",
59 b->data->min_key.inode,
60 b->data->min_key.offset,
64 l->max = b->data->max_key;
66 if (b->level > r->depth) {
67 l = &r->l[b->level - 1];
69 bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, l->min), c,
70 "btree node min doesn't match min of child nodes: %llu:%llu != %llu:%llu",
71 b->data->min_key.inode,
72 b->data->min_key.offset,
76 bch2_fs_inconsistent_on(bkey_cmp(b->data->max_key, l->max), c,
77 "btree node max doesn't match max of child nodes: %llu:%llu != %llu:%llu",
78 b->data->max_key.inode,
79 b->data->max_key.offset,
83 if (bkey_cmp(b->data->max_key, POS_MAX))
85 btree_type_successor(b->btree_id,
90 u8 bch2_btree_key_recalc_oldest_gen(struct bch_fs *c, struct bkey_s_c k)
92 const struct bch_extent_ptr *ptr;
95 if (bkey_extent_is_data(k.k)) {
96 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
98 extent_for_each_ptr(e, ptr) {
99 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
100 size_t b = PTR_BUCKET_NR(ca, ptr);
102 if (gen_after(ca->oldest_gens[b], ptr->gen))
103 ca->oldest_gens[b] = ptr->gen;
105 max_stale = max(max_stale, ptr_stale(ca, ptr));
113 * For runtime mark and sweep:
115 static u8 bch2_gc_mark_key(struct bch_fs *c, enum bkey_type type,
116 struct bkey_s_c k, unsigned flags)
118 struct gc_pos pos = { 0 };
119 struct bch_fs_usage *stats;
123 stats = this_cpu_ptr(c->usage_percpu);
125 case BKEY_TYPE_BTREE:
126 bch2_mark_key(c, k, c->opts.btree_node_size, true, pos, stats,
128 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
129 BCH_BUCKET_MARK_GC_LOCK_HELD);
131 case BKEY_TYPE_EXTENTS:
132 bch2_mark_key(c, k, k.k->size, false, pos, stats,
134 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
135 BCH_BUCKET_MARK_GC_LOCK_HELD);
136 ret = bch2_btree_key_recalc_oldest_gen(c, k);
146 int bch2_btree_mark_key_initial(struct bch_fs *c, enum bkey_type type,
149 enum bch_data_type data_type = type == BKEY_TYPE_BTREE
150 ? BCH_DATA_BTREE : BCH_DATA_USER;
153 if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
154 fsck_err_on(!bch2_bkey_replicas_marked(c, data_type, k), c,
155 "superblock not marked as containing replicas (type %u)",
157 ret = bch2_mark_bkey_replicas(c, data_type, k);
164 case BCH_EXTENT_CACHED: {
165 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
166 const struct bch_extent_ptr *ptr;
168 extent_for_each_ptr(e, ptr) {
169 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
170 size_t b = PTR_BUCKET_NR(ca, ptr);
171 struct bucket *g = PTR_BUCKET(ca, ptr);
173 if (mustfix_fsck_err_on(!g->mark.gen_valid, c,
174 "found ptr with missing gen in alloc btree,\n"
176 bch2_data_types[data_type],
178 g->_mark.gen = ptr->gen;
179 g->_mark.gen_valid = 1;
180 set_bit(b, ca->buckets_dirty);
183 if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
184 "%s ptr gen in the future: %u > %u",
185 bch2_data_types[data_type],
186 ptr->gen, g->mark.gen)) {
187 g->_mark.gen = ptr->gen;
188 g->_mark.gen_valid = 1;
189 set_bit(b, ca->buckets_dirty);
190 set_bit(BCH_FS_FIXED_GENS, &c->flags);
198 atomic64_set(&c->key_version,
199 max_t(u64, k.k->version.lo,
200 atomic64_read(&c->key_version)));
202 bch2_gc_mark_key(c, type, k, BCH_BUCKET_MARK_NOATOMIC);
207 static unsigned btree_gc_mark_node(struct bch_fs *c, struct btree *b)
209 enum bkey_type type = btree_node_type(b);
210 struct btree_node_iter iter;
211 struct bkey unpacked;
215 if (btree_node_has_ptrs(b))
216 for_each_btree_node_key_unpack(b, k, &iter,
217 btree_node_is_extents(b),
219 bch2_bkey_debugcheck(c, b, k);
220 stale = max(stale, bch2_gc_mark_key(c, type, k, 0));
226 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
228 write_seqcount_begin(&c->gc_pos_lock);
230 write_seqcount_end(&c->gc_pos_lock);
233 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
235 BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
236 __gc_pos_set(c, new_pos);
239 static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id)
241 struct btree_iter iter;
243 struct range_checks r;
244 unsigned depth = btree_id == BTREE_ID_EXTENTS ? 0 : 1;
249 * if expensive_debug_checks is on, run range_checks on all leaf nodes:
251 if (expensive_debug_checks(c))
254 btree_node_range_checks_init(&r, depth);
256 __for_each_btree_node(&iter, c, btree_id, POS_MIN,
257 0, depth, BTREE_ITER_PREFETCH, b) {
258 btree_node_range_checks(c, b, &r);
260 bch2_verify_btree_nr_keys(b);
262 max_stale = btree_gc_mark_node(c, b);
264 gc_pos_set(c, gc_pos_btree_node(b));
267 bch2_btree_node_rewrite(c, &iter,
269 BTREE_INSERT_USE_RESERVE|
270 BTREE_INSERT_GC_LOCK_HELD);
271 else if (!btree_gc_rewrite_disabled(c) &&
272 (btree_gc_always_rewrite(c) || max_stale > 16))
273 bch2_btree_node_rewrite(c, &iter,
276 BTREE_INSERT_GC_LOCK_HELD);
278 bch2_btree_iter_cond_resched(&iter);
280 ret = bch2_btree_iter_unlock(&iter);
284 mutex_lock(&c->btree_root_lock);
286 b = c->btree_roots[btree_id].b;
287 if (!btree_node_fake(b))
288 bch2_gc_mark_key(c, BKEY_TYPE_BTREE, bkey_i_to_s_c(&b->key), 0);
289 gc_pos_set(c, gc_pos_btree_root(b->btree_id));
291 mutex_unlock(&c->btree_root_lock);
295 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
297 enum bch_data_type type,
300 u64 b = sector_to_bucket(ca, start);
304 min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
306 bch2_mark_metadata_bucket(c, ca, b, type, sectors,
307 gc_phase(GC_PHASE_SB), flags);
310 } while (start < end);
313 void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
316 struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
320 lockdep_assert_held(&c->sb_lock);
322 for (i = 0; i < layout->nr_superblocks; i++) {
323 u64 offset = le64_to_cpu(layout->sb_offset[i]);
325 if (offset == BCH_SB_SECTOR)
326 mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
329 mark_metadata_sectors(c, ca, offset,
330 offset + (1 << layout->sb_max_size_bits),
334 spin_lock(&c->journal.lock);
336 for (i = 0; i < ca->journal.nr; i++) {
337 b = ca->journal.buckets[i];
338 bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_JOURNAL,
340 gc_phase(GC_PHASE_SB), flags);
343 spin_unlock(&c->journal.lock);
346 static void bch2_mark_superblocks(struct bch_fs *c)
351 mutex_lock(&c->sb_lock);
352 gc_pos_set(c, gc_phase(GC_PHASE_SB));
354 for_each_online_member(ca, c, i)
355 bch2_mark_dev_superblock(c, ca,
356 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
357 BCH_BUCKET_MARK_GC_LOCK_HELD);
358 mutex_unlock(&c->sb_lock);
361 /* Also see bch2_pending_btree_node_free_insert_done() */
362 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
364 struct gc_pos pos = { 0 };
365 struct bch_fs_usage stats = { 0 };
366 struct btree_update *as;
367 struct pending_btree_node_free *d;
369 mutex_lock(&c->btree_interior_update_lock);
370 gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
372 for_each_pending_btree_node_free(c, as, d)
373 if (d->index_update_done)
374 bch2_mark_key(c, bkey_i_to_s_c(&d->key),
375 c->opts.btree_node_size, true, pos,
377 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
378 BCH_BUCKET_MARK_GC_LOCK_HELD);
380 * Don't apply stats - pending deletes aren't tracked in
384 mutex_unlock(&c->btree_interior_update_lock);
387 static void bch2_mark_allocator_buckets(struct bch_fs *c)
390 struct open_bucket *ob;
394 spin_lock(&c->freelist_lock);
395 gc_pos_set(c, gc_pos_alloc(c, NULL));
397 for_each_member_device(ca, c, ci) {
398 fifo_for_each_entry(i, &ca->free_inc, iter)
399 bch2_mark_alloc_bucket(c, ca, i, true,
400 gc_pos_alloc(c, NULL),
401 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
402 BCH_BUCKET_MARK_GC_LOCK_HELD);
406 for (j = 0; j < RESERVE_NR; j++)
407 fifo_for_each_entry(i, &ca->free[j], iter)
408 bch2_mark_alloc_bucket(c, ca, i, true,
409 gc_pos_alloc(c, NULL),
410 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
411 BCH_BUCKET_MARK_GC_LOCK_HELD);
414 spin_unlock(&c->freelist_lock);
416 for (ob = c->open_buckets;
417 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
419 spin_lock(&ob->lock);
421 gc_pos_set(c, gc_pos_alloc(c, ob));
422 ca = bch_dev_bkey_exists(c, ob->ptr.dev);
423 bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
425 BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE|
426 BCH_BUCKET_MARK_GC_LOCK_HELD);
428 spin_unlock(&ob->lock);
432 static void bch2_gc_start(struct bch_fs *c)
435 struct bucket_array *buckets;
436 struct bucket_mark new;
441 lg_global_lock(&c->usage_lock);
444 * Indicates to buckets code that gc is now in progress - done under
445 * usage_lock to avoid racing with bch2_mark_key():
447 __gc_pos_set(c, GC_POS_MIN);
449 /* Save a copy of the existing bucket stats while we recompute them: */
450 for_each_member_device(ca, c, i) {
451 ca->usage_cached = __bch2_dev_usage_read(ca);
452 for_each_possible_cpu(cpu) {
453 struct bch_dev_usage *p =
454 per_cpu_ptr(ca->usage_percpu, cpu);
455 memset(p, 0, sizeof(*p));
459 c->usage_cached = __bch2_fs_usage_read(c);
460 for_each_possible_cpu(cpu) {
461 struct bch_fs_usage *p =
462 per_cpu_ptr(c->usage_percpu, cpu);
464 memset(p->s, 0, sizeof(p->s));
467 lg_global_unlock(&c->usage_lock);
469 /* Clear bucket marks: */
470 for_each_member_device(ca, c, i) {
471 down_read(&ca->bucket_lock);
472 buckets = bucket_array(ca);
474 for (b = buckets->first_bucket; b < buckets->nbuckets; b++) {
475 bucket_cmpxchg(buckets->b + b, new, ({
476 new.owned_by_allocator = 0;
478 new.cached_sectors = 0;
479 new.dirty_sectors = 0;
481 ca->oldest_gens[b] = new.gen;
483 up_read(&ca->bucket_lock);
488 * bch_gc - recompute bucket marks and oldest_gen, rewrite btree nodes
490 void bch2_gc(struct bch_fs *c)
493 u64 start_time = local_clock();
497 * Walk _all_ references to buckets, and recompute them:
499 * Order matters here:
500 * - Concurrent GC relies on the fact that we have a total ordering for
501 * everything that GC walks - see gc_will_visit_node(),
502 * gc_will_visit_root()
504 * - also, references move around in the course of index updates and
505 * various other crap: everything needs to agree on the ordering
506 * references are allowed to move around in - e.g., we're allowed to
507 * start with a reference owned by an open_bucket (the allocator) and
508 * move it to the btree, but not the reverse.
510 * This is necessary to ensure that gc doesn't miss references that
511 * move around - if references move backwards in the ordering GC
512 * uses, GC could skip past them
517 * Do this before taking gc_lock - bch2_disk_reservation_get() blocks on
518 * gc_lock if sectors_available goes to 0:
520 bch2_recalc_sectors_available(c);
522 down_write(&c->gc_lock);
523 if (test_bit(BCH_FS_GC_FAILURE, &c->flags))
529 while (c->gc_pos.phase < (int) BTREE_ID_NR) {
530 int ret = c->btree_roots[c->gc_pos.phase].b
531 ? bch2_gc_btree(c, (int) c->gc_pos.phase)
535 bch_err(c, "btree gc failed: %d", ret);
536 set_bit(BCH_FS_GC_FAILURE, &c->flags);
540 gc_pos_set(c, gc_phase(c->gc_pos.phase + 1));
543 bch2_mark_superblocks(c);
544 bch2_mark_pending_btree_node_frees(c);
545 bch2_mark_allocator_buckets(c);
547 for_each_member_device(ca, c, i)
548 atomic_long_set(&ca->saturated_count, 0);
550 /* Indicates that gc is no longer in progress: */
551 gc_pos_set(c, gc_phase(GC_PHASE_DONE));
554 up_write(&c->gc_lock);
556 bch2_time_stats_update(&c->btree_gc_time, start_time);
559 * Wake up allocator in case it was waiting for buckets
560 * because of not being able to inc gens
562 for_each_member_device(ca, c, i)
563 bch2_wake_allocator(ca);
566 * At startup, allocations can happen directly instead of via the
567 * allocator thread - issue wakeup in case they blocked on gc_lock:
569 closure_wake_up(&c->freelist_wait);
572 /* Btree coalescing */
574 static void recalc_packed_keys(struct btree *b)
576 struct bkey_packed *k;
578 memset(&b->nr, 0, sizeof(b->nr));
580 BUG_ON(b->nsets != 1);
582 for (k = btree_bkey_first(b, b->set);
583 k != btree_bkey_last(b, b->set);
585 btree_keys_account_key_add(&b->nr, 0, k);
588 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
589 struct btree *old_nodes[GC_MERGE_NODES])
591 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
592 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
593 unsigned blocks = btree_blocks(c) * 2 / 3;
594 struct btree *new_nodes[GC_MERGE_NODES];
595 struct btree_update *as;
596 struct keylist keylist;
597 struct bkey_format_state format_state;
598 struct bkey_format new_format;
600 memset(new_nodes, 0, sizeof(new_nodes));
601 bch2_keylist_init(&keylist, NULL);
603 /* Count keys that are not deleted */
604 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
605 u64s += old_nodes[i]->nr.live_u64s;
607 nr_old_nodes = nr_new_nodes = i;
609 /* Check if all keys in @old_nodes could fit in one fewer node */
610 if (nr_old_nodes <= 1 ||
611 __vstruct_blocks(struct btree_node, c->block_bits,
612 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
615 /* Find a format that all keys in @old_nodes can pack into */
616 bch2_bkey_format_init(&format_state);
618 for (i = 0; i < nr_old_nodes; i++)
619 __bch2_btree_calc_format(&format_state, old_nodes[i]);
621 new_format = bch2_bkey_format_done(&format_state);
623 /* Check if repacking would make any nodes too big to fit */
624 for (i = 0; i < nr_old_nodes; i++)
625 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
626 trace_btree_gc_coalesce_fail(c,
627 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
631 if (bch2_keylist_realloc(&keylist, NULL, 0,
632 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
633 trace_btree_gc_coalesce_fail(c,
634 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
638 as = bch2_btree_update_start(c, iter->btree_id,
639 btree_update_reserve_required(c, parent) + nr_old_nodes,
641 BTREE_INSERT_USE_RESERVE,
644 trace_btree_gc_coalesce_fail(c,
645 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
646 bch2_keylist_free(&keylist, NULL);
650 trace_btree_gc_coalesce(c, old_nodes[0]);
652 for (i = 0; i < nr_old_nodes; i++)
653 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
655 /* Repack everything with @new_format and sort down to one bset */
656 for (i = 0; i < nr_old_nodes; i++)
658 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
662 * Conceptually we concatenate the nodes together and slice them
663 * up at different boundaries.
665 for (i = nr_new_nodes - 1; i > 0; --i) {
666 struct btree *n1 = new_nodes[i];
667 struct btree *n2 = new_nodes[i - 1];
669 struct bset *s1 = btree_bset_first(n1);
670 struct bset *s2 = btree_bset_first(n2);
671 struct bkey_packed *k, *last = NULL;
673 /* Calculate how many keys from @n2 we could fit inside @n1 */
677 k < vstruct_last(s2) &&
678 vstruct_blocks_plus(n1->data, c->block_bits,
679 u64s + k->u64s) <= blocks;
685 if (u64s == le16_to_cpu(s2->u64s)) {
686 /* n2 fits entirely in n1 */
687 n1->key.k.p = n1->data->max_key = n2->data->max_key;
689 memcpy_u64s(vstruct_last(s1),
691 le16_to_cpu(s2->u64s));
692 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
694 set_btree_bset_end(n1, n1->set);
696 six_unlock_write(&n2->lock);
697 bch2_btree_node_free_never_inserted(c, n2);
698 six_unlock_intent(&n2->lock);
700 memmove(new_nodes + i - 1,
702 sizeof(new_nodes[0]) * (nr_new_nodes - i));
703 new_nodes[--nr_new_nodes] = NULL;
705 /* move part of n2 into n1 */
706 n1->key.k.p = n1->data->max_key =
707 bkey_unpack_pos(n1, last);
710 btree_type_successor(iter->btree_id,
713 memcpy_u64s(vstruct_last(s1),
715 le16_add_cpu(&s1->u64s, u64s);
718 vstruct_idx(s2, u64s),
719 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
720 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
722 set_btree_bset_end(n1, n1->set);
723 set_btree_bset_end(n2, n2->set);
727 for (i = 0; i < nr_new_nodes; i++) {
728 struct btree *n = new_nodes[i];
730 recalc_packed_keys(n);
731 btree_node_reset_sib_u64s(n);
733 bch2_btree_build_aux_trees(n);
734 six_unlock_write(&n->lock);
736 bch2_btree_node_write(c, n, SIX_LOCK_intent);
740 * The keys for the old nodes get deleted. We don't want to insert keys
741 * that compare equal to the keys for the new nodes we'll also be
742 * inserting - we can't because keys on a keylist must be strictly
743 * greater than the previous keys, and we also don't need to since the
744 * key for the new node will serve the same purpose (overwriting the key
747 for (i = 0; i < nr_old_nodes; i++) {
748 struct bkey_i delete;
751 for (j = 0; j < nr_new_nodes; j++)
752 if (!bkey_cmp(old_nodes[i]->key.k.p,
753 new_nodes[j]->key.k.p))
756 bkey_init(&delete.k);
757 delete.k.p = old_nodes[i]->key.k.p;
758 bch2_keylist_add_in_order(&keylist, &delete);
764 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
765 * does the lookup once and thus expects the keys to be in sorted order
766 * so we have to make sure the new keys are correctly ordered with
767 * respect to the deleted keys added in the previous loop
769 for (i = 0; i < nr_new_nodes; i++)
770 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
772 /* Insert the newly coalesced nodes */
773 bch2_btree_insert_node(as, parent, iter, &keylist);
775 BUG_ON(!bch2_keylist_empty(&keylist));
777 BUG_ON(iter->l[old_nodes[0]->level].b != old_nodes[0]);
779 BUG_ON(!bch2_btree_iter_node_replace(iter, new_nodes[0]));
781 for (i = 0; i < nr_new_nodes; i++)
782 bch2_btree_open_bucket_put(c, new_nodes[i]);
784 /* Free the old nodes and update our sliding window */
785 for (i = 0; i < nr_old_nodes; i++) {
786 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
787 six_unlock_intent(&old_nodes[i]->lock);
790 * the index update might have triggered a split, in which case
791 * the nodes we coalesced - the new nodes we just created -
792 * might not be sibling nodes anymore - don't add them to the
793 * sliding window (except the first):
796 old_nodes[i] = new_nodes[i];
800 six_unlock_intent(&new_nodes[i]->lock);
804 bch2_btree_update_done(as);
805 bch2_keylist_free(&keylist, NULL);
808 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
810 struct btree_iter iter;
814 /* Sliding window of adjacent btree nodes */
815 struct btree *merge[GC_MERGE_NODES];
816 u32 lock_seq[GC_MERGE_NODES];
819 * XXX: We don't have a good way of positively matching on sibling nodes
820 * that have the same parent - this code works by handling the cases
821 * where they might not have the same parent, and is thus fragile. Ugh.
823 * Perhaps redo this to use multiple linked iterators?
825 memset(merge, 0, sizeof(merge));
827 __for_each_btree_node(&iter, c, btree_id, POS_MIN,
829 BTREE_ITER_PREFETCH, b) {
830 memmove(merge + 1, merge,
831 sizeof(merge) - sizeof(merge[0]));
832 memmove(lock_seq + 1, lock_seq,
833 sizeof(lock_seq) - sizeof(lock_seq[0]));
837 for (i = 1; i < GC_MERGE_NODES; i++) {
839 !six_relock_intent(&merge[i]->lock, lock_seq[i]))
842 if (merge[i]->level != merge[0]->level) {
843 six_unlock_intent(&merge[i]->lock);
847 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
849 bch2_coalesce_nodes(c, &iter, merge);
851 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
852 lock_seq[i] = merge[i]->lock.state.seq;
853 six_unlock_intent(&merge[i]->lock);
856 lock_seq[0] = merge[0]->lock.state.seq;
858 if (test_bit(BCH_FS_GC_STOPPING, &c->flags)) {
859 bch2_btree_iter_unlock(&iter);
863 bch2_btree_iter_cond_resched(&iter);
866 * If the parent node wasn't relocked, it might have been split
867 * and the nodes in our sliding window might not have the same
868 * parent anymore - blow away the sliding window:
870 if (btree_iter_node(&iter, iter.level + 1) &&
871 !btree_node_intent_locked(&iter, iter.level + 1))
873 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
875 return bch2_btree_iter_unlock(&iter);
879 * bch_coalesce - coalesce adjacent nodes with low occupancy
881 void bch2_coalesce(struct bch_fs *c)
885 if (test_bit(BCH_FS_GC_FAILURE, &c->flags))
888 down_read(&c->gc_lock);
889 trace_gc_coalesce_start(c);
891 for (id = 0; id < BTREE_ID_NR; id++) {
892 int ret = c->btree_roots[id].b
893 ? bch2_coalesce_btree(c, id)
897 if (ret != -ESHUTDOWN)
898 bch_err(c, "btree coalescing failed: %d", ret);
899 set_bit(BCH_FS_GC_FAILURE, &c->flags);
904 trace_gc_coalesce_end(c);
905 up_read(&c->gc_lock);
908 static int bch2_gc_thread(void *arg)
910 struct bch_fs *c = arg;
911 struct io_clock *clock = &c->io_clock[WRITE];
912 unsigned long last = atomic_long_read(&clock->now);
913 unsigned last_kick = atomic_read(&c->kick_gc);
919 set_current_state(TASK_INTERRUPTIBLE);
921 if (kthread_should_stop()) {
922 __set_current_state(TASK_RUNNING);
926 if (atomic_read(&c->kick_gc) != last_kick)
929 if (c->btree_gc_periodic) {
930 unsigned long next = last + c->capacity / 16;
932 if (atomic_long_read(&clock->now) >= next)
935 bch2_io_clock_schedule_timeout(clock, next);
942 __set_current_state(TASK_RUNNING);
944 last = atomic_long_read(&clock->now);
945 last_kick = atomic_read(&c->kick_gc);
949 debug_check_no_locks_held();
955 void bch2_gc_thread_stop(struct bch_fs *c)
957 set_bit(BCH_FS_GC_STOPPING, &c->flags);
960 kthread_stop(c->gc_thread);
963 clear_bit(BCH_FS_GC_STOPPING, &c->flags);
966 int bch2_gc_thread_start(struct bch_fs *c)
968 struct task_struct *p;
970 BUG_ON(c->gc_thread);
972 p = kthread_create(bch2_gc_thread, c, "bcache_gc");
977 wake_up_process(c->gc_thread);
981 /* Initial GC computes bucket marks during startup */
983 static int bch2_initial_gc_btree(struct bch_fs *c, enum btree_id id)
985 struct btree_iter iter;
987 struct range_checks r;
990 btree_node_range_checks_init(&r, 0);
992 if (!c->btree_roots[id].b)
995 b = c->btree_roots[id].b;
996 if (!btree_node_fake(b))
997 ret = bch2_btree_mark_key_initial(c, BKEY_TYPE_BTREE,
998 bkey_i_to_s_c(&b->key));
1003 * We have to hit every btree node before starting journal replay, in
1004 * order for the journal seq blacklist machinery to work:
1006 for_each_btree_node(&iter, c, id, POS_MIN, BTREE_ITER_PREFETCH, b) {
1007 btree_node_range_checks(c, b, &r);
1009 if (btree_node_has_ptrs(b)) {
1010 struct btree_node_iter node_iter;
1011 struct bkey unpacked;
1014 for_each_btree_node_key_unpack(b, k, &node_iter,
1015 btree_node_is_extents(b),
1017 ret = bch2_btree_mark_key_initial(c,
1018 btree_node_type(b), k);
1024 bch2_btree_iter_cond_resched(&iter);
1027 return bch2_btree_iter_unlock(&iter) ?: ret;
1030 static int __bch2_initial_gc(struct bch_fs *c, struct list_head *journal)
1036 mutex_lock(&c->sb_lock);
1037 if (!bch2_sb_get_replicas(c->disk_sb)) {
1038 if (BCH_SB_INITIALIZED(c->disk_sb))
1039 bch_info(c, "building replicas info");
1040 set_bit(BCH_FS_REBUILD_REPLICAS, &c->flags);
1042 mutex_unlock(&c->sb_lock);
1046 for (id = 0; id < BTREE_ID_NR; id++) {
1047 ret = bch2_initial_gc_btree(c, id);
1052 ret = bch2_journal_mark(c, journal);
1056 if (test_bit(BCH_FS_FIXED_GENS, &c->flags)) {
1058 bch_info(c, "Unable to fix bucket gens, looping");
1062 bch_info(c, "Fixed gens, restarting initial mark and sweep:");
1063 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
1068 * Skip past versions that might have possibly been used (as nonces),
1069 * but hadn't had their pointers written:
1071 if (c->sb.encryption_type)
1072 atomic64_add(1 << 16, &c->key_version);
1074 bch2_mark_superblocks(c);
1076 gc_pos_set(c, gc_phase(GC_PHASE_DONE));
1077 set_bit(BCH_FS_INITIAL_GC_DONE, &c->flags);
1082 int bch2_initial_gc(struct bch_fs *c, struct list_head *journal)
1086 down_write(&c->gc_lock);
1087 ret = __bch2_initial_gc(c, journal);
1088 up_write(&c->gc_lock);