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