GNU Linux-libre 4.14.313-gnu1
[releases.git] / drivers / md / bcache / request.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Main bcache entry point - handle a read or a write request and decide what to
4  * do with it; the make_request functions are called by the block layer.
5  *
6  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
7  * Copyright 2012 Google, Inc.
8  */
9
10 #include "bcache.h"
11 #include "btree.h"
12 #include "debug.h"
13 #include "request.h"
14 #include "writeback.h"
15
16 #include <linux/module.h>
17 #include <linux/hash.h>
18 #include <linux/random.h>
19 #include <linux/backing-dev.h>
20
21 #include <trace/events/bcache.h>
22
23 #define CUTOFF_CACHE_ADD        95
24 #define CUTOFF_CACHE_READA      90
25
26 struct kmem_cache *bch_search_cache;
27
28 static void bch_data_insert_start(struct closure *);
29
30 static unsigned cache_mode(struct cached_dev *dc, struct bio *bio)
31 {
32         return BDEV_CACHE_MODE(&dc->sb);
33 }
34
35 static bool verify(struct cached_dev *dc, struct bio *bio)
36 {
37         return dc->verify;
38 }
39
40 static void bio_csum(struct bio *bio, struct bkey *k)
41 {
42         struct bio_vec bv;
43         struct bvec_iter iter;
44         uint64_t csum = 0;
45
46         bio_for_each_segment(bv, bio, iter) {
47                 void *d = kmap(bv.bv_page) + bv.bv_offset;
48                 csum = bch_crc64_update(csum, d, bv.bv_len);
49                 kunmap(bv.bv_page);
50         }
51
52         k->ptr[KEY_PTRS(k)] = csum & (~0ULL >> 1);
53 }
54
55 /* Insert data into cache */
56
57 static void bch_data_insert_keys(struct closure *cl)
58 {
59         struct data_insert_op *op = container_of(cl, struct data_insert_op, cl);
60         atomic_t *journal_ref = NULL;
61         struct bkey *replace_key = op->replace ? &op->replace_key : NULL;
62         int ret;
63
64         /*
65          * If we're looping, might already be waiting on
66          * another journal write - can't wait on more than one journal write at
67          * a time
68          *
69          * XXX: this looks wrong
70          */
71 #if 0
72         while (atomic_read(&s->cl.remaining) & CLOSURE_WAITING)
73                 closure_sync(&s->cl);
74 #endif
75
76         if (!op->replace)
77                 journal_ref = bch_journal(op->c, &op->insert_keys,
78                                           op->flush_journal ? cl : NULL);
79
80         ret = bch_btree_insert(op->c, &op->insert_keys,
81                                journal_ref, replace_key);
82         if (ret == -ESRCH) {
83                 op->replace_collision = true;
84         } else if (ret) {
85                 op->status              = BLK_STS_RESOURCE;
86                 op->insert_data_done    = true;
87         }
88
89         if (journal_ref)
90                 atomic_dec_bug(journal_ref);
91
92         if (!op->insert_data_done) {
93                 continue_at(cl, bch_data_insert_start, op->wq);
94                 return;
95         }
96
97         bch_keylist_free(&op->insert_keys);
98         closure_return(cl);
99 }
100
101 static int bch_keylist_realloc(struct keylist *l, unsigned u64s,
102                                struct cache_set *c)
103 {
104         size_t oldsize = bch_keylist_nkeys(l);
105         size_t newsize = oldsize + u64s;
106
107         /*
108          * The journalling code doesn't handle the case where the keys to insert
109          * is bigger than an empty write: If we just return -ENOMEM here,
110          * bio_insert() and bio_invalidate() will insert the keys created so far
111          * and finish the rest when the keylist is empty.
112          */
113         if (newsize * sizeof(uint64_t) > block_bytes(c) - sizeof(struct jset))
114                 return -ENOMEM;
115
116         return __bch_keylist_realloc(l, u64s);
117 }
118
119 static void bch_data_invalidate(struct closure *cl)
120 {
121         struct data_insert_op *op = container_of(cl, struct data_insert_op, cl);
122         struct bio *bio = op->bio;
123
124         pr_debug("invalidating %i sectors from %llu",
125                  bio_sectors(bio), (uint64_t) bio->bi_iter.bi_sector);
126
127         while (bio_sectors(bio)) {
128                 unsigned sectors = min(bio_sectors(bio),
129                                        1U << (KEY_SIZE_BITS - 1));
130
131                 if (bch_keylist_realloc(&op->insert_keys, 2, op->c))
132                         goto out;
133
134                 bio->bi_iter.bi_sector  += sectors;
135                 bio->bi_iter.bi_size    -= sectors << 9;
136
137                 bch_keylist_add(&op->insert_keys,
138                                 &KEY(op->inode, bio->bi_iter.bi_sector, sectors));
139         }
140
141         op->insert_data_done = true;
142         bio_put(bio);
143 out:
144         continue_at(cl, bch_data_insert_keys, op->wq);
145 }
146
147 static void bch_data_insert_error(struct closure *cl)
148 {
149         struct data_insert_op *op = container_of(cl, struct data_insert_op, cl);
150
151         /*
152          * Our data write just errored, which means we've got a bunch of keys to
153          * insert that point to data that wasn't succesfully written.
154          *
155          * We don't have to insert those keys but we still have to invalidate
156          * that region of the cache - so, if we just strip off all the pointers
157          * from the keys we'll accomplish just that.
158          */
159
160         struct bkey *src = op->insert_keys.keys, *dst = op->insert_keys.keys;
161
162         while (src != op->insert_keys.top) {
163                 struct bkey *n = bkey_next(src);
164
165                 SET_KEY_PTRS(src, 0);
166                 memmove(dst, src, bkey_bytes(src));
167
168                 dst = bkey_next(dst);
169                 src = n;
170         }
171
172         op->insert_keys.top = dst;
173
174         bch_data_insert_keys(cl);
175 }
176
177 static void bch_data_insert_endio(struct bio *bio)
178 {
179         struct closure *cl = bio->bi_private;
180         struct data_insert_op *op = container_of(cl, struct data_insert_op, cl);
181
182         if (bio->bi_status) {
183                 /* TODO: We could try to recover from this. */
184                 if (op->writeback)
185                         op->status = bio->bi_status;
186                 else if (!op->replace)
187                         set_closure_fn(cl, bch_data_insert_error, op->wq);
188                 else
189                         set_closure_fn(cl, NULL, NULL);
190         }
191
192         bch_bbio_endio(op->c, bio, bio->bi_status, "writing data to cache");
193 }
194
195 static void bch_data_insert_start(struct closure *cl)
196 {
197         struct data_insert_op *op = container_of(cl, struct data_insert_op, cl);
198         struct bio *bio = op->bio, *n;
199
200         if (op->bypass)
201                 return bch_data_invalidate(cl);
202
203         if (atomic_sub_return(bio_sectors(bio), &op->c->sectors_to_gc) < 0)
204                 wake_up_gc(op->c);
205
206         /*
207          * Journal writes are marked REQ_PREFLUSH; if the original write was a
208          * flush, it'll wait on the journal write.
209          */
210         bio->bi_opf &= ~(REQ_PREFLUSH|REQ_FUA);
211
212         do {
213                 unsigned i;
214                 struct bkey *k;
215                 struct bio_set *split = op->c->bio_split;
216
217                 /* 1 for the device pointer and 1 for the chksum */
218                 if (bch_keylist_realloc(&op->insert_keys,
219                                         3 + (op->csum ? 1 : 0),
220                                         op->c)) {
221                         continue_at(cl, bch_data_insert_keys, op->wq);
222                         return;
223                 }
224
225                 k = op->insert_keys.top;
226                 bkey_init(k);
227                 SET_KEY_INODE(k, op->inode);
228                 SET_KEY_OFFSET(k, bio->bi_iter.bi_sector);
229
230                 if (!bch_alloc_sectors(op->c, k, bio_sectors(bio),
231                                        op->write_point, op->write_prio,
232                                        op->writeback))
233                         goto err;
234
235                 n = bio_next_split(bio, KEY_SIZE(k), GFP_NOIO, split);
236
237                 n->bi_end_io    = bch_data_insert_endio;
238                 n->bi_private   = cl;
239
240                 if (op->writeback) {
241                         SET_KEY_DIRTY(k, true);
242
243                         for (i = 0; i < KEY_PTRS(k); i++)
244                                 SET_GC_MARK(PTR_BUCKET(op->c, k, i),
245                                             GC_MARK_DIRTY);
246                 }
247
248                 SET_KEY_CSUM(k, op->csum);
249                 if (KEY_CSUM(k))
250                         bio_csum(n, k);
251
252                 trace_bcache_cache_insert(k);
253                 bch_keylist_push(&op->insert_keys);
254
255                 bio_set_op_attrs(n, REQ_OP_WRITE, 0);
256                 bch_submit_bbio(n, op->c, k, 0);
257         } while (n != bio);
258
259         op->insert_data_done = true;
260         continue_at(cl, bch_data_insert_keys, op->wq);
261         return;
262 err:
263         /* bch_alloc_sectors() blocks if s->writeback = true */
264         BUG_ON(op->writeback);
265
266         /*
267          * But if it's not a writeback write we'd rather just bail out if
268          * there aren't any buckets ready to write to - it might take awhile and
269          * we might be starving btree writes for gc or something.
270          */
271
272         if (!op->replace) {
273                 /*
274                  * Writethrough write: We can't complete the write until we've
275                  * updated the index. But we don't want to delay the write while
276                  * we wait for buckets to be freed up, so just invalidate the
277                  * rest of the write.
278                  */
279                 op->bypass = true;
280                 return bch_data_invalidate(cl);
281         } else {
282                 /*
283                  * From a cache miss, we can just insert the keys for the data
284                  * we have written or bail out if we didn't do anything.
285                  */
286                 op->insert_data_done = true;
287                 bio_put(bio);
288
289                 if (!bch_keylist_empty(&op->insert_keys))
290                         continue_at(cl, bch_data_insert_keys, op->wq);
291                 else
292                         closure_return(cl);
293         }
294 }
295
296 /**
297  * bch_data_insert - stick some data in the cache
298  *
299  * This is the starting point for any data to end up in a cache device; it could
300  * be from a normal write, or a writeback write, or a write to a flash only
301  * volume - it's also used by the moving garbage collector to compact data in
302  * mostly empty buckets.
303  *
304  * It first writes the data to the cache, creating a list of keys to be inserted
305  * (if the data had to be fragmented there will be multiple keys); after the
306  * data is written it calls bch_journal, and after the keys have been added to
307  * the next journal write they're inserted into the btree.
308  *
309  * It inserts the data in s->cache_bio; bi_sector is used for the key offset,
310  * and op->inode is used for the key inode.
311  *
312  * If s->bypass is true, instead of inserting the data it invalidates the
313  * region of the cache represented by s->cache_bio and op->inode.
314  */
315 void bch_data_insert(struct closure *cl)
316 {
317         struct data_insert_op *op = container_of(cl, struct data_insert_op, cl);
318
319         trace_bcache_write(op->c, op->inode, op->bio,
320                            op->writeback, op->bypass);
321
322         bch_keylist_init(&op->insert_keys);
323         bio_get(op->bio);
324         bch_data_insert_start(cl);
325 }
326
327 /* Congested? */
328
329 unsigned bch_get_congested(struct cache_set *c)
330 {
331         int i;
332         long rand;
333
334         if (!c->congested_read_threshold_us &&
335             !c->congested_write_threshold_us)
336                 return 0;
337
338         i = (local_clock_us() - c->congested_last_us) / 1024;
339         if (i < 0)
340                 return 0;
341
342         i += atomic_read(&c->congested);
343         if (i >= 0)
344                 return 0;
345
346         i += CONGESTED_MAX;
347
348         if (i > 0)
349                 i = fract_exp_two(i, 6);
350
351         rand = get_random_int();
352         i -= bitmap_weight(&rand, BITS_PER_LONG);
353
354         return i > 0 ? i : 1;
355 }
356
357 static void add_sequential(struct task_struct *t)
358 {
359         ewma_add(t->sequential_io_avg,
360                  t->sequential_io, 8, 0);
361
362         t->sequential_io = 0;
363 }
364
365 static struct hlist_head *iohash(struct cached_dev *dc, uint64_t k)
366 {
367         return &dc->io_hash[hash_64(k, RECENT_IO_BITS)];
368 }
369
370 static bool check_should_bypass(struct cached_dev *dc, struct bio *bio)
371 {
372         struct cache_set *c = dc->disk.c;
373         unsigned mode = cache_mode(dc, bio);
374         unsigned sectors, congested = bch_get_congested(c);
375         struct task_struct *task = current;
376         struct io *i;
377
378         if (test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags) ||
379             c->gc_stats.in_use > CUTOFF_CACHE_ADD ||
380             (bio_op(bio) == REQ_OP_DISCARD))
381                 goto skip;
382
383         if (mode == CACHE_MODE_NONE ||
384             (mode == CACHE_MODE_WRITEAROUND &&
385              op_is_write(bio_op(bio))))
386                 goto skip;
387
388         if (bio->bi_iter.bi_sector & (c->sb.block_size - 1) ||
389             bio_sectors(bio) & (c->sb.block_size - 1)) {
390                 pr_debug("skipping unaligned io");
391                 goto skip;
392         }
393
394         if (bypass_torture_test(dc)) {
395                 if ((get_random_int() & 3) == 3)
396                         goto skip;
397                 else
398                         goto rescale;
399         }
400
401         if (!congested && !dc->sequential_cutoff)
402                 goto rescale;
403
404         spin_lock(&dc->io_lock);
405
406         hlist_for_each_entry(i, iohash(dc, bio->bi_iter.bi_sector), hash)
407                 if (i->last == bio->bi_iter.bi_sector &&
408                     time_before(jiffies, i->jiffies))
409                         goto found;
410
411         i = list_first_entry(&dc->io_lru, struct io, lru);
412
413         add_sequential(task);
414         i->sequential = 0;
415 found:
416         if (i->sequential + bio->bi_iter.bi_size > i->sequential)
417                 i->sequential   += bio->bi_iter.bi_size;
418
419         i->last                  = bio_end_sector(bio);
420         i->jiffies               = jiffies + msecs_to_jiffies(5000);
421         task->sequential_io      = i->sequential;
422
423         hlist_del(&i->hash);
424         hlist_add_head(&i->hash, iohash(dc, i->last));
425         list_move_tail(&i->lru, &dc->io_lru);
426
427         spin_unlock(&dc->io_lock);
428
429         sectors = max(task->sequential_io,
430                       task->sequential_io_avg) >> 9;
431
432         if (dc->sequential_cutoff &&
433             sectors >= dc->sequential_cutoff >> 9) {
434                 trace_bcache_bypass_sequential(bio);
435                 goto skip;
436         }
437
438         if (congested && sectors >= congested) {
439                 trace_bcache_bypass_congested(bio);
440                 goto skip;
441         }
442
443 rescale:
444         bch_rescale_priorities(c, bio_sectors(bio));
445         return false;
446 skip:
447         bch_mark_sectors_bypassed(c, dc, bio_sectors(bio));
448         return true;
449 }
450
451 /* Cache lookup */
452
453 struct search {
454         /* Stack frame for bio_complete */
455         struct closure          cl;
456
457         struct bbio             bio;
458         struct bio              *orig_bio;
459         struct bio              *cache_miss;
460         struct bcache_device    *d;
461
462         unsigned                insert_bio_sectors;
463         unsigned                recoverable:1;
464         unsigned                write:1;
465         unsigned                read_dirty_data:1;
466         unsigned                cache_missed:1;
467
468         unsigned long           start_time;
469
470         struct btree_op         op;
471         struct data_insert_op   iop;
472 };
473
474 static void bch_cache_read_endio(struct bio *bio)
475 {
476         struct bbio *b = container_of(bio, struct bbio, bio);
477         struct closure *cl = bio->bi_private;
478         struct search *s = container_of(cl, struct search, cl);
479
480         /*
481          * If the bucket was reused while our bio was in flight, we might have
482          * read the wrong data. Set s->error but not error so it doesn't get
483          * counted against the cache device, but we'll still reread the data
484          * from the backing device.
485          */
486
487         if (bio->bi_status)
488                 s->iop.status = bio->bi_status;
489         else if (!KEY_DIRTY(&b->key) &&
490                  ptr_stale(s->iop.c, &b->key, 0)) {
491                 atomic_long_inc(&s->iop.c->cache_read_races);
492                 s->iop.status = BLK_STS_IOERR;
493         }
494
495         bch_bbio_endio(s->iop.c, bio, bio->bi_status, "reading from cache");
496 }
497
498 /*
499  * Read from a single key, handling the initial cache miss if the key starts in
500  * the middle of the bio
501  */
502 static int cache_lookup_fn(struct btree_op *op, struct btree *b, struct bkey *k)
503 {
504         struct search *s = container_of(op, struct search, op);
505         struct bio *n, *bio = &s->bio.bio;
506         struct bkey *bio_key;
507         unsigned ptr;
508
509         if (bkey_cmp(k, &KEY(s->iop.inode, bio->bi_iter.bi_sector, 0)) <= 0)
510                 return MAP_CONTINUE;
511
512         if (KEY_INODE(k) != s->iop.inode ||
513             KEY_START(k) > bio->bi_iter.bi_sector) {
514                 unsigned bio_sectors = bio_sectors(bio);
515                 unsigned sectors = KEY_INODE(k) == s->iop.inode
516                         ? min_t(uint64_t, INT_MAX,
517                                 KEY_START(k) - bio->bi_iter.bi_sector)
518                         : INT_MAX;
519
520                 int ret = s->d->cache_miss(b, s, bio, sectors);
521                 if (ret != MAP_CONTINUE)
522                         return ret;
523
524                 /* if this was a complete miss we shouldn't get here */
525                 BUG_ON(bio_sectors <= sectors);
526         }
527
528         if (!KEY_SIZE(k))
529                 return MAP_CONTINUE;
530
531         /* XXX: figure out best pointer - for multiple cache devices */
532         ptr = 0;
533
534         PTR_BUCKET(b->c, k, ptr)->prio = INITIAL_PRIO;
535
536         if (KEY_DIRTY(k))
537                 s->read_dirty_data = true;
538
539         n = bio_next_split(bio, min_t(uint64_t, INT_MAX,
540                                       KEY_OFFSET(k) - bio->bi_iter.bi_sector),
541                            GFP_NOIO, s->d->bio_split);
542
543         bio_key = &container_of(n, struct bbio, bio)->key;
544         bch_bkey_copy_single_ptr(bio_key, k, ptr);
545
546         bch_cut_front(&KEY(s->iop.inode, n->bi_iter.bi_sector, 0), bio_key);
547         bch_cut_back(&KEY(s->iop.inode, bio_end_sector(n), 0), bio_key);
548
549         n->bi_end_io    = bch_cache_read_endio;
550         n->bi_private   = &s->cl;
551
552         /*
553          * The bucket we're reading from might be reused while our bio
554          * is in flight, and we could then end up reading the wrong
555          * data.
556          *
557          * We guard against this by checking (in cache_read_endio()) if
558          * the pointer is stale again; if so, we treat it as an error
559          * and reread from the backing device (but we don't pass that
560          * error up anywhere).
561          */
562
563         __bch_submit_bbio(n, b->c);
564         return n == bio ? MAP_DONE : MAP_CONTINUE;
565 }
566
567 static void cache_lookup(struct closure *cl)
568 {
569         struct search *s = container_of(cl, struct search, iop.cl);
570         struct bio *bio = &s->bio.bio;
571         struct cached_dev *dc;
572         int ret;
573
574         bch_btree_op_init(&s->op, -1);
575
576         ret = bch_btree_map_keys(&s->op, s->iop.c,
577                                  &KEY(s->iop.inode, bio->bi_iter.bi_sector, 0),
578                                  cache_lookup_fn, MAP_END_KEY);
579         if (ret == -EAGAIN) {
580                 continue_at(cl, cache_lookup, bcache_wq);
581                 return;
582         }
583
584         /*
585          * We might meet err when searching the btree, If that happens, we will
586          * get negative ret, in this scenario we should not recover data from
587          * backing device (when cache device is dirty) because we don't know
588          * whether bkeys the read request covered are all clean.
589          *
590          * And after that happened, s->iop.status is still its initial value
591          * before we submit s->bio.bio
592          */
593         if (ret < 0) {
594                 BUG_ON(ret == -EINTR);
595                 if (s->d && s->d->c &&
596                                 !UUID_FLASH_ONLY(&s->d->c->uuids[s->d->id])) {
597                         dc = container_of(s->d, struct cached_dev, disk);
598                         if (dc && atomic_read(&dc->has_dirty))
599                                 s->recoverable = false;
600                 }
601                 if (!s->iop.status)
602                         s->iop.status = BLK_STS_IOERR;
603         }
604
605         closure_return(cl);
606 }
607
608 /* Common code for the make_request functions */
609
610 static void request_endio(struct bio *bio)
611 {
612         struct closure *cl = bio->bi_private;
613
614         if (bio->bi_status) {
615                 struct search *s = container_of(cl, struct search, cl);
616                 s->iop.status = bio->bi_status;
617                 /* Only cache read errors are recoverable */
618                 s->recoverable = false;
619         }
620
621         bio_put(bio);
622         closure_put(cl);
623 }
624
625 static void bio_complete(struct search *s)
626 {
627         if (s->orig_bio) {
628                 struct request_queue *q = s->orig_bio->bi_disk->queue;
629                 generic_end_io_acct(q, bio_data_dir(s->orig_bio),
630                                     &s->d->disk->part0, s->start_time);
631
632                 trace_bcache_request_end(s->d, s->orig_bio);
633                 s->orig_bio->bi_status = s->iop.status;
634                 bio_endio(s->orig_bio);
635                 s->orig_bio = NULL;
636         }
637 }
638
639 static void do_bio_hook(struct search *s, struct bio *orig_bio)
640 {
641         struct bio *bio = &s->bio.bio;
642
643         bio_init(bio, NULL, 0);
644         __bio_clone_fast(bio, orig_bio);
645         bio->bi_end_io          = request_endio;
646         bio->bi_private         = &s->cl;
647
648         bio_cnt_set(bio, 3);
649 }
650
651 static void search_free(struct closure *cl)
652 {
653         struct search *s = container_of(cl, struct search, cl);
654
655         if (s->iop.bio)
656                 bio_put(s->iop.bio);
657
658         bio_complete(s);
659         closure_debug_destroy(cl);
660         mempool_free(s, s->d->c->search);
661 }
662
663 static inline struct search *search_alloc(struct bio *bio,
664                                           struct bcache_device *d)
665 {
666         struct search *s;
667
668         s = mempool_alloc(d->c->search, GFP_NOIO);
669
670         closure_init(&s->cl, NULL);
671         do_bio_hook(s, bio);
672
673         s->orig_bio             = bio;
674         s->cache_miss           = NULL;
675         s->cache_missed         = 0;
676         s->d                    = d;
677         s->recoverable          = 1;
678         s->write                = op_is_write(bio_op(bio));
679         s->read_dirty_data      = 0;
680         s->start_time           = jiffies;
681
682         s->iop.c                = d->c;
683         s->iop.bio              = NULL;
684         s->iop.inode            = d->id;
685         s->iop.write_point      = hash_long((unsigned long) current, 16);
686         s->iop.write_prio       = 0;
687         s->iop.status           = 0;
688         s->iop.flags            = 0;
689         s->iop.flush_journal    = op_is_flush(bio->bi_opf);
690         s->iop.wq               = bcache_wq;
691
692         return s;
693 }
694
695 /* Cached devices */
696
697 static void cached_dev_bio_complete(struct closure *cl)
698 {
699         struct search *s = container_of(cl, struct search, cl);
700         struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
701
702         search_free(cl);
703         cached_dev_put(dc);
704 }
705
706 /* Process reads */
707
708 static void cached_dev_cache_miss_done(struct closure *cl)
709 {
710         struct search *s = container_of(cl, struct search, cl);
711
712         if (s->iop.replace_collision)
713                 bch_mark_cache_miss_collision(s->iop.c, s->d);
714
715         if (s->iop.bio)
716                 bio_free_pages(s->iop.bio);
717
718         cached_dev_bio_complete(cl);
719 }
720
721 static void cached_dev_read_error(struct closure *cl)
722 {
723         struct search *s = container_of(cl, struct search, cl);
724         struct bio *bio = &s->bio.bio;
725
726         /*
727          * If read request hit dirty data (s->read_dirty_data is true),
728          * then recovery a failed read request from cached device may
729          * get a stale data back. So read failure recovery is only
730          * permitted when read request hit clean data in cache device,
731          * or when cache read race happened.
732          */
733         if (s->recoverable && !s->read_dirty_data) {
734                 /* Retry from the backing device: */
735                 trace_bcache_read_retry(s->orig_bio);
736
737                 s->iop.status = 0;
738                 do_bio_hook(s, s->orig_bio);
739
740                 /* XXX: invalidate cache */
741
742                 closure_bio_submit(bio, cl);
743         }
744
745         continue_at(cl, cached_dev_cache_miss_done, NULL);
746 }
747
748 static void cached_dev_read_done(struct closure *cl)
749 {
750         struct search *s = container_of(cl, struct search, cl);
751         struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
752
753         /*
754          * We had a cache miss; cache_bio now contains data ready to be inserted
755          * into the cache.
756          *
757          * First, we copy the data we just read from cache_bio's bounce buffers
758          * to the buffers the original bio pointed to:
759          */
760
761         if (s->iop.bio) {
762                 bio_reset(s->iop.bio);
763                 s->iop.bio->bi_iter.bi_sector = s->cache_miss->bi_iter.bi_sector;
764                 bio_copy_dev(s->iop.bio, s->cache_miss);
765                 s->iop.bio->bi_iter.bi_size = s->insert_bio_sectors << 9;
766                 bch_bio_map(s->iop.bio, NULL);
767
768                 bio_copy_data(s->cache_miss, s->iop.bio);
769
770                 bio_put(s->cache_miss);
771                 s->cache_miss = NULL;
772         }
773
774         if (verify(dc, &s->bio.bio) && s->recoverable && !s->read_dirty_data)
775                 bch_data_verify(dc, s->orig_bio);
776
777         bio_complete(s);
778
779         if (s->iop.bio &&
780             !test_bit(CACHE_SET_STOPPING, &s->iop.c->flags)) {
781                 BUG_ON(!s->iop.replace);
782                 closure_call(&s->iop.cl, bch_data_insert, NULL, cl);
783         }
784
785         continue_at(cl, cached_dev_cache_miss_done, NULL);
786 }
787
788 static void cached_dev_read_done_bh(struct closure *cl)
789 {
790         struct search *s = container_of(cl, struct search, cl);
791         struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
792
793         bch_mark_cache_accounting(s->iop.c, s->d,
794                                   !s->cache_missed, s->iop.bypass);
795         trace_bcache_read(s->orig_bio, !s->cache_missed, s->iop.bypass);
796
797         if (s->iop.status)
798                 continue_at_nobarrier(cl, cached_dev_read_error, bcache_wq);
799         else if (s->iop.bio || verify(dc, &s->bio.bio))
800                 continue_at_nobarrier(cl, cached_dev_read_done, bcache_wq);
801         else
802                 continue_at_nobarrier(cl, cached_dev_bio_complete, NULL);
803 }
804
805 static int cached_dev_cache_miss(struct btree *b, struct search *s,
806                                  struct bio *bio, unsigned sectors)
807 {
808         int ret = MAP_CONTINUE;
809         unsigned reada = 0;
810         struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
811         struct bio *miss, *cache_bio;
812
813         s->cache_missed = 1;
814
815         if (s->cache_miss || s->iop.bypass) {
816                 miss = bio_next_split(bio, sectors, GFP_NOIO, s->d->bio_split);
817                 ret = miss == bio ? MAP_DONE : MAP_CONTINUE;
818                 goto out_submit;
819         }
820
821         if (!(bio->bi_opf & REQ_RAHEAD) &&
822             !(bio->bi_opf & REQ_META) &&
823             s->iop.c->gc_stats.in_use < CUTOFF_CACHE_READA)
824                 reada = min_t(sector_t, dc->readahead >> 9,
825                               get_capacity(bio->bi_disk) - bio_end_sector(bio));
826
827         s->insert_bio_sectors = min(sectors, bio_sectors(bio) + reada);
828
829         s->iop.replace_key = KEY(s->iop.inode,
830                                  bio->bi_iter.bi_sector + s->insert_bio_sectors,
831                                  s->insert_bio_sectors);
832
833         ret = bch_btree_insert_check_key(b, &s->op, &s->iop.replace_key);
834         if (ret)
835                 return ret;
836
837         s->iop.replace = true;
838
839         miss = bio_next_split(bio, sectors, GFP_NOIO, s->d->bio_split);
840
841         /* btree_search_recurse()'s btree iterator is no good anymore */
842         ret = miss == bio ? MAP_DONE : -EINTR;
843
844         cache_bio = bio_alloc_bioset(GFP_NOWAIT,
845                         DIV_ROUND_UP(s->insert_bio_sectors, PAGE_SECTORS),
846                         dc->disk.bio_split);
847         if (!cache_bio)
848                 goto out_submit;
849
850         cache_bio->bi_iter.bi_sector    = miss->bi_iter.bi_sector;
851         bio_copy_dev(cache_bio, miss);
852         cache_bio->bi_iter.bi_size      = s->insert_bio_sectors << 9;
853
854         cache_bio->bi_end_io    = request_endio;
855         cache_bio->bi_private   = &s->cl;
856
857         bch_bio_map(cache_bio, NULL);
858         if (bio_alloc_pages(cache_bio, __GFP_NOWARN|GFP_NOIO))
859                 goto out_put;
860
861         if (reada)
862                 bch_mark_cache_readahead(s->iop.c, s->d);
863
864         s->cache_miss   = miss;
865         s->iop.bio      = cache_bio;
866         bio_get(cache_bio);
867         closure_bio_submit(cache_bio, &s->cl);
868
869         return ret;
870 out_put:
871         bio_put(cache_bio);
872 out_submit:
873         miss->bi_end_io         = request_endio;
874         miss->bi_private        = &s->cl;
875         closure_bio_submit(miss, &s->cl);
876         return ret;
877 }
878
879 static void cached_dev_read(struct cached_dev *dc, struct search *s)
880 {
881         struct closure *cl = &s->cl;
882
883         closure_call(&s->iop.cl, cache_lookup, NULL, cl);
884         continue_at(cl, cached_dev_read_done_bh, NULL);
885 }
886
887 /* Process writes */
888
889 static void cached_dev_write_complete(struct closure *cl)
890 {
891         struct search *s = container_of(cl, struct search, cl);
892         struct cached_dev *dc = container_of(s->d, struct cached_dev, disk);
893
894         up_read_non_owner(&dc->writeback_lock);
895         cached_dev_bio_complete(cl);
896 }
897
898 static void cached_dev_write(struct cached_dev *dc, struct search *s)
899 {
900         struct closure *cl = &s->cl;
901         struct bio *bio = &s->bio.bio;
902         struct bkey start = KEY(dc->disk.id, bio->bi_iter.bi_sector, 0);
903         struct bkey end = KEY(dc->disk.id, bio_end_sector(bio), 0);
904
905         bch_keybuf_check_overlapping(&s->iop.c->moving_gc_keys, &start, &end);
906
907         down_read_non_owner(&dc->writeback_lock);
908         if (bch_keybuf_check_overlapping(&dc->writeback_keys, &start, &end)) {
909                 /*
910                  * We overlap with some dirty data undergoing background
911                  * writeback, force this write to writeback
912                  */
913                 s->iop.bypass = false;
914                 s->iop.writeback = true;
915         }
916
917         /*
918          * Discards aren't _required_ to do anything, so skipping if
919          * check_overlapping returned true is ok
920          *
921          * But check_overlapping drops dirty keys for which io hasn't started,
922          * so we still want to call it.
923          */
924         if (bio_op(bio) == REQ_OP_DISCARD)
925                 s->iop.bypass = true;
926
927         if (should_writeback(dc, s->orig_bio,
928                              cache_mode(dc, bio),
929                              s->iop.bypass)) {
930                 s->iop.bypass = false;
931                 s->iop.writeback = true;
932         }
933
934         if (s->iop.bypass) {
935                 s->iop.bio = s->orig_bio;
936                 bio_get(s->iop.bio);
937
938                 if ((bio_op(bio) != REQ_OP_DISCARD) ||
939                     blk_queue_discard(bdev_get_queue(dc->bdev)))
940                         closure_bio_submit(bio, cl);
941         } else if (s->iop.writeback) {
942                 bch_writeback_add(dc);
943                 s->iop.bio = bio;
944
945                 if (bio->bi_opf & REQ_PREFLUSH) {
946                         /* Also need to send a flush to the backing device */
947                         struct bio *flush = bio_alloc_bioset(GFP_NOIO, 0,
948                                                              dc->disk.bio_split);
949
950                         bio_copy_dev(flush, bio);
951                         flush->bi_end_io = request_endio;
952                         flush->bi_private = cl;
953                         flush->bi_opf = REQ_OP_WRITE | REQ_PREFLUSH;
954
955                         closure_bio_submit(flush, cl);
956                 }
957         } else {
958                 s->iop.bio = bio_clone_fast(bio, GFP_NOIO, dc->disk.bio_split);
959
960                 closure_bio_submit(bio, cl);
961         }
962
963         closure_call(&s->iop.cl, bch_data_insert, NULL, cl);
964         continue_at(cl, cached_dev_write_complete, NULL);
965 }
966
967 static void cached_dev_nodata(struct closure *cl)
968 {
969         struct search *s = container_of(cl, struct search, cl);
970         struct bio *bio = &s->bio.bio;
971
972         if (s->iop.flush_journal)
973                 bch_journal_meta(s->iop.c, cl);
974
975         /* If it's a flush, we send the flush to the backing device too */
976         closure_bio_submit(bio, cl);
977
978         continue_at(cl, cached_dev_bio_complete, NULL);
979 }
980
981 /* Cached devices - read & write stuff */
982
983 static blk_qc_t cached_dev_make_request(struct request_queue *q,
984                                         struct bio *bio)
985 {
986         struct search *s;
987         struct bcache_device *d = bio->bi_disk->private_data;
988         struct cached_dev *dc = container_of(d, struct cached_dev, disk);
989         int rw = bio_data_dir(bio);
990
991         generic_start_io_acct(q, rw, bio_sectors(bio), &d->disk->part0);
992
993         bio_set_dev(bio, dc->bdev);
994         bio->bi_iter.bi_sector += dc->sb.data_offset;
995
996         if (cached_dev_get(dc)) {
997                 s = search_alloc(bio, d);
998                 trace_bcache_request_start(s->d, bio);
999
1000                 if (!bio->bi_iter.bi_size) {
1001                         /*
1002                          * can't call bch_journal_meta from under
1003                          * generic_make_request
1004                          */
1005                         continue_at_nobarrier(&s->cl,
1006                                               cached_dev_nodata,
1007                                               bcache_wq);
1008                 } else {
1009                         s->iop.bypass = check_should_bypass(dc, bio);
1010
1011                         if (rw)
1012                                 cached_dev_write(dc, s);
1013                         else
1014                                 cached_dev_read(dc, s);
1015                 }
1016         } else {
1017                 if ((bio_op(bio) == REQ_OP_DISCARD) &&
1018                     !blk_queue_discard(bdev_get_queue(dc->bdev)))
1019                         bio_endio(bio);
1020                 else
1021                         generic_make_request(bio);
1022         }
1023
1024         return BLK_QC_T_NONE;
1025 }
1026
1027 static int cached_dev_ioctl(struct bcache_device *d, fmode_t mode,
1028                             unsigned int cmd, unsigned long arg)
1029 {
1030         struct cached_dev *dc = container_of(d, struct cached_dev, disk);
1031         return __blkdev_driver_ioctl(dc->bdev, mode, cmd, arg);
1032 }
1033
1034 static int cached_dev_congested(void *data, int bits)
1035 {
1036         struct bcache_device *d = data;
1037         struct cached_dev *dc = container_of(d, struct cached_dev, disk);
1038         struct request_queue *q = bdev_get_queue(dc->bdev);
1039         int ret = 0;
1040
1041         if (bdi_congested(q->backing_dev_info, bits))
1042                 return 1;
1043
1044         if (cached_dev_get(dc)) {
1045                 unsigned i;
1046                 struct cache *ca;
1047
1048                 for_each_cache(ca, d->c, i) {
1049                         q = bdev_get_queue(ca->bdev);
1050                         ret |= bdi_congested(q->backing_dev_info, bits);
1051                 }
1052
1053                 cached_dev_put(dc);
1054         }
1055
1056         return ret;
1057 }
1058
1059 void bch_cached_dev_request_init(struct cached_dev *dc)
1060 {
1061         struct gendisk *g = dc->disk.disk;
1062
1063         g->queue->make_request_fn               = cached_dev_make_request;
1064         g->queue->backing_dev_info->congested_fn = cached_dev_congested;
1065         dc->disk.cache_miss                     = cached_dev_cache_miss;
1066         dc->disk.ioctl                          = cached_dev_ioctl;
1067 }
1068
1069 /* Flash backed devices */
1070
1071 static int flash_dev_cache_miss(struct btree *b, struct search *s,
1072                                 struct bio *bio, unsigned sectors)
1073 {
1074         unsigned bytes = min(sectors, bio_sectors(bio)) << 9;
1075
1076         swap(bio->bi_iter.bi_size, bytes);
1077         zero_fill_bio(bio);
1078         swap(bio->bi_iter.bi_size, bytes);
1079
1080         bio_advance(bio, bytes);
1081
1082         if (!bio->bi_iter.bi_size)
1083                 return MAP_DONE;
1084
1085         return MAP_CONTINUE;
1086 }
1087
1088 static void flash_dev_nodata(struct closure *cl)
1089 {
1090         struct search *s = container_of(cl, struct search, cl);
1091
1092         if (s->iop.flush_journal)
1093                 bch_journal_meta(s->iop.c, cl);
1094
1095         continue_at(cl, search_free, NULL);
1096 }
1097
1098 static blk_qc_t flash_dev_make_request(struct request_queue *q,
1099                                              struct bio *bio)
1100 {
1101         struct search *s;
1102         struct closure *cl;
1103         struct bcache_device *d = bio->bi_disk->private_data;
1104         int rw = bio_data_dir(bio);
1105
1106         generic_start_io_acct(q, rw, bio_sectors(bio), &d->disk->part0);
1107
1108         s = search_alloc(bio, d);
1109         cl = &s->cl;
1110         bio = &s->bio.bio;
1111
1112         trace_bcache_request_start(s->d, bio);
1113
1114         if (!bio->bi_iter.bi_size) {
1115                 /*
1116                  * can't call bch_journal_meta from under
1117                  * generic_make_request
1118                  */
1119                 continue_at_nobarrier(&s->cl,
1120                                       flash_dev_nodata,
1121                                       bcache_wq);
1122                 return BLK_QC_T_NONE;
1123         } else if (rw) {
1124                 bch_keybuf_check_overlapping(&s->iop.c->moving_gc_keys,
1125                                         &KEY(d->id, bio->bi_iter.bi_sector, 0),
1126                                         &KEY(d->id, bio_end_sector(bio), 0));
1127
1128                 s->iop.bypass           = (bio_op(bio) == REQ_OP_DISCARD) != 0;
1129                 s->iop.writeback        = true;
1130                 s->iop.bio              = bio;
1131
1132                 closure_call(&s->iop.cl, bch_data_insert, NULL, cl);
1133         } else {
1134                 closure_call(&s->iop.cl, cache_lookup, NULL, cl);
1135         }
1136
1137         continue_at(cl, search_free, NULL);
1138         return BLK_QC_T_NONE;
1139 }
1140
1141 static int flash_dev_ioctl(struct bcache_device *d, fmode_t mode,
1142                            unsigned int cmd, unsigned long arg)
1143 {
1144         return -ENOTTY;
1145 }
1146
1147 static int flash_dev_congested(void *data, int bits)
1148 {
1149         struct bcache_device *d = data;
1150         struct request_queue *q;
1151         struct cache *ca;
1152         unsigned i;
1153         int ret = 0;
1154
1155         for_each_cache(ca, d->c, i) {
1156                 q = bdev_get_queue(ca->bdev);
1157                 ret |= bdi_congested(q->backing_dev_info, bits);
1158         }
1159
1160         return ret;
1161 }
1162
1163 void bch_flash_dev_request_init(struct bcache_device *d)
1164 {
1165         struct gendisk *g = d->disk;
1166
1167         g->queue->make_request_fn               = flash_dev_make_request;
1168         g->queue->backing_dev_info->congested_fn = flash_dev_congested;
1169         d->cache_miss                           = flash_dev_cache_miss;
1170         d->ioctl                                = flash_dev_ioctl;
1171 }
1172
1173 void bch_request_exit(void)
1174 {
1175         if (bch_search_cache)
1176                 kmem_cache_destroy(bch_search_cache);
1177 }
1178
1179 int __init bch_request_init(void)
1180 {
1181         bch_search_cache = KMEM_CACHE(search, 0);
1182         if (!bch_search_cache)
1183                 return -ENOMEM;
1184
1185         return 0;
1186 }