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