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