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