2 * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4 * Uses a block device as cache for other block devices; optimized for SSDs.
5 * All allocation is done in buckets, which should match the erase block size
8 * Buckets containing cached data are kept on a heap sorted by priority;
9 * bucket priority is increased on cache hit, and periodically all the buckets
10 * on the heap have their priority scaled down. This currently is just used as
11 * an LRU but in the future should allow for more intelligent heuristics.
13 * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
14 * counter. Garbage collection is used to remove stale pointers.
16 * Indexing is done via a btree; nodes are not necessarily fully sorted, rather
17 * as keys are inserted we only sort the pages that have not yet been written.
18 * When garbage collection is run, we resort the entire node.
20 * All configuration is done via sysfs; see Documentation/bcache.txt.
27 #include "writeback.h"
29 #include <linux/slab.h>
30 #include <linux/bitops.h>
31 #include <linux/freezer.h>
32 #include <linux/hash.h>
33 #include <linux/kthread.h>
34 #include <linux/prefetch.h>
35 #include <linux/random.h>
36 #include <linux/rcupdate.h>
37 #include <trace/events/bcache.h>
41 * register_bcache: Return errors out to userspace correctly
43 * Writeback: don't undirty key until after a cache flush
45 * Create an iterator for key pointers
47 * On btree write error, mark bucket such that it won't be freed from the cache
50 * Check for bad keys in replay
52 * Refcount journal entries in journal_replay
55 * Finish incremental gc
56 * Gc should free old UUIDs, data for invalid UUIDs
58 * Provide a way to list backing device UUIDs we have data cached for, and
59 * probably how long it's been since we've seen them, and a way to invalidate
60 * dirty data for devices that will never be attached again
62 * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
63 * that based on that and how much dirty data we have we can keep writeback
66 * Add a tracepoint or somesuch to watch for writeback starvation
68 * When btree depth > 1 and splitting an interior node, we have to make sure
69 * alloc_bucket() cannot fail. This should be true but is not completely
72 * Make sure all allocations get charged to the root cgroup
76 * If data write is less than hard sector size of ssd, round up offset in open
77 * bucket to the next whole sector
79 * Also lookup by cgroup in get_open_bucket()
81 * Superblock needs to be fleshed out for multiple cache devices
83 * Add a sysfs tunable for the number of writeback IOs in flight
85 * Add a sysfs tunable for the number of open data buckets
87 * IO tracking: Can we track when one process is doing io on behalf of another?
88 * IO tracking: Don't use just an average, weigh more recent stuff higher
90 * Test module load/unload
94 BTREE_INSERT_STATUS_INSERT,
95 BTREE_INSERT_STATUS_BACK_MERGE,
96 BTREE_INSERT_STATUS_OVERWROTE,
97 BTREE_INSERT_STATUS_FRONT_MERGE,
100 #define MAX_NEED_GC 64
101 #define MAX_SAVE_PRIO 72
103 #define PTR_DIRTY_BIT (((uint64_t) 1 << 36))
105 #define PTR_HASH(c, k) \
106 (((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
108 static struct workqueue_struct *btree_io_wq;
110 static inline bool should_split(struct btree *b)
112 struct bset *i = write_block(b);
113 return b->written >= btree_blocks(b) ||
114 (b->written + __set_blocks(i, i->keys + 15, block_bytes(b->c))
118 #define insert_lock(s, b) ((b)->level <= (s)->lock)
121 * These macros are for recursing down the btree - they handle the details of
122 * locking and looking up nodes in the cache for you. They're best treated as
123 * mere syntax when reading code that uses them.
125 * op->lock determines whether we take a read or a write lock at a given depth.
126 * If you've got a read lock and find that you need a write lock (i.e. you're
127 * going to have to split), set op->lock and return -EINTR; btree_root() will
128 * call you again and you'll have the correct lock.
132 * btree - recurse down the btree on a specified key
133 * @fn: function to call, which will be passed the child node
134 * @key: key to recurse on
135 * @b: parent btree node
136 * @op: pointer to struct btree_op
138 #define btree(fn, key, b, op, ...) \
140 int _r, l = (b)->level - 1; \
141 bool _w = l <= (op)->lock; \
142 struct btree *_child = bch_btree_node_get((b)->c, key, l, _w); \
143 if (!IS_ERR(_child)) { \
144 _child->parent = (b); \
145 _r = bch_btree_ ## fn(_child, op, ##__VA_ARGS__); \
146 rw_unlock(_w, _child); \
148 _r = PTR_ERR(_child); \
153 * btree_root - call a function on the root of the btree
154 * @fn: function to call, which will be passed the child node
156 * @op: pointer to struct btree_op
158 #define btree_root(fn, c, op, ...) \
162 struct btree *_b = (c)->root; \
163 bool _w = insert_lock(op, _b); \
164 rw_lock(_w, _b, _b->level); \
165 if (_b == (c)->root && \
166 _w == insert_lock(op, _b)) { \
168 _r = bch_btree_ ## fn(_b, op, ##__VA_ARGS__); \
173 bch_cannibalize_unlock(c); \
174 if (_r == -ENOSPC) { \
175 wait_event((c)->try_wait, \
179 } while (_r == -EINTR); \
181 finish_wait(&(c)->bucket_wait, &(op)->wait); \
185 /* Btree key manipulation */
187 void bkey_put(struct cache_set *c, struct bkey *k)
191 for (i = 0; i < KEY_PTRS(k); i++)
192 if (ptr_available(c, k, i))
193 atomic_dec_bug(&PTR_BUCKET(c, k, i)->pin);
198 static uint64_t btree_csum_set(struct btree *b, struct bset *i)
200 uint64_t crc = b->key.ptr[0];
201 void *data = (void *) i + 8, *end = bset_bkey_last(i);
203 crc = bch_crc64_update(crc, data, end - data);
204 return crc ^ 0xffffffffffffffffULL;
207 void bch_btree_node_read_done(struct btree *b)
209 const char *err = "bad btree header";
210 struct bset *i = btree_bset_first(b);
211 struct btree_iter *iter;
213 iter = mempool_alloc(b->c->fill_iter, GFP_NOWAIT);
214 iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
217 #ifdef CONFIG_BCACHE_DEBUG
225 b->written < btree_blocks(b) && i->seq == b->sets[0].data->seq;
226 i = write_block(b)) {
227 err = "unsupported bset version";
228 if (i->version > BCACHE_BSET_VERSION)
231 err = "bad btree header";
232 if (b->written + set_blocks(i, block_bytes(b->c)) >
237 if (i->magic != bset_magic(&b->c->sb))
240 err = "bad checksum";
241 switch (i->version) {
243 if (i->csum != csum_set(i))
246 case BCACHE_BSET_VERSION:
247 if (i->csum != btree_csum_set(b, i))
253 if (i != b->sets[0].data && !i->keys)
256 bch_btree_iter_push(iter, i->start, bset_bkey_last(i));
258 b->written += set_blocks(i, block_bytes(b->c));
261 err = "corrupted btree";
262 for (i = write_block(b);
263 bset_sector_offset(b, i) < KEY_SIZE(&b->key);
264 i = ((void *) i) + block_bytes(b->c))
265 if (i->seq == b->sets[0].data->seq)
268 bch_btree_sort_and_fix_extents(b, iter, &b->c->sort);
271 err = "short btree key";
272 if (b->sets[0].size &&
273 bkey_cmp(&b->key, &b->sets[0].end) < 0)
276 if (b->written < btree_blocks(b))
277 bch_bset_init_next(b, write_block(b), bset_magic(&b->c->sb));
279 mempool_free(iter, b->c->fill_iter);
282 set_btree_node_io_error(b);
283 bch_cache_set_error(b->c, "%s at bucket %zu, block %u, %u keys",
284 err, PTR_BUCKET_NR(b->c, &b->key, 0),
285 bset_block_offset(b, i), i->keys);
289 static void btree_node_read_endio(struct bio *bio, int error)
291 struct closure *cl = bio->bi_private;
295 static void bch_btree_node_read(struct btree *b)
297 uint64_t start_time = local_clock();
301 trace_bcache_btree_read(b);
303 closure_init_stack(&cl);
305 bio = bch_bbio_alloc(b->c);
306 bio->bi_rw = REQ_META|READ_SYNC;
307 bio->bi_iter.bi_size = KEY_SIZE(&b->key) << 9;
308 bio->bi_end_io = btree_node_read_endio;
309 bio->bi_private = &cl;
311 bch_bio_map(bio, b->sets[0].data);
313 bch_submit_bbio(bio, b->c, &b->key, 0);
316 if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
317 set_btree_node_io_error(b);
319 bch_bbio_free(bio, b->c);
321 if (btree_node_io_error(b))
324 bch_btree_node_read_done(b);
325 bch_time_stats_update(&b->c->btree_read_time, start_time);
329 bch_cache_set_error(b->c, "io error reading bucket %zu",
330 PTR_BUCKET_NR(b->c, &b->key, 0));
333 static void btree_complete_write(struct btree *b, struct btree_write *w)
335 if (w->prio_blocked &&
336 !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
337 wake_up_allocators(b->c);
340 atomic_dec_bug(w->journal);
341 __closure_wake_up(&b->c->journal.wait);
348 static void btree_node_write_unlock(struct closure *cl)
350 struct btree *b = container_of(cl, struct btree, io);
355 static void __btree_node_write_done(struct closure *cl)
357 struct btree *b = container_of(cl, struct btree, io);
358 struct btree_write *w = btree_prev_write(b);
360 bch_bbio_free(b->bio, b->c);
362 btree_complete_write(b, w);
364 if (btree_node_dirty(b))
365 queue_delayed_work(btree_io_wq, &b->work,
366 msecs_to_jiffies(30000));
368 closure_return_with_destructor(cl, btree_node_write_unlock);
371 static void btree_node_write_done(struct closure *cl)
373 struct btree *b = container_of(cl, struct btree, io);
377 bio_for_each_segment_all(bv, b->bio, n)
378 __free_page(bv->bv_page);
380 __btree_node_write_done(cl);
383 static void btree_node_write_endio(struct bio *bio, int error)
385 struct closure *cl = bio->bi_private;
386 struct btree *b = container_of(cl, struct btree, io);
389 set_btree_node_io_error(b);
391 bch_bbio_count_io_errors(b->c, bio, error, "writing btree");
395 static void do_btree_node_write(struct btree *b)
397 struct closure *cl = &b->io;
398 struct bset *i = btree_bset_last(b);
401 i->version = BCACHE_BSET_VERSION;
402 i->csum = btree_csum_set(b, i);
405 b->bio = bch_bbio_alloc(b->c);
407 b->bio->bi_end_io = btree_node_write_endio;
408 b->bio->bi_private = cl;
409 b->bio->bi_rw = REQ_META|WRITE_SYNC|REQ_FUA;
410 b->bio->bi_iter.bi_size = roundup(set_bytes(i), block_bytes(b->c));
411 bch_bio_map(b->bio, i);
414 * If we're appending to a leaf node, we don't technically need FUA -
415 * this write just needs to be persisted before the next journal write,
416 * which will be marked FLUSH|FUA.
418 * Similarly if we're writing a new btree root - the pointer is going to
419 * be in the next journal entry.
421 * But if we're writing a new btree node (that isn't a root) or
422 * appending to a non leaf btree node, we need either FUA or a flush
423 * when we write the parent with the new pointer. FUA is cheaper than a
424 * flush, and writes appending to leaf nodes aren't blocking anything so
425 * just make all btree node writes FUA to keep things sane.
428 bkey_copy(&k.key, &b->key);
429 SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) +
430 bset_sector_offset(b, i));
432 if (!bio_alloc_pages(b->bio, GFP_NOIO)) {
435 void *base = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
437 bio_for_each_segment_all(bv, b->bio, j)
438 memcpy(page_address(bv->bv_page),
439 base + j * PAGE_SIZE, PAGE_SIZE);
441 bch_submit_bbio(b->bio, b->c, &k.key, 0);
443 continue_at(cl, btree_node_write_done, NULL);
446 bch_bio_map(b->bio, i);
448 bch_submit_bbio(b->bio, b->c, &k.key, 0);
451 continue_at_nobarrier(cl, __btree_node_write_done, NULL);
455 void bch_btree_node_write(struct btree *b, struct closure *parent)
457 struct bset *i = btree_bset_last(b);
459 trace_bcache_btree_write(b);
461 BUG_ON(current->bio_list);
462 BUG_ON(b->written >= btree_blocks(b));
463 BUG_ON(b->written && !i->keys);
464 BUG_ON(btree_bset_first(b)->seq != i->seq);
465 bch_check_keys(b, "writing");
467 cancel_delayed_work(&b->work);
469 /* If caller isn't waiting for write, parent refcount is cache set */
471 closure_init(&b->io, parent ?: &b->c->cl);
473 clear_bit(BTREE_NODE_dirty, &b->flags);
474 change_bit(BTREE_NODE_write_idx, &b->flags);
476 do_btree_node_write(b);
478 b->written += set_blocks(i, block_bytes(b->c));
479 atomic_long_add(set_blocks(i, block_bytes(b->c)) * b->c->sb.block_size,
480 &PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
482 /* If not a leaf node, always sort */
483 if (b->level && b->nsets)
484 bch_btree_sort(b, &b->c->sort);
486 bch_btree_sort_lazy(b, &b->c->sort);
489 * do verify if there was more than one set initially (i.e. we did a
490 * sort) and we sorted down to a single set:
492 if (i != b->sets->data && !b->nsets)
495 if (b->written < btree_blocks(b))
496 bch_bset_init_next(b, write_block(b), bset_magic(&b->c->sb));
499 static void bch_btree_node_write_sync(struct btree *b)
503 closure_init_stack(&cl);
504 bch_btree_node_write(b, &cl);
508 static void btree_node_write_work(struct work_struct *w)
510 struct btree *b = container_of(to_delayed_work(w), struct btree, work);
512 rw_lock(true, b, b->level);
514 if (btree_node_dirty(b))
515 bch_btree_node_write(b, NULL);
519 static void bch_btree_leaf_dirty(struct btree *b, atomic_t *journal_ref)
521 struct bset *i = btree_bset_last(b);
522 struct btree_write *w = btree_current_write(b);
527 if (!btree_node_dirty(b))
528 queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
530 set_btree_node_dirty(b);
534 journal_pin_cmp(b->c, w->journal, journal_ref)) {
535 atomic_dec_bug(w->journal);
540 w->journal = journal_ref;
541 atomic_inc(w->journal);
545 /* Force write if set is too big */
546 if (set_bytes(i) > PAGE_SIZE - 48 &&
548 bch_btree_node_write(b, NULL);
552 * Btree in memory cache - allocation/freeing
553 * mca -> memory cache
556 static void mca_reinit(struct btree *b)
564 for (i = 0; i < MAX_BSETS; i++)
567 * Second loop starts at 1 because b->sets[0]->data is the memory we
570 for (i = 1; i < MAX_BSETS; i++)
571 b->sets[i].data = NULL;
574 #define mca_reserve(c) (((c->root && c->root->level) \
575 ? c->root->level : 1) * 8 + 16)
576 #define mca_can_free(c) \
577 max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
579 static void mca_data_free(struct btree *b)
581 BUG_ON(b->io_mutex.count != 1);
583 bch_btree_keys_free(b);
585 b->c->bucket_cache_used--;
586 list_move(&b->list, &b->c->btree_cache_freed);
589 static void mca_bucket_free(struct btree *b)
591 BUG_ON(btree_node_dirty(b));
594 hlist_del_init_rcu(&b->hash);
595 list_move(&b->list, &b->c->btree_cache_freeable);
598 static unsigned btree_order(struct bkey *k)
600 return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
603 static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
605 if (!bch_btree_keys_alloc(b,
607 ilog2(b->c->btree_pages),
610 b->c->bucket_cache_used++;
611 list_move(&b->list, &b->c->btree_cache);
613 list_move(&b->list, &b->c->btree_cache_freed);
617 static struct btree *mca_bucket_alloc(struct cache_set *c,
618 struct bkey *k, gfp_t gfp)
620 struct btree *b = kzalloc(sizeof(struct btree), gfp);
624 init_rwsem(&b->lock);
625 lockdep_set_novalidate_class(&b->lock);
626 INIT_LIST_HEAD(&b->list);
627 INIT_DELAYED_WORK(&b->work, btree_node_write_work);
629 sema_init(&b->io_mutex, 1);
631 mca_data_alloc(b, k, gfp);
635 static int mca_reap(struct btree *b, unsigned min_order, bool flush)
639 closure_init_stack(&cl);
640 lockdep_assert_held(&b->c->bucket_lock);
642 if (!down_write_trylock(&b->lock))
645 BUG_ON(btree_node_dirty(b) && !b->sets[0].data);
647 if (b->page_order < min_order)
651 if (btree_node_dirty(b))
654 if (down_trylock(&b->io_mutex))
659 if (btree_node_dirty(b))
660 bch_btree_node_write_sync(b);
662 /* wait for any in flight btree write */
672 static unsigned long bch_mca_scan(struct shrinker *shrink,
673 struct shrink_control *sc)
675 struct cache_set *c = container_of(shrink, struct cache_set, shrink);
677 unsigned long i, nr = sc->nr_to_scan;
678 unsigned long freed = 0;
680 if (c->shrinker_disabled)
686 /* Return -1 if we can't do anything right now */
687 if (sc->gfp_mask & __GFP_IO)
688 mutex_lock(&c->bucket_lock);
689 else if (!mutex_trylock(&c->bucket_lock))
693 * It's _really_ critical that we don't free too many btree nodes - we
694 * have to always leave ourselves a reserve. The reserve is how we
695 * guarantee that allocating memory for a new btree node can always
696 * succeed, so that inserting keys into the btree can always succeed and
697 * IO can always make forward progress:
699 nr /= c->btree_pages;
700 nr = min_t(unsigned long, nr, mca_can_free(c));
703 list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
708 !mca_reap(b, 0, false)) {
715 for (i = 0; (nr--) && i < c->bucket_cache_used; i++) {
716 if (list_empty(&c->btree_cache))
719 b = list_first_entry(&c->btree_cache, struct btree, list);
720 list_rotate_left(&c->btree_cache);
723 !mca_reap(b, 0, false)) {
732 mutex_unlock(&c->bucket_lock);
736 static unsigned long bch_mca_count(struct shrinker *shrink,
737 struct shrink_control *sc)
739 struct cache_set *c = container_of(shrink, struct cache_set, shrink);
741 if (c->shrinker_disabled)
747 return mca_can_free(c) * c->btree_pages;
750 void bch_btree_cache_free(struct cache_set *c)
754 closure_init_stack(&cl);
756 if (c->shrink.list.next)
757 unregister_shrinker(&c->shrink);
759 mutex_lock(&c->bucket_lock);
761 #ifdef CONFIG_BCACHE_DEBUG
763 list_move(&c->verify_data->list, &c->btree_cache);
765 free_pages((unsigned long) c->verify_ondisk, ilog2(bucket_pages(c)));
768 list_splice(&c->btree_cache_freeable,
771 while (!list_empty(&c->btree_cache)) {
772 b = list_first_entry(&c->btree_cache, struct btree, list);
774 if (btree_node_dirty(b))
775 btree_complete_write(b, btree_current_write(b));
776 clear_bit(BTREE_NODE_dirty, &b->flags);
781 while (!list_empty(&c->btree_cache_freed)) {
782 b = list_first_entry(&c->btree_cache_freed,
785 cancel_delayed_work_sync(&b->work);
789 mutex_unlock(&c->bucket_lock);
792 int bch_btree_cache_alloc(struct cache_set *c)
796 for (i = 0; i < mca_reserve(c); i++)
797 if (!mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL))
800 list_splice_init(&c->btree_cache,
801 &c->btree_cache_freeable);
803 #ifdef CONFIG_BCACHE_DEBUG
804 mutex_init(&c->verify_lock);
806 c->verify_ondisk = (void *)
807 __get_free_pages(GFP_KERNEL, ilog2(bucket_pages(c)));
809 c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
811 if (c->verify_data &&
812 c->verify_data->sets[0].data)
813 list_del_init(&c->verify_data->list);
815 c->verify_data = NULL;
818 c->shrink.count_objects = bch_mca_count;
819 c->shrink.scan_objects = bch_mca_scan;
821 c->shrink.batch = c->btree_pages * 2;
822 register_shrinker(&c->shrink);
827 /* Btree in memory cache - hash table */
829 static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
831 return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
834 static struct btree *mca_find(struct cache_set *c, struct bkey *k)
839 hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
840 if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
848 static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k)
852 trace_bcache_btree_cache_cannibalize(c);
854 if (!c->try_harder) {
855 c->try_harder = current;
856 c->try_harder_start = local_clock();
857 } else if (c->try_harder != current)
858 return ERR_PTR(-ENOSPC);
860 list_for_each_entry_reverse(b, &c->btree_cache, list)
861 if (!mca_reap(b, btree_order(k), false))
864 list_for_each_entry_reverse(b, &c->btree_cache, list)
865 if (!mca_reap(b, btree_order(k), true))
868 return ERR_PTR(-ENOMEM);
872 * We can only have one thread cannibalizing other cached btree nodes at a time,
873 * or we'll deadlock. We use an open coded mutex to ensure that, which a
874 * cannibalize_bucket() will take. This means every time we unlock the root of
875 * the btree, we need to release this lock if we have it held.
877 static void bch_cannibalize_unlock(struct cache_set *c)
879 if (c->try_harder == current) {
880 bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
881 c->try_harder = NULL;
882 wake_up(&c->try_wait);
886 static struct btree *mca_alloc(struct cache_set *c, struct bkey *k, int level)
890 BUG_ON(current->bio_list);
892 lockdep_assert_held(&c->bucket_lock);
897 /* btree_free() doesn't free memory; it sticks the node on the end of
898 * the list. Check if there's any freed nodes there:
900 list_for_each_entry(b, &c->btree_cache_freeable, list)
901 if (!mca_reap(b, btree_order(k), false))
904 /* We never free struct btree itself, just the memory that holds the on
905 * disk node. Check the freed list before allocating a new one:
907 list_for_each_entry(b, &c->btree_cache_freed, list)
908 if (!mca_reap(b, 0, false)) {
909 mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
910 if (!b->sets[0].data)
916 b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
920 BUG_ON(!down_write_trylock(&b->lock));
924 BUG_ON(b->io_mutex.count != 1);
926 bkey_copy(&b->key, k);
927 list_move(&b->list, &c->btree_cache);
928 hlist_del_init_rcu(&b->hash);
929 hlist_add_head_rcu(&b->hash, mca_hash(c, k));
931 lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
933 b->parent = (void *) ~0UL;
936 b->ops = &bch_extent_keys_ops;
938 b->ops = &bch_btree_keys_ops;
947 b = mca_cannibalize(c, k);
955 * bch_btree_node_get - find a btree node in the cache and lock it, reading it
956 * in from disk if necessary.
958 * If IO is necessary and running under generic_make_request, returns -EAGAIN.
960 * The btree node will have either a read or a write lock held, depending on
961 * level and op->lock.
963 struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
964 int level, bool write)
974 if (current->bio_list)
975 return ERR_PTR(-EAGAIN);
977 mutex_lock(&c->bucket_lock);
978 b = mca_alloc(c, k, level);
979 mutex_unlock(&c->bucket_lock);
986 bch_btree_node_read(b);
989 downgrade_write(&b->lock);
991 rw_lock(write, b, level);
992 if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
996 BUG_ON(b->level != level);
1001 for (; i <= b->nsets && b->sets[i].size; i++) {
1002 prefetch(b->sets[i].tree);
1003 prefetch(b->sets[i].data);
1006 for (; i <= b->nsets; i++)
1007 prefetch(b->sets[i].data);
1009 if (btree_node_io_error(b)) {
1010 rw_unlock(write, b);
1011 return ERR_PTR(-EIO);
1014 BUG_ON(!b->written);
1019 static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
1023 mutex_lock(&c->bucket_lock);
1024 b = mca_alloc(c, k, level);
1025 mutex_unlock(&c->bucket_lock);
1027 if (!IS_ERR_OR_NULL(b)) {
1028 bch_btree_node_read(b);
1035 static void btree_node_free(struct btree *b)
1039 trace_bcache_btree_node_free(b);
1041 BUG_ON(b == b->c->root);
1043 if (btree_node_dirty(b))
1044 btree_complete_write(b, btree_current_write(b));
1045 clear_bit(BTREE_NODE_dirty, &b->flags);
1047 cancel_delayed_work(&b->work);
1049 mutex_lock(&b->c->bucket_lock);
1051 for (i = 0; i < KEY_PTRS(&b->key); i++) {
1052 BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
1054 bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
1055 PTR_BUCKET(b->c, &b->key, i));
1058 bch_bucket_free(b->c, &b->key);
1060 mutex_unlock(&b->c->bucket_lock);
1063 struct btree *bch_btree_node_alloc(struct cache_set *c, int level, bool wait)
1066 struct btree *b = ERR_PTR(-EAGAIN);
1068 mutex_lock(&c->bucket_lock);
1070 if (__bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, wait))
1073 bkey_put(c, &k.key);
1074 SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
1076 b = mca_alloc(c, &k.key, level);
1082 "Tried to allocate bucket that was in btree cache");
1087 bch_bset_init_next(b, b->sets->data, bset_magic(&b->c->sb));
1089 mutex_unlock(&c->bucket_lock);
1091 trace_bcache_btree_node_alloc(b);
1094 bch_bucket_free(c, &k.key);
1096 mutex_unlock(&c->bucket_lock);
1098 trace_bcache_btree_node_alloc_fail(b);
1102 static struct btree *btree_node_alloc_replacement(struct btree *b, bool wait)
1104 struct btree *n = bch_btree_node_alloc(b->c, b->level, wait);
1105 if (!IS_ERR_OR_NULL(n)) {
1106 bch_btree_sort_into(b, n, &b->c->sort);
1107 bkey_copy_key(&n->key, &b->key);
1113 static void make_btree_freeing_key(struct btree *b, struct bkey *k)
1117 bkey_copy(k, &b->key);
1118 bkey_copy_key(k, &ZERO_KEY);
1120 for (i = 0; i < KEY_PTRS(k); i++) {
1121 uint8_t g = PTR_BUCKET(b->c, k, i)->gen + 1;
1123 SET_PTR_GEN(k, i, g);
1126 atomic_inc(&b->c->prio_blocked);
1129 static int btree_check_reserve(struct btree *b, struct btree_op *op)
1131 struct cache_set *c = b->c;
1133 unsigned i, reserve = c->root->level * 2 + 1;
1136 mutex_lock(&c->bucket_lock);
1138 for_each_cache(ca, c, i)
1139 if (fifo_used(&ca->free[RESERVE_BTREE]) < reserve) {
1141 prepare_to_wait(&c->bucket_wait, &op->wait,
1142 TASK_UNINTERRUPTIBLE);
1147 mutex_unlock(&c->bucket_lock);
1151 /* Garbage collection */
1153 uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1160 * ptr_invalid() can't return true for the keys that mark btree nodes as
1161 * freed, but since ptr_bad() returns true we'll never actually use them
1162 * for anything and thus we don't want mark their pointers here
1164 if (!bkey_cmp(k, &ZERO_KEY))
1167 for (i = 0; i < KEY_PTRS(k); i++) {
1168 if (!ptr_available(c, k, i))
1171 g = PTR_BUCKET(c, k, i);
1173 if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1174 g->gc_gen = PTR_GEN(k, i);
1176 if (ptr_stale(c, k, i)) {
1177 stale = max(stale, ptr_stale(c, k, i));
1181 cache_bug_on(GC_MARK(g) &&
1182 (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1183 c, "inconsistent ptrs: mark = %llu, level = %i",
1187 SET_GC_MARK(g, GC_MARK_METADATA);
1188 else if (KEY_DIRTY(k))
1189 SET_GC_MARK(g, GC_MARK_DIRTY);
1191 /* guard against overflow */
1192 SET_GC_SECTORS_USED(g, min_t(unsigned,
1193 GC_SECTORS_USED(g) + KEY_SIZE(k),
1196 BUG_ON(!GC_SECTORS_USED(g));
1202 #define btree_mark_key(b, k) __bch_btree_mark_key(b->c, b->level, k)
1204 static bool btree_gc_mark_node(struct btree *b, struct gc_stat *gc)
1207 unsigned keys = 0, good_keys = 0;
1209 struct btree_iter iter;
1210 struct bset_tree *t;
1214 for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1215 stale = max(stale, btree_mark_key(b, k));
1218 if (bch_ptr_bad(b, k))
1221 gc->key_bytes += bkey_u64s(k);
1225 gc->data += KEY_SIZE(k);
1228 for (t = b->sets; t <= &b->sets[b->nsets]; t++)
1229 btree_bug_on(t->size &&
1230 bset_written(b, t) &&
1231 bkey_cmp(&b->key, &t->end) < 0,
1232 b, "found short btree key in gc");
1234 if (b->c->gc_always_rewrite)
1240 if ((keys - good_keys) * 2 > keys)
1246 #define GC_MERGE_NODES 4U
1248 struct gc_merge_info {
1253 static int bch_btree_insert_node(struct btree *, struct btree_op *,
1254 struct keylist *, atomic_t *, struct bkey *);
1256 static int btree_gc_coalesce(struct btree *b, struct btree_op *op,
1257 struct keylist *keylist, struct gc_stat *gc,
1258 struct gc_merge_info *r)
1260 unsigned i, nodes = 0, keys = 0, blocks;
1261 struct btree *new_nodes[GC_MERGE_NODES];
1265 memset(new_nodes, 0, sizeof(new_nodes));
1266 closure_init_stack(&cl);
1268 while (nodes < GC_MERGE_NODES && !IS_ERR_OR_NULL(r[nodes].b))
1269 keys += r[nodes++].keys;
1271 blocks = btree_default_blocks(b->c) * 2 / 3;
1274 __set_blocks(b->sets[0].data, keys,
1275 block_bytes(b->c)) > blocks * (nodes - 1))
1278 for (i = 0; i < nodes; i++) {
1279 new_nodes[i] = btree_node_alloc_replacement(r[i].b, false);
1280 if (IS_ERR_OR_NULL(new_nodes[i]))
1281 goto out_nocoalesce;
1284 for (i = nodes - 1; i > 0; --i) {
1285 struct bset *n1 = btree_bset_first(new_nodes[i]);
1286 struct bset *n2 = btree_bset_first(new_nodes[i - 1]);
1287 struct bkey *k, *last = NULL;
1293 k < bset_bkey_last(n2);
1295 if (__set_blocks(n1, n1->keys + keys +
1297 block_bytes(b->c)) > blocks)
1301 keys += bkey_u64s(k);
1305 * Last node we're not getting rid of - we're getting
1306 * rid of the node at r[0]. Have to try and fit all of
1307 * the remaining keys into this node; we can't ensure
1308 * they will always fit due to rounding and variable
1309 * length keys (shouldn't be possible in practice,
1312 if (__set_blocks(n1, n1->keys + n2->keys,
1313 block_bytes(b->c)) >
1314 btree_blocks(new_nodes[i]))
1315 goto out_nocoalesce;
1318 /* Take the key of the node we're getting rid of */
1322 BUG_ON(__set_blocks(n1, n1->keys + keys, block_bytes(b->c)) >
1323 btree_blocks(new_nodes[i]));
1326 bkey_copy_key(&new_nodes[i]->key, last);
1328 memcpy(bset_bkey_last(n1),
1330 (void *) bset_bkey_idx(n2, keys) - (void *) n2->start);
1333 r[i].keys = n1->keys;
1336 bset_bkey_idx(n2, keys),
1337 (void *) bset_bkey_last(n2) -
1338 (void *) bset_bkey_idx(n2, keys));
1342 if (__bch_keylist_realloc(keylist,
1343 bkey_u64s(&new_nodes[i]->key)))
1344 goto out_nocoalesce;
1346 bch_btree_node_write(new_nodes[i], &cl);
1347 bch_keylist_add(keylist, &new_nodes[i]->key);
1350 for (i = 0; i < nodes; i++) {
1351 if (__bch_keylist_realloc(keylist, bkey_u64s(&r[i].b->key)))
1352 goto out_nocoalesce;
1354 make_btree_freeing_key(r[i].b, keylist->top);
1355 bch_keylist_push(keylist);
1358 /* We emptied out this node */
1359 BUG_ON(btree_bset_first(new_nodes[0])->keys);
1360 btree_node_free(new_nodes[0]);
1361 rw_unlock(true, new_nodes[0]);
1365 for (i = 0; i < nodes; i++) {
1366 btree_node_free(r[i].b);
1367 rw_unlock(true, r[i].b);
1369 r[i].b = new_nodes[i];
1372 bch_btree_insert_node(b, op, keylist, NULL, NULL);
1373 BUG_ON(!bch_keylist_empty(keylist));
1375 memmove(r, r + 1, sizeof(r[0]) * (nodes - 1));
1376 r[nodes - 1].b = ERR_PTR(-EINTR);
1378 trace_bcache_btree_gc_coalesce(nodes);
1381 /* Invalidated our iterator */
1387 while ((k = bch_keylist_pop(keylist)))
1388 if (!bkey_cmp(k, &ZERO_KEY))
1389 atomic_dec(&b->c->prio_blocked);
1391 for (i = 0; i < nodes; i++)
1392 if (!IS_ERR_OR_NULL(new_nodes[i])) {
1393 btree_node_free(new_nodes[i]);
1394 rw_unlock(true, new_nodes[i]);
1399 static unsigned btree_gc_count_keys(struct btree *b)
1402 struct btree_iter iter;
1405 for_each_key_filter(b, k, &iter, bch_ptr_bad)
1406 ret += bkey_u64s(k);
1411 static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1412 struct closure *writes, struct gc_stat *gc)
1416 bool should_rewrite;
1419 struct keylist keys;
1420 struct btree_iter iter;
1421 struct gc_merge_info r[GC_MERGE_NODES];
1422 struct gc_merge_info *last = r + GC_MERGE_NODES - 1;
1424 bch_keylist_init(&keys);
1425 bch_btree_iter_init(b, &iter, &b->c->gc_done);
1427 for (i = 0; i < GC_MERGE_NODES; i++)
1428 r[i].b = ERR_PTR(-EINTR);
1431 k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
1433 r->b = bch_btree_node_get(b->c, k, b->level - 1, true);
1435 ret = PTR_ERR(r->b);
1439 r->keys = btree_gc_count_keys(r->b);
1441 ret = btree_gc_coalesce(b, op, &keys, gc, r);
1449 if (!IS_ERR(last->b)) {
1450 should_rewrite = btree_gc_mark_node(last->b, gc);
1451 if (should_rewrite &&
1452 !btree_check_reserve(b, NULL)) {
1453 n = btree_node_alloc_replacement(last->b,
1456 if (!IS_ERR_OR_NULL(n)) {
1457 bch_btree_node_write_sync(n);
1458 bch_keylist_add(&keys, &n->key);
1460 make_btree_freeing_key(last->b,
1462 bch_keylist_push(&keys);
1464 btree_node_free(last->b);
1466 bch_btree_insert_node(b, op, &keys,
1468 BUG_ON(!bch_keylist_empty(&keys));
1470 rw_unlock(true, last->b);
1473 /* Invalidated our iterator */
1479 if (last->b->level) {
1480 ret = btree_gc_recurse(last->b, op, writes, gc);
1485 bkey_copy_key(&b->c->gc_done, &last->b->key);
1488 * Must flush leaf nodes before gc ends, since replace
1489 * operations aren't journalled
1491 if (btree_node_dirty(last->b))
1492 bch_btree_node_write(last->b, writes);
1493 rw_unlock(true, last->b);
1496 memmove(r + 1, r, sizeof(r[0]) * (GC_MERGE_NODES - 1));
1499 if (need_resched()) {
1505 for (i = 0; i < GC_MERGE_NODES; i++)
1506 if (!IS_ERR_OR_NULL(r[i].b)) {
1507 if (btree_node_dirty(r[i].b))
1508 bch_btree_node_write(r[i].b, writes);
1509 rw_unlock(true, r[i].b);
1512 bch_keylist_free(&keys);
1517 static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1518 struct closure *writes, struct gc_stat *gc)
1520 struct btree *n = NULL;
1522 bool should_rewrite;
1524 should_rewrite = btree_gc_mark_node(b, gc);
1525 if (should_rewrite) {
1526 n = btree_node_alloc_replacement(b, false);
1528 if (!IS_ERR_OR_NULL(n)) {
1529 bch_btree_node_write_sync(n);
1530 bch_btree_set_root(n);
1539 ret = btree_gc_recurse(b, op, writes, gc);
1544 bkey_copy_key(&b->c->gc_done, &b->key);
1549 static void btree_gc_start(struct cache_set *c)
1555 if (!c->gc_mark_valid)
1558 mutex_lock(&c->bucket_lock);
1560 c->gc_mark_valid = 0;
1561 c->gc_done = ZERO_KEY;
1563 for_each_cache(ca, c, i)
1564 for_each_bucket(b, ca) {
1566 if (!atomic_read(&b->pin)) {
1567 SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
1568 SET_GC_SECTORS_USED(b, 0);
1572 mutex_unlock(&c->bucket_lock);
1575 size_t bch_btree_gc_finish(struct cache_set *c)
1577 size_t available = 0;
1582 mutex_lock(&c->bucket_lock);
1585 c->gc_mark_valid = 1;
1589 for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1590 SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1593 for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1594 SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1597 /* don't reclaim buckets to which writeback keys point */
1599 for (i = 0; i < c->nr_uuids; i++) {
1600 struct bcache_device *d = c->devices[i];
1601 struct cached_dev *dc;
1602 struct keybuf_key *w, *n;
1605 if (!d || UUID_FLASH_ONLY(&c->uuids[i]))
1607 dc = container_of(d, struct cached_dev, disk);
1609 spin_lock(&dc->writeback_keys.lock);
1610 rbtree_postorder_for_each_entry_safe(w, n,
1611 &dc->writeback_keys.keys, node)
1612 for (j = 0; j < KEY_PTRS(&w->key); j++)
1613 SET_GC_MARK(PTR_BUCKET(c, &w->key, j),
1615 spin_unlock(&dc->writeback_keys.lock);
1619 for_each_cache(ca, c, i) {
1622 ca->invalidate_needs_gc = 0;
1624 for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1625 SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1627 for (i = ca->prio_buckets;
1628 i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1629 SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1631 for_each_bucket(b, ca) {
1632 b->last_gc = b->gc_gen;
1633 c->need_gc = max(c->need_gc, bucket_gc_gen(b));
1635 if (!atomic_read(&b->pin) &&
1636 GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1638 if (!GC_SECTORS_USED(b))
1639 bch_bucket_add_unused(ca, b);
1644 mutex_unlock(&c->bucket_lock);
1648 static void bch_btree_gc(struct cache_set *c)
1651 unsigned long available;
1652 struct gc_stat stats;
1653 struct closure writes;
1655 uint64_t start_time = local_clock();
1657 trace_bcache_gc_start(c);
1659 memset(&stats, 0, sizeof(struct gc_stat));
1660 closure_init_stack(&writes);
1661 bch_btree_op_init(&op, SHRT_MAX);
1666 ret = btree_root(gc_root, c, &op, &writes, &stats);
1667 closure_sync(&writes);
1669 if (ret && ret != -EAGAIN)
1670 pr_warn("gc failed!");
1673 available = bch_btree_gc_finish(c);
1674 wake_up_allocators(c);
1676 bch_time_stats_update(&c->btree_gc_time, start_time);
1678 stats.key_bytes *= sizeof(uint64_t);
1680 stats.in_use = (c->nbuckets - available) * 100 / c->nbuckets;
1681 memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
1683 trace_bcache_gc_end(c);
1688 static int bch_gc_thread(void *arg)
1690 struct cache_set *c = arg;
1698 set_current_state(TASK_INTERRUPTIBLE);
1699 if (kthread_should_stop())
1702 mutex_lock(&c->bucket_lock);
1704 for_each_cache(ca, c, i)
1705 if (ca->invalidate_needs_gc) {
1706 mutex_unlock(&c->bucket_lock);
1707 set_current_state(TASK_RUNNING);
1711 mutex_unlock(&c->bucket_lock);
1720 int bch_gc_thread_start(struct cache_set *c)
1722 c->gc_thread = kthread_create(bch_gc_thread, c, "bcache_gc");
1723 if (IS_ERR(c->gc_thread))
1724 return PTR_ERR(c->gc_thread);
1726 set_task_state(c->gc_thread, TASK_INTERRUPTIBLE);
1730 /* Initial partial gc */
1732 static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1733 unsigned long **seen)
1737 struct bkey *k, *p = NULL;
1739 struct btree_iter iter;
1741 for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1742 for (i = 0; i < KEY_PTRS(k); i++) {
1743 if (!ptr_available(b->c, k, i))
1746 g = PTR_BUCKET(b->c, k, i);
1748 if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1749 seen[PTR_DEV(k, i)]) ||
1750 !ptr_stale(b->c, k, i)) {
1751 g->gen = PTR_GEN(k, i);
1754 g->prio = BTREE_PRIO;
1755 else if (g->prio == BTREE_PRIO)
1756 g->prio = INITIAL_PRIO;
1760 btree_mark_key(b, k);
1764 bch_btree_iter_init(b, &iter, NULL);
1767 k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
1769 btree_node_prefetch(b->c, k, b->level - 1);
1772 ret = btree(check_recurse, p, b, op, seen);
1775 } while (p && !ret);
1781 int bch_btree_check(struct cache_set *c)
1785 unsigned long *seen[MAX_CACHES_PER_SET];
1788 memset(seen, 0, sizeof(seen));
1789 bch_btree_op_init(&op, SHRT_MAX);
1791 for (i = 0; c->cache[i]; i++) {
1792 size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1793 seen[i] = kmalloc(n, GFP_KERNEL);
1797 /* Disables the seen array until prio_read() uses it too */
1798 memset(seen[i], 0xFF, n);
1801 ret = btree_root(check_recurse, c, &op, seen);
1803 for (i = 0; i < MAX_CACHES_PER_SET; i++)
1808 /* Btree insertion */
1810 static bool fix_overlapping_extents(struct btree *b, struct bkey *insert,
1811 struct btree_iter *iter,
1812 struct bkey *replace_key)
1814 void subtract_dirty(struct bkey *k, uint64_t offset, int sectors)
1817 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1821 uint64_t old_offset;
1822 unsigned old_size, sectors_found = 0;
1825 struct bkey *k = bch_btree_iter_next(iter);
1829 if (bkey_cmp(&START_KEY(k), insert) >= 0) {
1836 if (bkey_cmp(k, &START_KEY(insert)) <= 0)
1839 old_offset = KEY_START(k);
1840 old_size = KEY_SIZE(k);
1843 * We might overlap with 0 size extents; we can't skip these
1844 * because if they're in the set we're inserting to we have to
1845 * adjust them so they don't overlap with the key we're
1846 * inserting. But we don't want to check them for replace
1850 if (replace_key && KEY_SIZE(k)) {
1852 * k might have been split since we inserted/found the
1853 * key we're replacing
1856 uint64_t offset = KEY_START(k) -
1857 KEY_START(replace_key);
1859 /* But it must be a subset of the replace key */
1860 if (KEY_START(k) < KEY_START(replace_key) ||
1861 KEY_OFFSET(k) > KEY_OFFSET(replace_key))
1864 /* We didn't find a key that we were supposed to */
1865 if (KEY_START(k) > KEY_START(insert) + sectors_found)
1868 if (KEY_PTRS(k) != KEY_PTRS(replace_key) ||
1869 KEY_DIRTY(k) != KEY_DIRTY(replace_key))
1875 BUG_ON(!KEY_PTRS(replace_key));
1877 for (i = 0; i < KEY_PTRS(replace_key); i++)
1878 if (k->ptr[i] != replace_key->ptr[i] + offset)
1881 sectors_found = KEY_OFFSET(k) - KEY_START(insert);
1884 if (bkey_cmp(insert, k) < 0 &&
1885 bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0) {
1887 * We overlapped in the middle of an existing key: that
1888 * means we have to split the old key. But we have to do
1889 * slightly different things depending on whether the
1890 * old key has been written out yet.
1895 subtract_dirty(k, KEY_START(insert), KEY_SIZE(insert));
1897 if (bkey_written(b, k)) {
1899 * We insert a new key to cover the top of the
1900 * old key, and the old key is modified in place
1901 * to represent the bottom split.
1903 * It's completely arbitrary whether the new key
1904 * is the top or the bottom, but it has to match
1905 * up with what btree_sort_fixup() does - it
1906 * doesn't check for this kind of overlap, it
1907 * depends on us inserting a new key for the top
1910 top = bch_bset_search(b, bset_tree_last(b),
1912 bch_bset_insert(b, top, k);
1914 BKEY_PADDED(key) temp;
1915 bkey_copy(&temp.key, k);
1916 bch_bset_insert(b, k, &temp.key);
1920 bch_cut_front(insert, top);
1921 bch_cut_back(&START_KEY(insert), k);
1922 bch_bset_fix_invalidated_key(b, k);
1926 if (bkey_cmp(insert, k) < 0) {
1927 bch_cut_front(insert, k);
1929 if (bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0)
1930 old_offset = KEY_START(insert);
1932 if (bkey_written(b, k) &&
1933 bkey_cmp(&START_KEY(insert), &START_KEY(k)) <= 0) {
1935 * Completely overwrote, so we don't have to
1936 * invalidate the binary search tree
1938 bch_cut_front(k, k);
1940 __bch_cut_back(&START_KEY(insert), k);
1941 bch_bset_fix_invalidated_key(b, k);
1945 subtract_dirty(k, old_offset, old_size - KEY_SIZE(k));
1950 if (!sectors_found) {
1952 } else if (sectors_found < KEY_SIZE(insert)) {
1953 SET_KEY_OFFSET(insert, KEY_OFFSET(insert) -
1954 (KEY_SIZE(insert) - sectors_found));
1955 SET_KEY_SIZE(insert, sectors_found);
1962 static bool btree_insert_key(struct btree *b, struct btree_op *op,
1963 struct bkey *k, struct bkey *replace_key)
1965 struct bset *i = btree_bset_last(b);
1966 struct bkey *m, *prev;
1967 unsigned status = BTREE_INSERT_STATUS_INSERT;
1969 BUG_ON(bkey_cmp(k, &b->key) > 0);
1970 BUG_ON(b->level && !KEY_PTRS(k));
1971 BUG_ON(!b->level && !KEY_OFFSET(k));
1974 struct btree_iter iter;
1977 * bset_search() returns the first key that is strictly greater
1978 * than the search key - but for back merging, we want to find
1982 m = bch_btree_iter_init(b, &iter, PRECEDING_KEY(&START_KEY(k)));
1984 if (fix_overlapping_extents(b, k, &iter, replace_key)) {
1985 op->insert_collision = true;
1990 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1991 KEY_START(k), KEY_SIZE(k));
1993 while (m != bset_bkey_last(i) &&
1994 bkey_cmp(k, &START_KEY(m)) > 0)
1995 prev = m, m = bkey_next(m);
1997 if (key_merging_disabled(b->c))
2000 /* prev is in the tree, if we merge we're done */
2001 status = BTREE_INSERT_STATUS_BACK_MERGE;
2003 bch_bkey_try_merge(b, prev, k))
2006 status = BTREE_INSERT_STATUS_OVERWROTE;
2007 if (m != bset_bkey_last(i) &&
2008 KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
2011 status = BTREE_INSERT_STATUS_FRONT_MERGE;
2012 if (m != bset_bkey_last(i) &&
2013 bch_bkey_try_merge(b, k, m))
2016 BUG_ON(replace_key);
2017 m = bch_bset_search(b, bset_tree_last(b), k);
2020 insert: bch_bset_insert(b, m, k);
2021 copy: bkey_copy(m, k);
2023 bch_check_keys(b, "%u for %s", status,
2024 replace_key ? "replace" : "insert");
2026 if (b->level && !KEY_OFFSET(k))
2027 btree_current_write(b)->prio_blocked++;
2029 trace_bcache_btree_insert_key(b, k, replace_key != NULL, status);
2034 static bool bch_btree_insert_keys(struct btree *b, struct btree_op *op,
2035 struct keylist *insert_keys,
2036 struct bkey *replace_key)
2039 int oldsize = bch_count_data(b);
2041 while (!bch_keylist_empty(insert_keys)) {
2042 struct bset *i = write_block(b);
2043 struct bkey *k = insert_keys->keys;
2046 __set_blocks(i, i->keys + bkey_u64s(k),
2047 block_bytes(b->c)) > btree_blocks(b))
2050 if (bkey_cmp(k, &b->key) <= 0) {
2054 ret |= btree_insert_key(b, op, k, replace_key);
2055 bch_keylist_pop_front(insert_keys);
2056 } else if (bkey_cmp(&START_KEY(k), &b->key) < 0) {
2057 BKEY_PADDED(key) temp;
2058 bkey_copy(&temp.key, insert_keys->keys);
2060 bch_cut_back(&b->key, &temp.key);
2061 bch_cut_front(&b->key, insert_keys->keys);
2063 ret |= btree_insert_key(b, op, &temp.key, replace_key);
2070 BUG_ON(!bch_keylist_empty(insert_keys) && b->level);
2072 BUG_ON(bch_count_data(b) < oldsize);
2076 static int btree_split(struct btree *b, struct btree_op *op,
2077 struct keylist *insert_keys,
2078 struct bkey *replace_key)
2081 struct btree *n1, *n2 = NULL, *n3 = NULL;
2082 uint64_t start_time = local_clock();
2084 struct keylist parent_keys;
2086 closure_init_stack(&cl);
2087 bch_keylist_init(&parent_keys);
2090 btree_check_reserve(b, op))
2093 n1 = btree_node_alloc_replacement(b, true);
2097 split = set_blocks(btree_bset_first(n1),
2098 block_bytes(n1->c)) > (btree_blocks(b) * 4) / 5;
2103 trace_bcache_btree_node_split(b, btree_bset_first(n1)->keys);
2105 n2 = bch_btree_node_alloc(b->c, b->level, true);
2110 n3 = bch_btree_node_alloc(b->c, b->level + 1, true);
2115 bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2118 * Has to be a linear search because we don't have an auxiliary
2122 while (keys < (btree_bset_first(n1)->keys * 3) / 5)
2123 keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1),
2126 bkey_copy_key(&n1->key,
2127 bset_bkey_idx(btree_bset_first(n1), keys));
2128 keys += bkey_u64s(bset_bkey_idx(btree_bset_first(n1), keys));
2130 btree_bset_first(n2)->keys = btree_bset_first(n1)->keys - keys;
2131 btree_bset_first(n1)->keys = keys;
2133 memcpy(btree_bset_first(n2)->start,
2134 bset_bkey_last(btree_bset_first(n1)),
2135 btree_bset_first(n2)->keys * sizeof(uint64_t));
2137 bkey_copy_key(&n2->key, &b->key);
2139 bch_keylist_add(&parent_keys, &n2->key);
2140 bch_btree_node_write(n2, &cl);
2141 rw_unlock(true, n2);
2143 trace_bcache_btree_node_compact(b, btree_bset_first(n1)->keys);
2145 bch_btree_insert_keys(n1, op, insert_keys, replace_key);
2148 bch_keylist_add(&parent_keys, &n1->key);
2149 bch_btree_node_write(n1, &cl);
2152 /* Depth increases, make a new root */
2153 bkey_copy_key(&n3->key, &MAX_KEY);
2154 bch_btree_insert_keys(n3, op, &parent_keys, NULL);
2155 bch_btree_node_write(n3, &cl);
2158 bch_btree_set_root(n3);
2159 rw_unlock(true, n3);
2162 } else if (!b->parent) {
2163 /* Root filled up but didn't need to be split */
2165 bch_btree_set_root(n1);
2169 /* Split a non root node */
2171 make_btree_freeing_key(b, parent_keys.top);
2172 bch_keylist_push(&parent_keys);
2176 bch_btree_insert_node(b->parent, op, &parent_keys, NULL, NULL);
2177 BUG_ON(!bch_keylist_empty(&parent_keys));
2180 rw_unlock(true, n1);
2182 bch_time_stats_update(&b->c->btree_split_time, start_time);
2186 bkey_put(b->c, &n2->key);
2187 btree_node_free(n2);
2188 rw_unlock(true, n2);
2190 bkey_put(b->c, &n1->key);
2191 btree_node_free(n1);
2192 rw_unlock(true, n1);
2194 WARN(1, "bcache: btree split failed");
2196 if (n3 == ERR_PTR(-EAGAIN) ||
2197 n2 == ERR_PTR(-EAGAIN) ||
2198 n1 == ERR_PTR(-EAGAIN))
2204 static int bch_btree_insert_node(struct btree *b, struct btree_op *op,
2205 struct keylist *insert_keys,
2206 atomic_t *journal_ref,
2207 struct bkey *replace_key)
2209 BUG_ON(b->level && replace_key);
2211 if (should_split(b)) {
2212 if (current->bio_list) {
2213 op->lock = b->c->root->level + 1;
2215 } else if (op->lock <= b->c->root->level) {
2216 op->lock = b->c->root->level + 1;
2219 /* Invalidated all iterators */
2220 return btree_split(b, op, insert_keys, replace_key) ?:
2224 BUG_ON(write_block(b) != btree_bset_last(b));
2226 if (bch_btree_insert_keys(b, op, insert_keys, replace_key)) {
2228 bch_btree_leaf_dirty(b, journal_ref);
2230 bch_btree_node_write_sync(b);
2237 int bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
2238 struct bkey *check_key)
2241 uint64_t btree_ptr = b->key.ptr[0];
2242 unsigned long seq = b->seq;
2243 struct keylist insert;
2244 bool upgrade = op->lock == -1;
2246 bch_keylist_init(&insert);
2249 rw_unlock(false, b);
2250 rw_lock(true, b, b->level);
2252 if (b->key.ptr[0] != btree_ptr ||
2257 SET_KEY_PTRS(check_key, 1);
2258 get_random_bytes(&check_key->ptr[0], sizeof(uint64_t));
2260 SET_PTR_DEV(check_key, 0, PTR_CHECK_DEV);
2262 bch_keylist_add(&insert, check_key);
2264 ret = bch_btree_insert_node(b, op, &insert, NULL, NULL);
2266 BUG_ON(!ret && !bch_keylist_empty(&insert));
2269 downgrade_write(&b->lock);
2273 struct btree_insert_op {
2275 struct keylist *keys;
2276 atomic_t *journal_ref;
2277 struct bkey *replace_key;
2280 static int btree_insert_fn(struct btree_op *b_op, struct btree *b)
2282 struct btree_insert_op *op = container_of(b_op,
2283 struct btree_insert_op, op);
2285 int ret = bch_btree_insert_node(b, &op->op, op->keys,
2286 op->journal_ref, op->replace_key);
2287 if (ret && !bch_keylist_empty(op->keys))
2293 int bch_btree_insert(struct cache_set *c, struct keylist *keys,
2294 atomic_t *journal_ref, struct bkey *replace_key)
2296 struct btree_insert_op op;
2299 BUG_ON(current->bio_list);
2300 BUG_ON(bch_keylist_empty(keys));
2302 bch_btree_op_init(&op.op, 0);
2304 op.journal_ref = journal_ref;
2305 op.replace_key = replace_key;
2307 while (!ret && !bch_keylist_empty(keys)) {
2309 ret = bch_btree_map_leaf_nodes(&op.op, c,
2310 &START_KEY(keys->keys),
2317 pr_err("error %i", ret);
2319 while ((k = bch_keylist_pop(keys)))
2321 } else if (op.op.insert_collision)
2327 void bch_btree_set_root(struct btree *b)
2332 closure_init_stack(&cl);
2334 trace_bcache_btree_set_root(b);
2336 BUG_ON(!b->written);
2338 for (i = 0; i < KEY_PTRS(&b->key); i++)
2339 BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2341 mutex_lock(&b->c->bucket_lock);
2342 list_del_init(&b->list);
2343 mutex_unlock(&b->c->bucket_lock);
2347 bch_journal_meta(b->c, &cl);
2351 /* Map across nodes or keys */
2353 static int bch_btree_map_nodes_recurse(struct btree *b, struct btree_op *op,
2355 btree_map_nodes_fn *fn, int flags)
2357 int ret = MAP_CONTINUE;
2361 struct btree_iter iter;
2363 bch_btree_iter_init(b, &iter, from);
2365 while ((k = bch_btree_iter_next_filter(&iter, b,
2367 ret = btree(map_nodes_recurse, k, b,
2368 op, from, fn, flags);
2371 if (ret != MAP_CONTINUE)
2376 if (!b->level || flags == MAP_ALL_NODES)
2382 int __bch_btree_map_nodes(struct btree_op *op, struct cache_set *c,
2383 struct bkey *from, btree_map_nodes_fn *fn, int flags)
2385 return btree_root(map_nodes_recurse, c, op, from, fn, flags);
2388 static int bch_btree_map_keys_recurse(struct btree *b, struct btree_op *op,
2389 struct bkey *from, btree_map_keys_fn *fn,
2392 int ret = MAP_CONTINUE;
2394 struct btree_iter iter;
2396 bch_btree_iter_init(b, &iter, from);
2398 while ((k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad))) {
2401 : btree(map_keys_recurse, k, b, op, from, fn, flags);
2404 if (ret != MAP_CONTINUE)
2408 if (!b->level && (flags & MAP_END_KEY))
2409 ret = fn(op, b, &KEY(KEY_INODE(&b->key),
2410 KEY_OFFSET(&b->key), 0));
2415 int bch_btree_map_keys(struct btree_op *op, struct cache_set *c,
2416 struct bkey *from, btree_map_keys_fn *fn, int flags)
2418 return btree_root(map_keys_recurse, c, op, from, fn, flags);
2423 static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2425 /* Overlapping keys compare equal */
2426 if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2428 if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2433 static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2434 struct keybuf_key *r)
2436 return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2444 keybuf_pred_fn *pred;
2447 static int refill_keybuf_fn(struct btree_op *op, struct btree *b,
2450 struct refill *refill = container_of(op, struct refill, op);
2451 struct keybuf *buf = refill->buf;
2452 int ret = MAP_CONTINUE;
2454 if (bkey_cmp(k, refill->end) >= 0) {
2459 if (!KEY_SIZE(k)) /* end key */
2462 if (refill->pred(buf, k)) {
2463 struct keybuf_key *w;
2465 spin_lock(&buf->lock);
2467 w = array_alloc(&buf->freelist);
2469 spin_unlock(&buf->lock);
2474 bkey_copy(&w->key, k);
2476 if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2477 array_free(&buf->freelist, w);
2481 if (array_freelist_empty(&buf->freelist))
2484 spin_unlock(&buf->lock);
2487 buf->last_scanned = *k;
2491 void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
2492 struct bkey *end, keybuf_pred_fn *pred)
2494 struct bkey start = buf->last_scanned;
2495 struct refill refill;
2499 bch_btree_op_init(&refill.op, -1);
2500 refill.nr_found = 0;
2505 bch_btree_map_keys(&refill.op, c, &buf->last_scanned,
2506 refill_keybuf_fn, MAP_END_KEY);
2508 trace_bcache_keyscan(refill.nr_found,
2509 KEY_INODE(&start), KEY_OFFSET(&start),
2510 KEY_INODE(&buf->last_scanned),
2511 KEY_OFFSET(&buf->last_scanned));
2513 spin_lock(&buf->lock);
2515 if (!RB_EMPTY_ROOT(&buf->keys)) {
2516 struct keybuf_key *w;
2517 w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2518 buf->start = START_KEY(&w->key);
2520 w = RB_LAST(&buf->keys, struct keybuf_key, node);
2523 buf->start = MAX_KEY;
2527 spin_unlock(&buf->lock);
2530 static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2532 rb_erase(&w->node, &buf->keys);
2533 array_free(&buf->freelist, w);
2536 void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2538 spin_lock(&buf->lock);
2539 __bch_keybuf_del(buf, w);
2540 spin_unlock(&buf->lock);
2543 bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2547 struct keybuf_key *p, *w, s;
2550 if (bkey_cmp(end, &buf->start) <= 0 ||
2551 bkey_cmp(start, &buf->end) >= 0)
2554 spin_lock(&buf->lock);
2555 w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2557 while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2559 w = RB_NEXT(w, node);
2564 __bch_keybuf_del(buf, p);
2567 spin_unlock(&buf->lock);
2571 struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2573 struct keybuf_key *w;
2574 spin_lock(&buf->lock);
2576 w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2578 while (w && w->private)
2579 w = RB_NEXT(w, node);
2582 w->private = ERR_PTR(-EINTR);
2584 spin_unlock(&buf->lock);
2588 struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2591 keybuf_pred_fn *pred)
2593 struct keybuf_key *ret;
2596 ret = bch_keybuf_next(buf);
2600 if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2601 pr_debug("scan finished");
2605 bch_refill_keybuf(c, buf, end, pred);
2611 void bch_keybuf_init(struct keybuf *buf)
2613 buf->last_scanned = MAX_KEY;
2614 buf->keys = RB_ROOT;
2616 spin_lock_init(&buf->lock);
2617 array_allocator_init(&buf->freelist);
2620 void bch_btree_exit(void)
2623 destroy_workqueue(btree_io_wq);
2626 int __init bch_btree_init(void)
2628 btree_io_wq = create_singlethread_workqueue("bch_btree_io");