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