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