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 const struct rhashtable_params bch_btree_cache_params = {
61 .head_offset = offsetof(struct btree, hash),
62 .key_offset = offsetof(struct btree, key.v),
63 .key_len = sizeof(struct bch_extent_ptr),
66 static void btree_node_data_alloc(struct bch_fs *c, struct btree *b, gfp_t gfp)
68 struct btree_cache *bc = &c->btree_cache;
70 b->data = kvpmalloc(btree_bytes(c), gfp);
74 if (bch2_btree_keys_alloc(b, btree_page_order(c), gfp))
78 list_move(&b->list, &bc->freeable);
81 kvpfree(b->data, btree_bytes(c));
83 list_move(&b->list, &bc->freed);
86 static struct btree *btree_node_mem_alloc(struct bch_fs *c, gfp_t gfp)
88 struct btree *b = kzalloc(sizeof(struct btree), gfp);
92 bkey_extent_init(&b->key);
93 six_lock_init(&b->lock);
94 INIT_LIST_HEAD(&b->list);
95 INIT_LIST_HEAD(&b->write_blocked);
97 btree_node_data_alloc(c, b, gfp);
98 return b->data ? b : NULL;
101 /* Btree in memory cache - hash table */
103 void bch2_btree_node_hash_remove(struct btree_cache *bc, struct btree *b)
105 rhashtable_remove_fast(&bc->table, &b->hash, bch_btree_cache_params);
107 /* Cause future lookups for this node to fail: */
108 bkey_i_to_extent(&b->key)->v._data[0] = 0;
111 int __bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b)
113 return rhashtable_lookup_insert_fast(&bc->table, &b->hash,
114 bch_btree_cache_params);
117 int bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b,
118 unsigned level, enum btree_id id)
125 mutex_lock(&bc->lock);
126 ret = __bch2_btree_node_hash_insert(bc, b);
128 list_add(&b->list, &bc->live);
129 mutex_unlock(&bc->lock);
135 static inline struct btree *btree_cache_find(struct btree_cache *bc,
136 const struct bkey_i *k)
138 return rhashtable_lookup_fast(&bc->table, &PTR_HASH(k),
139 bch_btree_cache_params);
143 * this version is for btree nodes that have already been freed (we're not
144 * reaping a real btree node)
146 static int __btree_node_reclaim(struct bch_fs *c, struct btree *b, bool flush)
148 struct btree_cache *bc = &c->btree_cache;
151 lockdep_assert_held(&bc->lock);
153 if (!six_trylock_intent(&b->lock))
156 if (!six_trylock_write(&b->lock))
157 goto out_unlock_intent;
159 if (btree_node_noevict(b))
162 if (!btree_node_may_write(b))
165 if (btree_node_dirty(b) ||
166 btree_node_write_in_flight(b) ||
167 btree_node_read_in_flight(b)) {
171 wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
172 TASK_UNINTERRUPTIBLE);
175 * Using the underscore version because we don't want to compact
176 * bsets after the write, since this node is about to be evicted
177 * - unless btree verify mode is enabled, since it runs out of
178 * the post write cleanup:
180 if (verify_btree_ondisk(c))
181 bch2_btree_node_write(c, b, SIX_LOCK_intent);
183 __bch2_btree_node_write(c, b, SIX_LOCK_read);
185 /* wait for any in flight btree write */
186 btree_node_wait_on_io(b);
189 if (PTR_HASH(&b->key) && !ret)
190 trace_btree_node_reap(c, b);
193 six_unlock_write(&b->lock);
195 six_unlock_intent(&b->lock);
200 static int btree_node_reclaim(struct bch_fs *c, struct btree *b)
202 return __btree_node_reclaim(c, b, false);
205 static int btree_node_write_and_reclaim(struct bch_fs *c, struct btree *b)
207 return __btree_node_reclaim(c, b, true);
210 static unsigned long bch2_btree_cache_scan(struct shrinker *shrink,
211 struct shrink_control *sc)
213 struct bch_fs *c = container_of(shrink, struct bch_fs,
215 struct btree_cache *bc = &c->btree_cache;
217 unsigned long nr = sc->nr_to_scan;
218 unsigned long can_free;
219 unsigned long touched = 0;
220 unsigned long freed = 0;
223 if (btree_shrinker_disabled(c))
226 /* Return -1 if we can't do anything right now */
227 if (sc->gfp_mask & __GFP_IO)
228 mutex_lock(&bc->lock);
229 else if (!mutex_trylock(&bc->lock))
233 * It's _really_ critical that we don't free too many btree nodes - we
234 * have to always leave ourselves a reserve. The reserve is how we
235 * guarantee that allocating memory for a new btree node can always
236 * succeed, so that inserting keys into the btree can always succeed and
237 * IO can always make forward progress:
239 nr /= btree_pages(c);
240 can_free = btree_cache_can_free(bc);
241 nr = min_t(unsigned long, nr, can_free);
244 list_for_each_entry_safe(b, t, &bc->freeable, list) {
251 !btree_node_reclaim(c, b)) {
252 btree_node_data_free(c, b);
253 six_unlock_write(&b->lock);
254 six_unlock_intent(&b->lock);
259 list_for_each_entry_safe(b, t, &bc->live, list) {
264 if (&t->list != &bc->live)
265 list_move_tail(&bc->live, &t->list);
269 if (!btree_node_accessed(b) &&
270 !btree_node_reclaim(c, b)) {
271 /* can't call bch2_btree_node_hash_remove under lock */
273 if (&t->list != &bc->live)
274 list_move_tail(&bc->live, &t->list);
276 btree_node_data_free(c, b);
277 mutex_unlock(&bc->lock);
279 bch2_btree_node_hash_remove(bc, b);
280 six_unlock_write(&b->lock);
281 six_unlock_intent(&b->lock);
286 if (sc->gfp_mask & __GFP_IO)
287 mutex_lock(&bc->lock);
288 else if (!mutex_trylock(&bc->lock))
292 clear_btree_node_accessed(b);
295 mutex_unlock(&bc->lock);
297 return (unsigned long) freed * btree_pages(c);
300 static unsigned long bch2_btree_cache_count(struct shrinker *shrink,
301 struct shrink_control *sc)
303 struct bch_fs *c = container_of(shrink, struct bch_fs,
305 struct btree_cache *bc = &c->btree_cache;
307 if (btree_shrinker_disabled(c))
310 return btree_cache_can_free(bc) * btree_pages(c);
313 void bch2_fs_btree_cache_exit(struct bch_fs *c)
315 struct btree_cache *bc = &c->btree_cache;
319 if (bc->shrink.list.next)
320 unregister_shrinker(&bc->shrink);
322 mutex_lock(&bc->lock);
324 #ifdef CONFIG_BCACHEFS_DEBUG
326 list_move(&c->verify_data->list, &bc->live);
328 kvpfree(c->verify_ondisk, btree_bytes(c));
331 for (i = 0; i < BTREE_ID_NR; i++)
332 if (c->btree_roots[i].b)
333 list_add(&c->btree_roots[i].b->list, &bc->live);
335 list_splice(&bc->freeable, &bc->live);
337 while (!list_empty(&bc->live)) {
338 b = list_first_entry(&bc->live, struct btree, list);
340 if (btree_node_dirty(b))
341 bch2_btree_complete_write(c, b, btree_current_write(b));
342 clear_btree_node_dirty(b);
344 btree_node_data_free(c, b);
347 while (!list_empty(&bc->freed)) {
348 b = list_first_entry(&bc->freed, struct btree, list);
353 mutex_unlock(&bc->lock);
355 if (bc->table_init_done)
356 rhashtable_destroy(&bc->table);
359 int bch2_fs_btree_cache_init(struct bch_fs *c)
361 struct btree_cache *bc = &c->btree_cache;
365 ret = rhashtable_init(&bc->table, &bch_btree_cache_params);
369 bc->table_init_done = true;
371 bch2_recalc_btree_reserve(c);
373 for (i = 0; i < bc->reserve; i++)
374 if (!btree_node_mem_alloc(c, GFP_KERNEL))
377 list_splice_init(&bc->live, &bc->freeable);
379 #ifdef CONFIG_BCACHEFS_DEBUG
380 mutex_init(&c->verify_lock);
382 c->verify_ondisk = kvpmalloc(btree_bytes(c), GFP_KERNEL);
383 if (!c->verify_ondisk)
386 c->verify_data = btree_node_mem_alloc(c, GFP_KERNEL);
390 list_del_init(&c->verify_data->list);
393 bc->shrink.count_objects = bch2_btree_cache_count;
394 bc->shrink.scan_objects = bch2_btree_cache_scan;
395 bc->shrink.seeks = 4;
396 bc->shrink.batch = btree_pages(c) * 2;
397 register_shrinker(&bc->shrink);
402 void bch2_fs_btree_cache_init_early(struct btree_cache *bc)
404 mutex_init(&bc->lock);
405 INIT_LIST_HEAD(&bc->live);
406 INIT_LIST_HEAD(&bc->freeable);
407 INIT_LIST_HEAD(&bc->freed);
411 * We can only have one thread cannibalizing other cached btree nodes at a time,
412 * or we'll deadlock. We use an open coded mutex to ensure that, which a
413 * cannibalize_bucket() will take. This means every time we unlock the root of
414 * the btree, we need to release this lock if we have it held.
416 void bch2_btree_cache_cannibalize_unlock(struct bch_fs *c)
418 struct btree_cache *bc = &c->btree_cache;
420 if (bc->alloc_lock == current) {
421 trace_btree_node_cannibalize_unlock(c);
422 bc->alloc_lock = NULL;
423 closure_wake_up(&bc->alloc_wait);
427 int bch2_btree_cache_cannibalize_lock(struct bch_fs *c, struct closure *cl)
429 struct btree_cache *bc = &c->btree_cache;
430 struct task_struct *old;
432 old = cmpxchg(&bc->alloc_lock, NULL, current);
433 if (old == NULL || old == current)
437 trace_btree_node_cannibalize_lock_fail(c);
441 closure_wait(&bc->alloc_wait, cl);
443 /* Try again, after adding ourselves to waitlist */
444 old = cmpxchg(&bc->alloc_lock, NULL, current);
445 if (old == NULL || old == current) {
447 closure_wake_up(&bc->alloc_wait);
451 trace_btree_node_cannibalize_lock_fail(c);
455 trace_btree_node_cannibalize_lock(c);
459 static struct btree *btree_node_cannibalize(struct bch_fs *c)
461 struct btree_cache *bc = &c->btree_cache;
464 list_for_each_entry_reverse(b, &bc->live, list)
465 if (!btree_node_reclaim(c, b))
469 list_for_each_entry_reverse(b, &bc->live, list)
470 if (!btree_node_write_and_reclaim(c, b))
474 * Rare case: all nodes were intent-locked.
477 WARN_ONCE(1, "btree cache cannibalize failed\n");
482 struct btree *bch2_btree_node_mem_alloc(struct bch_fs *c)
484 struct btree_cache *bc = &c->btree_cache;
486 u64 start_time = local_clock();
488 mutex_lock(&bc->lock);
491 * btree_free() doesn't free memory; it sticks the node on the end of
492 * the list. Check if there's any freed nodes there:
494 list_for_each_entry(b, &bc->freeable, list)
495 if (!btree_node_reclaim(c, b))
499 * We never free struct btree itself, just the memory that holds the on
500 * disk node. Check the freed list before allocating a new one:
502 list_for_each_entry(b, &bc->freed, list)
503 if (!btree_node_reclaim(c, b)) {
504 btree_node_data_alloc(c, b, __GFP_NOWARN|GFP_NOIO);
508 six_unlock_write(&b->lock);
509 six_unlock_intent(&b->lock);
513 b = btree_node_mem_alloc(c, __GFP_NOWARN|GFP_NOIO);
517 BUG_ON(!six_trylock_intent(&b->lock));
518 BUG_ON(!six_trylock_write(&b->lock));
520 BUG_ON(btree_node_hashed(b));
521 BUG_ON(btree_node_write_in_flight(b));
523 list_del_init(&b->list);
524 mutex_unlock(&bc->lock);
531 b->whiteout_u64s = 0;
532 b->uncompacted_whiteout_u64s = 0;
533 bch2_btree_keys_init(b, &c->expensive_debug_checks);
535 bch2_time_stats_update(&c->btree_node_mem_alloc_time, start_time);
539 /* Try to cannibalize another cached btree node: */
540 if (bc->alloc_lock == current) {
541 b = btree_node_cannibalize(c);
542 list_del_init(&b->list);
543 mutex_unlock(&bc->lock);
545 bch2_btree_node_hash_remove(bc, b);
547 trace_btree_node_cannibalize(c);
551 mutex_unlock(&bc->lock);
552 return ERR_PTR(-ENOMEM);
555 /* Slowpath, don't want it inlined into btree_iter_traverse() */
556 static noinline struct btree *bch2_btree_node_fill(struct bch_fs *c,
557 struct btree_iter *iter,
558 const struct bkey_i *k,
560 enum six_lock_type lock_type)
562 struct btree_cache *bc = &c->btree_cache;
566 * Parent node must be locked, else we could read in a btree node that's
569 BUG_ON(!btree_node_locked(iter, level + 1));
571 b = bch2_btree_node_mem_alloc(c);
575 bkey_copy(&b->key, k);
576 if (bch2_btree_node_hash_insert(bc, b, level, iter->btree_id)) {
577 /* raced with another fill: */
579 /* mark as unhashed... */
580 bkey_i_to_extent(&b->key)->v._data[0] = 0;
582 mutex_lock(&bc->lock);
583 list_add(&b->list, &bc->freeable);
584 mutex_unlock(&bc->lock);
586 six_unlock_write(&b->lock);
587 six_unlock_intent(&b->lock);
592 * If the btree node wasn't cached, we can't drop our lock on
593 * the parent until after it's added to the cache - because
594 * otherwise we could race with a btree_split() freeing the node
595 * we're trying to lock.
597 * But the deadlock described below doesn't exist in this case,
598 * so it's safe to not drop the parent lock until here:
600 if (btree_node_read_locked(iter, level + 1))
601 btree_node_unlock(iter, level + 1);
603 bch2_btree_node_read(c, b, true);
604 six_unlock_write(&b->lock);
606 if (lock_type == SIX_LOCK_read)
607 six_lock_downgrade(&b->lock);
613 * bch_btree_node_get - find a btree node in the cache and lock it, reading it
614 * in from disk if necessary.
616 * If IO is necessary and running under generic_make_request, returns -EAGAIN.
618 * The btree node will have either a read or a write lock held, depending on
619 * the @write parameter.
621 struct btree *bch2_btree_node_get(struct bch_fs *c, struct btree_iter *iter,
622 const struct bkey_i *k, unsigned level,
623 enum six_lock_type lock_type)
625 struct btree_cache *bc = &c->btree_cache;
629 /* btree_node_fill() requires parent to be locked: */
630 EBUG_ON(!btree_node_locked(iter, level + 1));
631 EBUG_ON(level >= BTREE_MAX_DEPTH);
634 b = btree_cache_find(bc, k);
639 * We must have the parent locked to call bch2_btree_node_fill(),
640 * else we could read in a btree node from disk that's been
643 b = bch2_btree_node_fill(c, iter, k, level, lock_type);
645 /* We raced and found the btree node in the cache */
653 * There's a potential deadlock with splits and insertions into
654 * interior nodes we have to avoid:
656 * The other thread might be holding an intent lock on the node
657 * we want, and they want to update its parent node so they're
658 * going to upgrade their intent lock on the parent node to a
661 * But if we're holding a read lock on the parent, and we're
662 * trying to get the intent lock they're holding, we deadlock.
664 * So to avoid this we drop the read locks on parent nodes when
665 * we're starting to take intent locks - and handle the race.
667 * The race is that they might be about to free the node we
668 * want, and dropping our read lock on the parent node lets them
669 * update the parent marking the node we want as freed, and then
672 * To guard against this, btree nodes are evicted from the cache
673 * when they're freed - and PTR_HASH() is zeroed out, which we
674 * check for after we lock the node.
676 * Then, bch2_btree_node_relock() on the parent will fail - because
677 * the parent was modified, when the pointer to the node we want
678 * was removed - and we'll bail out:
680 if (btree_node_read_locked(iter, level + 1))
681 btree_node_unlock(iter, level + 1);
683 if (!btree_node_lock(b, k->k.p, level, iter, lock_type))
684 return ERR_PTR(-EINTR);
686 if (unlikely(PTR_HASH(&b->key) != PTR_HASH(k) ||
689 six_unlock_type(&b->lock, lock_type);
690 if (bch2_btree_node_relock(iter, level + 1))
693 return ERR_PTR(-EINTR);
697 wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
698 TASK_UNINTERRUPTIBLE);
700 prefetch(b->aux_data);
702 for_each_bset(b, t) {
703 void *p = (u64 *) b->aux_data + t->aux_data_offset;
705 prefetch(p + L1_CACHE_BYTES * 0);
706 prefetch(p + L1_CACHE_BYTES * 1);
707 prefetch(p + L1_CACHE_BYTES * 2);
710 /* avoid atomic set bit if it's not needed: */
711 if (btree_node_accessed(b))
712 set_btree_node_accessed(b);
714 if (unlikely(btree_node_read_error(b))) {
715 six_unlock_type(&b->lock, lock_type);
716 return ERR_PTR(-EIO);
719 EBUG_ON(!b->written);
720 EBUG_ON(b->btree_id != iter->btree_id ||
721 BTREE_NODE_LEVEL(b->data) != level ||
722 bkey_cmp(b->data->max_key, k->k.p));
727 struct btree *bch2_btree_node_get_sibling(struct bch_fs *c,
728 struct btree_iter *iter,
730 enum btree_node_sibling sib)
732 struct btree *parent;
733 struct btree_node_iter node_iter;
734 struct bkey_packed *k;
737 unsigned level = b->level;
739 parent = iter->nodes[level + 1];
743 if (!bch2_btree_node_relock(iter, level + 1)) {
744 bch2_btree_iter_set_locks_want(iter, level + 2);
745 return ERR_PTR(-EINTR);
748 node_iter = iter->node_iters[parent->level];
750 k = bch2_btree_node_iter_peek_all(&node_iter, parent);
751 BUG_ON(bkey_cmp_left_packed(parent, k, &b->key.k.p));
754 k = sib == btree_prev_sib
755 ? bch2_btree_node_iter_prev_all(&node_iter, parent)
756 : (bch2_btree_node_iter_advance(&node_iter, parent),
757 bch2_btree_node_iter_peek_all(&node_iter, parent));
760 } while (bkey_deleted(k));
762 bch2_bkey_unpack(parent, &tmp.k, k);
764 ret = bch2_btree_node_get(c, iter, &tmp.k, level, SIX_LOCK_intent);
766 if (IS_ERR(ret) && PTR_ERR(ret) == -EINTR) {
767 btree_node_unlock(iter, level);
769 if (!bch2_btree_node_relock(iter, level + 1)) {
770 bch2_btree_iter_set_locks_want(iter, level + 2);
771 return ERR_PTR(-EINTR);
774 ret = bch2_btree_node_get(c, iter, &tmp.k, level, SIX_LOCK_intent);
777 if (!IS_ERR(ret) && !bch2_btree_node_relock(iter, level)) {
778 six_unlock_intent(&ret->lock);
779 ret = ERR_PTR(-EINTR);
785 void bch2_btree_node_prefetch(struct bch_fs *c, const struct bkey_i *k,
786 unsigned level, enum btree_id btree_id)
788 struct btree_cache *bc = &c->btree_cache;
791 BUG_ON(level >= BTREE_MAX_DEPTH);
794 b = btree_cache_find(bc, k);
800 b = bch2_btree_node_mem_alloc(c);
804 bkey_copy(&b->key, k);
805 if (bch2_btree_node_hash_insert(bc, b, level, btree_id)) {
806 /* raced with another fill: */
808 /* mark as unhashed... */
809 bkey_i_to_extent(&b->key)->v._data[0] = 0;
811 mutex_lock(&bc->lock);
812 list_add(&b->list, &bc->freeable);
813 mutex_unlock(&bc->lock);
817 bch2_btree_node_read(c, b, false);
819 six_unlock_write(&b->lock);
820 six_unlock_intent(&b->lock);
823 int bch2_print_btree_node(struct bch_fs *c, struct btree *b,
824 char *buf, size_t len)
826 const struct bkey_format *f = &b->format;
827 struct bset_stats stats;
830 memset(&stats, 0, sizeof(stats));
832 bch2_val_to_text(c, BKEY_TYPE_BTREE, ptrs, sizeof(ptrs),
833 bkey_i_to_s_c(&b->key));
834 bch2_btree_keys_stats(b, &stats);
836 return scnprintf(buf, len,
837 "l %u %llu:%llu - %llu:%llu:\n"
839 " format: u64s %u fields %u %u %u %u %u\n"
840 " unpack fn len: %u\n"
841 " bytes used %zu/%zu (%zu%% full)\n"
842 " sib u64s: %u, %u (merge threshold %zu)\n"
843 " nr packed keys %u\n"
844 " nr unpacked keys %u\n"
846 " failed unpacked %zu\n"
848 " failed overflow %zu\n",
850 b->data->min_key.inode,
851 b->data->min_key.offset,
852 b->data->max_key.inode,
853 b->data->max_key.offset,
856 f->bits_per_field[0],
857 f->bits_per_field[1],
858 f->bits_per_field[2],
859 f->bits_per_field[3],
860 f->bits_per_field[4],
862 b->nr.live_u64s * sizeof(u64),
863 btree_bytes(c) - sizeof(struct btree_node),
864 b->nr.live_u64s * 100 / btree_max_u64s(c),
867 BTREE_FOREGROUND_MERGE_THRESHOLD(c),
871 stats.failed_unpacked,
873 stats.failed_overflow);