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