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