]> git.ipfire.org Git - thirdparty/kernel/stable.git/blame - drivers/md/bcache/btree.c
bcache: Track dirty data by stripe
[thirdparty/kernel/stable.git] / drivers / md / bcache / btree.c
CommitLineData
cafe5635
KO
1/*
2 * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
3 *
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
6 * of the device.
7 *
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.
12 *
13 * Buckets have an 8 bit counter; freeing is accomplished by incrementing the
14 * counter. Garbage collection is used to remove stale pointers.
15 *
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.
19 *
20 * All configuration is done via sysfs; see Documentation/bcache.txt.
21 */
22
23#include "bcache.h"
24#include "btree.h"
25#include "debug.h"
26#include "request.h"
279afbad 27#include "writeback.h"
cafe5635
KO
28
29#include <linux/slab.h>
30#include <linux/bitops.h>
31#include <linux/hash.h>
cd953ed0 32#include <linux/prefetch.h>
cafe5635
KO
33#include <linux/random.h>
34#include <linux/rcupdate.h>
35#include <trace/events/bcache.h>
36
37/*
38 * Todo:
39 * register_bcache: Return errors out to userspace correctly
40 *
41 * Writeback: don't undirty key until after a cache flush
42 *
43 * Create an iterator for key pointers
44 *
45 * On btree write error, mark bucket such that it won't be freed from the cache
46 *
47 * Journalling:
48 * Check for bad keys in replay
49 * Propagate barriers
50 * Refcount journal entries in journal_replay
51 *
52 * Garbage collection:
53 * Finish incremental gc
54 * Gc should free old UUIDs, data for invalid UUIDs
55 *
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
59 *
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
62 * from being starved
63 *
64 * Add a tracepoint or somesuch to watch for writeback starvation
65 *
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
68 * obvious.
69 *
70 * Make sure all allocations get charged to the root cgroup
71 *
72 * Plugging?
73 *
74 * If data write is less than hard sector size of ssd, round up offset in open
75 * bucket to the next whole sector
76 *
77 * Also lookup by cgroup in get_open_bucket()
78 *
79 * Superblock needs to be fleshed out for multiple cache devices
80 *
81 * Add a sysfs tunable for the number of writeback IOs in flight
82 *
83 * Add a sysfs tunable for the number of open data buckets
84 *
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
87 *
88 * Test module load/unload
89 */
90
91static const char * const op_types[] = {
92 "insert", "replace"
93};
94
95static const char *op_type(struct btree_op *op)
96{
97 return op_types[op->type];
98}
99
100#define MAX_NEED_GC 64
101#define MAX_SAVE_PRIO 72
102
103#define PTR_DIRTY_BIT (((uint64_t) 1 << 36))
104
105#define PTR_HASH(c, k) \
106 (((k)->ptr[0] >> c->bucket_bits) | PTR_GEN(k, 0))
107
108struct workqueue_struct *bch_gc_wq;
109static struct workqueue_struct *btree_io_wq;
110
111void bch_btree_op_init_stack(struct btree_op *op)
112{
113 memset(op, 0, sizeof(struct btree_op));
114 closure_init_stack(&op->cl);
115 op->lock = -1;
116 bch_keylist_init(&op->keys);
117}
118
119/* Btree key manipulation */
120
121static void bkey_put(struct cache_set *c, struct bkey *k, int level)
122{
123 if ((level && KEY_OFFSET(k)) || !level)
124 __bkey_put(c, k);
125}
126
127/* Btree IO */
128
129static uint64_t btree_csum_set(struct btree *b, struct bset *i)
130{
131 uint64_t crc = b->key.ptr[0];
132 void *data = (void *) i + 8, *end = end(i);
133
169ef1cf 134 crc = bch_crc64_update(crc, data, end - data);
c19ed23a 135 return crc ^ 0xffffffffffffffffULL;
cafe5635
KO
136}
137
57943511 138void bch_btree_node_read_done(struct btree *b)
cafe5635 139{
cafe5635 140 const char *err = "bad btree header";
57943511
KO
141 struct bset *i = b->sets[0].data;
142 struct btree_iter *iter;
cafe5635 143
57943511
KO
144 iter = mempool_alloc(b->c->fill_iter, GFP_NOWAIT);
145 iter->size = b->c->sb.bucket_size / b->c->sb.block_size;
cafe5635
KO
146 iter->used = 0;
147
57943511 148 if (!i->seq)
cafe5635
KO
149 goto err;
150
151 for (;
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)
156 goto err;
157
158 err = "bad btree header";
159 if (b->written + set_blocks(i, b->c) > btree_blocks(b))
160 goto err;
161
162 err = "bad magic";
163 if (i->magic != bset_magic(b->c))
164 goto err;
165
166 err = "bad checksum";
167 switch (i->version) {
168 case 0:
169 if (i->csum != csum_set(i))
170 goto err;
171 break;
172 case BCACHE_BSET_VERSION:
173 if (i->csum != btree_csum_set(b, i))
174 goto err;
175 break;
176 }
177
178 err = "empty set";
179 if (i != b->sets[0].data && !i->keys)
180 goto err;
181
182 bch_btree_iter_push(iter, i->start, end(i));
183
184 b->written += set_blocks(i, b->c);
185 }
186
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)
192 goto err;
193
194 bch_btree_sort_and_fix_extents(b, iter);
195
196 i = b->sets[0].data;
197 err = "short btree key";
198 if (b->sets[0].size &&
199 bkey_cmp(&b->key, &b->sets[0].end) < 0)
200 goto err;
201
202 if (b->written < btree_blocks(b))
203 bch_bset_init_next(b);
204out:
57943511
KO
205 mempool_free(iter, b->c->fill_iter);
206 return;
cafe5635
KO
207err:
208 set_btree_node_io_error(b);
07e86ccb 209 bch_cache_set_error(b->c, "%s at bucket %zu, block %zu, %u keys",
cafe5635
KO
210 err, PTR_BUCKET_NR(b->c, &b->key, 0),
211 index(i, b), i->keys);
212 goto out;
213}
214
57943511 215static void btree_node_read_endio(struct bio *bio, int error)
cafe5635 216{
57943511
KO
217 struct closure *cl = bio->bi_private;
218 closure_put(cl);
219}
cafe5635 220
57943511
KO
221void bch_btree_node_read(struct btree *b)
222{
223 uint64_t start_time = local_clock();
224 struct closure cl;
225 struct bio *bio;
cafe5635 226
c37511b8
KO
227 trace_bcache_btree_read(b);
228
57943511 229 closure_init_stack(&cl);
cafe5635 230
57943511
KO
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;
cafe5635 236
57943511 237 bch_bio_map(bio, b->sets[0].data);
cafe5635 238
57943511
KO
239 bch_submit_bbio(bio, b->c, &b->key, 0);
240 closure_sync(&cl);
cafe5635 241
57943511
KO
242 if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
243 set_btree_node_io_error(b);
244
245 bch_bbio_free(bio, b->c);
246
247 if (btree_node_io_error(b))
248 goto err;
249
250 bch_btree_node_read_done(b);
251
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);
255
256 return;
257err:
258 bch_cache_set_error(b->c, "io error reading bucket %lu",
259 PTR_BUCKET_NR(b->c, &b->key, 0));
cafe5635
KO
260}
261
262static void btree_complete_write(struct btree *b, struct btree_write *w)
263{
264 if (w->prio_blocked &&
265 !atomic_sub_return(w->prio_blocked, &b->c->prio_blocked))
119ba0f8 266 wake_up_allocators(b->c);
cafe5635
KO
267
268 if (w->journal) {
269 atomic_dec_bug(w->journal);
270 __closure_wake_up(&b->c->journal.wait);
271 }
272
cafe5635
KO
273 w->prio_blocked = 0;
274 w->journal = NULL;
cafe5635
KO
275}
276
57943511 277static void __btree_node_write_done(struct closure *cl)
cafe5635
KO
278{
279 struct btree *b = container_of(cl, struct btree, io.cl);
280 struct btree_write *w = btree_prev_write(b);
281
282 bch_bbio_free(b->bio, b->c);
283 b->bio = NULL;
284 btree_complete_write(b, w);
285
286 if (btree_node_dirty(b))
287 queue_delayed_work(btree_io_wq, &b->work,
288 msecs_to_jiffies(30000));
289
290 closure_return(cl);
291}
292
57943511 293static void btree_node_write_done(struct closure *cl)
cafe5635
KO
294{
295 struct btree *b = container_of(cl, struct btree, io.cl);
296 struct bio_vec *bv;
297 int n;
298
299 __bio_for_each_segment(bv, b->bio, n, 0)
300 __free_page(bv->bv_page);
301
57943511 302 __btree_node_write_done(cl);
cafe5635
KO
303}
304
57943511
KO
305static void btree_node_write_endio(struct bio *bio, int error)
306{
307 struct closure *cl = bio->bi_private;
308 struct btree *b = container_of(cl, struct btree, io.cl);
309
310 if (error)
311 set_btree_node_io_error(b);
312
313 bch_bbio_count_io_errors(b->c, bio, error, "writing btree");
314 closure_put(cl);
315}
316
317static void do_btree_node_write(struct btree *b)
cafe5635
KO
318{
319 struct closure *cl = &b->io.cl;
320 struct bset *i = b->sets[b->nsets].data;
321 BKEY_PADDED(key) k;
322
323 i->version = BCACHE_BSET_VERSION;
324 i->csum = btree_csum_set(b, i);
325
57943511
KO
326 BUG_ON(b->bio);
327 b->bio = bch_bbio_alloc(b->c);
328
329 b->bio->bi_end_io = btree_node_write_endio;
330 b->bio->bi_private = &b->io.cl;
cafe5635
KO
331 b->bio->bi_rw = REQ_META|WRITE_SYNC;
332 b->bio->bi_size = set_blocks(i, b->c) * block_bytes(b->c);
169ef1cf 333 bch_bio_map(b->bio, i);
cafe5635
KO
334
335 bkey_copy(&k.key, &b->key);
336 SET_PTR_OFFSET(&k.key, 0, PTR_OFFSET(&k.key, 0) + bset_offset(b, i));
337
169ef1cf 338 if (!bch_bio_alloc_pages(b->bio, GFP_NOIO)) {
cafe5635
KO
339 int j;
340 struct bio_vec *bv;
341 void *base = (void *) ((unsigned long) i & ~(PAGE_SIZE - 1));
342
343 bio_for_each_segment(bv, b->bio, j)
344 memcpy(page_address(bv->bv_page),
345 base + j * PAGE_SIZE, PAGE_SIZE);
346
cafe5635
KO
347 bch_submit_bbio(b->bio, b->c, &k.key, 0);
348
57943511 349 continue_at(cl, btree_node_write_done, NULL);
cafe5635
KO
350 } else {
351 b->bio->bi_vcnt = 0;
169ef1cf 352 bch_bio_map(b->bio, i);
cafe5635 353
cafe5635
KO
354 bch_submit_bbio(b->bio, b->c, &k.key, 0);
355
356 closure_sync(cl);
57943511 357 __btree_node_write_done(cl);
cafe5635
KO
358 }
359}
360
57943511 361void bch_btree_node_write(struct btree *b, struct closure *parent)
cafe5635
KO
362{
363 struct bset *i = b->sets[b->nsets].data;
364
c37511b8
KO
365 trace_bcache_btree_write(b);
366
cafe5635 367 BUG_ON(current->bio_list);
57943511
KO
368 BUG_ON(b->written >= btree_blocks(b));
369 BUG_ON(b->written && !i->keys);
370 BUG_ON(b->sets->data->seq != i->seq);
c37511b8 371 bch_check_key_order(b, i);
cafe5635 372
cafe5635
KO
373 cancel_delayed_work(&b->work);
374
57943511
KO
375 /* If caller isn't waiting for write, parent refcount is cache set */
376 closure_lock(&b->io, parent ?: &b->c->cl);
377
cafe5635
KO
378 clear_bit(BTREE_NODE_dirty, &b->flags);
379 change_bit(BTREE_NODE_write_idx, &b->flags);
380
57943511 381 do_btree_node_write(b);
cafe5635 382
cafe5635
KO
383 b->written += set_blocks(i, b->c);
384 atomic_long_add(set_blocks(i, b->c) * b->c->sb.block_size,
385 &PTR_CACHE(b->c, &b->key, 0)->btree_sectors_written);
386
387 bch_btree_sort_lazy(b);
388
389 if (b->written < btree_blocks(b))
390 bch_bset_init_next(b);
391}
392
57943511 393static void btree_node_write_work(struct work_struct *w)
cafe5635
KO
394{
395 struct btree *b = container_of(to_delayed_work(w), struct btree, work);
396
57943511 397 rw_lock(true, b, b->level);
cafe5635
KO
398
399 if (btree_node_dirty(b))
57943511
KO
400 bch_btree_node_write(b, NULL);
401 rw_unlock(true, b);
cafe5635
KO
402}
403
57943511 404static void bch_btree_leaf_dirty(struct btree *b, struct btree_op *op)
cafe5635
KO
405{
406 struct bset *i = b->sets[b->nsets].data;
407 struct btree_write *w = btree_current_write(b);
408
57943511
KO
409 BUG_ON(!b->written);
410 BUG_ON(!i->keys);
cafe5635 411
57943511
KO
412 if (!btree_node_dirty(b))
413 queue_delayed_work(btree_io_wq, &b->work, 30 * HZ);
cafe5635 414
57943511 415 set_btree_node_dirty(b);
cafe5635 416
57943511 417 if (op && op->journal) {
cafe5635
KO
418 if (w->journal &&
419 journal_pin_cmp(b->c, w, op)) {
420 atomic_dec_bug(w->journal);
421 w->journal = NULL;
422 }
423
424 if (!w->journal) {
425 w->journal = op->journal;
426 atomic_inc(w->journal);
427 }
428 }
429
cafe5635 430 /* Force write if set is too big */
57943511
KO
431 if (set_bytes(i) > PAGE_SIZE - 48 &&
432 !current->bio_list)
433 bch_btree_node_write(b, NULL);
cafe5635
KO
434}
435
436/*
437 * Btree in memory cache - allocation/freeing
438 * mca -> memory cache
439 */
440
441static void mca_reinit(struct btree *b)
442{
443 unsigned i;
444
445 b->flags = 0;
446 b->written = 0;
447 b->nsets = 0;
448
449 for (i = 0; i < MAX_BSETS; i++)
450 b->sets[i].size = 0;
451 /*
452 * Second loop starts at 1 because b->sets[0]->data is the memory we
453 * allocated
454 */
455 for (i = 1; i < MAX_BSETS; i++)
456 b->sets[i].data = NULL;
457}
458
459#define mca_reserve(c) (((c->root && c->root->level) \
460 ? c->root->level : 1) * 8 + 16)
461#define mca_can_free(c) \
462 max_t(int, 0, c->bucket_cache_used - mca_reserve(c))
463
464static void mca_data_free(struct btree *b)
465{
466 struct bset_tree *t = b->sets;
467 BUG_ON(!closure_is_unlocked(&b->io.cl));
468
469 if (bset_prev_bytes(b) < PAGE_SIZE)
470 kfree(t->prev);
471 else
472 free_pages((unsigned long) t->prev,
473 get_order(bset_prev_bytes(b)));
474
475 if (bset_tree_bytes(b) < PAGE_SIZE)
476 kfree(t->tree);
477 else
478 free_pages((unsigned long) t->tree,
479 get_order(bset_tree_bytes(b)));
480
481 free_pages((unsigned long) t->data, b->page_order);
482
483 t->prev = NULL;
484 t->tree = NULL;
485 t->data = NULL;
486 list_move(&b->list, &b->c->btree_cache_freed);
487 b->c->bucket_cache_used--;
488}
489
490static void mca_bucket_free(struct btree *b)
491{
492 BUG_ON(btree_node_dirty(b));
493
494 b->key.ptr[0] = 0;
495 hlist_del_init_rcu(&b->hash);
496 list_move(&b->list, &b->c->btree_cache_freeable);
497}
498
499static unsigned btree_order(struct bkey *k)
500{
501 return ilog2(KEY_SIZE(k) / PAGE_SECTORS ?: 1);
502}
503
504static void mca_data_alloc(struct btree *b, struct bkey *k, gfp_t gfp)
505{
506 struct bset_tree *t = b->sets;
507 BUG_ON(t->data);
508
509 b->page_order = max_t(unsigned,
510 ilog2(b->c->btree_pages),
511 btree_order(k));
512
513 t->data = (void *) __get_free_pages(gfp, b->page_order);
514 if (!t->data)
515 goto err;
516
517 t->tree = bset_tree_bytes(b) < PAGE_SIZE
518 ? kmalloc(bset_tree_bytes(b), gfp)
519 : (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
520 if (!t->tree)
521 goto err;
522
523 t->prev = bset_prev_bytes(b) < PAGE_SIZE
524 ? kmalloc(bset_prev_bytes(b), gfp)
525 : (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
526 if (!t->prev)
527 goto err;
528
529 list_move(&b->list, &b->c->btree_cache);
530 b->c->bucket_cache_used++;
531 return;
532err:
533 mca_data_free(b);
534}
535
536static struct btree *mca_bucket_alloc(struct cache_set *c,
537 struct bkey *k, gfp_t gfp)
538{
539 struct btree *b = kzalloc(sizeof(struct btree), gfp);
540 if (!b)
541 return NULL;
542
543 init_rwsem(&b->lock);
544 lockdep_set_novalidate_class(&b->lock);
545 INIT_LIST_HEAD(&b->list);
57943511 546 INIT_DELAYED_WORK(&b->work, btree_node_write_work);
cafe5635
KO
547 b->c = c;
548 closure_init_unlocked(&b->io);
549
550 mca_data_alloc(b, k, gfp);
551 return b;
552}
553
554static int mca_reap(struct btree *b, struct closure *cl, unsigned min_order)
555{
556 lockdep_assert_held(&b->c->bucket_lock);
557
558 if (!down_write_trylock(&b->lock))
559 return -ENOMEM;
560
561 if (b->page_order < min_order) {
562 rw_unlock(true, b);
563 return -ENOMEM;
564 }
565
566 BUG_ON(btree_node_dirty(b) && !b->sets[0].data);
567
568 if (cl && btree_node_dirty(b))
57943511 569 bch_btree_node_write(b, NULL);
cafe5635
KO
570
571 if (cl)
572 closure_wait_event_async(&b->io.wait, cl,
573 atomic_read(&b->io.cl.remaining) == -1);
574
575 if (btree_node_dirty(b) ||
576 !closure_is_unlocked(&b->io.cl) ||
577 work_pending(&b->work.work)) {
578 rw_unlock(true, b);
579 return -EAGAIN;
580 }
581
582 return 0;
583}
584
585static int bch_mca_shrink(struct shrinker *shrink, struct shrink_control *sc)
586{
587 struct cache_set *c = container_of(shrink, struct cache_set, shrink);
588 struct btree *b, *t;
589 unsigned long i, nr = sc->nr_to_scan;
590
591 if (c->shrinker_disabled)
592 return 0;
593
594 if (c->try_harder)
595 return 0;
596
597 /*
598 * If nr == 0, we're supposed to return the number of items we have
599 * cached. Not allowed to return -1.
600 */
601 if (!nr)
602 return mca_can_free(c) * c->btree_pages;
603
604 /* Return -1 if we can't do anything right now */
605 if (sc->gfp_mask & __GFP_WAIT)
606 mutex_lock(&c->bucket_lock);
607 else if (!mutex_trylock(&c->bucket_lock))
608 return -1;
609
610 nr /= c->btree_pages;
611 nr = min_t(unsigned long, nr, mca_can_free(c));
612
613 i = 0;
614 list_for_each_entry_safe(b, t, &c->btree_cache_freeable, list) {
615 if (!nr)
616 break;
617
618 if (++i > 3 &&
619 !mca_reap(b, NULL, 0)) {
620 mca_data_free(b);
621 rw_unlock(true, b);
622 --nr;
623 }
624 }
625
626 /*
627 * Can happen right when we first start up, before we've read in any
628 * btree nodes
629 */
630 if (list_empty(&c->btree_cache))
631 goto out;
632
633 for (i = 0; nr && i < c->bucket_cache_used; i++) {
634 b = list_first_entry(&c->btree_cache, struct btree, list);
635 list_rotate_left(&c->btree_cache);
636
637 if (!b->accessed &&
638 !mca_reap(b, NULL, 0)) {
639 mca_bucket_free(b);
640 mca_data_free(b);
641 rw_unlock(true, b);
642 --nr;
643 } else
644 b->accessed = 0;
645 }
646out:
647 nr = mca_can_free(c) * c->btree_pages;
648 mutex_unlock(&c->bucket_lock);
649 return nr;
650}
651
652void bch_btree_cache_free(struct cache_set *c)
653{
654 struct btree *b;
655 struct closure cl;
656 closure_init_stack(&cl);
657
658 if (c->shrink.list.next)
659 unregister_shrinker(&c->shrink);
660
661 mutex_lock(&c->bucket_lock);
662
663#ifdef CONFIG_BCACHE_DEBUG
664 if (c->verify_data)
665 list_move(&c->verify_data->list, &c->btree_cache);
666#endif
667
668 list_splice(&c->btree_cache_freeable,
669 &c->btree_cache);
670
671 while (!list_empty(&c->btree_cache)) {
672 b = list_first_entry(&c->btree_cache, struct btree, list);
673
674 if (btree_node_dirty(b))
675 btree_complete_write(b, btree_current_write(b));
676 clear_bit(BTREE_NODE_dirty, &b->flags);
677
678 mca_data_free(b);
679 }
680
681 while (!list_empty(&c->btree_cache_freed)) {
682 b = list_first_entry(&c->btree_cache_freed,
683 struct btree, list);
684 list_del(&b->list);
685 cancel_delayed_work_sync(&b->work);
686 kfree(b);
687 }
688
689 mutex_unlock(&c->bucket_lock);
690}
691
692int bch_btree_cache_alloc(struct cache_set *c)
693{
694 unsigned i;
695
696 /* XXX: doesn't check for errors */
697
698 closure_init_unlocked(&c->gc);
699
700 for (i = 0; i < mca_reserve(c); i++)
701 mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
702
703 list_splice_init(&c->btree_cache,
704 &c->btree_cache_freeable);
705
706#ifdef CONFIG_BCACHE_DEBUG
707 mutex_init(&c->verify_lock);
708
709 c->verify_data = mca_bucket_alloc(c, &ZERO_KEY, GFP_KERNEL);
710
711 if (c->verify_data &&
712 c->verify_data->sets[0].data)
713 list_del_init(&c->verify_data->list);
714 else
715 c->verify_data = NULL;
716#endif
717
718 c->shrink.shrink = bch_mca_shrink;
719 c->shrink.seeks = 4;
720 c->shrink.batch = c->btree_pages * 2;
721 register_shrinker(&c->shrink);
722
723 return 0;
724}
725
726/* Btree in memory cache - hash table */
727
728static struct hlist_head *mca_hash(struct cache_set *c, struct bkey *k)
729{
730 return &c->bucket_hash[hash_32(PTR_HASH(c, k), BUCKET_HASH_BITS)];
731}
732
733static struct btree *mca_find(struct cache_set *c, struct bkey *k)
734{
735 struct btree *b;
736
737 rcu_read_lock();
738 hlist_for_each_entry_rcu(b, mca_hash(c, k), hash)
739 if (PTR_HASH(c, &b->key) == PTR_HASH(c, k))
740 goto out;
741 b = NULL;
742out:
743 rcu_read_unlock();
744 return b;
745}
746
747static struct btree *mca_cannibalize(struct cache_set *c, struct bkey *k,
748 int level, struct closure *cl)
749{
750 int ret = -ENOMEM;
751 struct btree *i;
752
c37511b8
KO
753 trace_bcache_btree_cache_cannibalize(c);
754
cafe5635
KO
755 if (!cl)
756 return ERR_PTR(-ENOMEM);
757
758 /*
759 * Trying to free up some memory - i.e. reuse some btree nodes - may
760 * require initiating IO to flush the dirty part of the node. If we're
761 * running under generic_make_request(), that IO will never finish and
762 * we would deadlock. Returning -EAGAIN causes the cache lookup code to
763 * punt to workqueue and retry.
764 */
765 if (current->bio_list)
766 return ERR_PTR(-EAGAIN);
767
768 if (c->try_harder && c->try_harder != cl) {
769 closure_wait_event_async(&c->try_wait, cl, !c->try_harder);
770 return ERR_PTR(-EAGAIN);
771 }
772
cafe5635
KO
773 c->try_harder = cl;
774 c->try_harder_start = local_clock();
775retry:
776 list_for_each_entry_reverse(i, &c->btree_cache, list) {
777 int r = mca_reap(i, cl, btree_order(k));
778 if (!r)
779 return i;
780 if (r != -ENOMEM)
781 ret = r;
782 }
783
784 if (ret == -EAGAIN &&
785 closure_blocking(cl)) {
786 mutex_unlock(&c->bucket_lock);
787 closure_sync(cl);
788 mutex_lock(&c->bucket_lock);
789 goto retry;
790 }
791
792 return ERR_PTR(ret);
793}
794
795/*
796 * We can only have one thread cannibalizing other cached btree nodes at a time,
797 * or we'll deadlock. We use an open coded mutex to ensure that, which a
798 * cannibalize_bucket() will take. This means every time we unlock the root of
799 * the btree, we need to release this lock if we have it held.
800 */
801void bch_cannibalize_unlock(struct cache_set *c, struct closure *cl)
802{
803 if (c->try_harder == cl) {
169ef1cf 804 bch_time_stats_update(&c->try_harder_time, c->try_harder_start);
cafe5635
KO
805 c->try_harder = NULL;
806 __closure_wake_up(&c->try_wait);
807 }
808}
809
810static struct btree *mca_alloc(struct cache_set *c, struct bkey *k,
811 int level, struct closure *cl)
812{
813 struct btree *b;
814
815 lockdep_assert_held(&c->bucket_lock);
816
817 if (mca_find(c, k))
818 return NULL;
819
820 /* btree_free() doesn't free memory; it sticks the node on the end of
821 * the list. Check if there's any freed nodes there:
822 */
823 list_for_each_entry(b, &c->btree_cache_freeable, list)
824 if (!mca_reap(b, NULL, btree_order(k)))
825 goto out;
826
827 /* We never free struct btree itself, just the memory that holds the on
828 * disk node. Check the freed list before allocating a new one:
829 */
830 list_for_each_entry(b, &c->btree_cache_freed, list)
831 if (!mca_reap(b, NULL, 0)) {
832 mca_data_alloc(b, k, __GFP_NOWARN|GFP_NOIO);
833 if (!b->sets[0].data)
834 goto err;
835 else
836 goto out;
837 }
838
839 b = mca_bucket_alloc(c, k, __GFP_NOWARN|GFP_NOIO);
840 if (!b)
841 goto err;
842
843 BUG_ON(!down_write_trylock(&b->lock));
844 if (!b->sets->data)
845 goto err;
846out:
847 BUG_ON(!closure_is_unlocked(&b->io.cl));
848
849 bkey_copy(&b->key, k);
850 list_move(&b->list, &c->btree_cache);
851 hlist_del_init_rcu(&b->hash);
852 hlist_add_head_rcu(&b->hash, mca_hash(c, k));
853
854 lock_set_subclass(&b->lock.dep_map, level + 1, _THIS_IP_);
855 b->level = level;
856
857 mca_reinit(b);
858
859 return b;
860err:
861 if (b)
862 rw_unlock(true, b);
863
864 b = mca_cannibalize(c, k, level, cl);
865 if (!IS_ERR(b))
866 goto out;
867
868 return b;
869}
870
871/**
872 * bch_btree_node_get - find a btree node in the cache and lock it, reading it
873 * in from disk if necessary.
874 *
875 * If IO is necessary, it uses the closure embedded in struct btree_op to wait;
876 * if that closure is in non blocking mode, will return -EAGAIN.
877 *
878 * The btree node will have either a read or a write lock held, depending on
879 * level and op->lock.
880 */
881struct btree *bch_btree_node_get(struct cache_set *c, struct bkey *k,
882 int level, struct btree_op *op)
883{
884 int i = 0;
885 bool write = level <= op->lock;
886 struct btree *b;
887
888 BUG_ON(level < 0);
889retry:
890 b = mca_find(c, k);
891
892 if (!b) {
57943511
KO
893 if (current->bio_list)
894 return ERR_PTR(-EAGAIN);
895
cafe5635
KO
896 mutex_lock(&c->bucket_lock);
897 b = mca_alloc(c, k, level, &op->cl);
898 mutex_unlock(&c->bucket_lock);
899
900 if (!b)
901 goto retry;
902 if (IS_ERR(b))
903 return b;
904
57943511 905 bch_btree_node_read(b);
cafe5635
KO
906
907 if (!write)
908 downgrade_write(&b->lock);
909 } else {
910 rw_lock(write, b, level);
911 if (PTR_HASH(c, &b->key) != PTR_HASH(c, k)) {
912 rw_unlock(write, b);
913 goto retry;
914 }
915 BUG_ON(b->level != level);
916 }
917
918 b->accessed = 1;
919
920 for (; i <= b->nsets && b->sets[i].size; i++) {
921 prefetch(b->sets[i].tree);
922 prefetch(b->sets[i].data);
923 }
924
925 for (; i <= b->nsets; i++)
926 prefetch(b->sets[i].data);
927
57943511 928 if (btree_node_io_error(b)) {
cafe5635 929 rw_unlock(write, b);
57943511
KO
930 return ERR_PTR(-EIO);
931 }
932
933 BUG_ON(!b->written);
cafe5635
KO
934
935 return b;
936}
937
938static void btree_node_prefetch(struct cache_set *c, struct bkey *k, int level)
939{
940 struct btree *b;
941
942 mutex_lock(&c->bucket_lock);
943 b = mca_alloc(c, k, level, NULL);
944 mutex_unlock(&c->bucket_lock);
945
946 if (!IS_ERR_OR_NULL(b)) {
57943511 947 bch_btree_node_read(b);
cafe5635
KO
948 rw_unlock(true, b);
949 }
950}
951
952/* Btree alloc */
953
954static void btree_node_free(struct btree *b, struct btree_op *op)
955{
956 unsigned i;
957
c37511b8
KO
958 trace_bcache_btree_node_free(b);
959
cafe5635
KO
960 /*
961 * The BUG_ON() in btree_node_get() implies that we must have a write
962 * lock on parent to free or even invalidate a node
963 */
964 BUG_ON(op->lock <= b->level);
965 BUG_ON(b == b->c->root);
cafe5635
KO
966
967 if (btree_node_dirty(b))
968 btree_complete_write(b, btree_current_write(b));
969 clear_bit(BTREE_NODE_dirty, &b->flags);
970
cafe5635
KO
971 cancel_delayed_work(&b->work);
972
973 mutex_lock(&b->c->bucket_lock);
974
975 for (i = 0; i < KEY_PTRS(&b->key); i++) {
976 BUG_ON(atomic_read(&PTR_BUCKET(b->c, &b->key, i)->pin));
977
978 bch_inc_gen(PTR_CACHE(b->c, &b->key, i),
979 PTR_BUCKET(b->c, &b->key, i));
980 }
981
982 bch_bucket_free(b->c, &b->key);
983 mca_bucket_free(b);
984 mutex_unlock(&b->c->bucket_lock);
985}
986
987struct btree *bch_btree_node_alloc(struct cache_set *c, int level,
988 struct closure *cl)
989{
990 BKEY_PADDED(key) k;
991 struct btree *b = ERR_PTR(-EAGAIN);
992
993 mutex_lock(&c->bucket_lock);
994retry:
995 if (__bch_bucket_alloc_set(c, WATERMARK_METADATA, &k.key, 1, cl))
996 goto err;
997
998 SET_KEY_SIZE(&k.key, c->btree_pages * PAGE_SECTORS);
999
1000 b = mca_alloc(c, &k.key, level, cl);
1001 if (IS_ERR(b))
1002 goto err_free;
1003
1004 if (!b) {
b1a67b0f
KO
1005 cache_bug(c,
1006 "Tried to allocate bucket that was in btree cache");
cafe5635
KO
1007 __bkey_put(c, &k.key);
1008 goto retry;
1009 }
1010
cafe5635
KO
1011 b->accessed = 1;
1012 bch_bset_init_next(b);
1013
1014 mutex_unlock(&c->bucket_lock);
c37511b8
KO
1015
1016 trace_bcache_btree_node_alloc(b);
cafe5635
KO
1017 return b;
1018err_free:
1019 bch_bucket_free(c, &k.key);
1020 __bkey_put(c, &k.key);
1021err:
1022 mutex_unlock(&c->bucket_lock);
c37511b8
KO
1023
1024 trace_bcache_btree_node_alloc_fail(b);
cafe5635
KO
1025 return b;
1026}
1027
1028static struct btree *btree_node_alloc_replacement(struct btree *b,
1029 struct closure *cl)
1030{
1031 struct btree *n = bch_btree_node_alloc(b->c, b->level, cl);
1032 if (!IS_ERR_OR_NULL(n))
1033 bch_btree_sort_into(b, n);
1034
1035 return n;
1036}
1037
1038/* Garbage collection */
1039
1040uint8_t __bch_btree_mark_key(struct cache_set *c, int level, struct bkey *k)
1041{
1042 uint8_t stale = 0;
1043 unsigned i;
1044 struct bucket *g;
1045
1046 /*
1047 * ptr_invalid() can't return true for the keys that mark btree nodes as
1048 * freed, but since ptr_bad() returns true we'll never actually use them
1049 * for anything and thus we don't want mark their pointers here
1050 */
1051 if (!bkey_cmp(k, &ZERO_KEY))
1052 return stale;
1053
1054 for (i = 0; i < KEY_PTRS(k); i++) {
1055 if (!ptr_available(c, k, i))
1056 continue;
1057
1058 g = PTR_BUCKET(c, k, i);
1059
1060 if (gen_after(g->gc_gen, PTR_GEN(k, i)))
1061 g->gc_gen = PTR_GEN(k, i);
1062
1063 if (ptr_stale(c, k, i)) {
1064 stale = max(stale, ptr_stale(c, k, i));
1065 continue;
1066 }
1067
1068 cache_bug_on(GC_MARK(g) &&
1069 (GC_MARK(g) == GC_MARK_METADATA) != (level != 0),
1070 c, "inconsistent ptrs: mark = %llu, level = %i",
1071 GC_MARK(g), level);
1072
1073 if (level)
1074 SET_GC_MARK(g, GC_MARK_METADATA);
1075 else if (KEY_DIRTY(k))
1076 SET_GC_MARK(g, GC_MARK_DIRTY);
1077
1078 /* guard against overflow */
1079 SET_GC_SECTORS_USED(g, min_t(unsigned,
1080 GC_SECTORS_USED(g) + KEY_SIZE(k),
1081 (1 << 14) - 1));
1082
1083 BUG_ON(!GC_SECTORS_USED(g));
1084 }
1085
1086 return stale;
1087}
1088
1089#define btree_mark_key(b, k) __bch_btree_mark_key(b->c, b->level, k)
1090
1091static int btree_gc_mark_node(struct btree *b, unsigned *keys,
1092 struct gc_stat *gc)
1093{
1094 uint8_t stale = 0;
1095 unsigned last_dev = -1;
1096 struct bcache_device *d = NULL;
1097 struct bkey *k;
1098 struct btree_iter iter;
1099 struct bset_tree *t;
1100
1101 gc->nodes++;
1102
1103 for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1104 if (last_dev != KEY_INODE(k)) {
1105 last_dev = KEY_INODE(k);
1106
1107 d = KEY_INODE(k) < b->c->nr_uuids
1108 ? b->c->devices[last_dev]
1109 : NULL;
1110 }
1111
1112 stale = max(stale, btree_mark_key(b, k));
1113
1114 if (bch_ptr_bad(b, k))
1115 continue;
1116
1117 *keys += bkey_u64s(k);
1118
1119 gc->key_bytes += bkey_u64s(k);
1120 gc->nkeys++;
1121
1122 gc->data += KEY_SIZE(k);
444fc0b6 1123 if (KEY_DIRTY(k))
cafe5635 1124 gc->dirty += KEY_SIZE(k);
cafe5635
KO
1125 }
1126
1127 for (t = b->sets; t <= &b->sets[b->nsets]; t++)
1128 btree_bug_on(t->size &&
1129 bset_written(b, t) &&
1130 bkey_cmp(&b->key, &t->end) < 0,
1131 b, "found short btree key in gc");
1132
1133 return stale;
1134}
1135
1136static struct btree *btree_gc_alloc(struct btree *b, struct bkey *k,
1137 struct btree_op *op)
1138{
1139 /*
1140 * We block priorities from being written for the duration of garbage
1141 * collection, so we can't sleep in btree_alloc() ->
1142 * bch_bucket_alloc_set(), or we'd risk deadlock - so we don't pass it
1143 * our closure.
1144 */
1145 struct btree *n = btree_node_alloc_replacement(b, NULL);
1146
1147 if (!IS_ERR_OR_NULL(n)) {
1148 swap(b, n);
57943511 1149 __bkey_put(b->c, &b->key);
cafe5635
KO
1150
1151 memcpy(k->ptr, b->key.ptr,
1152 sizeof(uint64_t) * KEY_PTRS(&b->key));
1153
cafe5635
KO
1154 btree_node_free(n, op);
1155 up_write(&n->lock);
1156 }
1157
1158 return b;
1159}
1160
1161/*
1162 * Leaving this at 2 until we've got incremental garbage collection done; it
1163 * could be higher (and has been tested with 4) except that garbage collection
1164 * could take much longer, adversely affecting latency.
1165 */
1166#define GC_MERGE_NODES 2U
1167
1168struct gc_merge_info {
1169 struct btree *b;
1170 struct bkey *k;
1171 unsigned keys;
1172};
1173
1174static void btree_gc_coalesce(struct btree *b, struct btree_op *op,
1175 struct gc_stat *gc, struct gc_merge_info *r)
1176{
1177 unsigned nodes = 0, keys = 0, blocks;
1178 int i;
1179
1180 while (nodes < GC_MERGE_NODES && r[nodes].b)
1181 keys += r[nodes++].keys;
1182
1183 blocks = btree_default_blocks(b->c) * 2 / 3;
1184
1185 if (nodes < 2 ||
1186 __set_blocks(b->sets[0].data, keys, b->c) > blocks * (nodes - 1))
1187 return;
1188
1189 for (i = nodes - 1; i >= 0; --i) {
1190 if (r[i].b->written)
1191 r[i].b = btree_gc_alloc(r[i].b, r[i].k, op);
1192
1193 if (r[i].b->written)
1194 return;
1195 }
1196
1197 for (i = nodes - 1; i > 0; --i) {
1198 struct bset *n1 = r[i].b->sets->data;
1199 struct bset *n2 = r[i - 1].b->sets->data;
1200 struct bkey *k, *last = NULL;
1201
1202 keys = 0;
1203
1204 if (i == 1) {
1205 /*
1206 * Last node we're not getting rid of - we're getting
1207 * rid of the node at r[0]. Have to try and fit all of
1208 * the remaining keys into this node; we can't ensure
1209 * they will always fit due to rounding and variable
1210 * length keys (shouldn't be possible in practice,
1211 * though)
1212 */
1213 if (__set_blocks(n1, n1->keys + r->keys,
1214 b->c) > btree_blocks(r[i].b))
1215 return;
1216
1217 keys = n2->keys;
1218 last = &r->b->key;
1219 } else
1220 for (k = n2->start;
1221 k < end(n2);
1222 k = bkey_next(k)) {
1223 if (__set_blocks(n1, n1->keys + keys +
1224 bkey_u64s(k), b->c) > blocks)
1225 break;
1226
1227 last = k;
1228 keys += bkey_u64s(k);
1229 }
1230
1231 BUG_ON(__set_blocks(n1, n1->keys + keys,
1232 b->c) > btree_blocks(r[i].b));
1233
1234 if (last) {
1235 bkey_copy_key(&r[i].b->key, last);
1236 bkey_copy_key(r[i].k, last);
1237 }
1238
1239 memcpy(end(n1),
1240 n2->start,
1241 (void *) node(n2, keys) - (void *) n2->start);
1242
1243 n1->keys += keys;
1244
1245 memmove(n2->start,
1246 node(n2, keys),
1247 (void *) end(n2) - (void *) node(n2, keys));
1248
1249 n2->keys -= keys;
1250
1251 r[i].keys = n1->keys;
1252 r[i - 1].keys = n2->keys;
1253 }
1254
1255 btree_node_free(r->b, op);
1256 up_write(&r->b->lock);
1257
c37511b8 1258 trace_bcache_btree_gc_coalesce(nodes);
cafe5635
KO
1259
1260 gc->nodes--;
1261 nodes--;
1262
1263 memmove(&r[0], &r[1], sizeof(struct gc_merge_info) * nodes);
1264 memset(&r[nodes], 0, sizeof(struct gc_merge_info));
1265}
1266
1267static int btree_gc_recurse(struct btree *b, struct btree_op *op,
1268 struct closure *writes, struct gc_stat *gc)
1269{
1270 void write(struct btree *r)
1271 {
1272 if (!r->written)
57943511
KO
1273 bch_btree_node_write(r, &op->cl);
1274 else if (btree_node_dirty(r))
1275 bch_btree_node_write(r, writes);
cafe5635
KO
1276
1277 up_write(&r->lock);
1278 }
1279
1280 int ret = 0, stale;
1281 unsigned i;
1282 struct gc_merge_info r[GC_MERGE_NODES];
1283
1284 memset(r, 0, sizeof(r));
1285
1286 while ((r->k = bch_next_recurse_key(b, &b->c->gc_done))) {
1287 r->b = bch_btree_node_get(b->c, r->k, b->level - 1, op);
1288
1289 if (IS_ERR(r->b)) {
1290 ret = PTR_ERR(r->b);
1291 break;
1292 }
1293
1294 r->keys = 0;
1295 stale = btree_gc_mark_node(r->b, &r->keys, gc);
1296
1297 if (!b->written &&
1298 (r->b->level || stale > 10 ||
1299 b->c->gc_always_rewrite))
1300 r->b = btree_gc_alloc(r->b, r->k, op);
1301
1302 if (r->b->level)
1303 ret = btree_gc_recurse(r->b, op, writes, gc);
1304
1305 if (ret) {
1306 write(r->b);
1307 break;
1308 }
1309
1310 bkey_copy_key(&b->c->gc_done, r->k);
1311
1312 if (!b->written)
1313 btree_gc_coalesce(b, op, gc, r);
1314
1315 if (r[GC_MERGE_NODES - 1].b)
1316 write(r[GC_MERGE_NODES - 1].b);
1317
1318 memmove(&r[1], &r[0],
1319 sizeof(struct gc_merge_info) * (GC_MERGE_NODES - 1));
1320
1321 /* When we've got incremental GC working, we'll want to do
1322 * if (should_resched())
1323 * return -EAGAIN;
1324 */
1325 cond_resched();
1326#if 0
1327 if (need_resched()) {
1328 ret = -EAGAIN;
1329 break;
1330 }
1331#endif
1332 }
1333
1334 for (i = 1; i < GC_MERGE_NODES && r[i].b; i++)
1335 write(r[i].b);
1336
1337 /* Might have freed some children, must remove their keys */
1338 if (!b->written)
1339 bch_btree_sort(b);
1340
1341 return ret;
1342}
1343
1344static int bch_btree_gc_root(struct btree *b, struct btree_op *op,
1345 struct closure *writes, struct gc_stat *gc)
1346{
1347 struct btree *n = NULL;
1348 unsigned keys = 0;
1349 int ret = 0, stale = btree_gc_mark_node(b, &keys, gc);
1350
1351 if (b->level || stale > 10)
1352 n = btree_node_alloc_replacement(b, NULL);
1353
1354 if (!IS_ERR_OR_NULL(n))
1355 swap(b, n);
1356
1357 if (b->level)
1358 ret = btree_gc_recurse(b, op, writes, gc);
1359
1360 if (!b->written || btree_node_dirty(b)) {
57943511 1361 bch_btree_node_write(b, n ? &op->cl : NULL);
cafe5635
KO
1362 }
1363
1364 if (!IS_ERR_OR_NULL(n)) {
1365 closure_sync(&op->cl);
1366 bch_btree_set_root(b);
1367 btree_node_free(n, op);
1368 rw_unlock(true, b);
1369 }
1370
1371 return ret;
1372}
1373
1374static void btree_gc_start(struct cache_set *c)
1375{
1376 struct cache *ca;
1377 struct bucket *b;
cafe5635
KO
1378 unsigned i;
1379
1380 if (!c->gc_mark_valid)
1381 return;
1382
1383 mutex_lock(&c->bucket_lock);
1384
1385 c->gc_mark_valid = 0;
1386 c->gc_done = ZERO_KEY;
1387
1388 for_each_cache(ca, c, i)
1389 for_each_bucket(b, ca) {
1390 b->gc_gen = b->gen;
1391 if (!atomic_read(&b->pin))
1392 SET_GC_MARK(b, GC_MARK_RECLAIMABLE);
1393 }
1394
cafe5635
KO
1395 mutex_unlock(&c->bucket_lock);
1396}
1397
1398size_t bch_btree_gc_finish(struct cache_set *c)
1399{
1400 size_t available = 0;
1401 struct bucket *b;
1402 struct cache *ca;
cafe5635
KO
1403 unsigned i;
1404
1405 mutex_lock(&c->bucket_lock);
1406
1407 set_gc_sectors(c);
1408 c->gc_mark_valid = 1;
1409 c->need_gc = 0;
1410
1411 if (c->root)
1412 for (i = 0; i < KEY_PTRS(&c->root->key); i++)
1413 SET_GC_MARK(PTR_BUCKET(c, &c->root->key, i),
1414 GC_MARK_METADATA);
1415
1416 for (i = 0; i < KEY_PTRS(&c->uuid_bucket); i++)
1417 SET_GC_MARK(PTR_BUCKET(c, &c->uuid_bucket, i),
1418 GC_MARK_METADATA);
1419
1420 for_each_cache(ca, c, i) {
1421 uint64_t *i;
1422
1423 ca->invalidate_needs_gc = 0;
1424
1425 for (i = ca->sb.d; i < ca->sb.d + ca->sb.keys; i++)
1426 SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1427
1428 for (i = ca->prio_buckets;
1429 i < ca->prio_buckets + prio_buckets(ca) * 2; i++)
1430 SET_GC_MARK(ca->buckets + *i, GC_MARK_METADATA);
1431
1432 for_each_bucket(b, ca) {
1433 b->last_gc = b->gc_gen;
1434 c->need_gc = max(c->need_gc, bucket_gc_gen(b));
1435
1436 if (!atomic_read(&b->pin) &&
1437 GC_MARK(b) == GC_MARK_RECLAIMABLE) {
1438 available++;
1439 if (!GC_SECTORS_USED(b))
1440 bch_bucket_add_unused(ca, b);
1441 }
1442 }
1443 }
1444
cafe5635
KO
1445 mutex_unlock(&c->bucket_lock);
1446 return available;
1447}
1448
1449static void bch_btree_gc(struct closure *cl)
1450{
1451 struct cache_set *c = container_of(cl, struct cache_set, gc.cl);
1452 int ret;
1453 unsigned long available;
1454 struct gc_stat stats;
1455 struct closure writes;
1456 struct btree_op op;
cafe5635 1457 uint64_t start_time = local_clock();
57943511 1458
c37511b8 1459 trace_bcache_gc_start(c);
cafe5635
KO
1460
1461 memset(&stats, 0, sizeof(struct gc_stat));
1462 closure_init_stack(&writes);
1463 bch_btree_op_init_stack(&op);
1464 op.lock = SHRT_MAX;
1465
1466 btree_gc_start(c);
1467
57943511
KO
1468 atomic_inc(&c->prio_blocked);
1469
cafe5635
KO
1470 ret = btree_root(gc_root, c, &op, &writes, &stats);
1471 closure_sync(&op.cl);
1472 closure_sync(&writes);
1473
1474 if (ret) {
cafe5635 1475 pr_warn("gc failed!");
cafe5635
KO
1476 continue_at(cl, bch_btree_gc, bch_gc_wq);
1477 }
1478
1479 /* Possibly wait for new UUIDs or whatever to hit disk */
1480 bch_journal_meta(c, &op.cl);
1481 closure_sync(&op.cl);
1482
1483 available = bch_btree_gc_finish(c);
1484
57943511
KO
1485 atomic_dec(&c->prio_blocked);
1486 wake_up_allocators(c);
1487
169ef1cf 1488 bch_time_stats_update(&c->btree_gc_time, start_time);
cafe5635
KO
1489
1490 stats.key_bytes *= sizeof(uint64_t);
1491 stats.dirty <<= 9;
1492 stats.data <<= 9;
1493 stats.in_use = (c->nbuckets - available) * 100 / c->nbuckets;
1494 memcpy(&c->gc_stats, &stats, sizeof(struct gc_stat));
cafe5635 1495
c37511b8 1496 trace_bcache_gc_end(c);
cafe5635
KO
1497
1498 continue_at(cl, bch_moving_gc, bch_gc_wq);
1499}
1500
1501void bch_queue_gc(struct cache_set *c)
1502{
1503 closure_trylock_call(&c->gc.cl, bch_btree_gc, bch_gc_wq, &c->cl);
1504}
1505
1506/* Initial partial gc */
1507
1508static int bch_btree_check_recurse(struct btree *b, struct btree_op *op,
1509 unsigned long **seen)
1510{
1511 int ret;
1512 unsigned i;
1513 struct bkey *k;
1514 struct bucket *g;
1515 struct btree_iter iter;
1516
1517 for_each_key_filter(b, k, &iter, bch_ptr_invalid) {
1518 for (i = 0; i < KEY_PTRS(k); i++) {
1519 if (!ptr_available(b->c, k, i))
1520 continue;
1521
1522 g = PTR_BUCKET(b->c, k, i);
1523
1524 if (!__test_and_set_bit(PTR_BUCKET_NR(b->c, k, i),
1525 seen[PTR_DEV(k, i)]) ||
1526 !ptr_stale(b->c, k, i)) {
1527 g->gen = PTR_GEN(k, i);
1528
1529 if (b->level)
1530 g->prio = BTREE_PRIO;
1531 else if (g->prio == BTREE_PRIO)
1532 g->prio = INITIAL_PRIO;
1533 }
1534 }
1535
1536 btree_mark_key(b, k);
1537 }
1538
1539 if (b->level) {
1540 k = bch_next_recurse_key(b, &ZERO_KEY);
1541
1542 while (k) {
1543 struct bkey *p = bch_next_recurse_key(b, k);
1544 if (p)
1545 btree_node_prefetch(b->c, p, b->level - 1);
1546
1547 ret = btree(check_recurse, k, b, op, seen);
1548 if (ret)
1549 return ret;
1550
1551 k = p;
1552 }
1553 }
1554
1555 return 0;
1556}
1557
1558int bch_btree_check(struct cache_set *c, struct btree_op *op)
1559{
1560 int ret = -ENOMEM;
1561 unsigned i;
1562 unsigned long *seen[MAX_CACHES_PER_SET];
1563
1564 memset(seen, 0, sizeof(seen));
1565
1566 for (i = 0; c->cache[i]; i++) {
1567 size_t n = DIV_ROUND_UP(c->cache[i]->sb.nbuckets, 8);
1568 seen[i] = kmalloc(n, GFP_KERNEL);
1569 if (!seen[i])
1570 goto err;
1571
1572 /* Disables the seen array until prio_read() uses it too */
1573 memset(seen[i], 0xFF, n);
1574 }
1575
1576 ret = btree_root(check_recurse, c, op, seen);
1577err:
1578 for (i = 0; i < MAX_CACHES_PER_SET; i++)
1579 kfree(seen[i]);
1580 return ret;
1581}
1582
1583/* Btree insertion */
1584
1585static void shift_keys(struct btree *b, struct bkey *where, struct bkey *insert)
1586{
1587 struct bset *i = b->sets[b->nsets].data;
1588
1589 memmove((uint64_t *) where + bkey_u64s(insert),
1590 where,
1591 (void *) end(i) - (void *) where);
1592
1593 i->keys += bkey_u64s(insert);
1594 bkey_copy(where, insert);
1595 bch_bset_fix_lookup_table(b, where);
1596}
1597
1598static bool fix_overlapping_extents(struct btree *b,
1599 struct bkey *insert,
1600 struct btree_iter *iter,
1601 struct btree_op *op)
1602{
279afbad 1603 void subtract_dirty(struct bkey *k, uint64_t offset, int sectors)
cafe5635 1604 {
279afbad
KO
1605 if (KEY_DIRTY(k))
1606 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1607 offset, -sectors);
cafe5635
KO
1608 }
1609
279afbad 1610 uint64_t old_offset;
cafe5635
KO
1611 unsigned old_size, sectors_found = 0;
1612
1613 while (1) {
1614 struct bkey *k = bch_btree_iter_next(iter);
1615 if (!k ||
1616 bkey_cmp(&START_KEY(k), insert) >= 0)
1617 break;
1618
1619 if (bkey_cmp(k, &START_KEY(insert)) <= 0)
1620 continue;
1621
279afbad 1622 old_offset = KEY_START(k);
cafe5635
KO
1623 old_size = KEY_SIZE(k);
1624
1625 /*
1626 * We might overlap with 0 size extents; we can't skip these
1627 * because if they're in the set we're inserting to we have to
1628 * adjust them so they don't overlap with the key we're
1629 * inserting. But we don't want to check them for BTREE_REPLACE
1630 * operations.
1631 */
1632
1633 if (op->type == BTREE_REPLACE &&
1634 KEY_SIZE(k)) {
1635 /*
1636 * k might have been split since we inserted/found the
1637 * key we're replacing
1638 */
1639 unsigned i;
1640 uint64_t offset = KEY_START(k) -
1641 KEY_START(&op->replace);
1642
1643 /* But it must be a subset of the replace key */
1644 if (KEY_START(k) < KEY_START(&op->replace) ||
1645 KEY_OFFSET(k) > KEY_OFFSET(&op->replace))
1646 goto check_failed;
1647
1648 /* We didn't find a key that we were supposed to */
1649 if (KEY_START(k) > KEY_START(insert) + sectors_found)
1650 goto check_failed;
1651
1652 if (KEY_PTRS(&op->replace) != KEY_PTRS(k))
1653 goto check_failed;
1654
1655 /* skip past gen */
1656 offset <<= 8;
1657
1658 BUG_ON(!KEY_PTRS(&op->replace));
1659
1660 for (i = 0; i < KEY_PTRS(&op->replace); i++)
1661 if (k->ptr[i] != op->replace.ptr[i] + offset)
1662 goto check_failed;
1663
1664 sectors_found = KEY_OFFSET(k) - KEY_START(insert);
1665 }
1666
1667 if (bkey_cmp(insert, k) < 0 &&
1668 bkey_cmp(&START_KEY(insert), &START_KEY(k)) > 0) {
1669 /*
1670 * We overlapped in the middle of an existing key: that
1671 * means we have to split the old key. But we have to do
1672 * slightly different things depending on whether the
1673 * old key has been written out yet.
1674 */
1675
1676 struct bkey *top;
1677
279afbad 1678 subtract_dirty(k, KEY_START(insert), KEY_SIZE(insert));
cafe5635
KO
1679
1680 if (bkey_written(b, k)) {
1681 /*
1682 * We insert a new key to cover the top of the
1683 * old key, and the old key is modified in place
1684 * to represent the bottom split.
1685 *
1686 * It's completely arbitrary whether the new key
1687 * is the top or the bottom, but it has to match
1688 * up with what btree_sort_fixup() does - it
1689 * doesn't check for this kind of overlap, it
1690 * depends on us inserting a new key for the top
1691 * here.
1692 */
1693 top = bch_bset_search(b, &b->sets[b->nsets],
1694 insert);
1695 shift_keys(b, top, k);
1696 } else {
1697 BKEY_PADDED(key) temp;
1698 bkey_copy(&temp.key, k);
1699 shift_keys(b, k, &temp.key);
1700 top = bkey_next(k);
1701 }
1702
1703 bch_cut_front(insert, top);
1704 bch_cut_back(&START_KEY(insert), k);
1705 bch_bset_fix_invalidated_key(b, k);
1706 return false;
1707 }
1708
1709 if (bkey_cmp(insert, k) < 0) {
1710 bch_cut_front(insert, k);
1711 } else {
1712 if (bkey_written(b, k) &&
1713 bkey_cmp(&START_KEY(insert), &START_KEY(k)) <= 0) {
1714 /*
1715 * Completely overwrote, so we don't have to
1716 * invalidate the binary search tree
1717 */
1718 bch_cut_front(k, k);
1719 } else {
1720 __bch_cut_back(&START_KEY(insert), k);
1721 bch_bset_fix_invalidated_key(b, k);
1722 }
1723 }
1724
279afbad 1725 subtract_dirty(k, old_offset, old_size - KEY_SIZE(k));
cafe5635
KO
1726 }
1727
1728check_failed:
1729 if (op->type == BTREE_REPLACE) {
1730 if (!sectors_found) {
1731 op->insert_collision = true;
1732 return true;
1733 } else if (sectors_found < KEY_SIZE(insert)) {
1734 SET_KEY_OFFSET(insert, KEY_OFFSET(insert) -
1735 (KEY_SIZE(insert) - sectors_found));
1736 SET_KEY_SIZE(insert, sectors_found);
1737 }
1738 }
1739
1740 return false;
1741}
1742
1743static bool btree_insert_key(struct btree *b, struct btree_op *op,
1744 struct bkey *k)
1745{
1746 struct bset *i = b->sets[b->nsets].data;
1747 struct bkey *m, *prev;
85b1492e 1748 unsigned status = BTREE_INSERT_STATUS_INSERT;
cafe5635
KO
1749
1750 BUG_ON(bkey_cmp(k, &b->key) > 0);
1751 BUG_ON(b->level && !KEY_PTRS(k));
1752 BUG_ON(!b->level && !KEY_OFFSET(k));
1753
1754 if (!b->level) {
1755 struct btree_iter iter;
1756 struct bkey search = KEY(KEY_INODE(k), KEY_START(k), 0);
1757
1758 /*
1759 * bset_search() returns the first key that is strictly greater
1760 * than the search key - but for back merging, we want to find
1761 * the first key that is greater than or equal to KEY_START(k) -
1762 * unless KEY_START(k) is 0.
1763 */
1764 if (KEY_OFFSET(&search))
1765 SET_KEY_OFFSET(&search, KEY_OFFSET(&search) - 1);
1766
1767 prev = NULL;
1768 m = bch_btree_iter_init(b, &iter, &search);
1769
1770 if (fix_overlapping_extents(b, k, &iter, op))
1771 return false;
1772
1773 while (m != end(i) &&
1774 bkey_cmp(k, &START_KEY(m)) > 0)
1775 prev = m, m = bkey_next(m);
1776
1777 if (key_merging_disabled(b->c))
1778 goto insert;
1779
1780 /* prev is in the tree, if we merge we're done */
85b1492e 1781 status = BTREE_INSERT_STATUS_BACK_MERGE;
cafe5635
KO
1782 if (prev &&
1783 bch_bkey_try_merge(b, prev, k))
1784 goto merged;
1785
85b1492e 1786 status = BTREE_INSERT_STATUS_OVERWROTE;
cafe5635
KO
1787 if (m != end(i) &&
1788 KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
1789 goto copy;
1790
85b1492e 1791 status = BTREE_INSERT_STATUS_FRONT_MERGE;
cafe5635
KO
1792 if (m != end(i) &&
1793 bch_bkey_try_merge(b, k, m))
1794 goto copy;
1795 } else
1796 m = bch_bset_search(b, &b->sets[b->nsets], k);
1797
1798insert: shift_keys(b, m, k);
1799copy: bkey_copy(m, k);
1800merged:
279afbad
KO
1801 if (KEY_DIRTY(k))
1802 bcache_dev_sectors_dirty_add(b->c, KEY_INODE(k),
1803 KEY_START(k), KEY_SIZE(k));
1804
85b1492e 1805 bch_check_keys(b, "%u for %s", status, op_type(op));
cafe5635
KO
1806
1807 if (b->level && !KEY_OFFSET(k))
57943511 1808 btree_current_write(b)->prio_blocked++;
cafe5635 1809
85b1492e 1810 trace_bcache_btree_insert_key(b, k, op->type, status);
cafe5635
KO
1811
1812 return true;
1813}
1814
1815bool bch_btree_insert_keys(struct btree *b, struct btree_op *op)
1816{
1817 bool ret = false;
1818 struct bkey *k;
1819 unsigned oldsize = bch_count_data(b);
1820
1821 while ((k = bch_keylist_pop(&op->keys))) {
1822 bkey_put(b->c, k, b->level);
1823 ret |= btree_insert_key(b, op, k);
1824 }
1825
1826 BUG_ON(bch_count_data(b) < oldsize);
1827 return ret;
1828}
1829
1830bool bch_btree_insert_check_key(struct btree *b, struct btree_op *op,
1831 struct bio *bio)
1832{
1833 bool ret = false;
1834 uint64_t btree_ptr = b->key.ptr[0];
1835 unsigned long seq = b->seq;
1836 BKEY_PADDED(k) tmp;
1837
1838 rw_unlock(false, b);
1839 rw_lock(true, b, b->level);
1840
1841 if (b->key.ptr[0] != btree_ptr ||
1842 b->seq != seq + 1 ||
1843 should_split(b))
1844 goto out;
1845
1846 op->replace = KEY(op->inode, bio_end(bio), bio_sectors(bio));
1847
1848 SET_KEY_PTRS(&op->replace, 1);
1849 get_random_bytes(&op->replace.ptr[0], sizeof(uint64_t));
1850
1851 SET_PTR_DEV(&op->replace, 0, PTR_CHECK_DEV);
1852
1853 bkey_copy(&tmp.k, &op->replace);
1854
1855 BUG_ON(op->type != BTREE_INSERT);
1856 BUG_ON(!btree_insert_key(b, op, &tmp.k));
cafe5635
KO
1857 ret = true;
1858out:
1859 downgrade_write(&b->lock);
1860 return ret;
1861}
1862
1863static int btree_split(struct btree *b, struct btree_op *op)
1864{
1865 bool split, root = b == b->c->root;
1866 struct btree *n1, *n2 = NULL, *n3 = NULL;
1867 uint64_t start_time = local_clock();
1868
1869 if (b->level)
1870 set_closure_blocking(&op->cl);
1871
1872 n1 = btree_node_alloc_replacement(b, &op->cl);
1873 if (IS_ERR(n1))
1874 goto err;
1875
1876 split = set_blocks(n1->sets[0].data, n1->c) > (btree_blocks(b) * 4) / 5;
1877
cafe5635
KO
1878 if (split) {
1879 unsigned keys = 0;
1880
c37511b8
KO
1881 trace_bcache_btree_node_split(b, n1->sets[0].data->keys);
1882
cafe5635
KO
1883 n2 = bch_btree_node_alloc(b->c, b->level, &op->cl);
1884 if (IS_ERR(n2))
1885 goto err_free1;
1886
1887 if (root) {
1888 n3 = bch_btree_node_alloc(b->c, b->level + 1, &op->cl);
1889 if (IS_ERR(n3))
1890 goto err_free2;
1891 }
1892
1893 bch_btree_insert_keys(n1, op);
1894
1895 /* Has to be a linear search because we don't have an auxiliary
1896 * search tree yet
1897 */
1898
1899 while (keys < (n1->sets[0].data->keys * 3) / 5)
1900 keys += bkey_u64s(node(n1->sets[0].data, keys));
1901
1902 bkey_copy_key(&n1->key, node(n1->sets[0].data, keys));
1903 keys += bkey_u64s(node(n1->sets[0].data, keys));
1904
1905 n2->sets[0].data->keys = n1->sets[0].data->keys - keys;
1906 n1->sets[0].data->keys = keys;
1907
1908 memcpy(n2->sets[0].data->start,
1909 end(n1->sets[0].data),
1910 n2->sets[0].data->keys * sizeof(uint64_t));
1911
1912 bkey_copy_key(&n2->key, &b->key);
1913
1914 bch_keylist_add(&op->keys, &n2->key);
57943511 1915 bch_btree_node_write(n2, &op->cl);
cafe5635 1916 rw_unlock(true, n2);
c37511b8
KO
1917 } else {
1918 trace_bcache_btree_node_compact(b, n1->sets[0].data->keys);
1919
cafe5635 1920 bch_btree_insert_keys(n1, op);
c37511b8 1921 }
cafe5635
KO
1922
1923 bch_keylist_add(&op->keys, &n1->key);
57943511 1924 bch_btree_node_write(n1, &op->cl);
cafe5635
KO
1925
1926 if (n3) {
1927 bkey_copy_key(&n3->key, &MAX_KEY);
1928 bch_btree_insert_keys(n3, op);
57943511 1929 bch_btree_node_write(n3, &op->cl);
cafe5635
KO
1930
1931 closure_sync(&op->cl);
1932 bch_btree_set_root(n3);
1933 rw_unlock(true, n3);
1934 } else if (root) {
1935 op->keys.top = op->keys.bottom;
1936 closure_sync(&op->cl);
1937 bch_btree_set_root(n1);
1938 } else {
1939 unsigned i;
1940
1941 bkey_copy(op->keys.top, &b->key);
1942 bkey_copy_key(op->keys.top, &ZERO_KEY);
1943
1944 for (i = 0; i < KEY_PTRS(&b->key); i++) {
1945 uint8_t g = PTR_BUCKET(b->c, &b->key, i)->gen + 1;
1946
1947 SET_PTR_GEN(op->keys.top, i, g);
1948 }
1949
1950 bch_keylist_push(&op->keys);
1951 closure_sync(&op->cl);
1952 atomic_inc(&b->c->prio_blocked);
1953 }
1954
1955 rw_unlock(true, n1);
1956 btree_node_free(b, op);
1957
169ef1cf 1958 bch_time_stats_update(&b->c->btree_split_time, start_time);
cafe5635
KO
1959
1960 return 0;
1961err_free2:
1962 __bkey_put(n2->c, &n2->key);
1963 btree_node_free(n2, op);
1964 rw_unlock(true, n2);
1965err_free1:
1966 __bkey_put(n1->c, &n1->key);
1967 btree_node_free(n1, op);
1968 rw_unlock(true, n1);
1969err:
1970 if (n3 == ERR_PTR(-EAGAIN) ||
1971 n2 == ERR_PTR(-EAGAIN) ||
1972 n1 == ERR_PTR(-EAGAIN))
1973 return -EAGAIN;
1974
1975 pr_warn("couldn't split");
1976 return -ENOMEM;
1977}
1978
1979static int bch_btree_insert_recurse(struct btree *b, struct btree_op *op,
1980 struct keylist *stack_keys)
1981{
1982 if (b->level) {
1983 int ret;
1984 struct bkey *insert = op->keys.bottom;
1985 struct bkey *k = bch_next_recurse_key(b, &START_KEY(insert));
1986
1987 if (!k) {
1988 btree_bug(b, "no key to recurse on at level %i/%i",
1989 b->level, b->c->root->level);
1990
1991 op->keys.top = op->keys.bottom;
1992 return -EIO;
1993 }
1994
1995 if (bkey_cmp(insert, k) > 0) {
1996 unsigned i;
1997
1998 if (op->type == BTREE_REPLACE) {
1999 __bkey_put(b->c, insert);
2000 op->keys.top = op->keys.bottom;
2001 op->insert_collision = true;
2002 return 0;
2003 }
2004
2005 for (i = 0; i < KEY_PTRS(insert); i++)
2006 atomic_inc(&PTR_BUCKET(b->c, insert, i)->pin);
2007
2008 bkey_copy(stack_keys->top, insert);
2009
2010 bch_cut_back(k, insert);
2011 bch_cut_front(k, stack_keys->top);
2012
2013 bch_keylist_push(stack_keys);
2014 }
2015
2016 ret = btree(insert_recurse, k, b, op, stack_keys);
2017 if (ret)
2018 return ret;
2019 }
2020
2021 if (!bch_keylist_empty(&op->keys)) {
2022 if (should_split(b)) {
2023 if (op->lock <= b->c->root->level) {
2024 BUG_ON(b->level);
2025 op->lock = b->c->root->level + 1;
2026 return -EINTR;
2027 }
2028 return btree_split(b, op);
2029 }
2030
2031 BUG_ON(write_block(b) != b->sets[b->nsets].data);
2032
57943511
KO
2033 if (bch_btree_insert_keys(b, op)) {
2034 if (!b->level)
2035 bch_btree_leaf_dirty(b, op);
2036 else
2037 bch_btree_node_write(b, &op->cl);
2038 }
cafe5635
KO
2039 }
2040
2041 return 0;
2042}
2043
2044int bch_btree_insert(struct btree_op *op, struct cache_set *c)
2045{
2046 int ret = 0;
2047 struct keylist stack_keys;
2048
2049 /*
2050 * Don't want to block with the btree locked unless we have to,
2051 * otherwise we get deadlocks with try_harder and between split/gc
2052 */
2053 clear_closure_blocking(&op->cl);
2054
2055 BUG_ON(bch_keylist_empty(&op->keys));
2056 bch_keylist_copy(&stack_keys, &op->keys);
2057 bch_keylist_init(&op->keys);
2058
2059 while (!bch_keylist_empty(&stack_keys) ||
2060 !bch_keylist_empty(&op->keys)) {
2061 if (bch_keylist_empty(&op->keys)) {
2062 bch_keylist_add(&op->keys,
2063 bch_keylist_pop(&stack_keys));
2064 op->lock = 0;
2065 }
2066
2067 ret = btree_root(insert_recurse, c, op, &stack_keys);
2068
2069 if (ret == -EAGAIN) {
2070 ret = 0;
2071 closure_sync(&op->cl);
2072 } else if (ret) {
2073 struct bkey *k;
2074
2075 pr_err("error %i trying to insert key for %s",
2076 ret, op_type(op));
2077
2078 while ((k = bch_keylist_pop(&stack_keys) ?:
2079 bch_keylist_pop(&op->keys)))
2080 bkey_put(c, k, 0);
2081 }
2082 }
2083
2084 bch_keylist_free(&stack_keys);
2085
2086 if (op->journal)
2087 atomic_dec_bug(op->journal);
2088 op->journal = NULL;
2089 return ret;
2090}
2091
2092void bch_btree_set_root(struct btree *b)
2093{
2094 unsigned i;
2095
c37511b8
KO
2096 trace_bcache_btree_set_root(b);
2097
cafe5635
KO
2098 BUG_ON(!b->written);
2099
2100 for (i = 0; i < KEY_PTRS(&b->key); i++)
2101 BUG_ON(PTR_BUCKET(b->c, &b->key, i)->prio != BTREE_PRIO);
2102
2103 mutex_lock(&b->c->bucket_lock);
2104 list_del_init(&b->list);
2105 mutex_unlock(&b->c->bucket_lock);
2106
2107 b->c->root = b;
2108 __bkey_put(b->c, &b->key);
2109
2110 bch_journal_meta(b->c, NULL);
cafe5635
KO
2111}
2112
2113/* Cache lookup */
2114
2115static int submit_partial_cache_miss(struct btree *b, struct btree_op *op,
2116 struct bkey *k)
2117{
2118 struct search *s = container_of(op, struct search, op);
2119 struct bio *bio = &s->bio.bio;
2120 int ret = 0;
2121
2122 while (!ret &&
2123 !op->lookup_done) {
2124 unsigned sectors = INT_MAX;
2125
2126 if (KEY_INODE(k) == op->inode) {
2127 if (KEY_START(k) <= bio->bi_sector)
2128 break;
2129
2130 sectors = min_t(uint64_t, sectors,
2131 KEY_START(k) - bio->bi_sector);
2132 }
2133
2134 ret = s->d->cache_miss(b, s, bio, sectors);
2135 }
2136
2137 return ret;
2138}
2139
2140/*
2141 * Read from a single key, handling the initial cache miss if the key starts in
2142 * the middle of the bio
2143 */
2144static int submit_partial_cache_hit(struct btree *b, struct btree_op *op,
2145 struct bkey *k)
2146{
2147 struct search *s = container_of(op, struct search, op);
2148 struct bio *bio = &s->bio.bio;
2149 unsigned ptr;
2150 struct bio *n;
2151
2152 int ret = submit_partial_cache_miss(b, op, k);
2153 if (ret || op->lookup_done)
2154 return ret;
2155
2156 /* XXX: figure out best pointer - for multiple cache devices */
2157 ptr = 0;
2158
2159 PTR_BUCKET(b->c, k, ptr)->prio = INITIAL_PRIO;
2160
2161 while (!op->lookup_done &&
2162 KEY_INODE(k) == op->inode &&
2163 bio->bi_sector < KEY_OFFSET(k)) {
2164 struct bkey *bio_key;
2165 sector_t sector = PTR_OFFSET(k, ptr) +
2166 (bio->bi_sector - KEY_START(k));
2167 unsigned sectors = min_t(uint64_t, INT_MAX,
2168 KEY_OFFSET(k) - bio->bi_sector);
2169
2170 n = bch_bio_split(bio, sectors, GFP_NOIO, s->d->bio_split);
2171 if (!n)
2172 return -EAGAIN;
2173
2174 if (n == bio)
2175 op->lookup_done = true;
2176
2177 bio_key = &container_of(n, struct bbio, bio)->key;
2178
2179 /*
2180 * The bucket we're reading from might be reused while our bio
2181 * is in flight, and we could then end up reading the wrong
2182 * data.
2183 *
2184 * We guard against this by checking (in cache_read_endio()) if
2185 * the pointer is stale again; if so, we treat it as an error
2186 * and reread from the backing device (but we don't pass that
2187 * error up anywhere).
2188 */
2189
2190 bch_bkey_copy_single_ptr(bio_key, k, ptr);
2191 SET_PTR_OFFSET(bio_key, 0, sector);
2192
2193 n->bi_end_io = bch_cache_read_endio;
2194 n->bi_private = &s->cl;
2195
cafe5635
KO
2196 __bch_submit_bbio(n, b->c);
2197 }
2198
2199 return 0;
2200}
2201
2202int bch_btree_search_recurse(struct btree *b, struct btree_op *op)
2203{
2204 struct search *s = container_of(op, struct search, op);
2205 struct bio *bio = &s->bio.bio;
2206
2207 int ret = 0;
2208 struct bkey *k;
2209 struct btree_iter iter;
2210 bch_btree_iter_init(b, &iter, &KEY(op->inode, bio->bi_sector, 0));
2211
cafe5635
KO
2212 do {
2213 k = bch_btree_iter_next_filter(&iter, b, bch_ptr_bad);
2214 if (!k) {
2215 /*
2216 * b->key would be exactly what we want, except that
2217 * pointers to btree nodes have nonzero size - we
2218 * wouldn't go far enough
2219 */
2220
2221 ret = submit_partial_cache_miss(b, op,
2222 &KEY(KEY_INODE(&b->key),
2223 KEY_OFFSET(&b->key), 0));
2224 break;
2225 }
2226
2227 ret = b->level
2228 ? btree(search_recurse, k, b, op)
2229 : submit_partial_cache_hit(b, op, k);
2230 } while (!ret &&
2231 !op->lookup_done);
2232
2233 return ret;
2234}
2235
2236/* Keybuf code */
2237
2238static inline int keybuf_cmp(struct keybuf_key *l, struct keybuf_key *r)
2239{
2240 /* Overlapping keys compare equal */
2241 if (bkey_cmp(&l->key, &START_KEY(&r->key)) <= 0)
2242 return -1;
2243 if (bkey_cmp(&START_KEY(&l->key), &r->key) >= 0)
2244 return 1;
2245 return 0;
2246}
2247
2248static inline int keybuf_nonoverlapping_cmp(struct keybuf_key *l,
2249 struct keybuf_key *r)
2250{
2251 return clamp_t(int64_t, bkey_cmp(&l->key, &r->key), -1, 1);
2252}
2253
2254static int bch_btree_refill_keybuf(struct btree *b, struct btree_op *op,
2255 struct keybuf *buf, struct bkey *end)
2256{
2257 struct btree_iter iter;
2258 bch_btree_iter_init(b, &iter, &buf->last_scanned);
2259
2260 while (!array_freelist_empty(&buf->freelist)) {
2261 struct bkey *k = bch_btree_iter_next_filter(&iter, b,
2262 bch_ptr_bad);
2263
2264 if (!b->level) {
2265 if (!k) {
2266 buf->last_scanned = b->key;
2267 break;
2268 }
2269
2270 buf->last_scanned = *k;
2271 if (bkey_cmp(&buf->last_scanned, end) >= 0)
2272 break;
2273
2274 if (buf->key_predicate(buf, k)) {
2275 struct keybuf_key *w;
2276
cafe5635
KO
2277 spin_lock(&buf->lock);
2278
2279 w = array_alloc(&buf->freelist);
2280
2281 w->private = NULL;
2282 bkey_copy(&w->key, k);
2283
2284 if (RB_INSERT(&buf->keys, w, node, keybuf_cmp))
2285 array_free(&buf->freelist, w);
2286
2287 spin_unlock(&buf->lock);
2288 }
2289 } else {
2290 if (!k)
2291 break;
2292
2293 btree(refill_keybuf, k, b, op, buf, end);
2294 /*
2295 * Might get an error here, but can't really do anything
2296 * and it'll get logged elsewhere. Just read what we
2297 * can.
2298 */
2299
2300 if (bkey_cmp(&buf->last_scanned, end) >= 0)
2301 break;
2302
2303 cond_resched();
2304 }
2305 }
2306
2307 return 0;
2308}
2309
2310void bch_refill_keybuf(struct cache_set *c, struct keybuf *buf,
2311 struct bkey *end)
2312{
2313 struct bkey start = buf->last_scanned;
2314 struct btree_op op;
2315 bch_btree_op_init_stack(&op);
2316
2317 cond_resched();
2318
2319 btree_root(refill_keybuf, c, &op, buf, end);
2320 closure_sync(&op.cl);
2321
2322 pr_debug("found %s keys from %llu:%llu to %llu:%llu",
2323 RB_EMPTY_ROOT(&buf->keys) ? "no" :
2324 array_freelist_empty(&buf->freelist) ? "some" : "a few",
2325 KEY_INODE(&start), KEY_OFFSET(&start),
2326 KEY_INODE(&buf->last_scanned), KEY_OFFSET(&buf->last_scanned));
2327
2328 spin_lock(&buf->lock);
2329
2330 if (!RB_EMPTY_ROOT(&buf->keys)) {
2331 struct keybuf_key *w;
2332 w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2333 buf->start = START_KEY(&w->key);
2334
2335 w = RB_LAST(&buf->keys, struct keybuf_key, node);
2336 buf->end = w->key;
2337 } else {
2338 buf->start = MAX_KEY;
2339 buf->end = MAX_KEY;
2340 }
2341
2342 spin_unlock(&buf->lock);
2343}
2344
2345static void __bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2346{
2347 rb_erase(&w->node, &buf->keys);
2348 array_free(&buf->freelist, w);
2349}
2350
2351void bch_keybuf_del(struct keybuf *buf, struct keybuf_key *w)
2352{
2353 spin_lock(&buf->lock);
2354 __bch_keybuf_del(buf, w);
2355 spin_unlock(&buf->lock);
2356}
2357
2358bool bch_keybuf_check_overlapping(struct keybuf *buf, struct bkey *start,
2359 struct bkey *end)
2360{
2361 bool ret = false;
2362 struct keybuf_key *p, *w, s;
2363 s.key = *start;
2364
2365 if (bkey_cmp(end, &buf->start) <= 0 ||
2366 bkey_cmp(start, &buf->end) >= 0)
2367 return false;
2368
2369 spin_lock(&buf->lock);
2370 w = RB_GREATER(&buf->keys, s, node, keybuf_nonoverlapping_cmp);
2371
2372 while (w && bkey_cmp(&START_KEY(&w->key), end) < 0) {
2373 p = w;
2374 w = RB_NEXT(w, node);
2375
2376 if (p->private)
2377 ret = true;
2378 else
2379 __bch_keybuf_del(buf, p);
2380 }
2381
2382 spin_unlock(&buf->lock);
2383 return ret;
2384}
2385
2386struct keybuf_key *bch_keybuf_next(struct keybuf *buf)
2387{
2388 struct keybuf_key *w;
2389 spin_lock(&buf->lock);
2390
2391 w = RB_FIRST(&buf->keys, struct keybuf_key, node);
2392
2393 while (w && w->private)
2394 w = RB_NEXT(w, node);
2395
2396 if (w)
2397 w->private = ERR_PTR(-EINTR);
2398
2399 spin_unlock(&buf->lock);
2400 return w;
2401}
2402
2403struct keybuf_key *bch_keybuf_next_rescan(struct cache_set *c,
2404 struct keybuf *buf,
2405 struct bkey *end)
2406{
2407 struct keybuf_key *ret;
2408
2409 while (1) {
2410 ret = bch_keybuf_next(buf);
2411 if (ret)
2412 break;
2413
2414 if (bkey_cmp(&buf->last_scanned, end) >= 0) {
2415 pr_debug("scan finished");
2416 break;
2417 }
2418
2419 bch_refill_keybuf(c, buf, end);
2420 }
2421
2422 return ret;
2423}
2424
2425void bch_keybuf_init(struct keybuf *buf, keybuf_pred_fn *fn)
2426{
2427 buf->key_predicate = fn;
2428 buf->last_scanned = MAX_KEY;
2429 buf->keys = RB_ROOT;
2430
2431 spin_lock_init(&buf->lock);
2432 array_allocator_init(&buf->freelist);
2433}
2434
2435void bch_btree_exit(void)
2436{
2437 if (btree_io_wq)
2438 destroy_workqueue(btree_io_wq);
2439 if (bch_gc_wq)
2440 destroy_workqueue(bch_gc_wq);
2441}
2442
2443int __init bch_btree_init(void)
2444{
2445 if (!(bch_gc_wq = create_singlethread_workqueue("bch_btree_gc")) ||
2446 !(btree_io_wq = create_singlethread_workqueue("bch_btree_io")))
2447 return -ENOMEM;
2448
2449 return 0;
2450}