3 #include "btree_cache.h"
5 #include "btree_iter.h"
6 #include "btree_locking.h"
10 #include <linux/prefetch.h>
11 #include <trace/events/bcachefs.h>
13 #define DEF_BTREE_ID(kwd, val, name) name,
15 const char * const bch2_btree_ids[] = {
16 DEFINE_BCH_BTREE_IDS()
22 void bch2_recalc_btree_reserve(struct bch_fs *c)
24 unsigned i, reserve = 16;
26 if (!c->btree_roots[0].b)
29 for (i = 0; i < BTREE_ID_NR; i++)
30 if (c->btree_roots[i].b)
31 reserve += min_t(unsigned, 1,
32 c->btree_roots[i].b->level) * 8;
34 c->btree_cache.reserve = reserve;
37 static inline unsigned btree_cache_can_free(struct btree_cache *bc)
39 return max_t(int, 0, bc->used - bc->reserve);
42 static void __btree_node_data_free(struct bch_fs *c, struct btree *b)
44 EBUG_ON(btree_node_write_in_flight(b));
46 kvpfree(b->data, btree_bytes(c));
48 bch2_btree_keys_free(b);
51 static void btree_node_data_free(struct bch_fs *c, struct btree *b)
53 struct btree_cache *bc = &c->btree_cache;
55 __btree_node_data_free(c, b);
57 list_move(&b->list, &bc->freed);
60 static int bch2_btree_cache_cmp_fn(struct rhashtable_compare_arg *arg,
63 const struct btree *b = obj;
64 const u64 *v = arg->key;
66 return PTR_HASH(&b->key) == *v ? 0 : 1;
69 static const struct rhashtable_params bch_btree_cache_params = {
70 .head_offset = offsetof(struct btree, hash),
71 .key_offset = offsetof(struct btree, key.v),
72 .key_len = sizeof(struct bch_extent_ptr),
73 .obj_cmpfn = bch2_btree_cache_cmp_fn,
76 static void btree_node_data_alloc(struct bch_fs *c, struct btree *b, gfp_t gfp)
78 struct btree_cache *bc = &c->btree_cache;
80 b->data = kvpmalloc(btree_bytes(c), gfp);
84 if (bch2_btree_keys_alloc(b, btree_page_order(c), gfp))
88 list_move(&b->list, &bc->freeable);
91 kvpfree(b->data, btree_bytes(c));
93 list_move(&b->list, &bc->freed);
96 static struct btree *btree_node_mem_alloc(struct bch_fs *c, gfp_t gfp)
98 struct btree *b = kzalloc(sizeof(struct btree), gfp);
102 bkey_extent_init(&b->key);
103 six_lock_init(&b->lock);
104 INIT_LIST_HEAD(&b->list);
105 INIT_LIST_HEAD(&b->write_blocked);
107 btree_node_data_alloc(c, b, gfp);
108 return b->data ? b : NULL;
111 /* Btree in memory cache - hash table */
113 void bch2_btree_node_hash_remove(struct btree_cache *bc, struct btree *b)
115 rhashtable_remove_fast(&bc->table, &b->hash, bch_btree_cache_params);
117 /* Cause future lookups for this node to fail: */
118 bkey_i_to_extent(&b->key)->v._data[0] = 0;
121 int __bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b)
123 return rhashtable_lookup_insert_fast(&bc->table, &b->hash,
124 bch_btree_cache_params);
127 int bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b,
128 unsigned level, enum btree_id id)
135 mutex_lock(&bc->lock);
136 ret = __bch2_btree_node_hash_insert(bc, b);
138 list_add(&b->list, &bc->live);
139 mutex_unlock(&bc->lock);
145 static inline struct btree *btree_cache_find(struct btree_cache *bc,
146 const struct bkey_i *k)
148 return rhashtable_lookup_fast(&bc->table, &PTR_HASH(k),
149 bch_btree_cache_params);
153 * this version is for btree nodes that have already been freed (we're not
154 * reaping a real btree node)
156 static int __btree_node_reclaim(struct bch_fs *c, struct btree *b, bool flush)
158 struct btree_cache *bc = &c->btree_cache;
161 lockdep_assert_held(&bc->lock);
163 if (!six_trylock_intent(&b->lock))
166 if (!six_trylock_write(&b->lock))
167 goto out_unlock_intent;
169 if (btree_node_noevict(b))
172 if (!btree_node_may_write(b))
175 if (btree_node_dirty(b) ||
176 btree_node_write_in_flight(b) ||
177 btree_node_read_in_flight(b)) {
181 wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
182 TASK_UNINTERRUPTIBLE);
185 * Using the underscore version because we don't want to compact
186 * bsets after the write, since this node is about to be evicted
187 * - unless btree verify mode is enabled, since it runs out of
188 * the post write cleanup:
190 if (verify_btree_ondisk(c))
191 bch2_btree_node_write(c, b, SIX_LOCK_intent);
193 __bch2_btree_node_write(c, b, SIX_LOCK_read);
195 /* wait for any in flight btree write */
196 btree_node_wait_on_io(b);
199 if (PTR_HASH(&b->key) && !ret)
200 trace_btree_node_reap(c, b);
203 six_unlock_write(&b->lock);
205 six_unlock_intent(&b->lock);
210 static int btree_node_reclaim(struct bch_fs *c, struct btree *b)
212 return __btree_node_reclaim(c, b, false);
215 static int btree_node_write_and_reclaim(struct bch_fs *c, struct btree *b)
217 return __btree_node_reclaim(c, b, true);
220 static unsigned long bch2_btree_cache_scan(struct shrinker *shrink,
221 struct shrink_control *sc)
223 struct bch_fs *c = container_of(shrink, struct bch_fs,
225 struct btree_cache *bc = &c->btree_cache;
227 unsigned long nr = sc->nr_to_scan;
228 unsigned long can_free;
229 unsigned long touched = 0;
230 unsigned long freed = 0;
233 if (btree_shrinker_disabled(c))
236 /* Return -1 if we can't do anything right now */
237 if (sc->gfp_mask & __GFP_IO)
238 mutex_lock(&bc->lock);
239 else if (!mutex_trylock(&bc->lock))
243 * It's _really_ critical that we don't free too many btree nodes - we
244 * have to always leave ourselves a reserve. The reserve is how we
245 * guarantee that allocating memory for a new btree node can always
246 * succeed, so that inserting keys into the btree can always succeed and
247 * IO can always make forward progress:
249 nr /= btree_pages(c);
250 can_free = btree_cache_can_free(bc);
251 nr = min_t(unsigned long, nr, can_free);
254 list_for_each_entry_safe(b, t, &bc->freeable, list) {
261 !btree_node_reclaim(c, b)) {
262 btree_node_data_free(c, b);
263 six_unlock_write(&b->lock);
264 six_unlock_intent(&b->lock);
269 list_for_each_entry_safe(b, t, &bc->live, list) {
274 if (&t->list != &bc->live)
275 list_move_tail(&bc->live, &t->list);
279 if (!btree_node_accessed(b) &&
280 !btree_node_reclaim(c, b)) {
281 /* can't call bch2_btree_node_hash_remove under lock */
283 if (&t->list != &bc->live)
284 list_move_tail(&bc->live, &t->list);
286 btree_node_data_free(c, b);
287 mutex_unlock(&bc->lock);
289 bch2_btree_node_hash_remove(bc, b);
290 six_unlock_write(&b->lock);
291 six_unlock_intent(&b->lock);
296 if (sc->gfp_mask & __GFP_IO)
297 mutex_lock(&bc->lock);
298 else if (!mutex_trylock(&bc->lock))
302 clear_btree_node_accessed(b);
305 mutex_unlock(&bc->lock);
307 return (unsigned long) freed * btree_pages(c);
310 static unsigned long bch2_btree_cache_count(struct shrinker *shrink,
311 struct shrink_control *sc)
313 struct bch_fs *c = container_of(shrink, struct bch_fs,
315 struct btree_cache *bc = &c->btree_cache;
317 if (btree_shrinker_disabled(c))
320 return btree_cache_can_free(bc) * btree_pages(c);
323 void bch2_fs_btree_cache_exit(struct bch_fs *c)
325 struct btree_cache *bc = &c->btree_cache;
329 if (bc->shrink.list.next)
330 unregister_shrinker(&bc->shrink);
332 mutex_lock(&bc->lock);
334 #ifdef CONFIG_BCACHEFS_DEBUG
336 list_move(&c->verify_data->list, &bc->live);
338 kvpfree(c->verify_ondisk, btree_bytes(c));
341 for (i = 0; i < BTREE_ID_NR; i++)
342 if (c->btree_roots[i].b)
343 list_add(&c->btree_roots[i].b->list, &bc->live);
345 list_splice(&bc->freeable, &bc->live);
347 while (!list_empty(&bc->live)) {
348 b = list_first_entry(&bc->live, struct btree, list);
350 BUG_ON(btree_node_read_in_flight(b) ||
351 btree_node_write_in_flight(b));
353 if (btree_node_dirty(b))
354 bch2_btree_complete_write(c, b, btree_current_write(b));
355 clear_btree_node_dirty(b);
357 btree_node_data_free(c, b);
360 while (!list_empty(&bc->freed)) {
361 b = list_first_entry(&bc->freed, struct btree, list);
366 mutex_unlock(&bc->lock);
368 if (bc->table_init_done)
369 rhashtable_destroy(&bc->table);
372 int bch2_fs_btree_cache_init(struct bch_fs *c)
374 struct btree_cache *bc = &c->btree_cache;
378 pr_verbose_init(c->opts, "");
380 ret = rhashtable_init(&bc->table, &bch_btree_cache_params);
384 bc->table_init_done = true;
386 bch2_recalc_btree_reserve(c);
388 for (i = 0; i < bc->reserve; i++)
389 if (!btree_node_mem_alloc(c, GFP_KERNEL)) {
394 list_splice_init(&bc->live, &bc->freeable);
396 #ifdef CONFIG_BCACHEFS_DEBUG
397 mutex_init(&c->verify_lock);
399 c->verify_ondisk = kvpmalloc(btree_bytes(c), GFP_KERNEL);
400 if (!c->verify_ondisk) {
405 c->verify_data = btree_node_mem_alloc(c, GFP_KERNEL);
406 if (!c->verify_data) {
411 list_del_init(&c->verify_data->list);
414 bc->shrink.count_objects = bch2_btree_cache_count;
415 bc->shrink.scan_objects = bch2_btree_cache_scan;
416 bc->shrink.seeks = 4;
417 bc->shrink.batch = btree_pages(c) * 2;
418 register_shrinker(&bc->shrink);
420 pr_verbose_init(c->opts, "ret %i", ret);
424 void bch2_fs_btree_cache_init_early(struct btree_cache *bc)
426 mutex_init(&bc->lock);
427 INIT_LIST_HEAD(&bc->live);
428 INIT_LIST_HEAD(&bc->freeable);
429 INIT_LIST_HEAD(&bc->freed);
433 * We can only have one thread cannibalizing other cached btree nodes at a time,
434 * or we'll deadlock. We use an open coded mutex to ensure that, which a
435 * cannibalize_bucket() will take. This means every time we unlock the root of
436 * the btree, we need to release this lock if we have it held.
438 void bch2_btree_cache_cannibalize_unlock(struct bch_fs *c)
440 struct btree_cache *bc = &c->btree_cache;
442 if (bc->alloc_lock == current) {
443 trace_btree_node_cannibalize_unlock(c);
444 bc->alloc_lock = NULL;
445 closure_wake_up(&bc->alloc_wait);
449 int bch2_btree_cache_cannibalize_lock(struct bch_fs *c, struct closure *cl)
451 struct btree_cache *bc = &c->btree_cache;
452 struct task_struct *old;
454 old = cmpxchg(&bc->alloc_lock, NULL, current);
455 if (old == NULL || old == current)
459 trace_btree_node_cannibalize_lock_fail(c);
463 closure_wait(&bc->alloc_wait, cl);
465 /* Try again, after adding ourselves to waitlist */
466 old = cmpxchg(&bc->alloc_lock, NULL, current);
467 if (old == NULL || old == current) {
469 closure_wake_up(&bc->alloc_wait);
473 trace_btree_node_cannibalize_lock_fail(c);
477 trace_btree_node_cannibalize_lock(c);
481 static struct btree *btree_node_cannibalize(struct bch_fs *c)
483 struct btree_cache *bc = &c->btree_cache;
486 list_for_each_entry_reverse(b, &bc->live, list)
487 if (!btree_node_reclaim(c, b))
491 list_for_each_entry_reverse(b, &bc->live, list)
492 if (!btree_node_write_and_reclaim(c, b))
496 * Rare case: all nodes were intent-locked.
499 WARN_ONCE(1, "btree cache cannibalize failed\n");
504 struct btree *bch2_btree_node_mem_alloc(struct bch_fs *c)
506 struct btree_cache *bc = &c->btree_cache;
508 u64 start_time = local_clock();
510 mutex_lock(&bc->lock);
513 * btree_free() doesn't free memory; it sticks the node on the end of
514 * the list. Check if there's any freed nodes there:
516 list_for_each_entry(b, &bc->freeable, list)
517 if (!btree_node_reclaim(c, b))
521 * We never free struct btree itself, just the memory that holds the on
522 * disk node. Check the freed list before allocating a new one:
524 list_for_each_entry(b, &bc->freed, list)
525 if (!btree_node_reclaim(c, b)) {
526 btree_node_data_alloc(c, b, __GFP_NOWARN|GFP_NOIO);
530 six_unlock_write(&b->lock);
531 six_unlock_intent(&b->lock);
535 b = btree_node_mem_alloc(c, __GFP_NOWARN|GFP_NOIO);
539 BUG_ON(!six_trylock_intent(&b->lock));
540 BUG_ON(!six_trylock_write(&b->lock));
542 BUG_ON(btree_node_hashed(b));
543 BUG_ON(btree_node_write_in_flight(b));
545 list_del_init(&b->list);
546 mutex_unlock(&bc->lock);
553 b->whiteout_u64s = 0;
554 b->uncompacted_whiteout_u64s = 0;
555 bch2_btree_keys_init(b, &c->expensive_debug_checks);
557 bch2_time_stats_update(&c->btree_node_mem_alloc_time, start_time);
561 /* Try to cannibalize another cached btree node: */
562 if (bc->alloc_lock == current) {
563 b = btree_node_cannibalize(c);
564 list_del_init(&b->list);
565 mutex_unlock(&bc->lock);
567 bch2_btree_node_hash_remove(bc, b);
569 trace_btree_node_cannibalize(c);
573 mutex_unlock(&bc->lock);
574 return ERR_PTR(-ENOMEM);
577 /* Slowpath, don't want it inlined into btree_iter_traverse() */
578 static noinline struct btree *bch2_btree_node_fill(struct bch_fs *c,
579 struct btree_iter *iter,
580 const struct bkey_i *k,
582 enum six_lock_type lock_type)
584 struct btree_cache *bc = &c->btree_cache;
588 * Parent node must be locked, else we could read in a btree node that's
591 BUG_ON(!btree_node_locked(iter, level + 1));
593 b = bch2_btree_node_mem_alloc(c);
597 bkey_copy(&b->key, k);
598 if (bch2_btree_node_hash_insert(bc, b, level, iter->btree_id)) {
599 /* raced with another fill: */
601 /* mark as unhashed... */
602 bkey_i_to_extent(&b->key)->v._data[0] = 0;
604 mutex_lock(&bc->lock);
605 list_add(&b->list, &bc->freeable);
606 mutex_unlock(&bc->lock);
608 six_unlock_write(&b->lock);
609 six_unlock_intent(&b->lock);
614 * If the btree node wasn't cached, we can't drop our lock on
615 * the parent until after it's added to the cache - because
616 * otherwise we could race with a btree_split() freeing the node
617 * we're trying to lock.
619 * But the deadlock described below doesn't exist in this case,
620 * so it's safe to not drop the parent lock until here:
622 if (btree_node_read_locked(iter, level + 1))
623 btree_node_unlock(iter, level + 1);
625 bch2_btree_node_read(c, b, true);
626 six_unlock_write(&b->lock);
628 if (lock_type == SIX_LOCK_read)
629 six_lock_downgrade(&b->lock);
635 * bch_btree_node_get - find a btree node in the cache and lock it, reading it
636 * in from disk if necessary.
638 * If IO is necessary and running under generic_make_request, returns -EAGAIN.
640 * The btree node will have either a read or a write lock held, depending on
641 * the @write parameter.
643 struct btree *bch2_btree_node_get(struct bch_fs *c, struct btree_iter *iter,
644 const struct bkey_i *k, unsigned level,
645 enum six_lock_type lock_type)
647 struct btree_cache *bc = &c->btree_cache;
651 /* btree_node_fill() requires parent to be locked: */
652 EBUG_ON(!btree_node_locked(iter, level + 1));
653 EBUG_ON(level >= BTREE_MAX_DEPTH);
656 b = btree_cache_find(bc, k);
661 * We must have the parent locked to call bch2_btree_node_fill(),
662 * else we could read in a btree node from disk that's been
665 b = bch2_btree_node_fill(c, iter, k, level, lock_type);
667 /* We raced and found the btree node in the cache */
675 * There's a potential deadlock with splits and insertions into
676 * interior nodes we have to avoid:
678 * The other thread might be holding an intent lock on the node
679 * we want, and they want to update its parent node so they're
680 * going to upgrade their intent lock on the parent node to a
683 * But if we're holding a read lock on the parent, and we're
684 * trying to get the intent lock they're holding, we deadlock.
686 * So to avoid this we drop the read locks on parent nodes when
687 * we're starting to take intent locks - and handle the race.
689 * The race is that they might be about to free the node we
690 * want, and dropping our read lock on the parent node lets them
691 * update the parent marking the node we want as freed, and then
694 * To guard against this, btree nodes are evicted from the cache
695 * when they're freed - and PTR_HASH() is zeroed out, which we
696 * check for after we lock the node.
698 * Then, bch2_btree_node_relock() on the parent will fail - because
699 * the parent was modified, when the pointer to the node we want
700 * was removed - and we'll bail out:
702 if (btree_node_read_locked(iter, level + 1))
703 btree_node_unlock(iter, level + 1);
705 if (!btree_node_lock(b, k->k.p, level, iter, lock_type))
706 return ERR_PTR(-EINTR);
708 if (unlikely(PTR_HASH(&b->key) != PTR_HASH(k) ||
711 six_unlock_type(&b->lock, lock_type);
712 if (bch2_btree_node_relock(iter, level + 1))
715 return ERR_PTR(-EINTR);
719 wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
720 TASK_UNINTERRUPTIBLE);
722 prefetch(b->aux_data);
724 for_each_bset(b, t) {
725 void *p = (u64 *) b->aux_data + t->aux_data_offset;
727 prefetch(p + L1_CACHE_BYTES * 0);
728 prefetch(p + L1_CACHE_BYTES * 1);
729 prefetch(p + L1_CACHE_BYTES * 2);
732 /* avoid atomic set bit if it's not needed: */
733 if (btree_node_accessed(b))
734 set_btree_node_accessed(b);
736 if (unlikely(btree_node_read_error(b))) {
737 six_unlock_type(&b->lock, lock_type);
738 return ERR_PTR(-EIO);
741 EBUG_ON(!b->written);
742 EBUG_ON(b->btree_id != iter->btree_id ||
743 BTREE_NODE_LEVEL(b->data) != level ||
744 bkey_cmp(b->data->max_key, k->k.p));
749 struct btree *bch2_btree_node_get_sibling(struct bch_fs *c,
750 struct btree_iter *iter,
752 enum btree_node_sibling sib)
754 struct btree *parent;
755 struct btree_node_iter node_iter;
756 struct bkey_packed *k;
759 unsigned level = b->level;
761 parent = btree_iter_node(iter, level + 1);
765 if (!bch2_btree_node_relock(iter, level + 1)) {
766 bch2_btree_iter_set_locks_want(iter, level + 2);
767 return ERR_PTR(-EINTR);
770 node_iter = iter->l[parent->level].iter;
772 k = bch2_btree_node_iter_peek_all(&node_iter, parent);
773 BUG_ON(bkey_cmp_left_packed(parent, k, &b->key.k.p));
776 k = sib == btree_prev_sib
777 ? bch2_btree_node_iter_prev_all(&node_iter, parent)
778 : (bch2_btree_node_iter_advance(&node_iter, parent),
779 bch2_btree_node_iter_peek_all(&node_iter, parent));
782 } while (bkey_deleted(k));
784 bch2_bkey_unpack(parent, &tmp.k, k);
786 ret = bch2_btree_node_get(c, iter, &tmp.k, level, SIX_LOCK_intent);
788 if (IS_ERR(ret) && PTR_ERR(ret) == -EINTR) {
789 btree_node_unlock(iter, level);
791 if (!bch2_btree_node_relock(iter, level + 1)) {
792 bch2_btree_iter_set_locks_want(iter, level + 2);
793 return ERR_PTR(-EINTR);
796 ret = bch2_btree_node_get(c, iter, &tmp.k, level, SIX_LOCK_intent);
799 if (!bch2_btree_node_relock(iter, level)) {
800 btree_iter_set_dirty(iter, BTREE_ITER_NEED_RELOCK);
803 six_unlock_intent(&ret->lock);
804 ret = ERR_PTR(-EINTR);
811 void bch2_btree_node_prefetch(struct bch_fs *c, const struct bkey_i *k,
812 unsigned level, enum btree_id btree_id)
814 struct btree_cache *bc = &c->btree_cache;
817 BUG_ON(level >= BTREE_MAX_DEPTH);
820 b = btree_cache_find(bc, k);
826 b = bch2_btree_node_mem_alloc(c);
830 bkey_copy(&b->key, k);
831 if (bch2_btree_node_hash_insert(bc, b, level, btree_id)) {
832 /* raced with another fill: */
834 /* mark as unhashed... */
835 bkey_i_to_extent(&b->key)->v._data[0] = 0;
837 mutex_lock(&bc->lock);
838 list_add(&b->list, &bc->freeable);
839 mutex_unlock(&bc->lock);
843 bch2_btree_node_read(c, b, false);
845 six_unlock_write(&b->lock);
846 six_unlock_intent(&b->lock);
849 int bch2_print_btree_node(struct bch_fs *c, struct btree *b,
850 char *buf, size_t len)
852 const struct bkey_format *f = &b->format;
853 struct bset_stats stats;
856 memset(&stats, 0, sizeof(stats));
858 bch2_val_to_text(c, BKEY_TYPE_BTREE, ptrs, sizeof(ptrs),
859 bkey_i_to_s_c(&b->key));
860 bch2_btree_keys_stats(b, &stats);
862 return scnprintf(buf, len,
863 "l %u %llu:%llu - %llu:%llu:\n"
865 " format: u64s %u fields %u %u %u %u %u\n"
866 " unpack fn len: %u\n"
867 " bytes used %zu/%zu (%zu%% full)\n"
868 " sib u64s: %u, %u (merge threshold %zu)\n"
869 " nr packed keys %u\n"
870 " nr unpacked keys %u\n"
872 " failed unpacked %zu\n"
874 " failed overflow %zu\n",
876 b->data->min_key.inode,
877 b->data->min_key.offset,
878 b->data->max_key.inode,
879 b->data->max_key.offset,
882 f->bits_per_field[0],
883 f->bits_per_field[1],
884 f->bits_per_field[2],
885 f->bits_per_field[3],
886 f->bits_per_field[4],
888 b->nr.live_u64s * sizeof(u64),
889 btree_bytes(c) - sizeof(struct btree_node),
890 b->nr.live_u64s * 100 / btree_max_u64s(c),
893 BTREE_FOREGROUND_MERGE_THRESHOLD(c),
897 stats.failed_unpacked,
899 stats.failed_overflow);