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