3 #include "btree_cache.h"
5 #include "btree_iter.h"
6 #include "btree_locking.h"
10 #include <trace/events/bcachefs.h>
12 #define DEF_BTREE_ID(kwd, val, name) name,
14 const char * const bch2_btree_ids[] = {
15 DEFINE_BCH_BTREE_IDS()
21 void bch2_recalc_btree_reserve(struct bch_fs *c)
23 unsigned i, reserve = 16;
25 if (!c->btree_roots[0].b)
28 for (i = 0; i < BTREE_ID_NR; i++)
29 if (c->btree_roots[i].b)
30 reserve += min_t(unsigned, 1,
31 c->btree_roots[i].b->level) * 8;
33 c->btree_cache_reserve = reserve;
36 #define mca_can_free(c) \
37 max_t(int, 0, c->btree_cache_used - c->btree_cache_reserve)
39 static void __mca_data_free(struct bch_fs *c, struct btree *b)
41 EBUG_ON(btree_node_write_in_flight(b));
43 free_pages((unsigned long) b->data, btree_page_order(c));
45 bch2_btree_keys_free(b);
48 static void mca_data_free(struct bch_fs *c, struct btree *b)
50 __mca_data_free(c, b);
51 c->btree_cache_used--;
52 list_move(&b->list, &c->btree_cache_freed);
55 #define PTR_HASH(_k) (bkey_i_to_extent_c(_k)->v._data[0])
57 static const struct rhashtable_params bch_btree_cache_params = {
58 .head_offset = offsetof(struct btree, hash),
59 .key_offset = offsetof(struct btree, key.v),
60 .key_len = sizeof(struct bch_extent_ptr),
63 static void mca_data_alloc(struct bch_fs *c, struct btree *b, gfp_t gfp)
65 unsigned order = ilog2(btree_pages(c));
67 b->data = (void *) __get_free_pages(gfp, order);
71 if (bch2_btree_keys_alloc(b, order, gfp))
74 c->btree_cache_used++;
75 list_move(&b->list, &c->btree_cache_freeable);
78 free_pages((unsigned long) b->data, order);
80 list_move(&b->list, &c->btree_cache_freed);
83 static struct btree *mca_bucket_alloc(struct bch_fs *c, gfp_t gfp)
85 struct btree *b = kzalloc(sizeof(struct btree), gfp);
89 six_lock_init(&b->lock);
90 INIT_LIST_HEAD(&b->list);
91 INIT_LIST_HEAD(&b->write_blocked);
93 mca_data_alloc(c, b, gfp);
94 return b->data ? b : NULL;
97 /* Btree in memory cache - hash table */
99 void bch2_btree_node_hash_remove(struct bch_fs *c, struct btree *b)
101 BUG_ON(btree_node_dirty(b));
105 rhashtable_remove_fast(&c->btree_cache_table, &b->hash,
106 bch_btree_cache_params);
108 /* Cause future lookups for this node to fail: */
109 bkey_i_to_extent(&b->key)->v._data[0] = 0;
112 int bch2_btree_node_hash_insert(struct bch_fs *c, struct btree *b,
113 unsigned level, enum btree_id id)
119 ret = rhashtable_lookup_insert_fast(&c->btree_cache_table, &b->hash,
120 bch_btree_cache_params);
124 mutex_lock(&c->btree_cache_lock);
125 list_add(&b->list, &c->btree_cache);
126 mutex_unlock(&c->btree_cache_lock);
132 static inline struct btree *mca_find(struct bch_fs *c,
133 const struct bkey_i *k)
135 return rhashtable_lookup_fast(&c->btree_cache_table, &PTR_HASH(k),
136 bch_btree_cache_params);
140 * this version is for btree nodes that have already been freed (we're not
141 * reaping a real btree node)
143 static int mca_reap_notrace(struct bch_fs *c, struct btree *b, bool flush)
145 lockdep_assert_held(&c->btree_cache_lock);
147 if (!six_trylock_intent(&b->lock))
150 if (!six_trylock_write(&b->lock))
151 goto out_unlock_intent;
153 if (btree_node_write_error(b) ||
154 btree_node_noevict(b))
157 if (!list_empty(&b->write_blocked))
161 (btree_node_dirty(b) ||
162 btree_node_write_in_flight(b)))
166 * Using the underscore version because we don't want to compact bsets
167 * after the write, since this node is about to be evicted - unless
168 * btree verify mode is enabled, since it runs out of the post write
171 if (btree_node_dirty(b)) {
172 if (verify_btree_ondisk(c))
173 bch2_btree_node_write(c, b, NULL, SIX_LOCK_intent, -1);
175 __bch2_btree_node_write(c, b, NULL, SIX_LOCK_read, -1);
178 /* wait for any in flight btree write */
179 wait_on_bit_io(&b->flags, BTREE_NODE_write_in_flight,
180 TASK_UNINTERRUPTIBLE);
184 six_unlock_write(&b->lock);
186 six_unlock_intent(&b->lock);
190 static int mca_reap(struct bch_fs *c, struct btree *b, bool flush)
192 int ret = mca_reap_notrace(c, b, flush);
194 trace_btree_node_reap(c, b, ret);
198 static unsigned long bch2_mca_scan(struct shrinker *shrink,
199 struct shrink_control *sc)
201 struct bch_fs *c = container_of(shrink, struct bch_fs,
204 unsigned long nr = sc->nr_to_scan;
205 unsigned long can_free;
206 unsigned long touched = 0;
207 unsigned long freed = 0;
210 if (btree_shrinker_disabled(c))
213 if (c->btree_cache_alloc_lock)
216 /* Return -1 if we can't do anything right now */
217 if (sc->gfp_mask & __GFP_IO)
218 mutex_lock(&c->btree_cache_lock);
219 else if (!mutex_trylock(&c->btree_cache_lock))
223 * It's _really_ critical that we don't free too many btree nodes - we
224 * have to always leave ourselves a reserve. The reserve is how we
225 * guarantee that allocating memory for a new btree node can always
226 * succeed, so that inserting keys into the btree can always succeed and
227 * IO can always make forward progress:
229 nr /= btree_pages(c);
230 can_free = mca_can_free(c);
231 nr = min_t(unsigned long, nr, can_free);
234 list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
241 !mca_reap_notrace(c, b, false)) {
243 six_unlock_write(&b->lock);
244 six_unlock_intent(&b->lock);
249 list_for_each_entry_safe(b, t, &c->btree_cache, list) {
254 if (&t->list != &c->btree_cache)
255 list_move_tail(&c->btree_cache, &t->list);
259 if (!btree_node_accessed(b) &&
260 !mca_reap(c, b, false)) {
261 /* can't call bch2_btree_node_hash_remove under btree_cache_lock */
263 if (&t->list != &c->btree_cache)
264 list_move_tail(&c->btree_cache, &t->list);
267 mutex_unlock(&c->btree_cache_lock);
269 bch2_btree_node_hash_remove(c, b);
270 six_unlock_write(&b->lock);
271 six_unlock_intent(&b->lock);
276 if (sc->gfp_mask & __GFP_IO)
277 mutex_lock(&c->btree_cache_lock);
278 else if (!mutex_trylock(&c->btree_cache_lock))
282 clear_btree_node_accessed(b);
285 mutex_unlock(&c->btree_cache_lock);
287 return (unsigned long) freed * btree_pages(c);
290 static unsigned long bch2_mca_count(struct shrinker *shrink,
291 struct shrink_control *sc)
293 struct bch_fs *c = container_of(shrink, struct bch_fs,
296 if (btree_shrinker_disabled(c))
299 if (c->btree_cache_alloc_lock)
302 return mca_can_free(c) * btree_pages(c);
305 void bch2_fs_btree_exit(struct bch_fs *c)
310 if (c->btree_cache_shrink.list.next)
311 unregister_shrinker(&c->btree_cache_shrink);
313 mutex_lock(&c->btree_cache_lock);
315 #ifdef CONFIG_BCACHEFS_DEBUG
317 list_move(&c->verify_data->list, &c->btree_cache);
319 free_pages((unsigned long) c->verify_ondisk, ilog2(btree_pages(c)));
322 for (i = 0; i < BTREE_ID_NR; i++)
323 if (c->btree_roots[i].b)
324 list_add(&c->btree_roots[i].b->list, &c->btree_cache);
326 list_splice(&c->btree_cache_freeable,
329 while (!list_empty(&c->btree_cache)) {
330 b = list_first_entry(&c->btree_cache, struct btree, list);
332 if (btree_node_dirty(b))
333 bch2_btree_complete_write(c, b, btree_current_write(b));
334 clear_btree_node_dirty(b);
339 while (!list_empty(&c->btree_cache_freed)) {
340 b = list_first_entry(&c->btree_cache_freed,
346 mutex_unlock(&c->btree_cache_lock);
348 if (c->btree_cache_table_init_done)
349 rhashtable_destroy(&c->btree_cache_table);
352 int bch2_fs_btree_init(struct bch_fs *c)
357 ret = rhashtable_init(&c->btree_cache_table, &bch_btree_cache_params);
361 c->btree_cache_table_init_done = true;
363 bch2_recalc_btree_reserve(c);
365 for (i = 0; i < c->btree_cache_reserve; i++)
366 if (!mca_bucket_alloc(c, GFP_KERNEL))
369 list_splice_init(&c->btree_cache,
370 &c->btree_cache_freeable);
372 #ifdef CONFIG_BCACHEFS_DEBUG
373 mutex_init(&c->verify_lock);
375 c->verify_ondisk = (void *)
376 __get_free_pages(GFP_KERNEL, ilog2(btree_pages(c)));
377 if (!c->verify_ondisk)
380 c->verify_data = mca_bucket_alloc(c, GFP_KERNEL);
384 list_del_init(&c->verify_data->list);
387 c->btree_cache_shrink.count_objects = bch2_mca_count;
388 c->btree_cache_shrink.scan_objects = bch2_mca_scan;
389 c->btree_cache_shrink.seeks = 4;
390 c->btree_cache_shrink.batch = btree_pages(c) * 2;
391 register_shrinker(&c->btree_cache_shrink);
397 * We can only have one thread cannibalizing other cached btree nodes at a time,
398 * or we'll deadlock. We use an open coded mutex to ensure that, which a
399 * cannibalize_bucket() will take. This means every time we unlock the root of
400 * the btree, we need to release this lock if we have it held.
402 void bch2_btree_node_cannibalize_unlock(struct bch_fs *c)
404 if (c->btree_cache_alloc_lock == current) {
405 trace_btree_node_cannibalize_unlock(c);
406 c->btree_cache_alloc_lock = NULL;
407 closure_wake_up(&c->mca_wait);
411 int bch2_btree_node_cannibalize_lock(struct bch_fs *c, struct closure *cl)
413 struct task_struct *old;
415 old = cmpxchg(&c->btree_cache_alloc_lock, NULL, current);
416 if (old == NULL || old == current)
420 trace_btree_node_cannibalize_lock_fail(c);
424 closure_wait(&c->mca_wait, cl);
426 /* Try again, after adding ourselves to waitlist */
427 old = cmpxchg(&c->btree_cache_alloc_lock, NULL, current);
428 if (old == NULL || old == current) {
430 closure_wake_up(&c->mca_wait);
434 trace_btree_node_cannibalize_lock_fail(c);
438 trace_btree_node_cannibalize_lock(c);
442 static struct btree *mca_cannibalize(struct bch_fs *c)
446 list_for_each_entry_reverse(b, &c->btree_cache, list)
447 if (!mca_reap(c, b, false))
451 list_for_each_entry_reverse(b, &c->btree_cache, list)
452 if (!mca_reap(c, b, true))
456 * Rare case: all nodes were intent-locked.
459 WARN_ONCE(1, "btree cache cannibalize failed\n");
464 struct btree *bch2_btree_node_mem_alloc(struct bch_fs *c)
467 u64 start_time = local_clock();
469 mutex_lock(&c->btree_cache_lock);
472 * btree_free() doesn't free memory; it sticks the node on the end of
473 * the list. Check if there's any freed nodes there:
475 list_for_each_entry(b, &c->btree_cache_freeable, list)
476 if (!mca_reap_notrace(c, b, false))
480 * We never free struct btree itself, just the memory that holds the on
481 * disk node. Check the freed list before allocating a new one:
483 list_for_each_entry(b, &c->btree_cache_freed, list)
484 if (!mca_reap_notrace(c, b, false)) {
485 mca_data_alloc(c, b, __GFP_NOWARN|GFP_NOIO);
489 six_unlock_write(&b->lock);
490 six_unlock_intent(&b->lock);
494 b = mca_bucket_alloc(c, __GFP_NOWARN|GFP_NOIO);
498 BUG_ON(!six_trylock_intent(&b->lock));
499 BUG_ON(!six_trylock_write(&b->lock));
501 BUG_ON(bkey_extent_is_data(&b->key.k) && PTR_HASH(&b->key));
502 BUG_ON(btree_node_write_in_flight(b));
504 list_del_init(&b->list);
505 mutex_unlock(&c->btree_cache_lock);
512 b->whiteout_u64s = 0;
513 b->uncompacted_whiteout_u64s = 0;
514 bch2_btree_keys_init(b, &c->expensive_debug_checks);
516 bch2_time_stats_update(&c->btree_node_mem_alloc_time, start_time);
520 /* Try to cannibalize another cached btree node: */
521 if (c->btree_cache_alloc_lock == current) {
522 b = mca_cannibalize(c);
523 list_del_init(&b->list);
524 mutex_unlock(&c->btree_cache_lock);
526 bch2_btree_node_hash_remove(c, b);
528 trace_btree_node_cannibalize(c);
532 mutex_unlock(&c->btree_cache_lock);
533 return ERR_PTR(-ENOMEM);
536 /* Slowpath, don't want it inlined into btree_iter_traverse() */
537 static noinline struct btree *bch2_btree_node_fill(struct btree_iter *iter,
538 const struct bkey_i *k,
540 enum six_lock_type lock_type)
542 struct bch_fs *c = iter->c;
545 b = bch2_btree_node_mem_alloc(c);
549 bkey_copy(&b->key, k);
550 if (bch2_btree_node_hash_insert(c, b, level, iter->btree_id)) {
551 /* raced with another fill: */
553 /* mark as unhashed... */
554 bkey_i_to_extent(&b->key)->v._data[0] = 0;
556 mutex_lock(&c->btree_cache_lock);
557 list_add(&b->list, &c->btree_cache_freeable);
558 mutex_unlock(&c->btree_cache_lock);
560 six_unlock_write(&b->lock);
561 six_unlock_intent(&b->lock);
566 * If the btree node wasn't cached, we can't drop our lock on
567 * the parent until after it's added to the cache - because
568 * otherwise we could race with a btree_split() freeing the node
569 * we're trying to lock.
571 * But the deadlock described below doesn't exist in this case,
572 * so it's safe to not drop the parent lock until here:
574 if (btree_node_read_locked(iter, level + 1))
575 btree_node_unlock(iter, level + 1);
577 bch2_btree_node_read(c, b);
578 six_unlock_write(&b->lock);
580 if (lock_type == SIX_LOCK_read)
581 six_lock_downgrade(&b->lock);
587 * bch_btree_node_get - find a btree node in the cache and lock it, reading it
588 * in from disk if necessary.
590 * If IO is necessary and running under generic_make_request, returns -EAGAIN.
592 * The btree node will have either a read or a write lock held, depending on
593 * the @write parameter.
595 struct btree *bch2_btree_node_get(struct btree_iter *iter,
596 const struct bkey_i *k, unsigned level,
597 enum six_lock_type lock_type)
602 BUG_ON(level >= BTREE_MAX_DEPTH);
605 b = mca_find(iter->c, k);
610 * We must have the parent locked to call bch2_btree_node_fill(),
611 * else we could read in a btree node from disk that's been
614 b = bch2_btree_node_fill(iter, k, level, lock_type);
616 /* We raced and found the btree node in the cache */
624 * There's a potential deadlock with splits and insertions into
625 * interior nodes we have to avoid:
627 * The other thread might be holding an intent lock on the node
628 * we want, and they want to update its parent node so they're
629 * going to upgrade their intent lock on the parent node to a
632 * But if we're holding a read lock on the parent, and we're
633 * trying to get the intent lock they're holding, we deadlock.
635 * So to avoid this we drop the read locks on parent nodes when
636 * we're starting to take intent locks - and handle the race.
638 * The race is that they might be about to free the node we
639 * want, and dropping our read lock on the parent node lets them
640 * update the parent marking the node we want as freed, and then
643 * To guard against this, btree nodes are evicted from the cache
644 * when they're freed - and PTR_HASH() is zeroed out, which we
645 * check for after we lock the node.
647 * Then, bch2_btree_node_relock() on the parent will fail - because
648 * the parent was modified, when the pointer to the node we want
649 * was removed - and we'll bail out:
651 if (btree_node_read_locked(iter, level + 1))
652 btree_node_unlock(iter, level + 1);
654 if (!btree_node_lock(b, k->k.p, level, iter, lock_type))
655 return ERR_PTR(-EINTR);
657 if (unlikely(PTR_HASH(&b->key) != PTR_HASH(k) ||
660 six_unlock_type(&b->lock, lock_type);
661 if (bch2_btree_node_relock(iter, level + 1))
664 return ERR_PTR(-EINTR);
668 prefetch(b->aux_data);
670 for_each_bset(b, t) {
671 void *p = (u64 *) b->aux_data + t->aux_data_offset;
673 prefetch(p + L1_CACHE_BYTES * 0);
674 prefetch(p + L1_CACHE_BYTES * 1);
675 prefetch(p + L1_CACHE_BYTES * 2);
678 /* avoid atomic set bit if it's not needed: */
679 if (btree_node_accessed(b))
680 set_btree_node_accessed(b);
682 if (unlikely(btree_node_read_error(b))) {
683 six_unlock_type(&b->lock, lock_type);
684 return ERR_PTR(-EIO);
687 EBUG_ON(!b->written);
688 EBUG_ON(b->btree_id != iter->btree_id ||
689 BTREE_NODE_LEVEL(b->data) != level ||
690 bkey_cmp(b->data->max_key, k->k.p));
695 int bch2_print_btree_node(struct bch_fs *c, struct btree *b,
696 char *buf, size_t len)
698 const struct bkey_format *f = &b->format;
699 struct bset_stats stats;
702 memset(&stats, 0, sizeof(stats));
704 bch2_val_to_text(c, BKEY_TYPE_BTREE, ptrs, sizeof(ptrs),
705 bkey_i_to_s_c(&b->key));
706 bch2_btree_keys_stats(b, &stats);
708 return scnprintf(buf, len,
709 "l %u %llu:%llu - %llu:%llu:\n"
711 " format: u64s %u fields %u %u %u %u %u\n"
712 " unpack fn len: %u\n"
713 " bytes used %zu/%zu (%zu%% full)\n"
714 " sib u64s: %u, %u (merge threshold %zu)\n"
715 " nr packed keys %u\n"
716 " nr unpacked keys %u\n"
718 " failed unpacked %zu\n"
720 " failed overflow %zu\n",
722 b->data->min_key.inode,
723 b->data->min_key.offset,
724 b->data->max_key.inode,
725 b->data->max_key.offset,
728 f->bits_per_field[0],
729 f->bits_per_field[1],
730 f->bits_per_field[2],
731 f->bits_per_field[3],
732 f->bits_per_field[4],
734 b->nr.live_u64s * sizeof(u64),
735 btree_bytes(c) - sizeof(struct btree_node),
736 b->nr.live_u64s * 100 / btree_max_u64s(c),
739 BTREE_FOREGROUND_MERGE_THRESHOLD(c),
743 stats.failed_unpacked,
745 stats.failed_overflow);