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/hash.h>
32 #include <linux/prefetch.h>
33 #include <linux/random.h>
34 #include <linux/rcupdate.h>
35 #include <trace/events/bcache.h>
39 * register_bcache: Return errors out to userspace correctly
41 * Writeback: don't undirty key until after a cache flush
43 * Create an iterator for key pointers
45 * On btree write error, mark bucket such that it won't be freed from the cache
48 * Check for bad keys in replay
50 * Refcount journal entries in journal_replay
53 * Finish incremental gc
54 * Gc should free old UUIDs, data for invalid UUIDs
56 * Provide a way to list backing device UUIDs we have data cached for, and
57 * probably how long it's been since we've seen them, and a way to invalidate
58 * dirty data for devices that will never be attached again
60 * Keep 1 min/5 min/15 min statistics of how busy a block device has been, so
61 * that based on that and how much dirty data we have we can keep writeback
64 * Add a tracepoint or somesuch to watch for writeback starvation
66 * When btree depth > 1 and splitting an interior node, we have to make sure
67 * alloc_bucket() cannot fail. This should be true but is not completely
70 * Make sure all allocations get charged to the root cgroup
74 * If data write is less than hard sector size of ssd, round up offset in open
75 * bucket to the next whole sector
77 * Also lookup by cgroup in get_open_bucket()
79 * Superblock needs to be fleshed out for multiple cache devices
81 * Add a sysfs tunable for the number of writeback IOs in flight
83 * Add a sysfs tunable for the number of open data buckets
85 * IO tracking: Can we track when one process is doing io on behalf of another?
86 * IO tracking: Don't use just an average, weigh more recent stuff higher
88 * Test module load/unload
91 static const char * const op_types
[] = {
95 static const char *op_type(struct btree_op
*op
)
97 return op_types
[op
->type
];
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 struct workqueue_struct
*bch_gc_wq
;
109 static struct workqueue_struct
*btree_io_wq
;
111 void bch_btree_op_init_stack(struct btree_op
*op
)
113 memset(op
, 0, sizeof(struct btree_op
));
114 closure_init_stack(&op
->cl
);
116 bch_keylist_init(&op
->keys
);
119 /* Btree key manipulation */
121 static void bkey_put(struct cache_set
*c
, struct bkey
*k
, int level
)
123 if ((level
&& KEY_OFFSET(k
)) || !level
)
129 static uint64_t btree_csum_set(struct btree
*b
, struct bset
*i
)
131 uint64_t crc
= b
->key
.ptr
[0];
132 void *data
= (void *) i
+ 8, *end
= end(i
);
134 crc
= bch_crc64_update(crc
, data
, end
- data
);
135 return crc
^ 0xffffffffffffffffULL
;
138 static void bch_btree_node_read_done(struct btree
*b
)
140 const char *err
= "bad btree header";
141 struct bset
*i
= b
->sets
[0].data
;
142 struct btree_iter
*iter
;
144 iter
= mempool_alloc(b
->c
->fill_iter
, GFP_NOIO
);
145 iter
->size
= b
->c
->sb
.bucket_size
/ b
->c
->sb
.block_size
;
152 b
->written
< btree_blocks(b
) && i
->seq
== b
->sets
[0].data
->seq
;
153 i
= write_block(b
)) {
154 err
= "unsupported bset version";
155 if (i
->version
> BCACHE_BSET_VERSION
)
158 err
= "bad btree header";
159 if (b
->written
+ set_blocks(i
, b
->c
) > btree_blocks(b
))
163 if (i
->magic
!= bset_magic(b
->c
))
166 err
= "bad checksum";
167 switch (i
->version
) {
169 if (i
->csum
!= csum_set(i
))
172 case BCACHE_BSET_VERSION
:
173 if (i
->csum
!= btree_csum_set(b
, i
))
179 if (i
!= b
->sets
[0].data
&& !i
->keys
)
182 bch_btree_iter_push(iter
, i
->start
, end(i
));
184 b
->written
+= set_blocks(i
, b
->c
);
187 err
= "corrupted btree";
188 for (i
= write_block(b
);
189 index(i
, b
) < btree_blocks(b
);
190 i
= ((void *) i
) + block_bytes(b
->c
))
191 if (i
->seq
== b
->sets
[0].data
->seq
)
194 bch_btree_sort_and_fix_extents(b
, iter
);
197 err
= "short btree key";
198 if (b
->sets
[0].size
&&
199 bkey_cmp(&b
->key
, &b
->sets
[0].end
) < 0)
202 if (b
->written
< btree_blocks(b
))
203 bch_bset_init_next(b
);
205 mempool_free(iter
, b
->c
->fill_iter
);
208 set_btree_node_io_error(b
);
209 bch_cache_set_error(b
->c
, "%s at bucket %zu, block %zu, %u keys",
210 err
, PTR_BUCKET_NR(b
->c
, &b
->key
, 0),
211 index(i
, b
), i
->keys
);
215 static void btree_node_read_endio(struct bio
*bio
, int error
)
217 struct closure
*cl
= bio
->bi_private
;
221 void bch_btree_node_read(struct btree
*b
)
223 uint64_t start_time
= local_clock();
227 trace_bcache_btree_read(b
);
229 closure_init_stack(&cl
);
231 bio
= bch_bbio_alloc(b
->c
);
232 bio
->bi_rw
= REQ_META
|READ_SYNC
;
233 bio
->bi_size
= KEY_SIZE(&b
->key
) << 9;
234 bio
->bi_end_io
= btree_node_read_endio
;
235 bio
->bi_private
= &cl
;
237 bch_bio_map(bio
, b
->sets
[0].data
);
239 bch_submit_bbio(bio
, b
->c
, &b
->key
, 0);
242 if (!test_bit(BIO_UPTODATE
, &bio
->bi_flags
))
243 set_btree_node_io_error(b
);
245 bch_bbio_free(bio
, b
->c
);
247 if (btree_node_io_error(b
))
250 bch_btree_node_read_done(b
);
252 spin_lock(&b
->c
->btree_read_time_lock
);
253 bch_time_stats_update(&b
->c
->btree_read_time
, start_time
);
254 spin_unlock(&b
->c
->btree_read_time_lock
);
258 bch_cache_set_error(b
->c
, "io error reading bucket %zu",
259 PTR_BUCKET_NR(b
->c
, &b
->key
, 0));
262 static void btree_complete_write(struct btree
*b
, struct btree_write
*w
)
264 if (w
->prio_blocked
&&
265 !atomic_sub_return(w
->prio_blocked
, &b
->c
->prio_blocked
))
266 wake_up_allocators(b
->c
);
269 atomic_dec_bug(w
->journal
);
270 __closure_wake_up(&b
->c
->journal
.wait
);
277 static void __btree_node_write_done(struct closure
*cl
)
279 struct btree
*b
= container_of(cl
, struct btree
, io
.cl
);
280 struct btree_write
*w
= btree_prev_write(b
);
282 bch_bbio_free(b
->bio
, b
->c
);
284 btree_complete_write(b
, w
);
286 if (btree_node_dirty(b
))
287 queue_delayed_work(btree_io_wq
, &b
->work
,
288 msecs_to_jiffies(30000));
293 static void btree_node_write_done(struct closure
*cl
)
295 struct btree
*b
= container_of(cl
, struct btree
, io
.cl
);
299 __bio_for_each_segment(bv
, b
->bio
, n
, 0)
300 __free_page(bv
->bv_page
);
302 __btree_node_write_done(cl
);
305 static void btree_node_write_endio(struct bio
*bio
, int error
)
307 struct closure
*cl
= bio
->bi_private
;
308 struct btree
*b
= container_of(cl
, struct btree
, io
.cl
);
311 set_btree_node_io_error(b
);
313 bch_bbio_count_io_errors(b
->c
, bio
, error
, "writing btree");
317 static void do_btree_node_write(struct btree
*b
)
319 struct closure
*cl
= &b
->io
.cl
;
320 struct bset
*i
= b
->sets
[b
->nsets
].data
;
323 i
->version
= BCACHE_BSET_VERSION
;
324 i
->csum
= btree_csum_set(b
, i
);
327 b
->bio
= bch_bbio_alloc(b
->c
);
329 b
->bio
->bi_end_io
= btree_node_write_endio
;
330 b
->bio
->bi_private
= &b
->io
.cl
;
331 b
->bio
->bi_rw
= REQ_META
|WRITE_SYNC
|REQ_FUA
;
332 b
->bio
->bi_size
= set_blocks(i
, b
->c
) * block_bytes(b
->c
);
333 bch_bio_map(b
->bio
, i
);
336 * If we're appending to a leaf node, we don't technically need FUA -
337 * this write just needs to be persisted before the next journal write,
338 * which will be marked FLUSH|FUA.
340 * Similarly if we're writing a new btree root - the pointer is going to
341 * be in the next journal entry.
343 * But if we're writing a new btree node (that isn't a root) or
344 * appending to a non leaf btree node, we need either FUA or a flush
345 * when we write the parent with the new pointer. FUA is cheaper than a
346 * flush, and writes appending to leaf nodes aren't blocking anything so
347 * just make all btree node writes FUA to keep things sane.
350 bkey_copy(&k
.key
, &b
->key
);
351 SET_PTR_OFFSET(&k
.key
, 0, PTR_OFFSET(&k
.key
, 0) + bset_offset(b
, i
));
353 if (!bio_alloc_pages(b
->bio
, GFP_NOIO
)) {
356 void *base
= (void *) ((unsigned long) i
& ~(PAGE_SIZE
- 1));
358 bio_for_each_segment(bv
, b
->bio
, j
)
359 memcpy(page_address(bv
->bv_page
),
360 base
+ j
* PAGE_SIZE
, PAGE_SIZE
);
362 bch_submit_bbio(b
->bio
, b
->c
, &k
.key
, 0);
364 continue_at(cl
, btree_node_write_done
, NULL
);
367 bch_bio_map(b
->bio
, i
);
369 bch_submit_bbio(b
->bio
, b
->c
, &k
.key
, 0);
372 __btree_node_write_done(cl
);
376 void bch_btree_node_write(struct btree
*b
, struct closure
*parent
)
378 struct bset
*i
= b
->sets
[b
->nsets
].data
;
380 trace_bcache_btree_write(b
);
382 BUG_ON(current
->bio_list
);
383 BUG_ON(b
->written
>= btree_blocks(b
));
384 BUG_ON(b
->written
&& !i
->keys
);
385 BUG_ON(b
->sets
->data
->seq
!= i
->seq
);
386 bch_check_key_order(b
, i
);
388 cancel_delayed_work(&b
->work
);
390 /* If caller isn't waiting for write, parent refcount is cache set */
391 closure_lock(&b
->io
, parent
?: &b
->c
->cl
);
393 clear_bit(BTREE_NODE_dirty
, &b
->flags
);
394 change_bit(BTREE_NODE_write_idx
, &b
->flags
);
396 do_btree_node_write(b
);
398 b
->written
+= set_blocks(i
, b
->c
);
399 atomic_long_add(set_blocks(i
, b
->c
) * b
->c
->sb
.block_size
,
400 &PTR_CACHE(b
->c
, &b
->key
, 0)->btree_sectors_written
);
402 bch_btree_sort_lazy(b
);
404 if (b
->written
< btree_blocks(b
))
405 bch_bset_init_next(b
);
408 static void btree_node_write_work(struct work_struct
*w
)
410 struct btree
*b
= container_of(to_delayed_work(w
), struct btree
, work
);
412 rw_lock(true, b
, b
->level
);
414 if (btree_node_dirty(b
))
415 bch_btree_node_write(b
, NULL
);
419 static void bch_btree_leaf_dirty(struct btree
*b
, struct btree_op
*op
)
421 struct bset
*i
= b
->sets
[b
->nsets
].data
;
422 struct btree_write
*w
= btree_current_write(b
);
427 if (!btree_node_dirty(b
))
428 queue_delayed_work(btree_io_wq
, &b
->work
, 30 * HZ
);
430 set_btree_node_dirty(b
);
432 if (op
&& op
->journal
) {
434 journal_pin_cmp(b
->c
, w
, op
)) {
435 atomic_dec_bug(w
->journal
);
440 w
->journal
= op
->journal
;
441 atomic_inc(w
->journal
);
445 /* Force write if set is too big */
446 if (set_bytes(i
) > PAGE_SIZE
- 48 &&
448 bch_btree_node_write(b
, NULL
);
452 * Btree in memory cache - allocation/freeing
453 * mca -> memory cache
456 static void mca_reinit(struct btree
*b
)
464 for (i
= 0; i
< MAX_BSETS
; i
++)
467 * Second loop starts at 1 because b->sets[0]->data is the memory we
470 for (i
= 1; i
< MAX_BSETS
; i
++)
471 b
->sets
[i
].data
= NULL
;
474 #define mca_reserve(c) (((c->root && c->root->level) \
475 ? c->root->level : 1) * 8 + 16)
476 #define mca_can_free(c) \
477 max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
479 static void mca_data_free(struct btree
*b
)
481 struct bset_tree
*t
= b
->sets
;
482 BUG_ON(!closure_is_unlocked(&b
->io
.cl
));
484 if (bset_prev_bytes(b
) < PAGE_SIZE
)
487 free_pages((unsigned long) t
->prev
,
488 get_order(bset_prev_bytes(b
)));
490 if (bset_tree_bytes(b
) < PAGE_SIZE
)
493 free_pages((unsigned long) t
->tree
,
494 get_order(bset_tree_bytes(b
)));
496 free_pages((unsigned long) t
->data
, b
->page_order
);
501 list_move(&b
->list
, &b
->c
->btree_cache_freed
);
502 b
->c
->bucket_cache_used
--;
505 static void mca_bucket_free(struct btree
*b
)
507 BUG_ON(btree_node_dirty(b
));
510 hlist_del_init_rcu(&b
->hash
);
511 list_move(&b
->list
, &b
->c
->btree_cache_freeable
);
514 static unsigned btree_order(struct bkey
*k
)
516 return ilog2(KEY_SIZE(k
) / PAGE_SECTORS
?: 1);
519 static void mca_data_alloc(struct btree
*b
, struct bkey
*k
, gfp_t gfp
)
521 struct bset_tree
*t
= b
->sets
;
524 b
->page_order
= max_t(unsigned,
525 ilog2(b
->c
->btree_pages
),
528 t
->data
= (void *) __get_free_pages(gfp
, b
->page_order
);
532 t
->tree
= bset_tree_bytes(b
) < PAGE_SIZE
533 ? kmalloc(bset_tree_bytes(b
), gfp
)
534 : (void *) __get_free_pages(gfp
, get_order(bset_tree_bytes(b
)));
538 t
->prev
= bset_prev_bytes(b
) < PAGE_SIZE
539 ? kmalloc(bset_prev_bytes(b
), gfp
)
540 : (void *) __get_free_pages(gfp
, get_order(bset_prev_bytes(b
)));
544 list_move(&b
->list
, &b
->c
->btree_cache
);
545 b
->c
->bucket_cache_used
++;
551 static struct btree
*mca_bucket_alloc(struct cache_set
*c
,
552 struct bkey
*k
, gfp_t gfp
)
554 struct btree
*b
= kzalloc(sizeof(struct btree
), gfp
);
558 init_rwsem(&b
->lock
);
559 lockdep_set_novalidate_class(&b
->lock
);
560 INIT_LIST_HEAD(&b
->list
);
561 INIT_DELAYED_WORK(&b
->work
, btree_node_write_work
);
563 closure_init_unlocked(&b
->io
);
565 mca_data_alloc(b
, k
, gfp
);
569 static int mca_reap(struct btree
*b
, struct closure
*cl
, unsigned min_order
)
571 lockdep_assert_held(&b
->c
->bucket_lock
);
573 if (!down_write_trylock(&b
->lock
))
576 if (b
->page_order
< min_order
) {
581 BUG_ON(btree_node_dirty(b
) && !b
->sets
[0].data
);
583 if (cl
&& btree_node_dirty(b
))
584 bch_btree_node_write(b
, NULL
);
587 closure_wait_event_async(&b
->io
.wait
, cl
,
588 atomic_read(&b
->io
.cl
.remaining
) == -1);
590 if (btree_node_dirty(b
) ||
591 !closure_is_unlocked(&b
->io
.cl
) ||
592 work_pending(&b
->work
.work
)) {
600 static unsigned long bch_mca_scan(struct shrinker
*shrink
,
601 struct shrink_control
*sc
)
603 struct cache_set
*c
= container_of(shrink
, struct cache_set
, shrink
);
605 unsigned long i
, nr
= sc
->nr_to_scan
;
606 unsigned long freed
= 0;
608 if (c
->shrinker_disabled
)
614 /* Return -1 if we can't do anything right now */
615 if (sc
->gfp_mask
& __GFP_IO
)
616 mutex_lock(&c
->bucket_lock
);
617 else if (!mutex_trylock(&c
->bucket_lock
))
621 * It's _really_ critical that we don't free too many btree nodes - we
622 * have to always leave ourselves a reserve. The reserve is how we
623 * guarantee that allocating memory for a new btree node can always
624 * succeed, so that inserting keys into the btree can always succeed and
625 * IO can always make forward progress:
627 nr
/= c
->btree_pages
;
628 nr
= min_t(unsigned long, nr
, mca_can_free(c
));
631 list_for_each_entry_safe(b
, t
, &c
->btree_cache_freeable
, list
) {
636 !mca_reap(b
, NULL
, 0)) {
644 * Can happen right when we first start up, before we've read in any
647 if (list_empty(&c
->btree_cache
))
650 for (i
= 0; (nr
--) && i
< c
->bucket_cache_used
; i
++) {
651 b
= list_first_entry(&c
->btree_cache
, struct btree
, list
);
652 list_rotate_left(&c
->btree_cache
);
655 !mca_reap(b
, NULL
, 0)) {
664 mutex_unlock(&c
->bucket_lock
);
668 static unsigned long bch_mca_count(struct shrinker
*shrink
,
669 struct shrink_control
*sc
)
671 struct cache_set
*c
= container_of(shrink
, struct cache_set
, shrink
);
673 if (c
->shrinker_disabled
)
679 return mca_can_free(c
) * c
->btree_pages
;
682 void bch_btree_cache_free(struct cache_set
*c
)
686 closure_init_stack(&cl
);
688 if (c
->shrink
.list
.next
)
689 unregister_shrinker(&c
->shrink
);
691 mutex_lock(&c
->bucket_lock
);
693 #ifdef CONFIG_BCACHE_DEBUG
695 list_move(&c
->verify_data
->list
, &c
->btree_cache
);
698 list_splice(&c
->btree_cache_freeable
,
701 while (!list_empty(&c
->btree_cache
)) {
702 b
= list_first_entry(&c
->btree_cache
, struct btree
, list
);
704 if (btree_node_dirty(b
))
705 btree_complete_write(b
, btree_current_write(b
));
706 clear_bit(BTREE_NODE_dirty
, &b
->flags
);
711 while (!list_empty(&c
->btree_cache_freed
)) {
712 b
= list_first_entry(&c
->btree_cache_freed
,
715 cancel_delayed_work_sync(&b
->work
);
719 mutex_unlock(&c
->bucket_lock
);
722 int bch_btree_cache_alloc(struct cache_set
*c
)
726 /* XXX: doesn't check for errors */
728 closure_init_unlocked(&c
->gc
);
730 for (i
= 0; i
< mca_reserve(c
); i
++)
731 mca_bucket_alloc(c
, &ZERO_KEY
, GFP_KERNEL
);
733 list_splice_init(&c
->btree_cache
,
734 &c
->btree_cache_freeable
);
736 #ifdef CONFIG_BCACHE_DEBUG
737 mutex_init(&c
->verify_lock
);
739 c
->verify_data
= mca_bucket_alloc(c
, &ZERO_KEY
, GFP_KERNEL
);
741 if (c
->verify_data
&&
742 c
->verify_data
->sets
[0].data
)
743 list_del_init(&c
->verify_data
->list
);
745 c
->verify_data
= NULL
;
748 c
->shrink
.count_objects
= bch_mca_count
;
749 c
->shrink
.scan_objects
= bch_mca_scan
;
751 c
->shrink
.batch
= c
->btree_pages
* 2;
752 register_shrinker(&c
->shrink
);
757 /* Btree in memory cache - hash table */
759 static struct hlist_head
*mca_hash(struct cache_set
*c
, struct bkey
*k
)
761 return &c
->bucket_hash
[hash_32(PTR_HASH(c
, k
), BUCKET_HASH_BITS
)];
764 static struct btree
*mca_find(struct cache_set
*c
, struct bkey
*k
)
769 hlist_for_each_entry_rcu(b
, mca_hash(c
, k
), hash
)
770 if (PTR_HASH(c
, &b
->key
) == PTR_HASH(c
, k
))
778 static struct btree
*mca_cannibalize(struct cache_set
*c
, struct bkey
*k
,
779 int level
, struct closure
*cl
)
784 trace_bcache_btree_cache_cannibalize(c
);
787 return ERR_PTR(-ENOMEM
);
790 * Trying to free up some memory - i.e. reuse some btree nodes - may
791 * require initiating IO to flush the dirty part of the node. If we're
792 * running under generic_make_request(), that IO will never finish and
793 * we would deadlock. Returning -EAGAIN causes the cache lookup code to
794 * punt to workqueue and retry.
796 if (current
->bio_list
)
797 return ERR_PTR(-EAGAIN
);
799 if (c
->try_harder
&& c
->try_harder
!= cl
) {
800 closure_wait_event_async(&c
->try_wait
, cl
, !c
->try_harder
);
801 return ERR_PTR(-EAGAIN
);
805 c
->try_harder_start
= local_clock();
807 list_for_each_entry_reverse(i
, &c
->btree_cache
, list
) {
808 int r
= mca_reap(i
, cl
, btree_order(k
));
815 if (ret
== -EAGAIN
&&
816 closure_blocking(cl
)) {
817 mutex_unlock(&c
->bucket_lock
);
819 mutex_lock(&c
->bucket_lock
);
827 * We can only have one thread cannibalizing other cached btree nodes at a time,
828 * or we'll deadlock. We use an open coded mutex to ensure that, which a
829 * cannibalize_bucket() will take. This means every time we unlock the root of
830 * the btree, we need to release this lock if we have it held.
832 void bch_cannibalize_unlock(struct cache_set
*c
, struct closure
*cl
)
834 if (c
->try_harder
== cl
) {
835 bch_time_stats_update(&c
->try_harder_time
, c
->try_harder_start
);
836 c
->try_harder
= NULL
;
837 __closure_wake_up(&c
->try_wait
);
841 static struct btree
*mca_alloc(struct cache_set
*c
, struct bkey
*k
,
842 int level
, struct closure
*cl
)
846 lockdep_assert_held(&c
->bucket_lock
);
851 /* btree_free() doesn't free memory; it sticks the node on the end of
852 * the list. Check if there's any freed nodes there:
854 list_for_each_entry(b
, &c
->btree_cache_freeable
, list
)
855 if (!mca_reap(b
, NULL
, btree_order(k
)))
858 /* We never free struct btree itself, just the memory that holds the on
859 * disk node. Check the freed list before allocating a new one:
861 list_for_each_entry(b
, &c
->btree_cache_freed
, list
)
862 if (!mca_reap(b
, NULL
, 0)) {
863 mca_data_alloc(b
, k
, __GFP_NOWARN
|GFP_NOIO
);
864 if (!b
->sets
[0].data
)
870 b
= mca_bucket_alloc(c
, k
, __GFP_NOWARN
|GFP_NOIO
);
874 BUG_ON(!down_write_trylock(&b
->lock
));
878 BUG_ON(!closure_is_unlocked(&b
->io
.cl
));
880 bkey_copy(&b
->key
, k
);
881 list_move(&b
->list
, &c
->btree_cache
);
882 hlist_del_init_rcu(&b
->hash
);
883 hlist_add_head_rcu(&b
->hash
, mca_hash(c
, k
));
885 lock_set_subclass(&b
->lock
.dep_map
, level
+ 1, _THIS_IP_
);
895 b
= mca_cannibalize(c
, k
, level
, cl
);
903 * bch_btree_node_get - find a btree node in the cache and lock it, reading it
904 * in from disk if necessary.
906 * If IO is necessary, it uses the closure embedded in struct btree_op to wait;
907 * if that closure is in non blocking mode, will return -EAGAIN.
909 * The btree node will have either a read or a write lock held, depending on
910 * level and op->lock.
912 struct btree
*bch_btree_node_get(struct cache_set
*c
, struct bkey
*k
,
913 int level
, struct btree_op
*op
)
916 bool write
= level
<= op
->lock
;
924 if (current
->bio_list
)
925 return ERR_PTR(-EAGAIN
);
927 mutex_lock(&c
->bucket_lock
);
928 b
= mca_alloc(c
, k
, level
, &op
->cl
);
929 mutex_unlock(&c
->bucket_lock
);
936 bch_btree_node_read(b
);
939 downgrade_write(&b
->lock
);
941 rw_lock(write
, b
, level
);
942 if (PTR_HASH(c
, &b
->key
) != PTR_HASH(c
, k
)) {
946 BUG_ON(b
->level
!= level
);
951 for (; i
<= b
->nsets
&& b
->sets
[i
].size
; i
++) {
952 prefetch(b
->sets
[i
].tree
);
953 prefetch(b
->sets
[i
].data
);
956 for (; i
<= b
->nsets
; i
++)
957 prefetch(b
->sets
[i
].data
);
959 if (btree_node_io_error(b
)) {
961 return ERR_PTR(-EIO
);
969 static void btree_node_prefetch(struct cache_set
*c
, struct bkey
*k
, int level
)
973 mutex_lock(&c
->bucket_lock
);
974 b
= mca_alloc(c
, k
, level
, NULL
);
975 mutex_unlock(&c
->bucket_lock
);
977 if (!IS_ERR_OR_NULL(b
)) {
978 bch_btree_node_read(b
);
985 static void btree_node_free(struct btree
*b
, struct btree_op
*op
)
989 trace_bcache_btree_node_free(b
);
992 * The BUG_ON() in btree_node_get() implies that we must have a write
993 * lock on parent to free or even invalidate a node
995 BUG_ON(op
->lock
<= b
->level
);
996 BUG_ON(b
== b
->c
->root
);
998 if (btree_node_dirty(b
))
999 btree_complete_write(b
, btree_current_write(b
));
1000 clear_bit(BTREE_NODE_dirty
, &b
->flags
);
1002 cancel_delayed_work(&b
->work
);
1004 mutex_lock(&b
->c
->bucket_lock
);
1006 for (i
= 0; i
< KEY_PTRS(&b
->key
); i
++) {
1007 BUG_ON(atomic_read(&PTR_BUCKET(b
->c
, &b
->key
, i
)->pin
));
1009 bch_inc_gen(PTR_CACHE(b
->c
, &b
->key
, i
),
1010 PTR_BUCKET(b
->c
, &b
->key
, i
));
1013 bch_bucket_free(b
->c
, &b
->key
);
1015 mutex_unlock(&b
->c
->bucket_lock
);
1018 struct btree
*bch_btree_node_alloc(struct cache_set
*c
, int level
,
1022 struct btree
*b
= ERR_PTR(-EAGAIN
);
1024 mutex_lock(&c
->bucket_lock
);
1026 if (__bch_bucket_alloc_set(c
, WATERMARK_METADATA
, &k
.key
, 1, cl
))
1029 SET_KEY_SIZE(&k
.key
, c
->btree_pages
* PAGE_SECTORS
);
1031 b
= mca_alloc(c
, &k
.key
, level
, cl
);
1037 "Tried to allocate bucket that was in btree cache");
1038 __bkey_put(c
, &k
.key
);
1043 bch_bset_init_next(b
);
1045 mutex_unlock(&c
->bucket_lock
);
1047 trace_bcache_btree_node_alloc(b
);
1050 bch_bucket_free(c
, &k
.key
);
1051 __bkey_put(c
, &k
.key
);
1053 mutex_unlock(&c
->bucket_lock
);
1055 trace_bcache_btree_node_alloc_fail(b
);
1059 static struct btree
*btree_node_alloc_replacement(struct btree
*b
,
1062 struct btree
*n
= bch_btree_node_alloc(b
->c
, b
->level
, cl
);
1063 if (!IS_ERR_OR_NULL(n
))
1064 bch_btree_sort_into(b
, n
);
1069 /* Garbage collection */
1071 uint8_t __bch_btree_mark_key(struct cache_set
*c
, int level
, struct bkey
*k
)
1078 * ptr_invalid() can't return true for the keys that mark btree nodes as
1079 * freed, but since ptr_bad() returns true we'll never actually use them
1080 * for anything and thus we don't want mark their pointers here
1082 if (!bkey_cmp(k
, &ZERO_KEY
))
1085 for (i
= 0; i
< KEY_PTRS(k
); i
++) {
1086 if (!ptr_available(c
, k
, i
))
1089 g
= PTR_BUCKET(c
, k
, i
);
1091 if (gen_after(g
->gc_gen
, PTR_GEN(k
, i
)))
1092 g
->gc_gen
= PTR_GEN(k
, i
);
1094 if (ptr_stale(c
, k
, i
)) {
1095 stale
= max(stale
, ptr_stale(c
, k
, i
));
1099 cache_bug_on(GC_MARK(g
) &&
1100 (GC_MARK(g
) == GC_MARK_METADATA
) != (level
!= 0),
1101 c
, "inconsistent ptrs: mark = %llu, level = %i",
1105 SET_GC_MARK(g
, GC_MARK_METADATA
);
1106 else if (KEY_DIRTY(k
))
1107 SET_GC_MARK(g
, GC_MARK_DIRTY
);
1109 /* guard against overflow */
1110 SET_GC_SECTORS_USED(g
, min_t(unsigned,
1111 GC_SECTORS_USED(g
) + KEY_SIZE(k
),
1114 BUG_ON(!GC_SECTORS_USED(g
));
1120 #define btree_mark_key(b, k) __bch_btree_mark_key(b->c, b->level, k)
1122 static int btree_gc_mark_node(struct btree
*b
, unsigned *keys
,
1126 unsigned last_dev
= -1;
1127 struct bcache_device
*d
= NULL
;
1129 struct btree_iter iter
;
1130 struct bset_tree
*t
;
1134 for_each_key_filter(b
, k
, &iter
, bch_ptr_invalid
) {
1135 if (last_dev
!= KEY_INODE(k
)) {
1136 last_dev
= KEY_INODE(k
);
1138 d
= KEY_INODE(k
) < b
->c
->nr_uuids
1139 ? b
->c
->devices
[last_dev
]
1143 stale
= max(stale
, btree_mark_key(b
, k
));
1145 if (bch_ptr_bad(b
, k
))
1148 *keys
+= bkey_u64s(k
);
1150 gc
->key_bytes
+= bkey_u64s(k
);
1153 gc
->data
+= KEY_SIZE(k
);
1155 gc
->dirty
+= KEY_SIZE(k
);
1158 for (t
= b
->sets
; t
<= &b
->sets
[b
->nsets
]; t
++)
1159 btree_bug_on(t
->size
&&
1160 bset_written(b
, t
) &&
1161 bkey_cmp(&b
->key
, &t
->end
) < 0,
1162 b
, "found short btree key in gc");
1167 static struct btree
*btree_gc_alloc(struct btree
*b
, struct bkey
*k
,
1168 struct btree_op
*op
)
1171 * We block priorities from being written for the duration of garbage
1172 * collection, so we can't sleep in btree_alloc() ->
1173 * bch_bucket_alloc_set(), or we'd risk deadlock - so we don't pass it
1176 struct btree
*n
= btree_node_alloc_replacement(b
, NULL
);
1178 if (!IS_ERR_OR_NULL(n
)) {
1180 __bkey_put(b
->c
, &b
->key
);
1182 memcpy(k
->ptr
, b
->key
.ptr
,
1183 sizeof(uint64_t) * KEY_PTRS(&b
->key
));
1185 btree_node_free(n
, op
);
1193 * Leaving this at 2 until we've got incremental garbage collection done; it
1194 * could be higher (and has been tested with 4) except that garbage collection
1195 * could take much longer, adversely affecting latency.
1197 #define GC_MERGE_NODES 2U
1199 struct gc_merge_info
{
1205 static void btree_gc_coalesce(struct btree
*b
, struct btree_op
*op
,
1206 struct gc_stat
*gc
, struct gc_merge_info
*r
)
1208 unsigned nodes
= 0, keys
= 0, blocks
;
1211 while (nodes
< GC_MERGE_NODES
&& r
[nodes
].b
)
1212 keys
+= r
[nodes
++].keys
;
1214 blocks
= btree_default_blocks(b
->c
) * 2 / 3;
1217 __set_blocks(b
->sets
[0].data
, keys
, b
->c
) > blocks
* (nodes
- 1))
1220 for (i
= nodes
- 1; i
>= 0; --i
) {
1221 if (r
[i
].b
->written
)
1222 r
[i
].b
= btree_gc_alloc(r
[i
].b
, r
[i
].k
, op
);
1224 if (r
[i
].b
->written
)
1228 for (i
= nodes
- 1; i
> 0; --i
) {
1229 struct bset
*n1
= r
[i
].b
->sets
->data
;
1230 struct bset
*n2
= r
[i
- 1].b
->sets
->data
;
1231 struct bkey
*k
, *last
= NULL
;
1237 * Last node we're not getting rid of - we're getting
1238 * rid of the node at r[0]. Have to try and fit all of
1239 * the remaining keys into this node; we can't ensure
1240 * they will always fit due to rounding and variable
1241 * length keys (shouldn't be possible in practice,
1244 if (__set_blocks(n1
, n1
->keys
+ r
->keys
,
1245 b
->c
) > btree_blocks(r
[i
].b
))
1254 if (__set_blocks(n1
, n1
->keys
+ keys
+
1255 bkey_u64s(k
), b
->c
) > blocks
)
1259 keys
+= bkey_u64s(k
);
1262 BUG_ON(__set_blocks(n1
, n1
->keys
+ keys
,
1263 b
->c
) > btree_blocks(r
[i
].b
));
1266 bkey_copy_key(&r
[i
].b
->key
, last
);
1267 bkey_copy_key(r
[i
].k
, last
);
1272 (void *) node(n2
, keys
) - (void *) n2
->start
);
1278 (void *) end(n2
) - (void *) node(n2
, keys
));
1282 r
[i
].keys
= n1
->keys
;
1283 r
[i
- 1].keys
= n2
->keys
;
1286 btree_node_free(r
->b
, op
);
1287 up_write(&r
->b
->lock
);
1289 trace_bcache_btree_gc_coalesce(nodes
);
1294 memmove(&r
[0], &r
[1], sizeof(struct gc_merge_info
) * nodes
);
1295 memset(&r
[nodes
], 0, sizeof(struct gc_merge_info
));
1298 static int btree_gc_recurse(struct btree
*b
, struct btree_op
*op
,
1299 struct closure
*writes
, struct gc_stat
*gc
)
1301 void write(struct btree
*r
)
1304 bch_btree_node_write(r
, &op
->cl
);
1305 else if (btree_node_dirty(r
))
1306 bch_btree_node_write(r
, writes
);
1313 struct gc_merge_info r
[GC_MERGE_NODES
];
1315 memset(r
, 0, sizeof(r
));
1317 while ((r
->k
= bch_next_recurse_key(b
, &b
->c
->gc_done
))) {
1318 r
->b
= bch_btree_node_get(b
->c
, r
->k
, b
->level
- 1, op
);
1321 ret
= PTR_ERR(r
->b
);
1326 stale
= btree_gc_mark_node(r
->b
, &r
->keys
, gc
);
1329 (r
->b
->level
|| stale
> 10 ||
1330 b
->c
->gc_always_rewrite
))
1331 r
->b
= btree_gc_alloc(r
->b
, r
->k
, op
);
1334 ret
= btree_gc_recurse(r
->b
, op
, writes
, gc
);
1341 bkey_copy_key(&b
->c
->gc_done
, r
->k
);
1344 btree_gc_coalesce(b
, op
, gc
, r
);
1346 if (r
[GC_MERGE_NODES
- 1].b
)
1347 write(r
[GC_MERGE_NODES
- 1].b
);
1349 memmove(&r
[1], &r
[0],
1350 sizeof(struct gc_merge_info
) * (GC_MERGE_NODES
- 1));
1352 /* When we've got incremental GC working, we'll want to do
1353 * if (should_resched())
1358 if (need_resched()) {
1365 for (i
= 1; i
< GC_MERGE_NODES
&& r
[i
].b
; i
++)
1368 /* Might have freed some children, must remove their keys */
1375 static int bch_btree_gc_root(struct btree
*b
, struct btree_op
*op
,
1376 struct closure
*writes
, struct gc_stat
*gc
)
1378 struct btree
*n
= NULL
;
1380 int ret
= 0, stale
= btree_gc_mark_node(b
, &keys
, gc
);
1382 if (b
->level
|| stale
> 10)
1383 n
= btree_node_alloc_replacement(b
, NULL
);
1385 if (!IS_ERR_OR_NULL(n
))
1389 ret
= btree_gc_recurse(b
, op
, writes
, gc
);
1391 if (!b
->written
|| btree_node_dirty(b
)) {
1392 bch_btree_node_write(b
, n
? &op
->cl
: NULL
);
1395 if (!IS_ERR_OR_NULL(n
)) {
1396 closure_sync(&op
->cl
);
1397 bch_btree_set_root(b
);
1398 btree_node_free(n
, op
);
1405 static void btree_gc_start(struct cache_set
*c
)
1411 if (!c
->gc_mark_valid
)
1414 mutex_lock(&c
->bucket_lock
);
1416 c
->gc_mark_valid
= 0;
1417 c
->gc_done
= ZERO_KEY
;
1419 for_each_cache(ca
, c
, i
)
1420 for_each_bucket(b
, ca
) {
1422 if (!atomic_read(&b
->pin
)) {
1423 SET_GC_MARK(b
, GC_MARK_RECLAIMABLE
);
1424 SET_GC_SECTORS_USED(b
, 0);
1428 mutex_unlock(&c
->bucket_lock
);
1431 size_t bch_btree_gc_finish(struct cache_set
*c
)
1433 size_t available
= 0;
1438 mutex_lock(&c
->bucket_lock
);
1441 c
->gc_mark_valid
= 1;
1445 for (i
= 0; i
< KEY_PTRS(&c
->root
->key
); i
++)
1446 SET_GC_MARK(PTR_BUCKET(c
, &c
->root
->key
, i
),
1449 for (i
= 0; i
< KEY_PTRS(&c
->uuid_bucket
); i
++)
1450 SET_GC_MARK(PTR_BUCKET(c
, &c
->uuid_bucket
, i
),
1453 for_each_cache(ca
, c
, i
) {
1456 ca
->invalidate_needs_gc
= 0;
1458 for (i
= ca
->sb
.d
; i
< ca
->sb
.d
+ ca
->sb
.keys
; i
++)
1459 SET_GC_MARK(ca
->buckets
+ *i
, GC_MARK_METADATA
);
1461 for (i
= ca
->prio_buckets
;
1462 i
< ca
->prio_buckets
+ prio_buckets(ca
) * 2; i
++)
1463 SET_GC_MARK(ca
->buckets
+ *i
, GC_MARK_METADATA
);
1465 for_each_bucket(b
, ca
) {
1466 b
->last_gc
= b
->gc_gen
;
1467 c
->need_gc
= max(c
->need_gc
, bucket_gc_gen(b
));
1469 if (!atomic_read(&b
->pin
) &&
1470 GC_MARK(b
) == GC_MARK_RECLAIMABLE
) {
1472 if (!GC_SECTORS_USED(b
))
1473 bch_bucket_add_unused(ca
, b
);
1478 mutex_unlock(&c
->bucket_lock
);
1482 static void bch_btree_gc(struct closure
*cl
)
1484 struct cache_set
*c
= container_of(cl
, struct cache_set
, gc
.cl
);
1486 unsigned long available
;
1487 struct gc_stat stats
;
1488 struct closure writes
;
1490 uint64_t start_time
= local_clock();
1492 trace_bcache_gc_start(c
);
1494 memset(&stats
, 0, sizeof(struct gc_stat
));
1495 closure_init_stack(&writes
);
1496 bch_btree_op_init_stack(&op
);
1501 atomic_inc(&c
->prio_blocked
);
1503 ret
= btree_root(gc_root
, c
, &op
, &writes
, &stats
);
1504 closure_sync(&op
.cl
);
1505 closure_sync(&writes
);
1508 pr_warn("gc failed!");
1509 continue_at(cl
, bch_btree_gc
, bch_gc_wq
);
1512 /* Possibly wait for new UUIDs or whatever to hit disk */
1513 bch_journal_meta(c
, &op
.cl
);
1514 closure_sync(&op
.cl
);
1516 available
= bch_btree_gc_finish(c
);
1518 atomic_dec(&c
->prio_blocked
);
1519 wake_up_allocators(c
);
1521 bch_time_stats_update(&c
->btree_gc_time
, start_time
);
1523 stats
.key_bytes
*= sizeof(uint64_t);
1526 stats
.in_use
= (c
->nbuckets
- available
) * 100 / c
->nbuckets
;
1527 memcpy(&c
->gc_stats
, &stats
, sizeof(struct gc_stat
));
1529 trace_bcache_gc_end(c
);
1531 continue_at(cl
, bch_moving_gc
, bch_gc_wq
);
1534 void bch_queue_gc(struct cache_set
*c
)
1536 closure_trylock_call(&c
->gc
.cl
, bch_btree_gc
, bch_gc_wq
, &c
->cl
);
1539 /* Initial partial gc */
1541 static int bch_btree_check_recurse(struct btree
*b
, struct btree_op
*op
,
1542 unsigned long **seen
)
1548 struct btree_iter iter
;
1550 for_each_key_filter(b
, k
, &iter
, bch_ptr_invalid
) {
1551 for (i
= 0; i
< KEY_PTRS(k
); i
++) {
1552 if (!ptr_available(b
->c
, k
, i
))
1555 g
= PTR_BUCKET(b
->c
, k
, i
);
1557 if (!__test_and_set_bit(PTR_BUCKET_NR(b
->c
, k
, i
),
1558 seen
[PTR_DEV(k
, i
)]) ||
1559 !ptr_stale(b
->c
, k
, i
)) {
1560 g
->gen
= PTR_GEN(k
, i
);
1563 g
->prio
= BTREE_PRIO
;
1564 else if (g
->prio
== BTREE_PRIO
)
1565 g
->prio
= INITIAL_PRIO
;
1569 btree_mark_key(b
, k
);
1573 k
= bch_next_recurse_key(b
, &ZERO_KEY
);
1576 struct bkey
*p
= bch_next_recurse_key(b
, k
);
1578 btree_node_prefetch(b
->c
, p
, b
->level
- 1);
1580 ret
= btree(check_recurse
, k
, b
, op
, seen
);
1591 int bch_btree_check(struct cache_set
*c
, struct btree_op
*op
)
1595 unsigned long *seen
[MAX_CACHES_PER_SET
];
1597 memset(seen
, 0, sizeof(seen
));
1599 for (i
= 0; c
->cache
[i
]; i
++) {
1600 size_t n
= DIV_ROUND_UP(c
->cache
[i
]->sb
.nbuckets
, 8);
1601 seen
[i
] = kmalloc(n
, GFP_KERNEL
);
1605 /* Disables the seen array until prio_read() uses it too */
1606 memset(seen
[i
], 0xFF, n
);
1609 ret
= btree_root(check_recurse
, c
, op
, seen
);
1611 for (i
= 0; i
< MAX_CACHES_PER_SET
; i
++)
1616 /* Btree insertion */
1618 static void shift_keys(struct btree
*b
, struct bkey
*where
, struct bkey
*insert
)
1620 struct bset
*i
= b
->sets
[b
->nsets
].data
;
1622 memmove((uint64_t *) where
+ bkey_u64s(insert
),
1624 (void *) end(i
) - (void *) where
);
1626 i
->keys
+= bkey_u64s(insert
);
1627 bkey_copy(where
, insert
);
1628 bch_bset_fix_lookup_table(b
, where
);
1631 static bool fix_overlapping_extents(struct btree
*b
,
1632 struct bkey
*insert
,
1633 struct btree_iter
*iter
,
1634 struct btree_op
*op
)
1636 void subtract_dirty(struct bkey
*k
, uint64_t offset
, int sectors
)
1639 bcache_dev_sectors_dirty_add(b
->c
, KEY_INODE(k
),
1643 uint64_t old_offset
;
1644 unsigned old_size
, sectors_found
= 0;
1647 struct bkey
*k
= bch_btree_iter_next(iter
);
1649 bkey_cmp(&START_KEY(k
), insert
) >= 0)
1652 if (bkey_cmp(k
, &START_KEY(insert
)) <= 0)
1655 old_offset
= KEY_START(k
);
1656 old_size
= KEY_SIZE(k
);
1659 * We might overlap with 0 size extents; we can't skip these
1660 * because if they're in the set we're inserting to we have to
1661 * adjust them so they don't overlap with the key we're
1662 * inserting. But we don't want to check them for BTREE_REPLACE
1666 if (op
->type
== BTREE_REPLACE
&&
1669 * k might have been split since we inserted/found the
1670 * key we're replacing
1673 uint64_t offset
= KEY_START(k
) -
1674 KEY_START(&op
->replace
);
1676 /* But it must be a subset of the replace key */
1677 if (KEY_START(k
) < KEY_START(&op
->replace
) ||
1678 KEY_OFFSET(k
) > KEY_OFFSET(&op
->replace
))
1681 /* We didn't find a key that we were supposed to */
1682 if (KEY_START(k
) > KEY_START(insert
) + sectors_found
)
1685 if (KEY_PTRS(&op
->replace
) != KEY_PTRS(k
))
1691 BUG_ON(!KEY_PTRS(&op
->replace
));
1693 for (i
= 0; i
< KEY_PTRS(&op
->replace
); i
++)
1694 if (k
->ptr
[i
] != op
->replace
.ptr
[i
] + offset
)
1697 sectors_found
= KEY_OFFSET(k
) - KEY_START(insert
);
1700 if (bkey_cmp(insert
, k
) < 0 &&
1701 bkey_cmp(&START_KEY(insert
), &START_KEY(k
)) > 0) {
1703 * We overlapped in the middle of an existing key: that
1704 * means we have to split the old key. But we have to do
1705 * slightly different things depending on whether the
1706 * old key has been written out yet.
1711 subtract_dirty(k
, KEY_START(insert
), KEY_SIZE(insert
));
1713 if (bkey_written(b
, k
)) {
1715 * We insert a new key to cover the top of the
1716 * old key, and the old key is modified in place
1717 * to represent the bottom split.
1719 * It's completely arbitrary whether the new key
1720 * is the top or the bottom, but it has to match
1721 * up with what btree_sort_fixup() does - it
1722 * doesn't check for this kind of overlap, it
1723 * depends on us inserting a new key for the top
1726 top
= bch_bset_search(b
, &b
->sets
[b
->nsets
],
1728 shift_keys(b
, top
, k
);
1730 BKEY_PADDED(key
) temp
;
1731 bkey_copy(&temp
.key
, k
);
1732 shift_keys(b
, k
, &temp
.key
);
1736 bch_cut_front(insert
, top
);
1737 bch_cut_back(&START_KEY(insert
), k
);
1738 bch_bset_fix_invalidated_key(b
, k
);
1742 if (bkey_cmp(insert
, k
) < 0) {
1743 bch_cut_front(insert
, k
);
1745 if (bkey_cmp(&START_KEY(insert
), &START_KEY(k
)) > 0)
1746 old_offset
= KEY_START(insert
);
1748 if (bkey_written(b
, k
) &&
1749 bkey_cmp(&START_KEY(insert
), &START_KEY(k
)) <= 0) {
1751 * Completely overwrote, so we don't have to
1752 * invalidate the binary search tree
1754 bch_cut_front(k
, k
);
1756 __bch_cut_back(&START_KEY(insert
), k
);
1757 bch_bset_fix_invalidated_key(b
, k
);
1761 subtract_dirty(k
, old_offset
, old_size
- KEY_SIZE(k
));
1765 if (op
->type
== BTREE_REPLACE
) {
1766 if (!sectors_found
) {
1767 op
->insert_collision
= true;
1769 } else if (sectors_found
< KEY_SIZE(insert
)) {
1770 SET_KEY_OFFSET(insert
, KEY_OFFSET(insert
) -
1771 (KEY_SIZE(insert
) - sectors_found
));
1772 SET_KEY_SIZE(insert
, sectors_found
);
1779 static bool btree_insert_key(struct btree
*b
, struct btree_op
*op
,
1782 struct bset
*i
= b
->sets
[b
->nsets
].data
;
1783 struct bkey
*m
, *prev
;
1784 unsigned status
= BTREE_INSERT_STATUS_INSERT
;
1786 BUG_ON(bkey_cmp(k
, &b
->key
) > 0);
1787 BUG_ON(b
->level
&& !KEY_PTRS(k
));
1788 BUG_ON(!b
->level
&& !KEY_OFFSET(k
));
1791 struct btree_iter iter
;
1792 struct bkey search
= KEY(KEY_INODE(k
), KEY_START(k
), 0);
1795 * bset_search() returns the first key that is strictly greater
1796 * than the search key - but for back merging, we want to find
1797 * the first key that is greater than or equal to KEY_START(k) -
1798 * unless KEY_START(k) is 0.
1800 if (KEY_OFFSET(&search
))
1801 SET_KEY_OFFSET(&search
, KEY_OFFSET(&search
) - 1);
1804 m
= bch_btree_iter_init(b
, &iter
, &search
);
1806 if (fix_overlapping_extents(b
, k
, &iter
, op
))
1810 bcache_dev_sectors_dirty_add(b
->c
, KEY_INODE(k
),
1811 KEY_START(k
), KEY_SIZE(k
));
1813 while (m
!= end(i
) &&
1814 bkey_cmp(k
, &START_KEY(m
)) > 0)
1815 prev
= m
, m
= bkey_next(m
);
1817 if (key_merging_disabled(b
->c
))
1820 /* prev is in the tree, if we merge we're done */
1821 status
= BTREE_INSERT_STATUS_BACK_MERGE
;
1823 bch_bkey_try_merge(b
, prev
, k
))
1826 status
= BTREE_INSERT_STATUS_OVERWROTE
;
1828 KEY_PTRS(m
) == KEY_PTRS(k
) && !KEY_SIZE(m
))
1831 status
= BTREE_INSERT_STATUS_FRONT_MERGE
;
1833 bch_bkey_try_merge(b
, k
, m
))
1836 m
= bch_bset_search(b
, &b
->sets
[b
->nsets
], k
);
1838 insert
: shift_keys(b
, m
, k
);
1839 copy
: bkey_copy(m
, k
);
1841 bch_check_keys(b
, "%u for %s", status
, op_type(op
));
1843 if (b
->level
&& !KEY_OFFSET(k
))
1844 btree_current_write(b
)->prio_blocked
++;
1846 trace_bcache_btree_insert_key(b
, k
, op
->type
, status
);
1851 static bool bch_btree_insert_keys(struct btree
*b
, struct btree_op
*op
)
1855 unsigned oldsize
= bch_count_data(b
);
1857 while ((k
= bch_keylist_pop(&op
->keys
))) {
1858 bkey_put(b
->c
, k
, b
->level
);
1859 ret
|= btree_insert_key(b
, op
, k
);
1862 BUG_ON(bch_count_data(b
) < oldsize
);
1866 bool bch_btree_insert_check_key(struct btree
*b
, struct btree_op
*op
,
1870 uint64_t btree_ptr
= b
->key
.ptr
[0];
1871 unsigned long seq
= b
->seq
;
1874 rw_unlock(false, b
);
1875 rw_lock(true, b
, b
->level
);
1877 if (b
->key
.ptr
[0] != btree_ptr
||
1878 b
->seq
!= seq
+ 1 ||
1882 op
->replace
= KEY(op
->inode
, bio_end_sector(bio
), bio_sectors(bio
));
1884 SET_KEY_PTRS(&op
->replace
, 1);
1885 get_random_bytes(&op
->replace
.ptr
[0], sizeof(uint64_t));
1887 SET_PTR_DEV(&op
->replace
, 0, PTR_CHECK_DEV
);
1889 bkey_copy(&tmp
.k
, &op
->replace
);
1891 BUG_ON(op
->type
!= BTREE_INSERT
);
1892 BUG_ON(!btree_insert_key(b
, op
, &tmp
.k
));
1895 downgrade_write(&b
->lock
);
1899 static int btree_split(struct btree
*b
, struct btree_op
*op
)
1901 bool split
, root
= b
== b
->c
->root
;
1902 struct btree
*n1
, *n2
= NULL
, *n3
= NULL
;
1903 uint64_t start_time
= local_clock();
1906 set_closure_blocking(&op
->cl
);
1908 n1
= btree_node_alloc_replacement(b
, &op
->cl
);
1912 split
= set_blocks(n1
->sets
[0].data
, n1
->c
) > (btree_blocks(b
) * 4) / 5;
1917 trace_bcache_btree_node_split(b
, n1
->sets
[0].data
->keys
);
1919 n2
= bch_btree_node_alloc(b
->c
, b
->level
, &op
->cl
);
1924 n3
= bch_btree_node_alloc(b
->c
, b
->level
+ 1, &op
->cl
);
1929 bch_btree_insert_keys(n1
, op
);
1931 /* Has to be a linear search because we don't have an auxiliary
1935 while (keys
< (n1
->sets
[0].data
->keys
* 3) / 5)
1936 keys
+= bkey_u64s(node(n1
->sets
[0].data
, keys
));
1938 bkey_copy_key(&n1
->key
, node(n1
->sets
[0].data
, keys
));
1939 keys
+= bkey_u64s(node(n1
->sets
[0].data
, keys
));
1941 n2
->sets
[0].data
->keys
= n1
->sets
[0].data
->keys
- keys
;
1942 n1
->sets
[0].data
->keys
= keys
;
1944 memcpy(n2
->sets
[0].data
->start
,
1945 end(n1
->sets
[0].data
),
1946 n2
->sets
[0].data
->keys
* sizeof(uint64_t));
1948 bkey_copy_key(&n2
->key
, &b
->key
);
1950 bch_keylist_add(&op
->keys
, &n2
->key
);
1951 bch_btree_node_write(n2
, &op
->cl
);
1952 rw_unlock(true, n2
);
1954 trace_bcache_btree_node_compact(b
, n1
->sets
[0].data
->keys
);
1956 bch_btree_insert_keys(n1
, op
);
1959 bch_keylist_add(&op
->keys
, &n1
->key
);
1960 bch_btree_node_write(n1
, &op
->cl
);
1963 bkey_copy_key(&n3
->key
, &MAX_KEY
);
1964 bch_btree_insert_keys(n3
, op
);
1965 bch_btree_node_write(n3
, &op
->cl
);
1967 closure_sync(&op
->cl
);
1968 bch_btree_set_root(n3
);
1969 rw_unlock(true, n3
);
1971 op
->keys
.top
= op
->keys
.bottom
;
1972 closure_sync(&op
->cl
);
1973 bch_btree_set_root(n1
);
1977 bkey_copy(op
->keys
.top
, &b
->key
);
1978 bkey_copy_key(op
->keys
.top
, &ZERO_KEY
);
1980 for (i
= 0; i
< KEY_PTRS(&b
->key
); i
++) {
1981 uint8_t g
= PTR_BUCKET(b
->c
, &b
->key
, i
)->gen
+ 1;
1983 SET_PTR_GEN(op
->keys
.top
, i
, g
);
1986 bch_keylist_push(&op
->keys
);
1987 closure_sync(&op
->cl
);
1988 atomic_inc(&b
->c
->prio_blocked
);
1991 rw_unlock(true, n1
);
1992 btree_node_free(b
, op
);
1994 bch_time_stats_update(&b
->c
->btree_split_time
, start_time
);
1998 __bkey_put(n2
->c
, &n2
->key
);
1999 btree_node_free(n2
, op
);
2000 rw_unlock(true, n2
);
2002 __bkey_put(n1
->c
, &n1
->key
);
2003 btree_node_free(n1
, op
);
2004 rw_unlock(true, n1
);
2006 if (n3
== ERR_PTR(-EAGAIN
) ||
2007 n2
== ERR_PTR(-EAGAIN
) ||
2008 n1
== ERR_PTR(-EAGAIN
))
2011 pr_warn("couldn't split");
2015 static int bch_btree_insert_recurse(struct btree
*b
, struct btree_op
*op
,
2016 struct keylist
*stack_keys
)
2020 struct bkey
*insert
= op
->keys
.bottom
;
2021 struct bkey
*k
= bch_next_recurse_key(b
, &START_KEY(insert
));
2024 btree_bug(b
, "no key to recurse on at level %i/%i",
2025 b
->level
, b
->c
->root
->level
);
2027 op
->keys
.top
= op
->keys
.bottom
;
2031 if (bkey_cmp(insert
, k
) > 0) {
2034 if (op
->type
== BTREE_REPLACE
) {
2035 __bkey_put(b
->c
, insert
);
2036 op
->keys
.top
= op
->keys
.bottom
;
2037 op
->insert_collision
= true;
2041 for (i
= 0; i
< KEY_PTRS(insert
); i
++)
2042 atomic_inc(&PTR_BUCKET(b
->c
, insert
, i
)->pin
);
2044 bkey_copy(stack_keys
->top
, insert
);
2046 bch_cut_back(k
, insert
);
2047 bch_cut_front(k
, stack_keys
->top
);
2049 bch_keylist_push(stack_keys
);
2052 ret
= btree(insert_recurse
, k
, b
, op
, stack_keys
);
2057 if (!bch_keylist_empty(&op
->keys
)) {
2058 if (should_split(b
)) {
2059 if (op
->lock
<= b
->c
->root
->level
) {
2061 op
->lock
= b
->c
->root
->level
+ 1;
2064 return btree_split(b
, op
);
2067 BUG_ON(write_block(b
) != b
->sets
[b
->nsets
].data
);
2069 if (bch_btree_insert_keys(b
, op
)) {
2071 bch_btree_leaf_dirty(b
, op
);
2073 bch_btree_node_write(b
, &op
->cl
);
2080 int bch_btree_insert(struct btree_op
*op
, struct cache_set
*c
)
2083 struct keylist stack_keys
;
2086 * Don't want to block with the btree locked unless we have to,
2087 * otherwise we get deadlocks with try_harder and between split/gc
2089 clear_closure_blocking(&op
->cl
);
2091 BUG_ON(bch_keylist_empty(&op
->keys
));
2092 bch_keylist_copy(&stack_keys
, &op
->keys
);
2093 bch_keylist_init(&op
->keys
);
2095 while (!bch_keylist_empty(&stack_keys
) ||
2096 !bch_keylist_empty(&op
->keys
)) {
2097 if (bch_keylist_empty(&op
->keys
)) {
2098 bch_keylist_add(&op
->keys
,
2099 bch_keylist_pop(&stack_keys
));
2103 ret
= btree_root(insert_recurse
, c
, op
, &stack_keys
);
2105 if (ret
== -EAGAIN
) {
2107 closure_sync(&op
->cl
);
2111 pr_err("error %i trying to insert key for %s",
2114 while ((k
= bch_keylist_pop(&stack_keys
) ?:
2115 bch_keylist_pop(&op
->keys
)))
2120 bch_keylist_free(&stack_keys
);
2123 atomic_dec_bug(op
->journal
);
2128 void bch_btree_set_root(struct btree
*b
)
2133 closure_init_stack(&cl
);
2135 trace_bcache_btree_set_root(b
);
2137 BUG_ON(!b
->written
);
2139 for (i
= 0; i
< KEY_PTRS(&b
->key
); i
++)
2140 BUG_ON(PTR_BUCKET(b
->c
, &b
->key
, i
)->prio
!= BTREE_PRIO
);
2142 mutex_lock(&b
->c
->bucket_lock
);
2143 list_del_init(&b
->list
);
2144 mutex_unlock(&b
->c
->bucket_lock
);
2147 __bkey_put(b
->c
, &b
->key
);
2149 bch_journal_meta(b
->c
, &cl
);
2155 static int submit_partial_cache_miss(struct btree
*b
, struct btree_op
*op
,
2158 struct search
*s
= container_of(op
, struct search
, op
);
2159 struct bio
*bio
= &s
->bio
.bio
;
2164 unsigned sectors
= INT_MAX
;
2166 if (KEY_INODE(k
) == op
->inode
) {
2167 if (KEY_START(k
) <= bio
->bi_sector
)
2170 sectors
= min_t(uint64_t, sectors
,
2171 KEY_START(k
) - bio
->bi_sector
);
2174 ret
= s
->d
->cache_miss(b
, s
, bio
, sectors
);
2181 * Read from a single key, handling the initial cache miss if the key starts in
2182 * the middle of the bio
2184 static int submit_partial_cache_hit(struct btree
*b
, struct btree_op
*op
,
2187 struct search
*s
= container_of(op
, struct search
, op
);
2188 struct bio
*bio
= &s
->bio
.bio
;
2192 int ret
= submit_partial_cache_miss(b
, op
, k
);
2193 if (ret
|| op
->lookup_done
)
2196 /* XXX: figure out best pointer - for multiple cache devices */
2199 PTR_BUCKET(b
->c
, k
, ptr
)->prio
= INITIAL_PRIO
;
2201 while (!op
->lookup_done
&&
2202 KEY_INODE(k
) == op
->inode
&&
2203 bio
->bi_sector
< KEY_OFFSET(k
)) {
2204 struct bkey
*bio_key
;
2205 sector_t sector
= PTR_OFFSET(k
, ptr
) +
2206 (bio
->bi_sector
- KEY_START(k
));
2207 unsigned sectors
= min_t(uint64_t, INT_MAX
,
2208 KEY_OFFSET(k
) - bio
->bi_sector
);
2210 n
= bch_bio_split(bio
, sectors
, GFP_NOIO
, s
->d
->bio_split
);
2212 op
->lookup_done
= true;
2214 bio_key
= &container_of(n
, struct bbio
, bio
)->key
;
2217 * The bucket we're reading from might be reused while our bio
2218 * is in flight, and we could then end up reading the wrong
2221 * We guard against this by checking (in cache_read_endio()) if
2222 * the pointer is stale again; if so, we treat it as an error
2223 * and reread from the backing device (but we don't pass that
2224 * error up anywhere).
2227 bch_bkey_copy_single_ptr(bio_key
, k
, ptr
);
2228 SET_PTR_OFFSET(bio_key
, 0, sector
);
2230 n
->bi_end_io
= bch_cache_read_endio
;
2231 n
->bi_private
= &s
->cl
;
2233 __bch_submit_bbio(n
, b
->c
);
2239 int bch_btree_search_recurse(struct btree
*b
, struct btree_op
*op
)
2241 struct search
*s
= container_of(op
, struct search
, op
);
2242 struct bio
*bio
= &s
->bio
.bio
;
2246 struct btree_iter iter
;
2247 bch_btree_iter_init(b
, &iter
, &KEY(op
->inode
, bio
->bi_sector
, 0));
2250 k
= bch_btree_iter_next_filter(&iter
, b
, bch_ptr_bad
);
2253 * b->key would be exactly what we want, except that
2254 * pointers to btree nodes have nonzero size - we
2255 * wouldn't go far enough
2258 ret
= submit_partial_cache_miss(b
, op
,
2259 &KEY(KEY_INODE(&b
->key
),
2260 KEY_OFFSET(&b
->key
), 0));
2265 ? btree(search_recurse
, k
, b
, op
)
2266 : submit_partial_cache_hit(b
, op
, k
);
2275 static inline int keybuf_cmp(struct keybuf_key
*l
, struct keybuf_key
*r
)
2277 /* Overlapping keys compare equal */
2278 if (bkey_cmp(&l
->key
, &START_KEY(&r
->key
)) <= 0)
2280 if (bkey_cmp(&START_KEY(&l
->key
), &r
->key
) >= 0)
2285 static inline int keybuf_nonoverlapping_cmp(struct keybuf_key
*l
,
2286 struct keybuf_key
*r
)
2288 return clamp_t(int64_t, bkey_cmp(&l
->key
, &r
->key
), -1, 1);
2291 static int bch_btree_refill_keybuf(struct btree
*b
, struct btree_op
*op
,
2292 struct keybuf
*buf
, struct bkey
*end
,
2293 keybuf_pred_fn
*pred
)
2295 struct btree_iter iter
;
2296 bch_btree_iter_init(b
, &iter
, &buf
->last_scanned
);
2298 while (!array_freelist_empty(&buf
->freelist
)) {
2299 struct bkey
*k
= bch_btree_iter_next_filter(&iter
, b
,
2304 buf
->last_scanned
= b
->key
;
2308 buf
->last_scanned
= *k
;
2309 if (bkey_cmp(&buf
->last_scanned
, end
) >= 0)
2313 struct keybuf_key
*w
;
2315 spin_lock(&buf
->lock
);
2317 w
= array_alloc(&buf
->freelist
);
2320 bkey_copy(&w
->key
, k
);
2322 if (RB_INSERT(&buf
->keys
, w
, node
, keybuf_cmp
))
2323 array_free(&buf
->freelist
, w
);
2325 spin_unlock(&buf
->lock
);
2331 btree(refill_keybuf
, k
, b
, op
, buf
, end
, pred
);
2333 * Might get an error here, but can't really do anything
2334 * and it'll get logged elsewhere. Just read what we
2338 if (bkey_cmp(&buf
->last_scanned
, end
) >= 0)
2348 void bch_refill_keybuf(struct cache_set
*c
, struct keybuf
*buf
,
2349 struct bkey
*end
, keybuf_pred_fn
*pred
)
2351 struct bkey start
= buf
->last_scanned
;
2353 bch_btree_op_init_stack(&op
);
2357 btree_root(refill_keybuf
, c
, &op
, buf
, end
, pred
);
2358 closure_sync(&op
.cl
);
2360 pr_debug("found %s keys from %llu:%llu to %llu:%llu",
2361 RB_EMPTY_ROOT(&buf
->keys
) ? "no" :
2362 array_freelist_empty(&buf
->freelist
) ? "some" : "a few",
2363 KEY_INODE(&start
), KEY_OFFSET(&start
),
2364 KEY_INODE(&buf
->last_scanned
), KEY_OFFSET(&buf
->last_scanned
));
2366 spin_lock(&buf
->lock
);
2368 if (!RB_EMPTY_ROOT(&buf
->keys
)) {
2369 struct keybuf_key
*w
;
2370 w
= RB_FIRST(&buf
->keys
, struct keybuf_key
, node
);
2371 buf
->start
= START_KEY(&w
->key
);
2373 w
= RB_LAST(&buf
->keys
, struct keybuf_key
, node
);
2376 buf
->start
= MAX_KEY
;
2380 spin_unlock(&buf
->lock
);
2383 static void __bch_keybuf_del(struct keybuf
*buf
, struct keybuf_key
*w
)
2385 rb_erase(&w
->node
, &buf
->keys
);
2386 array_free(&buf
->freelist
, w
);
2389 void bch_keybuf_del(struct keybuf
*buf
, struct keybuf_key
*w
)
2391 spin_lock(&buf
->lock
);
2392 __bch_keybuf_del(buf
, w
);
2393 spin_unlock(&buf
->lock
);
2396 bool bch_keybuf_check_overlapping(struct keybuf
*buf
, struct bkey
*start
,
2400 struct keybuf_key
*p
, *w
, s
;
2403 if (bkey_cmp(end
, &buf
->start
) <= 0 ||
2404 bkey_cmp(start
, &buf
->end
) >= 0)
2407 spin_lock(&buf
->lock
);
2408 w
= RB_GREATER(&buf
->keys
, s
, node
, keybuf_nonoverlapping_cmp
);
2410 while (w
&& bkey_cmp(&START_KEY(&w
->key
), end
) < 0) {
2412 w
= RB_NEXT(w
, node
);
2417 __bch_keybuf_del(buf
, p
);
2420 spin_unlock(&buf
->lock
);
2424 struct keybuf_key
*bch_keybuf_next(struct keybuf
*buf
)
2426 struct keybuf_key
*w
;
2427 spin_lock(&buf
->lock
);
2429 w
= RB_FIRST(&buf
->keys
, struct keybuf_key
, node
);
2431 while (w
&& w
->private)
2432 w
= RB_NEXT(w
, node
);
2435 w
->private = ERR_PTR(-EINTR
);
2437 spin_unlock(&buf
->lock
);
2441 struct keybuf_key
*bch_keybuf_next_rescan(struct cache_set
*c
,
2444 keybuf_pred_fn
*pred
)
2446 struct keybuf_key
*ret
;
2449 ret
= bch_keybuf_next(buf
);
2453 if (bkey_cmp(&buf
->last_scanned
, end
) >= 0) {
2454 pr_debug("scan finished");
2458 bch_refill_keybuf(c
, buf
, end
, pred
);
2464 void bch_keybuf_init(struct keybuf
*buf
)
2466 buf
->last_scanned
= MAX_KEY
;
2467 buf
->keys
= RB_ROOT
;
2469 spin_lock_init(&buf
->lock
);
2470 array_allocator_init(&buf
->freelist
);
2473 void bch_btree_exit(void)
2476 destroy_workqueue(btree_io_wq
);
2478 destroy_workqueue(bch_gc_wq
);
2481 int __init
bch_btree_init(void)
2483 if (!(bch_gc_wq
= create_singlethread_workqueue("bch_btree_gc")) ||
2484 !(btree_io_wq
= create_singlethread_workqueue("bch_btree_io")))