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