]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/io.c
8add8ccd129dade398cffe98d053cb983e97e0fd
[bcachefs-tools-debian] / libbcachefs / io.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Some low level IO code, and hacks for various block layer limitations
4  *
5  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6  * Copyright 2012 Google, Inc.
7  */
8
9 #include "bcachefs.h"
10 #include "alloc_background.h"
11 #include "alloc_foreground.h"
12 #include "bkey_on_stack.h"
13 #include "bset.h"
14 #include "btree_update.h"
15 #include "buckets.h"
16 #include "checksum.h"
17 #include "compress.h"
18 #include "clock.h"
19 #include "debug.h"
20 #include "disk_groups.h"
21 #include "ec.h"
22 #include "error.h"
23 #include "extent_update.h"
24 #include "inode.h"
25 #include "io.h"
26 #include "journal.h"
27 #include "keylist.h"
28 #include "move.h"
29 #include "rebalance.h"
30 #include "super.h"
31 #include "super-io.h"
32
33 #include <linux/blkdev.h>
34 #include <linux/random.h>
35 #include <linux/sched/mm.h>
36
37 #include <trace/events/bcachefs.h>
38
39 const char *bch2_blk_status_to_str(blk_status_t status)
40 {
41         if (status == BLK_STS_REMOVED)
42                 return "device removed";
43         return blk_status_to_str(status);
44 }
45
46 static bool bch2_target_congested(struct bch_fs *c, u16 target)
47 {
48         const struct bch_devs_mask *devs;
49         unsigned d, nr = 0, total = 0;
50         u64 now = local_clock(), last;
51         s64 congested;
52         struct bch_dev *ca;
53
54         if (!target)
55                 return false;
56
57         rcu_read_lock();
58         devs = bch2_target_to_mask(c, target) ?:
59                 &c->rw_devs[BCH_DATA_user];
60
61         for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
62                 ca = rcu_dereference(c->devs[d]);
63                 if (!ca)
64                         continue;
65
66                 congested = atomic_read(&ca->congested);
67                 last = READ_ONCE(ca->congested_last);
68                 if (time_after64(now, last))
69                         congested -= (now - last) >> 12;
70
71                 total += max(congested, 0LL);
72                 nr++;
73         }
74         rcu_read_unlock();
75
76         return bch2_rand_range(nr * CONGESTED_MAX) < total;
77 }
78
79 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
80                                        u64 now, int rw)
81 {
82         u64 latency_capable =
83                 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
84         /* ideally we'd be taking into account the device's variance here: */
85         u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
86         s64 latency_over = io_latency - latency_threshold;
87
88         if (latency_threshold && latency_over > 0) {
89                 /*
90                  * bump up congested by approximately latency_over * 4 /
91                  * latency_threshold - we don't need much accuracy here so don't
92                  * bother with the divide:
93                  */
94                 if (atomic_read(&ca->congested) < CONGESTED_MAX)
95                         atomic_add(latency_over >>
96                                    max_t(int, ilog2(latency_threshold) - 2, 0),
97                                    &ca->congested);
98
99                 ca->congested_last = now;
100         } else if (atomic_read(&ca->congested) > 0) {
101                 atomic_dec(&ca->congested);
102         }
103 }
104
105 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
106 {
107         atomic64_t *latency = &ca->cur_latency[rw];
108         u64 now = local_clock();
109         u64 io_latency = time_after64(now, submit_time)
110                 ? now - submit_time
111                 : 0;
112         u64 old, new, v = atomic64_read(latency);
113
114         do {
115                 old = v;
116
117                 /*
118                  * If the io latency was reasonably close to the current
119                  * latency, skip doing the update and atomic operation - most of
120                  * the time:
121                  */
122                 if (abs((int) (old - io_latency)) < (old >> 1) &&
123                     now & ~(~0 << 5))
124                         break;
125
126                 new = ewma_add(old, io_latency, 5);
127         } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
128
129         bch2_congested_acct(ca, io_latency, now, rw);
130
131         __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
132 }
133
134 /* Allocate, free from mempool: */
135
136 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
137 {
138         struct bvec_iter_all iter;
139         struct bio_vec *bv;
140
141         bio_for_each_segment_all(bv, bio, iter)
142                 if (bv->bv_page != ZERO_PAGE(0))
143                         mempool_free(bv->bv_page, &c->bio_bounce_pages);
144         bio->bi_vcnt = 0;
145 }
146
147 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
148 {
149         struct page *page;
150
151         if (likely(!*using_mempool)) {
152                 page = alloc_page(GFP_NOIO);
153                 if (unlikely(!page)) {
154                         mutex_lock(&c->bio_bounce_pages_lock);
155                         *using_mempool = true;
156                         goto pool_alloc;
157
158                 }
159         } else {
160 pool_alloc:
161                 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
162         }
163
164         return page;
165 }
166
167 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
168                                size_t size)
169 {
170         bool using_mempool = false;
171
172         while (size) {
173                 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
174                 unsigned len = min(PAGE_SIZE, size);
175
176                 BUG_ON(!bio_add_page(bio, page, len, 0));
177                 size -= len;
178         }
179
180         if (using_mempool)
181                 mutex_unlock(&c->bio_bounce_pages_lock);
182 }
183
184 /* Extent update path: */
185
186 static int sum_sector_overwrites(struct btree_trans *trans,
187                                  struct btree_iter *extent_iter,
188                                  struct bkey_i *new,
189                                  bool may_allocate,
190                                  bool *maybe_extending,
191                                  s64 *delta)
192 {
193         struct btree_iter *iter;
194         struct bkey_s_c old;
195         int ret = 0;
196
197         *maybe_extending = true;
198         *delta = 0;
199
200         iter = bch2_trans_copy_iter(trans, extent_iter);
201         if (IS_ERR(iter))
202                 return PTR_ERR(iter);
203
204         for_each_btree_key_continue(iter, BTREE_ITER_SLOTS, old, ret) {
205                 if (!may_allocate &&
206                     bch2_bkey_nr_ptrs_fully_allocated(old) <
207                     bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new))) {
208                         ret = -ENOSPC;
209                         break;
210                 }
211
212                 *delta += (min(new->k.p.offset,
213                               old.k->p.offset) -
214                           max(bkey_start_offset(&new->k),
215                               bkey_start_offset(old.k))) *
216                         (bkey_extent_is_allocation(&new->k) -
217                          bkey_extent_is_allocation(old.k));
218
219                 if (bkey_cmp(old.k->p, new->k.p) >= 0) {
220                         /*
221                          * Check if there's already data above where we're
222                          * going to be writing to - this means we're definitely
223                          * not extending the file:
224                          *
225                          * Note that it's not sufficient to check if there's
226                          * data up to the sector offset we're going to be
227                          * writing to, because i_size could be up to one block
228                          * less:
229                          */
230                         if (!bkey_cmp(old.k->p, new->k.p))
231                                 old = bch2_btree_iter_next(iter);
232
233                         if (old.k && !bkey_err(old) &&
234                             old.k->p.inode == extent_iter->pos.inode &&
235                             bkey_extent_is_data(old.k))
236                                 *maybe_extending = false;
237
238                         break;
239                 }
240         }
241
242         bch2_trans_iter_put(trans, iter);
243         return ret;
244 }
245
246 int bch2_extent_update(struct btree_trans *trans,
247                        struct btree_iter *iter,
248                        struct bkey_i *k,
249                        struct disk_reservation *disk_res,
250                        u64 *journal_seq,
251                        u64 new_i_size,
252                        s64 *i_sectors_delta)
253 {
254         /* this must live until after bch2_trans_commit(): */
255         struct bkey_inode_buf inode_p;
256         bool extending = false;
257         s64 delta = 0;
258         int ret;
259
260         ret = bch2_extent_trim_atomic(k, iter);
261         if (ret)
262                 return ret;
263
264         ret = sum_sector_overwrites(trans, iter, k,
265                         disk_res && disk_res->sectors != 0,
266                         &extending, &delta);
267         if (ret)
268                 return ret;
269
270         new_i_size = extending
271                 ? min(k->k.p.offset << 9, new_i_size)
272                 : 0;
273
274         if (delta || new_i_size) {
275                 struct btree_iter *inode_iter;
276                 struct bch_inode_unpacked inode_u;
277
278                 inode_iter = bch2_inode_peek(trans, &inode_u,
279                                 k->k.p.inode, BTREE_ITER_INTENT);
280                 if (IS_ERR(inode_iter))
281                         return PTR_ERR(inode_iter);
282
283                 /*
284                  * XXX:
285                  * writeback can race a bit with truncate, because truncate
286                  * first updates the inode then truncates the pagecache. This is
287                  * ugly, but lets us preserve the invariant that the in memory
288                  * i_size is always >= the on disk i_size.
289                  *
290                 BUG_ON(new_i_size > inode_u.bi_size &&
291                        (inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY));
292                  */
293                 BUG_ON(new_i_size > inode_u.bi_size && !extending);
294
295                 if (!(inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
296                     new_i_size > inode_u.bi_size)
297                         inode_u.bi_size = new_i_size;
298                 else
299                         new_i_size = 0;
300
301                 inode_u.bi_sectors += delta;
302
303                 if (delta || new_i_size) {
304                         bch2_inode_pack(&inode_p, &inode_u);
305                         bch2_trans_update(trans, inode_iter,
306                                           &inode_p.inode.k_i, 0);
307                 }
308
309                 bch2_trans_iter_put(trans, inode_iter);
310         }
311
312         bch2_trans_update(trans, iter, k, 0);
313
314         ret = bch2_trans_commit(trans, disk_res, journal_seq,
315                                 BTREE_INSERT_NOCHECK_RW|
316                                 BTREE_INSERT_NOFAIL|
317                                 BTREE_INSERT_USE_RESERVE);
318         if (!ret && i_sectors_delta)
319                 *i_sectors_delta += delta;
320
321         return ret;
322 }
323
324 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
325                    struct bpos end, u64 *journal_seq,
326                    s64 *i_sectors_delta)
327 {
328         struct bch_fs *c        = trans->c;
329         unsigned max_sectors    = KEY_SIZE_MAX & (~0 << c->block_bits);
330         struct bkey_s_c k;
331         int ret = 0, ret2 = 0;
332
333         while ((k = bch2_btree_iter_peek(iter)).k &&
334                bkey_cmp(iter->pos, end) < 0) {
335                 struct disk_reservation disk_res =
336                         bch2_disk_reservation_init(c, 0);
337                 struct bkey_i delete;
338
339                 bch2_trans_begin(trans);
340
341                 ret = bkey_err(k);
342                 if (ret)
343                         goto btree_err;
344
345                 bkey_init(&delete.k);
346                 delete.k.p = iter->pos;
347
348                 /* create the biggest key we can */
349                 bch2_key_resize(&delete.k, max_sectors);
350                 bch2_cut_back(end, &delete);
351
352                 ret = bch2_extent_update(trans, iter, &delete,
353                                 &disk_res, journal_seq,
354                                 0, i_sectors_delta);
355                 bch2_disk_reservation_put(c, &disk_res);
356 btree_err:
357                 if (ret == -EINTR) {
358                         ret2 = ret;
359                         ret = 0;
360                 }
361                 if (ret)
362                         break;
363         }
364
365         if (bkey_cmp(iter->pos, end) > 0) {
366                 bch2_btree_iter_set_pos(iter, end);
367                 ret = bch2_btree_iter_traverse(iter);
368         }
369
370         return ret ?: ret2;
371 }
372
373 int bch2_fpunch(struct bch_fs *c, u64 inum, u64 start, u64 end,
374                 u64 *journal_seq, s64 *i_sectors_delta)
375 {
376         struct btree_trans trans;
377         struct btree_iter *iter;
378         int ret = 0;
379
380         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
381         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
382                                    POS(inum, start),
383                                    BTREE_ITER_INTENT);
384
385         ret = bch2_fpunch_at(&trans, iter, POS(inum, end),
386                              journal_seq, i_sectors_delta);
387         bch2_trans_exit(&trans);
388
389         if (ret == -EINTR)
390                 ret = 0;
391
392         return ret;
393 }
394
395 int bch2_write_index_default(struct bch_write_op *op)
396 {
397         struct bch_fs *c = op->c;
398         struct bkey_on_stack sk;
399         struct keylist *keys = &op->insert_keys;
400         struct bkey_i *k = bch2_keylist_front(keys);
401         struct btree_trans trans;
402         struct btree_iter *iter;
403         int ret;
404
405         bkey_on_stack_init(&sk);
406         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
407
408         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
409                                    bkey_start_pos(&k->k),
410                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
411
412         do {
413                 bch2_trans_begin(&trans);
414
415                 k = bch2_keylist_front(keys);
416
417                 bkey_on_stack_realloc(&sk, c, k->k.u64s);
418                 bkey_copy(sk.k, k);
419                 bch2_cut_front(iter->pos, sk.k);
420
421                 ret = bch2_extent_update(&trans, iter, sk.k,
422                                          &op->res, op_journal_seq(op),
423                                          op->new_i_size, &op->i_sectors_delta);
424                 if (ret == -EINTR)
425                         continue;
426                 if (ret)
427                         break;
428
429                 if (bkey_cmp(iter->pos, k->k.p) >= 0)
430                         bch2_keylist_pop_front(keys);
431         } while (!bch2_keylist_empty(keys));
432
433         bch2_trans_exit(&trans);
434         bkey_on_stack_exit(&sk, c);
435
436         return ret;
437 }
438
439 /* Writes */
440
441 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
442                                enum bch_data_type type,
443                                const struct bkey_i *k)
444 {
445         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
446         const struct bch_extent_ptr *ptr;
447         struct bch_write_bio *n;
448         struct bch_dev *ca;
449
450         BUG_ON(c->opts.nochanges);
451
452         bkey_for_each_ptr(ptrs, ptr) {
453                 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
454                        !c->devs[ptr->dev]);
455
456                 ca = bch_dev_bkey_exists(c, ptr->dev);
457
458                 if (to_entry(ptr + 1) < ptrs.end) {
459                         n = to_wbio(bio_clone_fast(&wbio->bio, GFP_NOIO,
460                                                    &ca->replica_set));
461
462                         n->bio.bi_end_io        = wbio->bio.bi_end_io;
463                         n->bio.bi_private       = wbio->bio.bi_private;
464                         n->parent               = wbio;
465                         n->split                = true;
466                         n->bounce               = false;
467                         n->put_bio              = true;
468                         n->bio.bi_opf           = wbio->bio.bi_opf;
469                         bio_inc_remaining(&wbio->bio);
470                 } else {
471                         n = wbio;
472                         n->split                = false;
473                 }
474
475                 n->c                    = c;
476                 n->dev                  = ptr->dev;
477                 n->have_ioref           = bch2_dev_get_ioref(ca,
478                                         type == BCH_DATA_btree ? READ : WRITE);
479                 n->submit_time          = local_clock();
480                 n->bio.bi_iter.bi_sector = ptr->offset;
481
482                 if (!journal_flushes_device(ca))
483                         n->bio.bi_opf |= REQ_FUA;
484
485                 if (likely(n->have_ioref)) {
486                         this_cpu_add(ca->io_done->sectors[WRITE][type],
487                                      bio_sectors(&n->bio));
488
489                         bio_set_dev(&n->bio, ca->disk_sb.bdev);
490                         submit_bio(&n->bio);
491                 } else {
492                         n->bio.bi_status        = BLK_STS_REMOVED;
493                         bio_endio(&n->bio);
494                 }
495         }
496 }
497
498 static void __bch2_write(struct closure *);
499
500 static void bch2_write_done(struct closure *cl)
501 {
502         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
503         struct bch_fs *c = op->c;
504
505         if (!op->error && (op->flags & BCH_WRITE_FLUSH))
506                 op->error = bch2_journal_error(&c->journal);
507
508         bch2_disk_reservation_put(c, &op->res);
509         percpu_ref_put(&c->writes);
510         bch2_keylist_free(&op->insert_keys, op->inline_keys);
511
512         bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
513
514         if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
515                 up(&c->io_in_flight);
516
517         if (op->end_io) {
518                 EBUG_ON(cl->parent);
519                 closure_debug_destroy(cl);
520                 op->end_io(op);
521         } else {
522                 closure_return(cl);
523         }
524 }
525
526 /**
527  * bch_write_index - after a write, update index to point to new data
528  */
529 static void __bch2_write_index(struct bch_write_op *op)
530 {
531         struct bch_fs *c = op->c;
532         struct keylist *keys = &op->insert_keys;
533         struct bch_extent_ptr *ptr;
534         struct bkey_i *src, *dst = keys->keys, *n, *k;
535         unsigned dev;
536         int ret;
537
538         for (src = keys->keys; src != keys->top; src = n) {
539                 n = bkey_next(src);
540
541                 if (bkey_extent_is_direct_data(&src->k)) {
542                         bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
543                                             test_bit(ptr->dev, op->failed.d));
544
545                         if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src))) {
546                                 ret = -EIO;
547                                 goto err;
548                         }
549                 }
550
551                 if (dst != src)
552                         memmove_u64s_down(dst, src, src->u64s);
553                 dst = bkey_next(dst);
554         }
555
556         keys->top = dst;
557
558         /*
559          * probably not the ideal place to hook this in, but I don't
560          * particularly want to plumb io_opts all the way through the btree
561          * update stack right now
562          */
563         for_each_keylist_key(keys, k) {
564                 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
565
566                 if (bch2_bkey_is_incompressible(bkey_i_to_s_c(k)))
567                         bch2_check_set_feature(op->c, BCH_FEATURE_incompressible);
568
569         }
570
571         if (!bch2_keylist_empty(keys)) {
572                 u64 sectors_start = keylist_sectors(keys);
573                 int ret = op->index_update_fn(op);
574
575                 BUG_ON(ret == -EINTR);
576                 BUG_ON(keylist_sectors(keys) && !ret);
577
578                 op->written += sectors_start - keylist_sectors(keys);
579
580                 if (ret) {
581                         __bcache_io_error(c, "btree IO error %i", ret);
582                         op->error = ret;
583                 }
584         }
585 out:
586         /* If some a bucket wasn't written, we can't erasure code it: */
587         for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
588                 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
589
590         bch2_open_buckets_put(c, &op->open_buckets);
591         return;
592 err:
593         keys->top = keys->keys;
594         op->error = ret;
595         goto out;
596 }
597
598 static void bch2_write_index(struct closure *cl)
599 {
600         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
601         struct bch_fs *c = op->c;
602
603         __bch2_write_index(op);
604
605         if (!(op->flags & BCH_WRITE_DONE)) {
606                 continue_at(cl, __bch2_write, index_update_wq(op));
607         } else if (!op->error && (op->flags & BCH_WRITE_FLUSH)) {
608                 bch2_journal_flush_seq_async(&c->journal,
609                                              *op_journal_seq(op),
610                                              cl);
611                 continue_at(cl, bch2_write_done, index_update_wq(op));
612         } else {
613                 continue_at_nobarrier(cl, bch2_write_done, NULL);
614         }
615 }
616
617 static void bch2_write_endio(struct bio *bio)
618 {
619         struct closure *cl              = bio->bi_private;
620         struct bch_write_op *op         = container_of(cl, struct bch_write_op, cl);
621         struct bch_write_bio *wbio      = to_wbio(bio);
622         struct bch_write_bio *parent    = wbio->split ? wbio->parent : NULL;
623         struct bch_fs *c                = wbio->c;
624         struct bch_dev *ca              = bch_dev_bkey_exists(c, wbio->dev);
625
626         if (bch2_dev_io_err_on(bio->bi_status, ca, "data write: %s",
627                                bch2_blk_status_to_str(bio->bi_status)))
628                 set_bit(wbio->dev, op->failed.d);
629
630         if (wbio->have_ioref) {
631                 bch2_latency_acct(ca, wbio->submit_time, WRITE);
632                 percpu_ref_put(&ca->io_ref);
633         }
634
635         if (wbio->bounce)
636                 bch2_bio_free_pages_pool(c, bio);
637
638         if (wbio->put_bio)
639                 bio_put(bio);
640
641         if (parent)
642                 bio_endio(&parent->bio);
643         else if (!(op->flags & BCH_WRITE_SKIP_CLOSURE_PUT))
644                 closure_put(cl);
645         else
646                 continue_at_nobarrier(cl, bch2_write_index, index_update_wq(op));
647 }
648
649 static void init_append_extent(struct bch_write_op *op,
650                                struct write_point *wp,
651                                struct bversion version,
652                                struct bch_extent_crc_unpacked crc)
653 {
654         struct bch_fs *c = op->c;
655         struct bkey_i_extent *e;
656         struct open_bucket *ob;
657         unsigned i;
658
659         BUG_ON(crc.compressed_size > wp->sectors_free);
660         wp->sectors_free -= crc.compressed_size;
661         op->pos.offset += crc.uncompressed_size;
662
663         e = bkey_extent_init(op->insert_keys.top);
664         e->k.p          = op->pos;
665         e->k.size       = crc.uncompressed_size;
666         e->k.version    = version;
667
668         if (crc.csum_type ||
669             crc.compression_type ||
670             crc.nonce)
671                 bch2_extent_crc_append(&e->k_i, crc);
672
673         open_bucket_for_each(c, &wp->ptrs, ob, i) {
674                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
675                 union bch_extent_entry *end =
676                         bkey_val_end(bkey_i_to_s(&e->k_i));
677
678                 end->ptr = ob->ptr;
679                 end->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
680                 end->ptr.cached = !ca->mi.durability ||
681                         (op->flags & BCH_WRITE_CACHED) != 0;
682                 end->ptr.offset += ca->mi.bucket_size - ob->sectors_free;
683
684                 e->k.u64s++;
685
686                 BUG_ON(crc.compressed_size > ob->sectors_free);
687                 ob->sectors_free -= crc.compressed_size;
688         }
689
690         bch2_keylist_push(&op->insert_keys);
691 }
692
693 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
694                                         struct write_point *wp,
695                                         struct bio *src,
696                                         bool *page_alloc_failed,
697                                         void *buf)
698 {
699         struct bch_write_bio *wbio;
700         struct bio *bio;
701         unsigned output_available =
702                 min(wp->sectors_free << 9, src->bi_iter.bi_size);
703         unsigned pages = DIV_ROUND_UP(output_available +
704                                       (buf
705                                        ? ((unsigned long) buf & (PAGE_SIZE - 1))
706                                        : 0), PAGE_SIZE);
707
708         bio = bio_alloc_bioset(GFP_NOIO, pages, &c->bio_write);
709         wbio                    = wbio_init(bio);
710         wbio->put_bio           = true;
711         /* copy WRITE_SYNC flag */
712         wbio->bio.bi_opf        = src->bi_opf;
713
714         if (buf) {
715                 bch2_bio_map(bio, buf, output_available);
716                 return bio;
717         }
718
719         wbio->bounce            = true;
720
721         /*
722          * We can't use mempool for more than c->sb.encoded_extent_max
723          * worth of pages, but we'd like to allocate more if we can:
724          */
725         bch2_bio_alloc_pages_pool(c, bio,
726                                   min_t(unsigned, output_available,
727                                         c->sb.encoded_extent_max << 9));
728
729         if (bio->bi_iter.bi_size < output_available)
730                 *page_alloc_failed =
731                         bch2_bio_alloc_pages(bio,
732                                              output_available -
733                                              bio->bi_iter.bi_size,
734                                              GFP_NOFS) != 0;
735
736         return bio;
737 }
738
739 static int bch2_write_rechecksum(struct bch_fs *c,
740                                  struct bch_write_op *op,
741                                  unsigned new_csum_type)
742 {
743         struct bio *bio = &op->wbio.bio;
744         struct bch_extent_crc_unpacked new_crc;
745         int ret;
746
747         /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
748
749         if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
750             bch2_csum_type_is_encryption(new_csum_type))
751                 new_csum_type = op->crc.csum_type;
752
753         ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
754                                   NULL, &new_crc,
755                                   op->crc.offset, op->crc.live_size,
756                                   new_csum_type);
757         if (ret)
758                 return ret;
759
760         bio_advance(bio, op->crc.offset << 9);
761         bio->bi_iter.bi_size = op->crc.live_size << 9;
762         op->crc = new_crc;
763         return 0;
764 }
765
766 static int bch2_write_decrypt(struct bch_write_op *op)
767 {
768         struct bch_fs *c = op->c;
769         struct nonce nonce = extent_nonce(op->version, op->crc);
770         struct bch_csum csum;
771
772         if (!bch2_csum_type_is_encryption(op->crc.csum_type))
773                 return 0;
774
775         /*
776          * If we need to decrypt data in the write path, we'll no longer be able
777          * to verify the existing checksum (poly1305 mac, in this case) after
778          * it's decrypted - this is the last point we'll be able to reverify the
779          * checksum:
780          */
781         csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
782         if (bch2_crc_cmp(op->crc.csum, csum))
783                 return -EIO;
784
785         bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
786         op->crc.csum_type = 0;
787         op->crc.csum = (struct bch_csum) { 0, 0 };
788         return 0;
789 }
790
791 static enum prep_encoded_ret {
792         PREP_ENCODED_OK,
793         PREP_ENCODED_ERR,
794         PREP_ENCODED_CHECKSUM_ERR,
795         PREP_ENCODED_DO_WRITE,
796 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
797 {
798         struct bch_fs *c = op->c;
799         struct bio *bio = &op->wbio.bio;
800
801         if (!(op->flags & BCH_WRITE_DATA_ENCODED))
802                 return PREP_ENCODED_OK;
803
804         BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
805
806         /* Can we just write the entire extent as is? */
807         if (op->crc.uncompressed_size == op->crc.live_size &&
808             op->crc.compressed_size <= wp->sectors_free &&
809             (op->crc.compression_type == op->compression_type ||
810              op->incompressible)) {
811                 if (!crc_is_compressed(op->crc) &&
812                     op->csum_type != op->crc.csum_type &&
813                     bch2_write_rechecksum(c, op, op->csum_type))
814                         return PREP_ENCODED_CHECKSUM_ERR;
815
816                 return PREP_ENCODED_DO_WRITE;
817         }
818
819         /*
820          * If the data is compressed and we couldn't write the entire extent as
821          * is, we have to decompress it:
822          */
823         if (crc_is_compressed(op->crc)) {
824                 struct bch_csum csum;
825
826                 if (bch2_write_decrypt(op))
827                         return PREP_ENCODED_CHECKSUM_ERR;
828
829                 /* Last point we can still verify checksum: */
830                 csum = bch2_checksum_bio(c, op->crc.csum_type,
831                                          extent_nonce(op->version, op->crc),
832                                          bio);
833                 if (bch2_crc_cmp(op->crc.csum, csum))
834                         return PREP_ENCODED_CHECKSUM_ERR;
835
836                 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
837                         return PREP_ENCODED_ERR;
838         }
839
840         /*
841          * No longer have compressed data after this point - data might be
842          * encrypted:
843          */
844
845         /*
846          * If the data is checksummed and we're only writing a subset,
847          * rechecksum and adjust bio to point to currently live data:
848          */
849         if ((op->crc.live_size != op->crc.uncompressed_size ||
850              op->crc.csum_type != op->csum_type) &&
851             bch2_write_rechecksum(c, op, op->csum_type))
852                 return PREP_ENCODED_CHECKSUM_ERR;
853
854         /*
855          * If we want to compress the data, it has to be decrypted:
856          */
857         if ((op->compression_type ||
858              bch2_csum_type_is_encryption(op->crc.csum_type) !=
859              bch2_csum_type_is_encryption(op->csum_type)) &&
860             bch2_write_decrypt(op))
861                 return PREP_ENCODED_CHECKSUM_ERR;
862
863         return PREP_ENCODED_OK;
864 }
865
866 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
867                              struct bio **_dst)
868 {
869         struct bch_fs *c = op->c;
870         struct bio *src = &op->wbio.bio, *dst = src;
871         struct bvec_iter saved_iter;
872         void *ec_buf;
873         struct bpos ec_pos = op->pos;
874         unsigned total_output = 0, total_input = 0;
875         bool bounce = false;
876         bool page_alloc_failed = false;
877         int ret, more = 0;
878
879         BUG_ON(!bio_sectors(src));
880
881         ec_buf = bch2_writepoint_ec_buf(c, wp);
882
883         switch (bch2_write_prep_encoded_data(op, wp)) {
884         case PREP_ENCODED_OK:
885                 break;
886         case PREP_ENCODED_ERR:
887                 ret = -EIO;
888                 goto err;
889         case PREP_ENCODED_CHECKSUM_ERR:
890                 BUG();
891                 goto csum_err;
892         case PREP_ENCODED_DO_WRITE:
893                 /* XXX look for bug here */
894                 if (ec_buf) {
895                         dst = bch2_write_bio_alloc(c, wp, src,
896                                                    &page_alloc_failed,
897                                                    ec_buf);
898                         bio_copy_data(dst, src);
899                         bounce = true;
900                 }
901                 init_append_extent(op, wp, op->version, op->crc);
902                 goto do_write;
903         }
904
905         if (ec_buf ||
906             op->compression_type ||
907             (op->csum_type &&
908              !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
909             (bch2_csum_type_is_encryption(op->csum_type) &&
910              !(op->flags & BCH_WRITE_PAGES_OWNED))) {
911                 dst = bch2_write_bio_alloc(c, wp, src,
912                                            &page_alloc_failed,
913                                            ec_buf);
914                 bounce = true;
915         }
916
917         saved_iter = dst->bi_iter;
918
919         do {
920                 struct bch_extent_crc_unpacked crc =
921                         (struct bch_extent_crc_unpacked) { 0 };
922                 struct bversion version = op->version;
923                 size_t dst_len, src_len;
924
925                 if (page_alloc_failed &&
926                     bio_sectors(dst) < wp->sectors_free &&
927                     bio_sectors(dst) < c->sb.encoded_extent_max)
928                         break;
929
930                 BUG_ON(op->compression_type &&
931                        (op->flags & BCH_WRITE_DATA_ENCODED) &&
932                        bch2_csum_type_is_encryption(op->crc.csum_type));
933                 BUG_ON(op->compression_type && !bounce);
934
935                 crc.compression_type = op->incompressible
936                         ? BCH_COMPRESSION_TYPE_incompressible
937                         : op->compression_type
938                         ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
939                                             op->compression_type)
940                         : 0;
941                 if (!crc_is_compressed(crc)) {
942                         dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
943                         dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
944
945                         if (op->csum_type)
946                                 dst_len = min_t(unsigned, dst_len,
947                                                 c->sb.encoded_extent_max << 9);
948
949                         if (bounce) {
950                                 swap(dst->bi_iter.bi_size, dst_len);
951                                 bio_copy_data(dst, src);
952                                 swap(dst->bi_iter.bi_size, dst_len);
953                         }
954
955                         src_len = dst_len;
956                 }
957
958                 BUG_ON(!src_len || !dst_len);
959
960                 if (bch2_csum_type_is_encryption(op->csum_type)) {
961                         if (bversion_zero(version)) {
962                                 version.lo = atomic64_inc_return(&c->key_version);
963                         } else {
964                                 crc.nonce = op->nonce;
965                                 op->nonce += src_len >> 9;
966                         }
967                 }
968
969                 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
970                     !crc_is_compressed(crc) &&
971                     bch2_csum_type_is_encryption(op->crc.csum_type) ==
972                     bch2_csum_type_is_encryption(op->csum_type)) {
973                         /*
974                          * Note: when we're using rechecksum(), we need to be
975                          * checksumming @src because it has all the data our
976                          * existing checksum covers - if we bounced (because we
977                          * were trying to compress), @dst will only have the
978                          * part of the data the new checksum will cover.
979                          *
980                          * But normally we want to be checksumming post bounce,
981                          * because part of the reason for bouncing is so the
982                          * data can't be modified (by userspace) while it's in
983                          * flight.
984                          */
985                         if (bch2_rechecksum_bio(c, src, version, op->crc,
986                                         &crc, &op->crc,
987                                         src_len >> 9,
988                                         bio_sectors(src) - (src_len >> 9),
989                                         op->csum_type))
990                                 goto csum_err;
991                 } else {
992                         if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
993                             bch2_rechecksum_bio(c, src, version, op->crc,
994                                         NULL, &op->crc,
995                                         src_len >> 9,
996                                         bio_sectors(src) - (src_len >> 9),
997                                         op->crc.csum_type))
998                                 goto csum_err;
999
1000                         crc.compressed_size     = dst_len >> 9;
1001                         crc.uncompressed_size   = src_len >> 9;
1002                         crc.live_size           = src_len >> 9;
1003
1004                         swap(dst->bi_iter.bi_size, dst_len);
1005                         bch2_encrypt_bio(c, op->csum_type,
1006                                          extent_nonce(version, crc), dst);
1007                         crc.csum = bch2_checksum_bio(c, op->csum_type,
1008                                          extent_nonce(version, crc), dst);
1009                         crc.csum_type = op->csum_type;
1010                         swap(dst->bi_iter.bi_size, dst_len);
1011                 }
1012
1013                 init_append_extent(op, wp, version, crc);
1014
1015                 if (dst != src)
1016                         bio_advance(dst, dst_len);
1017                 bio_advance(src, src_len);
1018                 total_output    += dst_len;
1019                 total_input     += src_len;
1020         } while (dst->bi_iter.bi_size &&
1021                  src->bi_iter.bi_size &&
1022                  wp->sectors_free &&
1023                  !bch2_keylist_realloc(&op->insert_keys,
1024                                       op->inline_keys,
1025                                       ARRAY_SIZE(op->inline_keys),
1026                                       BKEY_EXTENT_U64s_MAX));
1027
1028         more = src->bi_iter.bi_size != 0;
1029
1030         dst->bi_iter = saved_iter;
1031
1032         if (dst == src && more) {
1033                 BUG_ON(total_output != total_input);
1034
1035                 dst = bio_split(src, total_input >> 9,
1036                                 GFP_NOIO, &c->bio_write);
1037                 wbio_init(dst)->put_bio = true;
1038                 /* copy WRITE_SYNC flag */
1039                 dst->bi_opf             = src->bi_opf;
1040         }
1041
1042         dst->bi_iter.bi_size = total_output;
1043 do_write:
1044         /* might have done a realloc... */
1045         bch2_ec_add_backpointer(c, wp, ec_pos, total_input >> 9);
1046
1047         *_dst = dst;
1048         return more;
1049 csum_err:
1050         bch_err(c, "error verifying existing checksum while "
1051                 "rewriting existing data (memory corruption?)");
1052         ret = -EIO;
1053 err:
1054         if (to_wbio(dst)->bounce)
1055                 bch2_bio_free_pages_pool(c, dst);
1056         if (to_wbio(dst)->put_bio)
1057                 bio_put(dst);
1058
1059         return ret;
1060 }
1061
1062 static void __bch2_write(struct closure *cl)
1063 {
1064         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1065         struct bch_fs *c = op->c;
1066         struct write_point *wp;
1067         struct bio *bio;
1068         bool skip_put = true;
1069         unsigned nofs_flags;
1070         int ret;
1071
1072         nofs_flags = memalloc_nofs_save();
1073 again:
1074         memset(&op->failed, 0, sizeof(op->failed));
1075
1076         do {
1077                 struct bkey_i *key_to_write;
1078                 unsigned key_to_write_offset = op->insert_keys.top_p -
1079                         op->insert_keys.keys_p;
1080
1081                 /* +1 for possible cache device: */
1082                 if (op->open_buckets.nr + op->nr_replicas + 1 >
1083                     ARRAY_SIZE(op->open_buckets.v))
1084                         goto flush_io;
1085
1086                 if (bch2_keylist_realloc(&op->insert_keys,
1087                                         op->inline_keys,
1088                                         ARRAY_SIZE(op->inline_keys),
1089                                         BKEY_EXTENT_U64s_MAX))
1090                         goto flush_io;
1091
1092                 if ((op->flags & BCH_WRITE_FROM_INTERNAL) &&
1093                     percpu_ref_is_dying(&c->writes)) {
1094                         ret = -EROFS;
1095                         goto err;
1096                 }
1097
1098                 /*
1099                  * The copygc thread is now global, which means it's no longer
1100                  * freeing up space on specific disks, which means that
1101                  * allocations for specific disks may hang arbitrarily long:
1102                  */
1103                 wp = bch2_alloc_sectors_start(c,
1104                         op->target,
1105                         op->opts.erasure_code,
1106                         op->write_point,
1107                         &op->devs_have,
1108                         op->nr_replicas,
1109                         op->nr_replicas_required,
1110                         op->alloc_reserve,
1111                         op->flags,
1112                         (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1113                                       BCH_WRITE_ONLY_SPECIFIED_DEVS)) ? NULL : cl);
1114                 EBUG_ON(!wp);
1115
1116                 if (unlikely(IS_ERR(wp))) {
1117                         if (unlikely(PTR_ERR(wp) != -EAGAIN)) {
1118                                 ret = PTR_ERR(wp);
1119                                 goto err;
1120                         }
1121
1122                         goto flush_io;
1123                 }
1124
1125                 /*
1126                  * It's possible for the allocator to fail, put us on the
1127                  * freelist waitlist, and then succeed in one of various retry
1128                  * paths: if that happens, we need to disable the skip_put
1129                  * optimization because otherwise there won't necessarily be a
1130                  * barrier before we free the bch_write_op:
1131                  */
1132                 if (atomic_read(&cl->remaining) & CLOSURE_WAITING)
1133                         skip_put = false;
1134
1135                 bch2_open_bucket_get(c, wp, &op->open_buckets);
1136                 ret = bch2_write_extent(op, wp, &bio);
1137                 bch2_alloc_sectors_done(c, wp);
1138
1139                 if (ret < 0)
1140                         goto err;
1141
1142                 if (ret) {
1143                         skip_put = false;
1144                 } else {
1145                         /*
1146                          * for the skip_put optimization this has to be set
1147                          * before we submit the bio:
1148                          */
1149                         op->flags |= BCH_WRITE_DONE;
1150                 }
1151
1152                 bio->bi_end_io  = bch2_write_endio;
1153                 bio->bi_private = &op->cl;
1154                 bio->bi_opf |= REQ_OP_WRITE;
1155
1156                 if (!skip_put)
1157                         closure_get(bio->bi_private);
1158                 else
1159                         op->flags |= BCH_WRITE_SKIP_CLOSURE_PUT;
1160
1161                 key_to_write = (void *) (op->insert_keys.keys_p +
1162                                          key_to_write_offset);
1163
1164                 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1165                                           key_to_write);
1166         } while (ret);
1167
1168         if (!skip_put)
1169                 continue_at(cl, bch2_write_index, index_update_wq(op));
1170 out:
1171         memalloc_nofs_restore(nofs_flags);
1172         return;
1173 err:
1174         op->error = ret;
1175         op->flags |= BCH_WRITE_DONE;
1176
1177         continue_at(cl, bch2_write_index, index_update_wq(op));
1178         goto out;
1179 flush_io:
1180         /*
1181          * If the write can't all be submitted at once, we generally want to
1182          * block synchronously as that signals backpressure to the caller.
1183          *
1184          * However, if we're running out of a workqueue, we can't block here
1185          * because we'll be blocking other work items from completing:
1186          */
1187         if (current->flags & PF_WQ_WORKER) {
1188                 continue_at(cl, bch2_write_index, index_update_wq(op));
1189                 goto out;
1190         }
1191
1192         closure_sync(cl);
1193
1194         if (!bch2_keylist_empty(&op->insert_keys)) {
1195                 __bch2_write_index(op);
1196
1197                 if (op->error) {
1198                         op->flags |= BCH_WRITE_DONE;
1199                         continue_at_nobarrier(cl, bch2_write_done, NULL);
1200                         goto out;
1201                 }
1202         }
1203
1204         goto again;
1205 }
1206
1207 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1208 {
1209         struct closure *cl = &op->cl;
1210         struct bio *bio = &op->wbio.bio;
1211         struct bvec_iter iter;
1212         struct bkey_i_inline_data *id;
1213         unsigned sectors;
1214         int ret;
1215
1216         bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1217
1218         ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1219                                    ARRAY_SIZE(op->inline_keys),
1220                                    BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1221         if (ret) {
1222                 op->error = ret;
1223                 goto err;
1224         }
1225
1226         sectors = bio_sectors(bio);
1227         op->pos.offset += sectors;
1228
1229         id = bkey_inline_data_init(op->insert_keys.top);
1230         id->k.p         = op->pos;
1231         id->k.version   = op->version;
1232         id->k.size      = sectors;
1233
1234         iter = bio->bi_iter;
1235         iter.bi_size = data_len;
1236         memcpy_from_bio(id->v.data, bio, iter);
1237
1238         while (data_len & 7)
1239                 id->v.data[data_len++] = '\0';
1240         set_bkey_val_bytes(&id->k, data_len);
1241         bch2_keylist_push(&op->insert_keys);
1242
1243         op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1244         op->flags |= BCH_WRITE_DONE;
1245
1246         continue_at_nobarrier(cl, bch2_write_index, NULL);
1247         return;
1248 err:
1249         bch2_write_done(&op->cl);
1250 }
1251
1252 /**
1253  * bch_write - handle a write to a cache device or flash only volume
1254  *
1255  * This is the starting point for any data to end up in a cache device; it could
1256  * be from a normal write, or a writeback write, or a write to a flash only
1257  * volume - it's also used by the moving garbage collector to compact data in
1258  * mostly empty buckets.
1259  *
1260  * It first writes the data to the cache, creating a list of keys to be inserted
1261  * (if the data won't fit in a single open bucket, there will be multiple keys);
1262  * after the data is written it calls bch_journal, and after the keys have been
1263  * added to the next journal write they're inserted into the btree.
1264  *
1265  * If op->discard is true, instead of inserting the data it invalidates the
1266  * region of the cache represented by op->bio and op->inode.
1267  */
1268 void bch2_write(struct closure *cl)
1269 {
1270         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1271         struct bio *bio = &op->wbio.bio;
1272         struct bch_fs *c = op->c;
1273         unsigned data_len;
1274
1275         BUG_ON(!op->nr_replicas);
1276         BUG_ON(!op->write_point.v);
1277         BUG_ON(!bkey_cmp(op->pos, POS_MAX));
1278
1279         op->start_time = local_clock();
1280         bch2_keylist_init(&op->insert_keys, op->inline_keys);
1281         wbio_init(bio)->put_bio = false;
1282
1283         if (bio_sectors(bio) & (c->opts.block_size - 1)) {
1284                 __bcache_io_error(c, "misaligned write");
1285                 op->error = -EIO;
1286                 goto err;
1287         }
1288
1289         if (c->opts.nochanges ||
1290             !percpu_ref_tryget(&c->writes)) {
1291                 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1292                         __bcache_io_error(c, "read only");
1293                 op->error = -EROFS;
1294                 goto err;
1295         }
1296
1297         /*
1298          * Can't ratelimit copygc - we'd deadlock:
1299          */
1300         if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1301                 down(&c->io_in_flight);
1302
1303         bch2_increment_clock(c, bio_sectors(bio), WRITE);
1304
1305         data_len = min_t(u64, bio->bi_iter.bi_size,
1306                          op->new_i_size - (op->pos.offset << 9));
1307
1308         if (c->opts.inline_data &&
1309             data_len <= min(block_bytes(c) / 2, 1024U)) {
1310                 bch2_write_data_inline(op, data_len);
1311                 return;
1312         }
1313
1314         continue_at_nobarrier(cl, __bch2_write, NULL);
1315         return;
1316 err:
1317         bch2_disk_reservation_put(c, &op->res);
1318
1319         if (op->end_io) {
1320                 EBUG_ON(cl->parent);
1321                 closure_debug_destroy(cl);
1322                 op->end_io(op);
1323         } else {
1324                 closure_return(cl);
1325         }
1326 }
1327
1328 /* Cache promotion on read */
1329
1330 struct promote_op {
1331         struct closure          cl;
1332         struct rcu_head         rcu;
1333         u64                     start_time;
1334
1335         struct rhash_head       hash;
1336         struct bpos             pos;
1337
1338         struct migrate_write    write;
1339         struct bio_vec          bi_inline_vecs[0]; /* must be last */
1340 };
1341
1342 static const struct rhashtable_params bch_promote_params = {
1343         .head_offset    = offsetof(struct promote_op, hash),
1344         .key_offset     = offsetof(struct promote_op, pos),
1345         .key_len        = sizeof(struct bpos),
1346 };
1347
1348 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1349                                   struct bpos pos,
1350                                   struct bch_io_opts opts,
1351                                   unsigned flags)
1352 {
1353         if (!(flags & BCH_READ_MAY_PROMOTE))
1354                 return false;
1355
1356         if (!opts.promote_target)
1357                 return false;
1358
1359         if (bch2_bkey_has_target(c, k, opts.promote_target))
1360                 return false;
1361
1362         if (bch2_target_congested(c, opts.promote_target)) {
1363                 /* XXX trace this */
1364                 return false;
1365         }
1366
1367         if (rhashtable_lookup_fast(&c->promote_table, &pos,
1368                                    bch_promote_params))
1369                 return false;
1370
1371         return true;
1372 }
1373
1374 static void promote_free(struct bch_fs *c, struct promote_op *op)
1375 {
1376         int ret;
1377
1378         ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1379                                      bch_promote_params);
1380         BUG_ON(ret);
1381         percpu_ref_put(&c->writes);
1382         kfree_rcu(op, rcu);
1383 }
1384
1385 static void promote_done(struct closure *cl)
1386 {
1387         struct promote_op *op =
1388                 container_of(cl, struct promote_op, cl);
1389         struct bch_fs *c = op->write.op.c;
1390
1391         bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1392                                op->start_time);
1393
1394         bch2_bio_free_pages_pool(c, &op->write.op.wbio.bio);
1395         promote_free(c, op);
1396 }
1397
1398 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1399 {
1400         struct bch_fs *c = rbio->c;
1401         struct closure *cl = &op->cl;
1402         struct bio *bio = &op->write.op.wbio.bio;
1403
1404         trace_promote(&rbio->bio);
1405
1406         /* we now own pages: */
1407         BUG_ON(!rbio->bounce);
1408         BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1409
1410         memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1411                sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1412         swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1413
1414         bch2_migrate_read_done(&op->write, rbio);
1415
1416         closure_init(cl, NULL);
1417         closure_call(&op->write.op.cl, bch2_write, c->wq, cl);
1418         closure_return_with_destructor(cl, promote_done);
1419 }
1420
1421 static struct promote_op *__promote_alloc(struct bch_fs *c,
1422                                           enum btree_id btree_id,
1423                                           struct bkey_s_c k,
1424                                           struct bpos pos,
1425                                           struct extent_ptr_decoded *pick,
1426                                           struct bch_io_opts opts,
1427                                           unsigned sectors,
1428                                           struct bch_read_bio **rbio)
1429 {
1430         struct promote_op *op = NULL;
1431         struct bio *bio;
1432         unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1433         int ret;
1434
1435         if (!percpu_ref_tryget(&c->writes))
1436                 return NULL;
1437
1438         op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1439         if (!op)
1440                 goto err;
1441
1442         op->start_time = local_clock();
1443         op->pos = pos;
1444
1445         /*
1446          * We don't use the mempool here because extents that aren't
1447          * checksummed or compressed can be too big for the mempool:
1448          */
1449         *rbio = kzalloc(sizeof(struct bch_read_bio) +
1450                         sizeof(struct bio_vec) * pages,
1451                         GFP_NOIO);
1452         if (!*rbio)
1453                 goto err;
1454
1455         rbio_init(&(*rbio)->bio, opts);
1456         bio_init(&(*rbio)->bio, (*rbio)->bio.bi_inline_vecs, pages);
1457
1458         if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1459                                  GFP_NOIO))
1460                 goto err;
1461
1462         (*rbio)->bounce         = true;
1463         (*rbio)->split          = true;
1464         (*rbio)->kmalloc        = true;
1465
1466         if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1467                                           bch_promote_params))
1468                 goto err;
1469
1470         bio = &op->write.op.wbio.bio;
1471         bio_init(bio, bio->bi_inline_vecs, pages);
1472
1473         ret = bch2_migrate_write_init(c, &op->write,
1474                         writepoint_hashed((unsigned long) current),
1475                         opts,
1476                         DATA_PROMOTE,
1477                         (struct data_opts) {
1478                                 .target         = opts.promote_target,
1479                                 .nr_replicas    = 1,
1480                         },
1481                         btree_id, k);
1482         BUG_ON(ret);
1483
1484         return op;
1485 err:
1486         if (*rbio)
1487                 bio_free_pages(&(*rbio)->bio);
1488         kfree(*rbio);
1489         *rbio = NULL;
1490         kfree(op);
1491         percpu_ref_put(&c->writes);
1492         return NULL;
1493 }
1494
1495 noinline
1496 static struct promote_op *promote_alloc(struct bch_fs *c,
1497                                                struct bvec_iter iter,
1498                                                struct bkey_s_c k,
1499                                                struct extent_ptr_decoded *pick,
1500                                                struct bch_io_opts opts,
1501                                                unsigned flags,
1502                                                struct bch_read_bio **rbio,
1503                                                bool *bounce,
1504                                                bool *read_full)
1505 {
1506         bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1507         /* data might have to be decompressed in the write path: */
1508         unsigned sectors = promote_full
1509                 ? max(pick->crc.compressed_size, pick->crc.live_size)
1510                 : bvec_iter_sectors(iter);
1511         struct bpos pos = promote_full
1512                 ? bkey_start_pos(k.k)
1513                 : POS(k.k->p.inode, iter.bi_sector);
1514         struct promote_op *promote;
1515
1516         if (!should_promote(c, k, pos, opts, flags))
1517                 return NULL;
1518
1519         promote = __promote_alloc(c,
1520                                   k.k->type == KEY_TYPE_reflink_v
1521                                   ? BTREE_ID_REFLINK
1522                                   : BTREE_ID_EXTENTS,
1523                                   k, pos, pick, opts, sectors, rbio);
1524         if (!promote)
1525                 return NULL;
1526
1527         *bounce         = true;
1528         *read_full      = promote_full;
1529         return promote;
1530 }
1531
1532 /* Read */
1533
1534 #define READ_RETRY_AVOID        1
1535 #define READ_RETRY              2
1536 #define READ_ERR                3
1537
1538 enum rbio_context {
1539         RBIO_CONTEXT_NULL,
1540         RBIO_CONTEXT_HIGHPRI,
1541         RBIO_CONTEXT_UNBOUND,
1542 };
1543
1544 static inline struct bch_read_bio *
1545 bch2_rbio_parent(struct bch_read_bio *rbio)
1546 {
1547         return rbio->split ? rbio->parent : rbio;
1548 }
1549
1550 __always_inline
1551 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
1552                            enum rbio_context context,
1553                            struct workqueue_struct *wq)
1554 {
1555         if (context <= rbio->context) {
1556                 fn(&rbio->work);
1557         } else {
1558                 rbio->work.func         = fn;
1559                 rbio->context           = context;
1560                 queue_work(wq, &rbio->work);
1561         }
1562 }
1563
1564 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
1565 {
1566         BUG_ON(rbio->bounce && !rbio->split);
1567
1568         if (rbio->promote)
1569                 promote_free(rbio->c, rbio->promote);
1570         rbio->promote = NULL;
1571
1572         if (rbio->bounce)
1573                 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
1574
1575         if (rbio->split) {
1576                 struct bch_read_bio *parent = rbio->parent;
1577
1578                 if (rbio->kmalloc)
1579                         kfree(rbio);
1580                 else
1581                         bio_put(&rbio->bio);
1582
1583                 rbio = parent;
1584         }
1585
1586         return rbio;
1587 }
1588
1589 /*
1590  * Only called on a top level bch_read_bio to complete an entire read request,
1591  * not a split:
1592  */
1593 static void bch2_rbio_done(struct bch_read_bio *rbio)
1594 {
1595         if (rbio->start_time)
1596                 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
1597                                        rbio->start_time);
1598         bio_endio(&rbio->bio);
1599 }
1600
1601 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
1602                                      struct bvec_iter bvec_iter, u64 inode,
1603                                      struct bch_io_failures *failed,
1604                                      unsigned flags)
1605 {
1606         struct btree_trans trans;
1607         struct btree_iter *iter;
1608         struct bkey_on_stack sk;
1609         struct bkey_s_c k;
1610         int ret;
1611
1612         flags &= ~BCH_READ_LAST_FRAGMENT;
1613         flags |= BCH_READ_MUST_CLONE;
1614
1615         bkey_on_stack_init(&sk);
1616         bch2_trans_init(&trans, c, 0, 0);
1617
1618         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
1619                                    rbio->pos, BTREE_ITER_SLOTS);
1620 retry:
1621         rbio->bio.bi_status = 0;
1622
1623         k = bch2_btree_iter_peek_slot(iter);
1624         if (bkey_err(k))
1625                 goto err;
1626
1627         bkey_on_stack_reassemble(&sk, c, k);
1628         k = bkey_i_to_s_c(sk.k);
1629         bch2_trans_unlock(&trans);
1630
1631         if (!bch2_bkey_matches_ptr(c, k,
1632                                    rbio->pick.ptr,
1633                                    rbio->pos.offset -
1634                                    rbio->pick.crc.offset)) {
1635                 /* extent we wanted to read no longer exists: */
1636                 rbio->hole = true;
1637                 goto out;
1638         }
1639
1640         ret = __bch2_read_extent(&trans, rbio, bvec_iter, k, 0, failed, flags);
1641         if (ret == READ_RETRY)
1642                 goto retry;
1643         if (ret)
1644                 goto err;
1645 out:
1646         bch2_rbio_done(rbio);
1647         bch2_trans_exit(&trans);
1648         bkey_on_stack_exit(&sk, c);
1649         return;
1650 err:
1651         rbio->bio.bi_status = BLK_STS_IOERR;
1652         goto out;
1653 }
1654
1655 static void bch2_read_retry(struct bch_fs *c, struct bch_read_bio *rbio,
1656                             struct bvec_iter bvec_iter, u64 inode,
1657                             struct bch_io_failures *failed, unsigned flags)
1658 {
1659         struct btree_trans trans;
1660         struct btree_iter *iter;
1661         struct bkey_on_stack sk;
1662         struct bkey_s_c k;
1663         int ret;
1664
1665         flags &= ~BCH_READ_LAST_FRAGMENT;
1666         flags |= BCH_READ_MUST_CLONE;
1667
1668         bkey_on_stack_init(&sk);
1669         bch2_trans_init(&trans, c, 0, 0);
1670 retry:
1671         bch2_trans_begin(&trans);
1672
1673         for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS,
1674                            POS(inode, bvec_iter.bi_sector),
1675                            BTREE_ITER_SLOTS, k, ret) {
1676                 unsigned bytes, sectors, offset_into_extent;
1677
1678                 bkey_on_stack_reassemble(&sk, c, k);
1679
1680                 offset_into_extent = iter->pos.offset -
1681                         bkey_start_offset(k.k);
1682                 sectors = k.k->size - offset_into_extent;
1683
1684                 ret = bch2_read_indirect_extent(&trans,
1685                                         &offset_into_extent, &sk);
1686                 if (ret)
1687                         break;
1688
1689                 k = bkey_i_to_s_c(sk.k);
1690
1691                 sectors = min(sectors, k.k->size - offset_into_extent);
1692
1693                 bch2_trans_unlock(&trans);
1694
1695                 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
1696                 swap(bvec_iter.bi_size, bytes);
1697
1698                 ret = __bch2_read_extent(&trans, rbio, bvec_iter, k,
1699                                 offset_into_extent, failed, flags);
1700                 switch (ret) {
1701                 case READ_RETRY:
1702                         goto retry;
1703                 case READ_ERR:
1704                         goto err;
1705                 };
1706
1707                 if (bytes == bvec_iter.bi_size)
1708                         goto out;
1709
1710                 swap(bvec_iter.bi_size, bytes);
1711                 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
1712         }
1713
1714         if (ret == -EINTR)
1715                 goto retry;
1716         /*
1717          * If we get here, it better have been because there was an error
1718          * reading a btree node
1719          */
1720         BUG_ON(!ret);
1721         __bcache_io_error(c, "btree IO error: %i", ret);
1722 err:
1723         rbio->bio.bi_status = BLK_STS_IOERR;
1724 out:
1725         bch2_trans_exit(&trans);
1726         bkey_on_stack_exit(&sk, c);
1727         bch2_rbio_done(rbio);
1728 }
1729
1730 static void bch2_rbio_retry(struct work_struct *work)
1731 {
1732         struct bch_read_bio *rbio =
1733                 container_of(work, struct bch_read_bio, work);
1734         struct bch_fs *c        = rbio->c;
1735         struct bvec_iter iter   = rbio->bvec_iter;
1736         unsigned flags          = rbio->flags;
1737         u64 inode               = rbio->pos.inode;
1738         struct bch_io_failures failed = { .nr = 0 };
1739
1740         trace_read_retry(&rbio->bio);
1741
1742         if (rbio->retry == READ_RETRY_AVOID)
1743                 bch2_mark_io_failure(&failed, &rbio->pick);
1744
1745         rbio->bio.bi_status = 0;
1746
1747         rbio = bch2_rbio_free(rbio);
1748
1749         flags |= BCH_READ_IN_RETRY;
1750         flags &= ~BCH_READ_MAY_PROMOTE;
1751
1752         if (flags & BCH_READ_NODECODE)
1753                 bch2_read_retry_nodecode(c, rbio, iter, inode, &failed, flags);
1754         else
1755                 bch2_read_retry(c, rbio, iter, inode, &failed, flags);
1756 }
1757
1758 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
1759                             blk_status_t error)
1760 {
1761         rbio->retry = retry;
1762
1763         if (rbio->flags & BCH_READ_IN_RETRY)
1764                 return;
1765
1766         if (retry == READ_ERR) {
1767                 rbio = bch2_rbio_free(rbio);
1768
1769                 rbio->bio.bi_status = error;
1770                 bch2_rbio_done(rbio);
1771         } else {
1772                 bch2_rbio_punt(rbio, bch2_rbio_retry,
1773                                RBIO_CONTEXT_UNBOUND, system_unbound_wq);
1774         }
1775 }
1776
1777 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
1778                                    struct bch_read_bio *rbio)
1779 {
1780         struct bch_fs *c = rbio->c;
1781         u64 data_offset = rbio->pos.offset - rbio->pick.crc.offset;
1782         struct bch_extent_crc_unpacked new_crc;
1783         struct btree_iter *iter = NULL;
1784         struct bkey_i *new;
1785         struct bkey_s_c k;
1786         int ret = 0;
1787
1788         if (crc_is_compressed(rbio->pick.crc))
1789                 return 0;
1790
1791         iter = bch2_trans_get_iter(trans, BTREE_ID_EXTENTS, rbio->pos,
1792                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1793         if ((ret = PTR_ERR_OR_ZERO(iter)))
1794                 goto out;
1795
1796         k = bch2_btree_iter_peek_slot(iter);
1797         if ((ret = bkey_err(k)))
1798                 goto out;
1799
1800         /*
1801          * going to be temporarily appending another checksum entry:
1802          */
1803         new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
1804                                  BKEY_EXTENT_U64s_MAX * 8);
1805         if ((ret = PTR_ERR_OR_ZERO(new)))
1806                 goto out;
1807
1808         bkey_reassemble(new, k);
1809         k = bkey_i_to_s_c(new);
1810
1811         if (bversion_cmp(k.k->version, rbio->version) ||
1812             !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
1813                 goto out;
1814
1815         /* Extent was merged? */
1816         if (bkey_start_offset(k.k) < data_offset ||
1817             k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
1818                 goto out;
1819
1820         if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
1821                         rbio->pick.crc, NULL, &new_crc,
1822                         bkey_start_offset(k.k) - data_offset, k.k->size,
1823                         rbio->pick.crc.csum_type)) {
1824                 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
1825                 ret = 0;
1826                 goto out;
1827         }
1828
1829         if (!bch2_bkey_narrow_crcs(new, new_crc))
1830                 goto out;
1831
1832         bch2_trans_update(trans, iter, new, 0);
1833 out:
1834         bch2_trans_iter_put(trans, iter);
1835         return ret;
1836 }
1837
1838 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
1839 {
1840         bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
1841                       __bch2_rbio_narrow_crcs(&trans, rbio));
1842 }
1843
1844 /* Inner part that may run in process context */
1845 static void __bch2_read_endio(struct work_struct *work)
1846 {
1847         struct bch_read_bio *rbio =
1848                 container_of(work, struct bch_read_bio, work);
1849         struct bch_fs *c        = rbio->c;
1850         struct bch_dev *ca      = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1851         struct bio *src         = &rbio->bio;
1852         struct bio *dst         = &bch2_rbio_parent(rbio)->bio;
1853         struct bvec_iter dst_iter = rbio->bvec_iter;
1854         struct bch_extent_crc_unpacked crc = rbio->pick.crc;
1855         struct nonce nonce = extent_nonce(rbio->version, crc);
1856         struct bch_csum csum;
1857
1858         /* Reset iterator for checksumming and copying bounced data: */
1859         if (rbio->bounce) {
1860                 src->bi_iter.bi_size            = crc.compressed_size << 9;
1861                 src->bi_iter.bi_idx             = 0;
1862                 src->bi_iter.bi_bvec_done       = 0;
1863         } else {
1864                 src->bi_iter                    = rbio->bvec_iter;
1865         }
1866
1867         csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
1868         if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
1869                 goto csum_err;
1870
1871         if (unlikely(rbio->narrow_crcs))
1872                 bch2_rbio_narrow_crcs(rbio);
1873
1874         if (rbio->flags & BCH_READ_NODECODE)
1875                 goto nodecode;
1876
1877         /* Adjust crc to point to subset of data we want: */
1878         crc.offset     += rbio->offset_into_extent;
1879         crc.live_size   = bvec_iter_sectors(rbio->bvec_iter);
1880
1881         if (crc_is_compressed(crc)) {
1882                 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1883                 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
1884                         goto decompression_err;
1885         } else {
1886                 /* don't need to decrypt the entire bio: */
1887                 nonce = nonce_add(nonce, crc.offset << 9);
1888                 bio_advance(src, crc.offset << 9);
1889
1890                 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
1891                 src->bi_iter.bi_size = dst_iter.bi_size;
1892
1893                 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1894
1895                 if (rbio->bounce) {
1896                         struct bvec_iter src_iter = src->bi_iter;
1897                         bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
1898                 }
1899         }
1900
1901         if (rbio->promote) {
1902                 /*
1903                  * Re encrypt data we decrypted, so it's consistent with
1904                  * rbio->crc:
1905                  */
1906                 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1907                 promote_start(rbio->promote, rbio);
1908                 rbio->promote = NULL;
1909         }
1910 nodecode:
1911         if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
1912                 rbio = bch2_rbio_free(rbio);
1913                 bch2_rbio_done(rbio);
1914         }
1915         return;
1916 csum_err:
1917         /*
1918          * Checksum error: if the bio wasn't bounced, we may have been
1919          * reading into buffers owned by userspace (that userspace can
1920          * scribble over) - retry the read, bouncing it this time:
1921          */
1922         if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
1923                 rbio->flags |= BCH_READ_MUST_BOUNCE;
1924                 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
1925                 return;
1926         }
1927
1928         bch2_dev_io_error(ca,
1929                 "data checksum error, inode %llu offset %llu: expected %0llx:%0llx got %0llx:%0llx (type %u)",
1930                 rbio->pos.inode, (u64) rbio->bvec_iter.bi_sector,
1931                 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
1932                 csum.hi, csum.lo, crc.csum_type);
1933         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
1934         return;
1935 decompression_err:
1936         __bcache_io_error(c, "decompression error, inode %llu offset %llu",
1937                           rbio->pos.inode,
1938                           (u64) rbio->bvec_iter.bi_sector);
1939         bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
1940         return;
1941 }
1942
1943 static void bch2_read_endio(struct bio *bio)
1944 {
1945         struct bch_read_bio *rbio =
1946                 container_of(bio, struct bch_read_bio, bio);
1947         struct bch_fs *c        = rbio->c;
1948         struct bch_dev *ca      = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1949         struct workqueue_struct *wq = NULL;
1950         enum rbio_context context = RBIO_CONTEXT_NULL;
1951
1952         if (rbio->have_ioref) {
1953                 bch2_latency_acct(ca, rbio->submit_time, READ);
1954                 percpu_ref_put(&ca->io_ref);
1955         }
1956
1957         if (!rbio->split)
1958                 rbio->bio.bi_end_io = rbio->end_io;
1959
1960         if (bch2_dev_io_err_on(bio->bi_status, ca, "data read; %s",
1961                                bch2_blk_status_to_str(bio->bi_status))) {
1962                 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
1963                 return;
1964         }
1965
1966         if (rbio->pick.ptr.cached &&
1967             (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
1968              ptr_stale(ca, &rbio->pick.ptr))) {
1969                 atomic_long_inc(&c->read_realloc_races);
1970
1971                 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
1972                         bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
1973                 else
1974                         bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
1975                 return;
1976         }
1977
1978         if (rbio->narrow_crcs ||
1979             crc_is_compressed(rbio->pick.crc) ||
1980             bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
1981                 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
1982         else if (rbio->pick.crc.csum_type)
1983                 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
1984
1985         bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
1986 }
1987
1988 int __bch2_read_indirect_extent(struct btree_trans *trans,
1989                                 unsigned *offset_into_extent,
1990                                 struct bkey_on_stack *orig_k)
1991 {
1992         struct btree_iter *iter;
1993         struct bkey_s_c k;
1994         u64 reflink_offset;
1995         int ret;
1996
1997         reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
1998                 *offset_into_extent;
1999
2000         iter = bch2_trans_get_iter(trans, BTREE_ID_REFLINK,
2001                                    POS(0, reflink_offset),
2002                                    BTREE_ITER_SLOTS);
2003         ret = PTR_ERR_OR_ZERO(iter);
2004         if (ret)
2005                 return ret;
2006
2007         k = bch2_btree_iter_peek_slot(iter);
2008         ret = bkey_err(k);
2009         if (ret)
2010                 goto err;
2011
2012         if (k.k->type != KEY_TYPE_reflink_v &&
2013             k.k->type != KEY_TYPE_indirect_inline_data) {
2014                 __bcache_io_error(trans->c,
2015                                 "pointer to nonexistent indirect extent");
2016                 ret = -EIO;
2017                 goto err;
2018         }
2019
2020         *offset_into_extent = iter->pos.offset - bkey_start_offset(k.k);
2021         bkey_on_stack_reassemble(orig_k, trans->c, k);
2022 err:
2023         bch2_trans_iter_put(trans, iter);
2024         return ret;
2025 }
2026
2027 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2028                        struct bvec_iter iter, struct bkey_s_c k,
2029                        unsigned offset_into_extent,
2030                        struct bch_io_failures *failed, unsigned flags)
2031 {
2032         struct bch_fs *c = trans->c;
2033         struct extent_ptr_decoded pick;
2034         struct bch_read_bio *rbio = NULL;
2035         struct bch_dev *ca;
2036         struct promote_op *promote = NULL;
2037         bool bounce = false, read_full = false, narrow_crcs = false;
2038         struct bpos pos = bkey_start_pos(k.k);
2039         int pick_ret;
2040
2041         if (bkey_extent_is_inline_data(k.k)) {
2042                 unsigned bytes = min_t(unsigned, iter.bi_size,
2043                                        bkey_inline_data_bytes(k.k));
2044
2045                 swap(iter.bi_size, bytes);
2046                 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2047                 swap(iter.bi_size, bytes);
2048                 bio_advance_iter(&orig->bio, &iter, bytes);
2049                 zero_fill_bio_iter(&orig->bio, iter);
2050                 goto out_read_done;
2051         }
2052
2053         pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2054
2055         /* hole or reservation - just zero fill: */
2056         if (!pick_ret)
2057                 goto hole;
2058
2059         if (pick_ret < 0) {
2060                 __bcache_io_error(c, "no device to read from");
2061                 goto err;
2062         }
2063
2064         if (pick_ret > 0)
2065                 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2066
2067         if (flags & BCH_READ_NODECODE) {
2068                 /*
2069                  * can happen if we retry, and the extent we were going to read
2070                  * has been merged in the meantime:
2071                  */
2072                 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2073                         goto hole;
2074
2075                 iter.bi_size    = pick.crc.compressed_size << 9;
2076                 goto get_bio;
2077         }
2078
2079         if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2080             bio_flagged(&orig->bio, BIO_CHAIN))
2081                 flags |= BCH_READ_MUST_CLONE;
2082
2083         narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2084                 bch2_can_narrow_extent_crcs(k, pick.crc);
2085
2086         if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2087                 flags |= BCH_READ_MUST_BOUNCE;
2088
2089         EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2090
2091         if (crc_is_compressed(pick.crc) ||
2092             (pick.crc.csum_type != BCH_CSUM_NONE &&
2093              (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2094               (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2095                (flags & BCH_READ_USER_MAPPED)) ||
2096               (flags & BCH_READ_MUST_BOUNCE)))) {
2097                 read_full = true;
2098                 bounce = true;
2099         }
2100
2101         if (orig->opts.promote_target)
2102                 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2103                                         &rbio, &bounce, &read_full);
2104
2105         if (!read_full) {
2106                 EBUG_ON(crc_is_compressed(pick.crc));
2107                 EBUG_ON(pick.crc.csum_type &&
2108                         (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2109                          bvec_iter_sectors(iter) != pick.crc.live_size ||
2110                          pick.crc.offset ||
2111                          offset_into_extent));
2112
2113                 pos.offset += offset_into_extent;
2114                 pick.ptr.offset += pick.crc.offset +
2115                         offset_into_extent;
2116                 offset_into_extent              = 0;
2117                 pick.crc.compressed_size        = bvec_iter_sectors(iter);
2118                 pick.crc.uncompressed_size      = bvec_iter_sectors(iter);
2119                 pick.crc.offset                 = 0;
2120                 pick.crc.live_size              = bvec_iter_sectors(iter);
2121                 offset_into_extent              = 0;
2122         }
2123 get_bio:
2124         if (rbio) {
2125                 /*
2126                  * promote already allocated bounce rbio:
2127                  * promote needs to allocate a bio big enough for uncompressing
2128                  * data in the write path, but we're not going to use it all
2129                  * here:
2130                  */
2131                 EBUG_ON(rbio->bio.bi_iter.bi_size <
2132                        pick.crc.compressed_size << 9);
2133                 rbio->bio.bi_iter.bi_size =
2134                         pick.crc.compressed_size << 9;
2135         } else if (bounce) {
2136                 unsigned sectors = pick.crc.compressed_size;
2137
2138                 rbio = rbio_init(bio_alloc_bioset(GFP_NOIO,
2139                                                   DIV_ROUND_UP(sectors, PAGE_SECTORS),
2140                                                   &c->bio_read_split),
2141                                  orig->opts);
2142
2143                 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2144                 rbio->bounce    = true;
2145                 rbio->split     = true;
2146         } else if (flags & BCH_READ_MUST_CLONE) {
2147                 /*
2148                  * Have to clone if there were any splits, due to error
2149                  * reporting issues (if a split errored, and retrying didn't
2150                  * work, when it reports the error to its parent (us) we don't
2151                  * know if the error was from our bio, and we should retry, or
2152                  * from the whole bio, in which case we don't want to retry and
2153                  * lose the error)
2154                  */
2155                 rbio = rbio_init(bio_clone_fast(&orig->bio, GFP_NOIO,
2156                                                 &c->bio_read_split),
2157                                  orig->opts);
2158                 rbio->bio.bi_iter = iter;
2159                 rbio->split     = true;
2160         } else {
2161                 rbio = orig;
2162                 rbio->bio.bi_iter = iter;
2163                 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2164         }
2165
2166         EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2167
2168         rbio->c                 = c;
2169         rbio->submit_time       = local_clock();
2170         if (rbio->split)
2171                 rbio->parent    = orig;
2172         else
2173                 rbio->end_io    = orig->bio.bi_end_io;
2174         rbio->bvec_iter         = iter;
2175         rbio->offset_into_extent= offset_into_extent;
2176         rbio->flags             = flags;
2177         rbio->have_ioref        = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2178         rbio->narrow_crcs       = narrow_crcs;
2179         rbio->hole              = 0;
2180         rbio->retry             = 0;
2181         rbio->context           = 0;
2182         /* XXX: only initialize this if needed */
2183         rbio->devs_have         = bch2_bkey_devs(k);
2184         rbio->pick              = pick;
2185         rbio->pos               = pos;
2186         rbio->version           = k.k->version;
2187         rbio->promote           = promote;
2188         INIT_WORK(&rbio->work, NULL);
2189
2190         rbio->bio.bi_opf        = orig->bio.bi_opf;
2191         rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2192         rbio->bio.bi_end_io     = bch2_read_endio;
2193
2194         if (rbio->bounce)
2195                 trace_read_bounce(&rbio->bio);
2196
2197         bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2198
2199         if (pick.ptr.cached)
2200                 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2201                         PTR_BUCKET_NR(ca, &pick.ptr), READ);
2202
2203         if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2204                 bio_inc_remaining(&orig->bio);
2205                 trace_read_split(&orig->bio);
2206         }
2207
2208         if (!rbio->pick.idx) {
2209                 if (!rbio->have_ioref) {
2210                         __bcache_io_error(c, "no device to read from");
2211                         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2212                         goto out;
2213                 }
2214
2215                 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2216                              bio_sectors(&rbio->bio));
2217                 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2218
2219                 if (likely(!(flags & BCH_READ_IN_RETRY)))
2220                         submit_bio(&rbio->bio);
2221                 else
2222                         submit_bio_wait(&rbio->bio);
2223         } else {
2224                 /* Attempting reconstruct read: */
2225                 if (bch2_ec_read_extent(c, rbio)) {
2226                         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2227                         goto out;
2228                 }
2229
2230                 if (likely(!(flags & BCH_READ_IN_RETRY)))
2231                         bio_endio(&rbio->bio);
2232         }
2233 out:
2234         if (likely(!(flags & BCH_READ_IN_RETRY))) {
2235                 return 0;
2236         } else {
2237                 int ret;
2238
2239                 rbio->context = RBIO_CONTEXT_UNBOUND;
2240                 bch2_read_endio(&rbio->bio);
2241
2242                 ret = rbio->retry;
2243                 rbio = bch2_rbio_free(rbio);
2244
2245                 if (ret == READ_RETRY_AVOID) {
2246                         bch2_mark_io_failure(failed, &pick);
2247                         ret = READ_RETRY;
2248                 }
2249
2250                 return ret;
2251         }
2252
2253 err:
2254         if (flags & BCH_READ_IN_RETRY)
2255                 return READ_ERR;
2256
2257         orig->bio.bi_status = BLK_STS_IOERR;
2258         goto out_read_done;
2259
2260 hole:
2261         /*
2262          * won't normally happen in the BCH_READ_NODECODE
2263          * (bch2_move_extent()) path, but if we retry and the extent we wanted
2264          * to read no longer exists we have to signal that:
2265          */
2266         if (flags & BCH_READ_NODECODE)
2267                 orig->hole = true;
2268
2269         zero_fill_bio_iter(&orig->bio, iter);
2270 out_read_done:
2271         if (flags & BCH_READ_LAST_FRAGMENT)
2272                 bch2_rbio_done(orig);
2273         return 0;
2274 }
2275
2276 void bch2_read(struct bch_fs *c, struct bch_read_bio *rbio, u64 inode)
2277 {
2278         struct btree_trans trans;
2279         struct btree_iter *iter;
2280         struct bkey_on_stack sk;
2281         struct bkey_s_c k;
2282         unsigned flags = BCH_READ_RETRY_IF_STALE|
2283                 BCH_READ_MAY_PROMOTE|
2284                 BCH_READ_USER_MAPPED;
2285         int ret;
2286
2287         BUG_ON(rbio->_state);
2288         BUG_ON(flags & BCH_READ_NODECODE);
2289         BUG_ON(flags & BCH_READ_IN_RETRY);
2290
2291         rbio->c = c;
2292         rbio->start_time = local_clock();
2293
2294         bkey_on_stack_init(&sk);
2295         bch2_trans_init(&trans, c, 0, 0);
2296 retry:
2297         bch2_trans_begin(&trans);
2298
2299         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
2300                                    POS(inode, rbio->bio.bi_iter.bi_sector),
2301                                    BTREE_ITER_SLOTS);
2302         while (1) {
2303                 unsigned bytes, sectors, offset_into_extent;
2304
2305                 bch2_btree_iter_set_pos(iter,
2306                                 POS(inode, rbio->bio.bi_iter.bi_sector));
2307
2308                 k = bch2_btree_iter_peek_slot(iter);
2309                 ret = bkey_err(k);
2310                 if (ret)
2311                         goto err;
2312
2313                 offset_into_extent = iter->pos.offset -
2314                         bkey_start_offset(k.k);
2315                 sectors = k.k->size - offset_into_extent;
2316
2317                 bkey_on_stack_reassemble(&sk, c, k);
2318
2319                 ret = bch2_read_indirect_extent(&trans,
2320                                         &offset_into_extent, &sk);
2321                 if (ret)
2322                         goto err;
2323
2324                 k = bkey_i_to_s_c(sk.k);
2325
2326                 /*
2327                  * With indirect extents, the amount of data to read is the min
2328                  * of the original extent and the indirect extent:
2329                  */
2330                 sectors = min(sectors, k.k->size - offset_into_extent);
2331
2332                 /*
2333                  * Unlock the iterator while the btree node's lock is still in
2334                  * cache, before doing the IO:
2335                  */
2336                 bch2_trans_unlock(&trans);
2337
2338                 bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
2339                 swap(rbio->bio.bi_iter.bi_size, bytes);
2340
2341                 if (rbio->bio.bi_iter.bi_size == bytes)
2342                         flags |= BCH_READ_LAST_FRAGMENT;
2343
2344                 bch2_read_extent(&trans, rbio, k, offset_into_extent, flags);
2345
2346                 if (flags & BCH_READ_LAST_FRAGMENT)
2347                         break;
2348
2349                 swap(rbio->bio.bi_iter.bi_size, bytes);
2350                 bio_advance(&rbio->bio, bytes);
2351         }
2352 out:
2353         bch2_trans_exit(&trans);
2354         bkey_on_stack_exit(&sk, c);
2355         return;
2356 err:
2357         if (ret == -EINTR)
2358                 goto retry;
2359
2360         bcache_io_error(c, &rbio->bio, "btree IO error: %i", ret);
2361         bch2_rbio_done(rbio);
2362         goto out;
2363 }
2364
2365 void bch2_fs_io_exit(struct bch_fs *c)
2366 {
2367         if (c->promote_table.tbl)
2368                 rhashtable_destroy(&c->promote_table);
2369         mempool_exit(&c->bio_bounce_pages);
2370         bioset_exit(&c->bio_write);
2371         bioset_exit(&c->bio_read_split);
2372         bioset_exit(&c->bio_read);
2373 }
2374
2375 int bch2_fs_io_init(struct bch_fs *c)
2376 {
2377         if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2378                         BIOSET_NEED_BVECS) ||
2379             bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2380                         BIOSET_NEED_BVECS) ||
2381             bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2382                         BIOSET_NEED_BVECS) ||
2383             mempool_init_page_pool(&c->bio_bounce_pages,
2384                                    max_t(unsigned,
2385                                          c->opts.btree_node_size,
2386                                          c->sb.encoded_extent_max) /
2387                                    PAGE_SECTORS, 0) ||
2388             rhashtable_init(&c->promote_table, &bch_promote_params))
2389                 return -ENOMEM;
2390
2391         return 0;
2392 }