]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/io.c
rust: Fix ptr casting in Fs::open()
[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 (type != BCH_DATA_btree && unlikely(c->opts.no_data_io)) {
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 static inline void bch2_write_queue(struct bch_write_op *op, struct write_point *wp)
854 {
855         op->btree_update_ready = false;
856         op->wp = wp;
857
858         spin_lock(&wp->writes_lock);
859         list_add_tail(&op->wp_list, &wp->writes);
860         if (wp->state == WRITE_POINT_stopped)
861                 __wp_update_state(wp, WRITE_POINT_waiting_io);
862         spin_unlock(&wp->writes_lock);
863 }
864
865 void bch2_write_point_do_index_updates(struct work_struct *work)
866 {
867         struct write_point *wp =
868                 container_of(work, struct write_point, index_update_work);
869         struct bch_write_op *op;
870
871         while (1) {
872                 spin_lock(&wp->writes_lock);
873                 list_for_each_entry(op, &wp->writes, wp_list)
874                         if (op->btree_update_ready) {
875                                 list_del(&op->wp_list);
876                                 goto unlock;
877                         }
878                 op = NULL;
879 unlock:
880                 wp_update_state(wp, op != NULL);
881                 spin_unlock(&wp->writes_lock);
882
883                 if (!op)
884                         break;
885
886                 op->flags |= BCH_WRITE_IN_WORKER;
887
888                 __bch2_write_index(op);
889
890                 if (!(op->flags & BCH_WRITE_DONE))
891                         __bch2_write(op);
892                 else
893                         bch2_write_done(&op->cl);
894         }
895 }
896
897 static void bch2_write_endio(struct bio *bio)
898 {
899         struct closure *cl              = bio->bi_private;
900         struct bch_write_op *op         = container_of(cl, struct bch_write_op, cl);
901         struct bch_write_bio *wbio      = to_wbio(bio);
902         struct bch_write_bio *parent    = wbio->split ? wbio->parent : NULL;
903         struct bch_fs *c                = wbio->c;
904         struct bch_dev *ca              = bch_dev_bkey_exists(c, wbio->dev);
905
906         if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
907                                     op->pos.inode,
908                                     wbio->inode_offset << 9,
909                                     "data write error: %s",
910                                     bch2_blk_status_to_str(bio->bi_status))) {
911                 set_bit(wbio->dev, op->failed.d);
912                 op->flags |= BCH_WRITE_IO_ERROR;
913         }
914
915         if (wbio->nocow)
916                 set_bit(wbio->dev, op->devs_need_flush->d);
917
918         if (wbio->have_ioref) {
919                 bch2_latency_acct(ca, wbio->submit_time, WRITE);
920                 percpu_ref_put(&ca->io_ref);
921         }
922
923         if (wbio->bounce)
924                 bch2_bio_free_pages_pool(c, bio);
925
926         if (wbio->put_bio)
927                 bio_put(bio);
928
929         if (parent)
930                 bio_endio(&parent->bio);
931         else
932                 closure_put(cl);
933 }
934
935 static void init_append_extent(struct bch_write_op *op,
936                                struct write_point *wp,
937                                struct bversion version,
938                                struct bch_extent_crc_unpacked crc)
939 {
940         struct bkey_i_extent *e;
941
942         op->pos.offset += crc.uncompressed_size;
943
944         e = bkey_extent_init(op->insert_keys.top);
945         e->k.p          = op->pos;
946         e->k.size       = crc.uncompressed_size;
947         e->k.version    = version;
948
949         if (crc.csum_type ||
950             crc.compression_type ||
951             crc.nonce)
952                 bch2_extent_crc_append(&e->k_i, crc);
953
954         bch2_alloc_sectors_append_ptrs_inlined(op->c, wp, &e->k_i, crc.compressed_size,
955                                        op->flags & BCH_WRITE_CACHED);
956
957         bch2_keylist_push(&op->insert_keys);
958 }
959
960 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
961                                         struct write_point *wp,
962                                         struct bio *src,
963                                         bool *page_alloc_failed,
964                                         void *buf)
965 {
966         struct bch_write_bio *wbio;
967         struct bio *bio;
968         unsigned output_available =
969                 min(wp->sectors_free << 9, src->bi_iter.bi_size);
970         unsigned pages = DIV_ROUND_UP(output_available +
971                                       (buf
972                                        ? ((unsigned long) buf & (PAGE_SIZE - 1))
973                                        : 0), PAGE_SIZE);
974
975         pages = min(pages, BIO_MAX_VECS);
976
977         bio = bio_alloc_bioset(NULL, pages, 0,
978                                GFP_NOIO, &c->bio_write);
979         wbio                    = wbio_init(bio);
980         wbio->put_bio           = true;
981         /* copy WRITE_SYNC flag */
982         wbio->bio.bi_opf        = src->bi_opf;
983
984         if (buf) {
985                 bch2_bio_map(bio, buf, output_available);
986                 return bio;
987         }
988
989         wbio->bounce            = true;
990
991         /*
992          * We can't use mempool for more than c->sb.encoded_extent_max
993          * worth of pages, but we'd like to allocate more if we can:
994          */
995         bch2_bio_alloc_pages_pool(c, bio,
996                                   min_t(unsigned, output_available,
997                                         c->opts.encoded_extent_max));
998
999         if (bio->bi_iter.bi_size < output_available)
1000                 *page_alloc_failed =
1001                         bch2_bio_alloc_pages(bio,
1002                                              output_available -
1003                                              bio->bi_iter.bi_size,
1004                                              GFP_NOFS) != 0;
1005
1006         return bio;
1007 }
1008
1009 static int bch2_write_rechecksum(struct bch_fs *c,
1010                                  struct bch_write_op *op,
1011                                  unsigned new_csum_type)
1012 {
1013         struct bio *bio = &op->wbio.bio;
1014         struct bch_extent_crc_unpacked new_crc;
1015         int ret;
1016
1017         /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
1018
1019         if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
1020             bch2_csum_type_is_encryption(new_csum_type))
1021                 new_csum_type = op->crc.csum_type;
1022
1023         ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
1024                                   NULL, &new_crc,
1025                                   op->crc.offset, op->crc.live_size,
1026                                   new_csum_type);
1027         if (ret)
1028                 return ret;
1029
1030         bio_advance(bio, op->crc.offset << 9);
1031         bio->bi_iter.bi_size = op->crc.live_size << 9;
1032         op->crc = new_crc;
1033         return 0;
1034 }
1035
1036 static int bch2_write_decrypt(struct bch_write_op *op)
1037 {
1038         struct bch_fs *c = op->c;
1039         struct nonce nonce = extent_nonce(op->version, op->crc);
1040         struct bch_csum csum;
1041         int ret;
1042
1043         if (!bch2_csum_type_is_encryption(op->crc.csum_type))
1044                 return 0;
1045
1046         /*
1047          * If we need to decrypt data in the write path, we'll no longer be able
1048          * to verify the existing checksum (poly1305 mac, in this case) after
1049          * it's decrypted - this is the last point we'll be able to reverify the
1050          * checksum:
1051          */
1052         csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
1053         if (bch2_crc_cmp(op->crc.csum, csum))
1054                 return -EIO;
1055
1056         ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
1057         op->crc.csum_type = 0;
1058         op->crc.csum = (struct bch_csum) { 0, 0 };
1059         return ret;
1060 }
1061
1062 static enum prep_encoded_ret {
1063         PREP_ENCODED_OK,
1064         PREP_ENCODED_ERR,
1065         PREP_ENCODED_CHECKSUM_ERR,
1066         PREP_ENCODED_DO_WRITE,
1067 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
1068 {
1069         struct bch_fs *c = op->c;
1070         struct bio *bio = &op->wbio.bio;
1071
1072         if (!(op->flags & BCH_WRITE_DATA_ENCODED))
1073                 return PREP_ENCODED_OK;
1074
1075         BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
1076
1077         /* Can we just write the entire extent as is? */
1078         if (op->crc.uncompressed_size == op->crc.live_size &&
1079             op->crc.compressed_size <= wp->sectors_free &&
1080             (op->crc.compression_type == op->compression_type ||
1081              op->incompressible)) {
1082                 if (!crc_is_compressed(op->crc) &&
1083                     op->csum_type != op->crc.csum_type &&
1084                     bch2_write_rechecksum(c, op, op->csum_type))
1085                         return PREP_ENCODED_CHECKSUM_ERR;
1086
1087                 return PREP_ENCODED_DO_WRITE;
1088         }
1089
1090         /*
1091          * If the data is compressed and we couldn't write the entire extent as
1092          * is, we have to decompress it:
1093          */
1094         if (crc_is_compressed(op->crc)) {
1095                 struct bch_csum csum;
1096
1097                 if (bch2_write_decrypt(op))
1098                         return PREP_ENCODED_CHECKSUM_ERR;
1099
1100                 /* Last point we can still verify checksum: */
1101                 csum = bch2_checksum_bio(c, op->crc.csum_type,
1102                                          extent_nonce(op->version, op->crc),
1103                                          bio);
1104                 if (bch2_crc_cmp(op->crc.csum, csum))
1105                         return PREP_ENCODED_CHECKSUM_ERR;
1106
1107                 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
1108                         return PREP_ENCODED_ERR;
1109         }
1110
1111         /*
1112          * No longer have compressed data after this point - data might be
1113          * encrypted:
1114          */
1115
1116         /*
1117          * If the data is checksummed and we're only writing a subset,
1118          * rechecksum and adjust bio to point to currently live data:
1119          */
1120         if ((op->crc.live_size != op->crc.uncompressed_size ||
1121              op->crc.csum_type != op->csum_type) &&
1122             bch2_write_rechecksum(c, op, op->csum_type))
1123                 return PREP_ENCODED_CHECKSUM_ERR;
1124
1125         /*
1126          * If we want to compress the data, it has to be decrypted:
1127          */
1128         if ((op->compression_type ||
1129              bch2_csum_type_is_encryption(op->crc.csum_type) !=
1130              bch2_csum_type_is_encryption(op->csum_type)) &&
1131             bch2_write_decrypt(op))
1132                 return PREP_ENCODED_CHECKSUM_ERR;
1133
1134         return PREP_ENCODED_OK;
1135 }
1136
1137 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
1138                              struct bio **_dst)
1139 {
1140         struct bch_fs *c = op->c;
1141         struct bio *src = &op->wbio.bio, *dst = src;
1142         struct bvec_iter saved_iter;
1143         void *ec_buf;
1144         unsigned total_output = 0, total_input = 0;
1145         bool bounce = false;
1146         bool page_alloc_failed = false;
1147         int ret, more = 0;
1148
1149         BUG_ON(!bio_sectors(src));
1150
1151         ec_buf = bch2_writepoint_ec_buf(c, wp);
1152
1153         switch (bch2_write_prep_encoded_data(op, wp)) {
1154         case PREP_ENCODED_OK:
1155                 break;
1156         case PREP_ENCODED_ERR:
1157                 ret = -EIO;
1158                 goto err;
1159         case PREP_ENCODED_CHECKSUM_ERR:
1160                 goto csum_err;
1161         case PREP_ENCODED_DO_WRITE:
1162                 /* XXX look for bug here */
1163                 if (ec_buf) {
1164                         dst = bch2_write_bio_alloc(c, wp, src,
1165                                                    &page_alloc_failed,
1166                                                    ec_buf);
1167                         bio_copy_data(dst, src);
1168                         bounce = true;
1169                 }
1170                 init_append_extent(op, wp, op->version, op->crc);
1171                 goto do_write;
1172         }
1173
1174         if (ec_buf ||
1175             op->compression_type ||
1176             (op->csum_type &&
1177              !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
1178             (bch2_csum_type_is_encryption(op->csum_type) &&
1179              !(op->flags & BCH_WRITE_PAGES_OWNED))) {
1180                 dst = bch2_write_bio_alloc(c, wp, src,
1181                                            &page_alloc_failed,
1182                                            ec_buf);
1183                 bounce = true;
1184         }
1185
1186         saved_iter = dst->bi_iter;
1187
1188         do {
1189                 struct bch_extent_crc_unpacked crc = { 0 };
1190                 struct bversion version = op->version;
1191                 size_t dst_len, src_len;
1192
1193                 if (page_alloc_failed &&
1194                     dst->bi_iter.bi_size  < (wp->sectors_free << 9) &&
1195                     dst->bi_iter.bi_size < c->opts.encoded_extent_max)
1196                         break;
1197
1198                 BUG_ON(op->compression_type &&
1199                        (op->flags & BCH_WRITE_DATA_ENCODED) &&
1200                        bch2_csum_type_is_encryption(op->crc.csum_type));
1201                 BUG_ON(op->compression_type && !bounce);
1202
1203                 crc.compression_type = op->incompressible
1204                         ? BCH_COMPRESSION_TYPE_incompressible
1205                         : op->compression_type
1206                         ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
1207                                             op->compression_type)
1208                         : 0;
1209                 if (!crc_is_compressed(crc)) {
1210                         dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
1211                         dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
1212
1213                         if (op->csum_type)
1214                                 dst_len = min_t(unsigned, dst_len,
1215                                                 c->opts.encoded_extent_max);
1216
1217                         if (bounce) {
1218                                 swap(dst->bi_iter.bi_size, dst_len);
1219                                 bio_copy_data(dst, src);
1220                                 swap(dst->bi_iter.bi_size, dst_len);
1221                         }
1222
1223                         src_len = dst_len;
1224                 }
1225
1226                 BUG_ON(!src_len || !dst_len);
1227
1228                 if (bch2_csum_type_is_encryption(op->csum_type)) {
1229                         if (bversion_zero(version)) {
1230                                 version.lo = atomic64_inc_return(&c->key_version);
1231                         } else {
1232                                 crc.nonce = op->nonce;
1233                                 op->nonce += src_len >> 9;
1234                         }
1235                 }
1236
1237                 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1238                     !crc_is_compressed(crc) &&
1239                     bch2_csum_type_is_encryption(op->crc.csum_type) ==
1240                     bch2_csum_type_is_encryption(op->csum_type)) {
1241                         u8 compression_type = crc.compression_type;
1242                         u16 nonce = crc.nonce;
1243                         /*
1244                          * Note: when we're using rechecksum(), we need to be
1245                          * checksumming @src because it has all the data our
1246                          * existing checksum covers - if we bounced (because we
1247                          * were trying to compress), @dst will only have the
1248                          * part of the data the new checksum will cover.
1249                          *
1250                          * But normally we want to be checksumming post bounce,
1251                          * because part of the reason for bouncing is so the
1252                          * data can't be modified (by userspace) while it's in
1253                          * flight.
1254                          */
1255                         if (bch2_rechecksum_bio(c, src, version, op->crc,
1256                                         &crc, &op->crc,
1257                                         src_len >> 9,
1258                                         bio_sectors(src) - (src_len >> 9),
1259                                         op->csum_type))
1260                                 goto csum_err;
1261                         /*
1262                          * rchecksum_bio sets compression_type on crc from op->crc,
1263                          * this isn't always correct as sometimes we're changing
1264                          * an extent from uncompressed to incompressible.
1265                          */
1266                         crc.compression_type = compression_type;
1267                         crc.nonce = nonce;
1268                 } else {
1269                         if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1270                             bch2_rechecksum_bio(c, src, version, op->crc,
1271                                         NULL, &op->crc,
1272                                         src_len >> 9,
1273                                         bio_sectors(src) - (src_len >> 9),
1274                                         op->crc.csum_type))
1275                                 goto csum_err;
1276
1277                         crc.compressed_size     = dst_len >> 9;
1278                         crc.uncompressed_size   = src_len >> 9;
1279                         crc.live_size           = src_len >> 9;
1280
1281                         swap(dst->bi_iter.bi_size, dst_len);
1282                         ret = bch2_encrypt_bio(c, op->csum_type,
1283                                                extent_nonce(version, crc), dst);
1284                         if (ret)
1285                                 goto err;
1286
1287                         crc.csum = bch2_checksum_bio(c, op->csum_type,
1288                                          extent_nonce(version, crc), dst);
1289                         crc.csum_type = op->csum_type;
1290                         swap(dst->bi_iter.bi_size, dst_len);
1291                 }
1292
1293                 init_append_extent(op, wp, version, crc);
1294
1295                 if (dst != src)
1296                         bio_advance(dst, dst_len);
1297                 bio_advance(src, src_len);
1298                 total_output    += dst_len;
1299                 total_input     += src_len;
1300         } while (dst->bi_iter.bi_size &&
1301                  src->bi_iter.bi_size &&
1302                  wp->sectors_free &&
1303                  !bch2_keylist_realloc(&op->insert_keys,
1304                                       op->inline_keys,
1305                                       ARRAY_SIZE(op->inline_keys),
1306                                       BKEY_EXTENT_U64s_MAX));
1307
1308         more = src->bi_iter.bi_size != 0;
1309
1310         dst->bi_iter = saved_iter;
1311
1312         if (dst == src && more) {
1313                 BUG_ON(total_output != total_input);
1314
1315                 dst = bio_split(src, total_input >> 9,
1316                                 GFP_NOIO, &c->bio_write);
1317                 wbio_init(dst)->put_bio = true;
1318                 /* copy WRITE_SYNC flag */
1319                 dst->bi_opf             = src->bi_opf;
1320         }
1321
1322         dst->bi_iter.bi_size = total_output;
1323 do_write:
1324         *_dst = dst;
1325         return more;
1326 csum_err:
1327         bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1328         ret = -EIO;
1329 err:
1330         if (to_wbio(dst)->bounce)
1331                 bch2_bio_free_pages_pool(c, dst);
1332         if (to_wbio(dst)->put_bio)
1333                 bio_put(dst);
1334
1335         return ret;
1336 }
1337
1338 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1339                                      struct bkey_s_c k)
1340 {
1341         struct bch_fs *c = op->c;
1342         struct bkey_s_c_extent e;
1343         struct extent_ptr_decoded p;
1344         const union bch_extent_entry *entry;
1345         unsigned replicas = 0;
1346
1347         if (k.k->type != KEY_TYPE_extent)
1348                 return false;
1349
1350         e = bkey_s_c_to_extent(k);
1351         extent_for_each_ptr_decode(e, p, entry) {
1352                 if (p.crc.csum_type ||
1353                     crc_is_compressed(p.crc) ||
1354                     p.has_ec)
1355                         return false;
1356
1357                 replicas += bch2_extent_ptr_durability(c, &p);
1358         }
1359
1360         return replicas >= op->opts.data_replicas;
1361 }
1362
1363 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1364 {
1365         struct bch_fs *c = op->c;
1366         const struct bch_extent_ptr *ptr;
1367         struct bkey_i *k;
1368
1369         for_each_keylist_key(&op->insert_keys, k) {
1370                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1371
1372                 bkey_for_each_ptr(ptrs, ptr)
1373                         bch2_bucket_nocow_unlock(&c->nocow_locks,
1374                                                PTR_BUCKET_POS(c, ptr),
1375                                                BUCKET_NOCOW_LOCK_UPDATE);
1376         }
1377 }
1378
1379 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1380                                                   struct btree_iter *iter,
1381                                                   struct bkey_i *orig,
1382                                                   struct bkey_s_c k,
1383                                                   u64 new_i_size)
1384 {
1385         struct bkey_i *new;
1386         struct bkey_ptrs ptrs;
1387         struct bch_extent_ptr *ptr;
1388         int ret;
1389
1390         if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1391                 /* trace this */
1392                 return 0;
1393         }
1394
1395         new = bch2_bkey_make_mut(trans, k);
1396         ret = PTR_ERR_OR_ZERO(new);
1397         if (ret)
1398                 return ret;
1399
1400         bch2_cut_front(bkey_start_pos(&orig->k), new);
1401         bch2_cut_back(orig->k.p, new);
1402
1403         ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1404         bkey_for_each_ptr(ptrs, ptr)
1405                 ptr->unwritten = 0;
1406
1407         /*
1408          * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1409          * that was done when we kicked off the write, and here it's important
1410          * that we update the extent that we wrote to - even if a snapshot has
1411          * since been created. The write is still outstanding, so we're ok
1412          * w.r.t. snapshot atomicity:
1413          */
1414         return  bch2_extent_update_i_size_sectors(trans, iter,
1415                                         min(new->k.p.offset << 9, new_i_size), 0) ?:
1416                 bch2_trans_update(trans, iter, new,
1417                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1418 }
1419
1420 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1421 {
1422         struct bch_fs *c = op->c;
1423         struct btree_trans trans;
1424         struct btree_iter iter;
1425         struct bkey_i *orig;
1426         struct bkey_s_c k;
1427         int ret;
1428
1429         bch2_trans_init(&trans, c, 0, 0);
1430
1431         for_each_keylist_key(&op->insert_keys, orig) {
1432                 ret = for_each_btree_key_upto_commit(&trans, iter, BTREE_ID_extents,
1433                                      bkey_start_pos(&orig->k), orig->k.p,
1434                                      BTREE_ITER_INTENT, k,
1435                                      NULL, NULL, BTREE_INSERT_NOFAIL, ({
1436                         bch2_nocow_write_convert_one_unwritten(&trans, &iter, orig, k, op->new_i_size);
1437                 }));
1438
1439                 if (ret && !bch2_err_matches(ret, EROFS)) {
1440                         struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
1441
1442                         bch_err_inum_offset_ratelimited(c,
1443                                 k->k.p.inode, k->k.p.offset << 9,
1444                                 "write error while doing btree update: %s",
1445                                 bch2_err_str(ret));
1446                 }
1447
1448                 if (ret) {
1449                         op->error = ret;
1450                         break;
1451                 }
1452         }
1453
1454         bch2_trans_exit(&trans);
1455 }
1456
1457 static void __bch2_nocow_write_done(struct bch_write_op *op)
1458 {
1459         bch2_nocow_write_unlock(op);
1460
1461         if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1462                 op->error = -EIO;
1463         } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1464                 bch2_nocow_write_convert_unwritten(op);
1465 }
1466
1467 static void bch2_nocow_write_done(struct closure *cl)
1468 {
1469         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1470
1471         __bch2_nocow_write_done(op);
1472         bch2_write_done(cl);
1473 }
1474
1475 static void bch2_nocow_write(struct bch_write_op *op)
1476 {
1477         struct bch_fs *c = op->c;
1478         struct btree_trans trans;
1479         struct btree_iter iter;
1480         struct bkey_s_c k;
1481         struct bkey_ptrs_c ptrs;
1482         const struct bch_extent_ptr *ptr, *ptr2;
1483         struct {
1484                 struct bpos     b;
1485                 unsigned        gen;
1486                 struct nocow_lock_bucket *l;
1487         } buckets[BCH_REPLICAS_MAX];
1488         unsigned nr_buckets = 0;
1489         u32 snapshot;
1490         int ret, i;
1491
1492         if (op->flags & BCH_WRITE_MOVE)
1493                 return;
1494
1495         bch2_trans_init(&trans, c, 0, 0);
1496 retry:
1497         bch2_trans_begin(&trans);
1498
1499         ret = bch2_subvolume_get_snapshot(&trans, op->subvol, &snapshot);
1500         if (unlikely(ret))
1501                 goto err;
1502
1503         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1504                              SPOS(op->pos.inode, op->pos.offset, snapshot),
1505                              BTREE_ITER_SLOTS);
1506         while (1) {
1507                 struct bio *bio = &op->wbio.bio;
1508
1509                 nr_buckets = 0;
1510
1511                 k = bch2_btree_iter_peek_slot(&iter);
1512                 ret = bkey_err(k);
1513                 if (ret)
1514                         break;
1515
1516                 /* fall back to normal cow write path? */
1517                 if (unlikely(k.k->p.snapshot != snapshot ||
1518                              !bch2_extent_is_writeable(op, k)))
1519                         break;
1520
1521                 if (bch2_keylist_realloc(&op->insert_keys,
1522                                         op->inline_keys,
1523                                         ARRAY_SIZE(op->inline_keys),
1524                                         k.k->u64s))
1525                         break;
1526
1527                 /* Get iorefs before dropping btree locks: */
1528                 ptrs = bch2_bkey_ptrs_c(k);
1529                 bkey_for_each_ptr(ptrs, ptr) {
1530                         buckets[nr_buckets].b = PTR_BUCKET_POS(c, ptr);
1531                         buckets[nr_buckets].gen = ptr->gen;
1532                         buckets[nr_buckets].l =
1533                                 bucket_nocow_lock(&c->nocow_locks,
1534                                                   bucket_to_u64(buckets[nr_buckets].b));
1535
1536                         prefetch(buckets[nr_buckets].l);
1537                         nr_buckets++;
1538
1539                         if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1540                                 goto err_get_ioref;
1541
1542                         if (ptr->unwritten)
1543                                 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1544                 }
1545
1546                 /* Unlock before taking nocow locks, doing IO: */
1547                 bkey_reassemble(op->insert_keys.top, k);
1548                 bch2_trans_unlock(&trans);
1549
1550                 bch2_cut_front(op->pos, op->insert_keys.top);
1551                 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1552                         bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1553
1554                 for (i = 0; i < nr_buckets; i++) {
1555                         struct bch_dev *ca = bch_dev_bkey_exists(c, buckets[i].b.inode);
1556                         struct nocow_lock_bucket *l = buckets[i].l;
1557                         bool stale;
1558
1559                         __bch2_bucket_nocow_lock(&c->nocow_locks, l,
1560                                                  bucket_to_u64(buckets[i].b),
1561                                                  BUCKET_NOCOW_LOCK_UPDATE);
1562
1563                         rcu_read_lock();
1564                         stale = gen_after(*bucket_gen(ca, buckets[i].b.offset), buckets[i].gen);
1565                         rcu_read_unlock();
1566
1567                         if (unlikely(stale))
1568                                 goto err_bucket_stale;
1569                 }
1570
1571                 bio = &op->wbio.bio;
1572                 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1573                         bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1574                                         GFP_KERNEL, &c->bio_write);
1575                         wbio_init(bio)->put_bio = true;
1576                         bio->bi_opf = op->wbio.bio.bi_opf;
1577                 } else {
1578                         op->flags |= BCH_WRITE_DONE;
1579                 }
1580
1581                 op->pos.offset += bio_sectors(bio);
1582                 op->written += bio_sectors(bio);
1583
1584                 bio->bi_end_io  = bch2_write_endio;
1585                 bio->bi_private = &op->cl;
1586                 bio->bi_opf |= REQ_OP_WRITE;
1587                 closure_get(&op->cl);
1588                 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1589                                           op->insert_keys.top, true);
1590
1591                 bch2_keylist_push(&op->insert_keys);
1592                 if (op->flags & BCH_WRITE_DONE)
1593                         break;
1594                 bch2_btree_iter_advance(&iter);
1595         }
1596 out:
1597         bch2_trans_iter_exit(&trans, &iter);
1598 err:
1599         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1600                 goto retry;
1601
1602         if (ret) {
1603                 bch_err_inum_offset_ratelimited(c,
1604                                 op->pos.inode,
1605                                 op->pos.offset << 9,
1606                                 "%s: btree lookup error %s",
1607                                 __func__, bch2_err_str(ret));
1608                 op->error = ret;
1609                 op->flags |= BCH_WRITE_DONE;
1610         }
1611
1612         bch2_trans_exit(&trans);
1613
1614         /* fallback to cow write path? */
1615         if (!(op->flags & BCH_WRITE_DONE)) {
1616                 closure_sync(&op->cl);
1617                 __bch2_nocow_write_done(op);
1618                 op->insert_keys.top = op->insert_keys.keys;
1619         } else if (op->flags & BCH_WRITE_SYNC) {
1620                 closure_sync(&op->cl);
1621                 bch2_nocow_write_done(&op->cl);
1622         } else {
1623                 /*
1624                  * XXX
1625                  * needs to run out of process context because ei_quota_lock is
1626                  * a mutex
1627                  */
1628                 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1629         }
1630         return;
1631 err_get_ioref:
1632         bkey_for_each_ptr(ptrs, ptr2) {
1633                 if (ptr2 == ptr)
1634                         break;
1635
1636                 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1637         }
1638
1639         /* Fall back to COW path: */
1640         goto out;
1641 err_bucket_stale:
1642         while (--i >= 0)
1643                 bch2_bucket_nocow_unlock(&c->nocow_locks,
1644                                          buckets[i].b,
1645                                          BUCKET_NOCOW_LOCK_UPDATE);
1646
1647         bkey_for_each_ptr(ptrs, ptr2)
1648                 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1649
1650         /* We can retry this: */
1651         ret = BCH_ERR_transaction_restart;
1652         goto out;
1653 }
1654
1655 static void __bch2_write(struct bch_write_op *op)
1656 {
1657         struct bch_fs *c = op->c;
1658         struct write_point *wp = NULL;
1659         struct bio *bio = NULL;
1660         unsigned nofs_flags;
1661         int ret;
1662
1663         nofs_flags = memalloc_nofs_save();
1664
1665         if (unlikely(op->opts.nocow && c->opts.nocow_enabled)) {
1666                 bch2_nocow_write(op);
1667                 if (op->flags & BCH_WRITE_DONE)
1668                         goto out_nofs_restore;
1669         }
1670 again:
1671         memset(&op->failed, 0, sizeof(op->failed));
1672         op->btree_update_ready = false;
1673
1674         do {
1675                 struct bkey_i *key_to_write;
1676                 unsigned key_to_write_offset = op->insert_keys.top_p -
1677                         op->insert_keys.keys_p;
1678
1679                 /* +1 for possible cache device: */
1680                 if (op->open_buckets.nr + op->nr_replicas + 1 >
1681                     ARRAY_SIZE(op->open_buckets.v))
1682                         break;
1683
1684                 if (bch2_keylist_realloc(&op->insert_keys,
1685                                         op->inline_keys,
1686                                         ARRAY_SIZE(op->inline_keys),
1687                                         BKEY_EXTENT_U64s_MAX))
1688                         break;
1689
1690                 /*
1691                  * The copygc thread is now global, which means it's no longer
1692                  * freeing up space on specific disks, which means that
1693                  * allocations for specific disks may hang arbitrarily long:
1694                  */
1695                 ret = bch2_trans_do(c, NULL, NULL, 0,
1696                         bch2_alloc_sectors_start_trans(&trans,
1697                                 op->target,
1698                                 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1699                                 op->write_point,
1700                                 &op->devs_have,
1701                                 op->nr_replicas,
1702                                 op->nr_replicas_required,
1703                                 op->alloc_reserve,
1704                                 op->flags,
1705                                 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1706                                               BCH_WRITE_ONLY_SPECIFIED_DEVS))
1707                                 ? NULL : &op->cl, &wp));
1708                 if (unlikely(ret)) {
1709                         if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1710                                 break;
1711
1712                         goto err;
1713                 }
1714
1715                 EBUG_ON(!wp);
1716
1717                 bch2_open_bucket_get(c, wp, &op->open_buckets);
1718                 ret = bch2_write_extent(op, wp, &bio);
1719
1720                 bch2_alloc_sectors_done_inlined(c, wp);
1721 err:
1722                 if (ret <= 0) {
1723                         op->flags |= BCH_WRITE_DONE;
1724
1725                         if (ret < 0) {
1726                                 op->error = ret;
1727                                 break;
1728                         }
1729                 }
1730
1731                 bio->bi_end_io  = bch2_write_endio;
1732                 bio->bi_private = &op->cl;
1733                 bio->bi_opf |= REQ_OP_WRITE;
1734
1735                 closure_get(bio->bi_private);
1736
1737                 key_to_write = (void *) (op->insert_keys.keys_p +
1738                                          key_to_write_offset);
1739
1740                 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1741                                           key_to_write, false);
1742         } while (ret);
1743
1744         /*
1745          * Sync or no?
1746          *
1747          * If we're running asynchronously, wne may still want to block
1748          * synchronously here if we weren't able to submit all of the IO at
1749          * once, as that signals backpressure to the caller.
1750          */
1751         if ((op->flags & BCH_WRITE_SYNC) ||
1752             (!(op->flags & BCH_WRITE_DONE) &&
1753              !(op->flags & BCH_WRITE_IN_WORKER))) {
1754                 closure_sync(&op->cl);
1755                 __bch2_write_index(op);
1756
1757                 if (!(op->flags & BCH_WRITE_DONE))
1758                         goto again;
1759                 bch2_write_done(&op->cl);
1760         } else {
1761                 bch2_write_queue(op, wp);
1762                 continue_at(&op->cl, bch2_write_index, NULL);
1763         }
1764 out_nofs_restore:
1765         memalloc_nofs_restore(nofs_flags);
1766 }
1767
1768 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1769 {
1770         struct bio *bio = &op->wbio.bio;
1771         struct bvec_iter iter;
1772         struct bkey_i_inline_data *id;
1773         unsigned sectors;
1774         int ret;
1775
1776         op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1777         op->flags |= BCH_WRITE_DONE;
1778
1779         bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1780
1781         ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1782                                    ARRAY_SIZE(op->inline_keys),
1783                                    BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1784         if (ret) {
1785                 op->error = ret;
1786                 goto err;
1787         }
1788
1789         sectors = bio_sectors(bio);
1790         op->pos.offset += sectors;
1791
1792         id = bkey_inline_data_init(op->insert_keys.top);
1793         id->k.p         = op->pos;
1794         id->k.version   = op->version;
1795         id->k.size      = sectors;
1796
1797         iter = bio->bi_iter;
1798         iter.bi_size = data_len;
1799         memcpy_from_bio(id->v.data, bio, iter);
1800
1801         while (data_len & 7)
1802                 id->v.data[data_len++] = '\0';
1803         set_bkey_val_bytes(&id->k, data_len);
1804         bch2_keylist_push(&op->insert_keys);
1805
1806         __bch2_write_index(op);
1807 err:
1808         bch2_write_done(&op->cl);
1809 }
1810
1811 /**
1812  * bch_write - handle a write to a cache device or flash only volume
1813  *
1814  * This is the starting point for any data to end up in a cache device; it could
1815  * be from a normal write, or a writeback write, or a write to a flash only
1816  * volume - it's also used by the moving garbage collector to compact data in
1817  * mostly empty buckets.
1818  *
1819  * It first writes the data to the cache, creating a list of keys to be inserted
1820  * (if the data won't fit in a single open bucket, there will be multiple keys);
1821  * after the data is written it calls bch_journal, and after the keys have been
1822  * added to the next journal write they're inserted into the btree.
1823  *
1824  * If op->discard is true, instead of inserting the data it invalidates the
1825  * region of the cache represented by op->bio and op->inode.
1826  */
1827 void bch2_write(struct closure *cl)
1828 {
1829         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1830         struct bio *bio = &op->wbio.bio;
1831         struct bch_fs *c = op->c;
1832         unsigned data_len;
1833
1834         EBUG_ON(op->cl.parent);
1835         BUG_ON(!op->nr_replicas);
1836         BUG_ON(!op->write_point.v);
1837         BUG_ON(bkey_eq(op->pos, POS_MAX));
1838
1839         op->start_time = local_clock();
1840         bch2_keylist_init(&op->insert_keys, op->inline_keys);
1841         wbio_init(bio)->put_bio = false;
1842
1843         if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1844                 bch_err_inum_offset_ratelimited(c,
1845                         op->pos.inode,
1846                         op->pos.offset << 9,
1847                         "misaligned write");
1848                 op->error = -EIO;
1849                 goto err;
1850         }
1851
1852         if (c->opts.nochanges ||
1853             !bch2_write_ref_tryget(c, BCH_WRITE_REF_write)) {
1854                 op->error = -BCH_ERR_erofs_no_writes;
1855                 goto err;
1856         }
1857
1858         this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1859         bch2_increment_clock(c, bio_sectors(bio), WRITE);
1860
1861         data_len = min_t(u64, bio->bi_iter.bi_size,
1862                          op->new_i_size - (op->pos.offset << 9));
1863
1864         if (c->opts.inline_data &&
1865             data_len <= min(block_bytes(c) / 2, 1024U)) {
1866                 bch2_write_data_inline(op, data_len);
1867                 return;
1868         }
1869
1870         __bch2_write(op);
1871         return;
1872 err:
1873         bch2_disk_reservation_put(c, &op->res);
1874
1875         closure_debug_destroy(&op->cl);
1876         if (op->end_io)
1877                 op->end_io(op);
1878 }
1879
1880 /* Cache promotion on read */
1881
1882 struct promote_op {
1883         struct rcu_head         rcu;
1884         u64                     start_time;
1885
1886         struct rhash_head       hash;
1887         struct bpos             pos;
1888
1889         struct data_update      write;
1890         struct bio_vec          bi_inline_vecs[0]; /* must be last */
1891 };
1892
1893 static const struct rhashtable_params bch_promote_params = {
1894         .head_offset    = offsetof(struct promote_op, hash),
1895         .key_offset     = offsetof(struct promote_op, pos),
1896         .key_len        = sizeof(struct bpos),
1897 };
1898
1899 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1900                                   struct bpos pos,
1901                                   struct bch_io_opts opts,
1902                                   unsigned flags)
1903 {
1904         if (!(flags & BCH_READ_MAY_PROMOTE))
1905                 return false;
1906
1907         if (!opts.promote_target)
1908                 return false;
1909
1910         if (bch2_bkey_has_target(c, k, opts.promote_target))
1911                 return false;
1912
1913         if (bkey_extent_is_unwritten(k))
1914                 return false;
1915
1916         if (bch2_target_congested(c, opts.promote_target)) {
1917                 /* XXX trace this */
1918                 return false;
1919         }
1920
1921         if (rhashtable_lookup_fast(&c->promote_table, &pos,
1922                                    bch_promote_params))
1923                 return false;
1924
1925         return true;
1926 }
1927
1928 static void promote_free(struct bch_fs *c, struct promote_op *op)
1929 {
1930         int ret;
1931
1932         bch2_data_update_exit(&op->write);
1933
1934         ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1935                                      bch_promote_params);
1936         BUG_ON(ret);
1937         bch2_write_ref_put(c, BCH_WRITE_REF_promote);
1938         kfree_rcu(op, rcu);
1939 }
1940
1941 static void promote_done(struct bch_write_op *wop)
1942 {
1943         struct promote_op *op =
1944                 container_of(wop, struct promote_op, write.op);
1945         struct bch_fs *c = op->write.op.c;
1946
1947         bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1948                                op->start_time);
1949         promote_free(c, op);
1950 }
1951
1952 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1953 {
1954         struct bio *bio = &op->write.op.wbio.bio;
1955
1956         trace_and_count(op->write.op.c, read_promote, &rbio->bio);
1957
1958         /* we now own pages: */
1959         BUG_ON(!rbio->bounce);
1960         BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1961
1962         memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1963                sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1964         swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1965
1966         bch2_data_update_read_done(&op->write, rbio->pick.crc);
1967 }
1968
1969 static struct promote_op *__promote_alloc(struct btree_trans *trans,
1970                                           enum btree_id btree_id,
1971                                           struct bkey_s_c k,
1972                                           struct bpos pos,
1973                                           struct extent_ptr_decoded *pick,
1974                                           struct bch_io_opts opts,
1975                                           unsigned sectors,
1976                                           struct bch_read_bio **rbio)
1977 {
1978         struct bch_fs *c = trans->c;
1979         struct promote_op *op = NULL;
1980         struct bio *bio;
1981         unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1982         int ret;
1983
1984         if (!bch2_write_ref_tryget(c, BCH_WRITE_REF_promote))
1985                 return NULL;
1986
1987         op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1988         if (!op)
1989                 goto err;
1990
1991         op->start_time = local_clock();
1992         op->pos = pos;
1993
1994         /*
1995          * We don't use the mempool here because extents that aren't
1996          * checksummed or compressed can be too big for the mempool:
1997          */
1998         *rbio = kzalloc(sizeof(struct bch_read_bio) +
1999                         sizeof(struct bio_vec) * pages,
2000                         GFP_NOIO);
2001         if (!*rbio)
2002                 goto err;
2003
2004         rbio_init(&(*rbio)->bio, opts);
2005         bio_init(&(*rbio)->bio, NULL, (*rbio)->bio.bi_inline_vecs, pages, 0);
2006
2007         if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
2008                                  GFP_NOIO))
2009                 goto err;
2010
2011         (*rbio)->bounce         = true;
2012         (*rbio)->split          = true;
2013         (*rbio)->kmalloc        = true;
2014
2015         if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
2016                                           bch_promote_params))
2017                 goto err;
2018
2019         bio = &op->write.op.wbio.bio;
2020         bio_init(bio, NULL, bio->bi_inline_vecs, pages, 0);
2021
2022         ret = bch2_data_update_init(trans, NULL, &op->write,
2023                         writepoint_hashed((unsigned long) current),
2024                         opts,
2025                         (struct data_update_opts) {
2026                                 .target         = opts.promote_target,
2027                                 .extra_replicas = 1,
2028                                 .write_flags    = BCH_WRITE_ALLOC_NOWAIT|BCH_WRITE_CACHED,
2029                         },
2030                         btree_id, k);
2031         if (ret == -BCH_ERR_nocow_lock_blocked) {
2032                 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
2033                                         bch_promote_params);
2034                 BUG_ON(ret);
2035                 goto err;
2036         }
2037
2038         BUG_ON(ret);
2039         op->write.op.end_io = promote_done;
2040
2041         return op;
2042 err:
2043         if (*rbio)
2044                 bio_free_pages(&(*rbio)->bio);
2045         kfree(*rbio);
2046         *rbio = NULL;
2047         kfree(op);
2048         bch2_write_ref_put(c, BCH_WRITE_REF_promote);
2049         return NULL;
2050 }
2051
2052 noinline
2053 static struct promote_op *promote_alloc(struct btree_trans *trans,
2054                                         struct bvec_iter iter,
2055                                         struct bkey_s_c k,
2056                                         struct extent_ptr_decoded *pick,
2057                                         struct bch_io_opts opts,
2058                                         unsigned flags,
2059                                         struct bch_read_bio **rbio,
2060                                         bool *bounce,
2061                                         bool *read_full)
2062 {
2063         struct bch_fs *c = trans->c;
2064         bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
2065         /* data might have to be decompressed in the write path: */
2066         unsigned sectors = promote_full
2067                 ? max(pick->crc.compressed_size, pick->crc.live_size)
2068                 : bvec_iter_sectors(iter);
2069         struct bpos pos = promote_full
2070                 ? bkey_start_pos(k.k)
2071                 : POS(k.k->p.inode, iter.bi_sector);
2072         struct promote_op *promote;
2073
2074         if (!should_promote(c, k, pos, opts, flags))
2075                 return NULL;
2076
2077         promote = __promote_alloc(trans,
2078                                   k.k->type == KEY_TYPE_reflink_v
2079                                   ? BTREE_ID_reflink
2080                                   : BTREE_ID_extents,
2081                                   k, pos, pick, opts, sectors, rbio);
2082         if (!promote)
2083                 return NULL;
2084
2085         *bounce         = true;
2086         *read_full      = promote_full;
2087         return promote;
2088 }
2089
2090 /* Read */
2091
2092 #define READ_RETRY_AVOID        1
2093 #define READ_RETRY              2
2094 #define READ_ERR                3
2095
2096 enum rbio_context {
2097         RBIO_CONTEXT_NULL,
2098         RBIO_CONTEXT_HIGHPRI,
2099         RBIO_CONTEXT_UNBOUND,
2100 };
2101
2102 static inline struct bch_read_bio *
2103 bch2_rbio_parent(struct bch_read_bio *rbio)
2104 {
2105         return rbio->split ? rbio->parent : rbio;
2106 }
2107
2108 __always_inline
2109 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
2110                            enum rbio_context context,
2111                            struct workqueue_struct *wq)
2112 {
2113         if (context <= rbio->context) {
2114                 fn(&rbio->work);
2115         } else {
2116                 rbio->work.func         = fn;
2117                 rbio->context           = context;
2118                 queue_work(wq, &rbio->work);
2119         }
2120 }
2121
2122 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
2123 {
2124         BUG_ON(rbio->bounce && !rbio->split);
2125
2126         if (rbio->promote)
2127                 promote_free(rbio->c, rbio->promote);
2128         rbio->promote = NULL;
2129
2130         if (rbio->bounce)
2131                 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
2132
2133         if (rbio->split) {
2134                 struct bch_read_bio *parent = rbio->parent;
2135
2136                 if (rbio->kmalloc)
2137                         kfree(rbio);
2138                 else
2139                         bio_put(&rbio->bio);
2140
2141                 rbio = parent;
2142         }
2143
2144         return rbio;
2145 }
2146
2147 /*
2148  * Only called on a top level bch_read_bio to complete an entire read request,
2149  * not a split:
2150  */
2151 static void bch2_rbio_done(struct bch_read_bio *rbio)
2152 {
2153         if (rbio->start_time)
2154                 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
2155                                        rbio->start_time);
2156         bio_endio(&rbio->bio);
2157 }
2158
2159 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
2160                                      struct bvec_iter bvec_iter,
2161                                      struct bch_io_failures *failed,
2162                                      unsigned flags)
2163 {
2164         struct btree_trans trans;
2165         struct btree_iter iter;
2166         struct bkey_buf sk;
2167         struct bkey_s_c k;
2168         int ret;
2169
2170         flags &= ~BCH_READ_LAST_FRAGMENT;
2171         flags |= BCH_READ_MUST_CLONE;
2172
2173         bch2_bkey_buf_init(&sk);
2174         bch2_trans_init(&trans, c, 0, 0);
2175
2176         bch2_trans_iter_init(&trans, &iter, rbio->data_btree,
2177                              rbio->read_pos, BTREE_ITER_SLOTS);
2178 retry:
2179         rbio->bio.bi_status = 0;
2180
2181         k = bch2_btree_iter_peek_slot(&iter);
2182         if (bkey_err(k))
2183                 goto err;
2184
2185         bch2_bkey_buf_reassemble(&sk, c, k);
2186         k = bkey_i_to_s_c(sk.k);
2187         bch2_trans_unlock(&trans);
2188
2189         if (!bch2_bkey_matches_ptr(c, k,
2190                                    rbio->pick.ptr,
2191                                    rbio->data_pos.offset -
2192                                    rbio->pick.crc.offset)) {
2193                 /* extent we wanted to read no longer exists: */
2194                 rbio->hole = true;
2195                 goto out;
2196         }
2197
2198         ret = __bch2_read_extent(&trans, rbio, bvec_iter,
2199                                  rbio->read_pos,
2200                                  rbio->data_btree,
2201                                  k, 0, failed, flags);
2202         if (ret == READ_RETRY)
2203                 goto retry;
2204         if (ret)
2205                 goto err;
2206 out:
2207         bch2_rbio_done(rbio);
2208         bch2_trans_iter_exit(&trans, &iter);
2209         bch2_trans_exit(&trans);
2210         bch2_bkey_buf_exit(&sk, c);
2211         return;
2212 err:
2213         rbio->bio.bi_status = BLK_STS_IOERR;
2214         goto out;
2215 }
2216
2217 static void bch2_rbio_retry(struct work_struct *work)
2218 {
2219         struct bch_read_bio *rbio =
2220                 container_of(work, struct bch_read_bio, work);
2221         struct bch_fs *c        = rbio->c;
2222         struct bvec_iter iter   = rbio->bvec_iter;
2223         unsigned flags          = rbio->flags;
2224         subvol_inum inum = {
2225                 .subvol = rbio->subvol,
2226                 .inum   = rbio->read_pos.inode,
2227         };
2228         struct bch_io_failures failed = { .nr = 0 };
2229
2230         trace_and_count(c, read_retry, &rbio->bio);
2231
2232         if (rbio->retry == READ_RETRY_AVOID)
2233                 bch2_mark_io_failure(&failed, &rbio->pick);
2234
2235         rbio->bio.bi_status = 0;
2236
2237         rbio = bch2_rbio_free(rbio);
2238
2239         flags |= BCH_READ_IN_RETRY;
2240         flags &= ~BCH_READ_MAY_PROMOTE;
2241
2242         if (flags & BCH_READ_NODECODE) {
2243                 bch2_read_retry_nodecode(c, rbio, iter, &failed, flags);
2244         } else {
2245                 flags &= ~BCH_READ_LAST_FRAGMENT;
2246                 flags |= BCH_READ_MUST_CLONE;
2247
2248                 __bch2_read(c, rbio, iter, inum, &failed, flags);
2249         }
2250 }
2251
2252 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
2253                             blk_status_t error)
2254 {
2255         rbio->retry = retry;
2256
2257         if (rbio->flags & BCH_READ_IN_RETRY)
2258                 return;
2259
2260         if (retry == READ_ERR) {
2261                 rbio = bch2_rbio_free(rbio);
2262
2263                 rbio->bio.bi_status = error;
2264                 bch2_rbio_done(rbio);
2265         } else {
2266                 bch2_rbio_punt(rbio, bch2_rbio_retry,
2267                                RBIO_CONTEXT_UNBOUND, system_unbound_wq);
2268         }
2269 }
2270
2271 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
2272                                    struct bch_read_bio *rbio)
2273 {
2274         struct bch_fs *c = rbio->c;
2275         u64 data_offset = rbio->data_pos.offset - rbio->pick.crc.offset;
2276         struct bch_extent_crc_unpacked new_crc;
2277         struct btree_iter iter;
2278         struct bkey_i *new;
2279         struct bkey_s_c k;
2280         int ret = 0;
2281
2282         if (crc_is_compressed(rbio->pick.crc))
2283                 return 0;
2284
2285         bch2_trans_iter_init(trans, &iter, rbio->data_btree, rbio->data_pos,
2286                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2287         k = bch2_btree_iter_peek_slot(&iter);
2288         if ((ret = bkey_err(k)))
2289                 goto out;
2290
2291         if (bversion_cmp(k.k->version, rbio->version) ||
2292             !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
2293                 goto out;
2294
2295         /* Extent was merged? */
2296         if (bkey_start_offset(k.k) < data_offset ||
2297             k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
2298                 goto out;
2299
2300         if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
2301                         rbio->pick.crc, NULL, &new_crc,
2302                         bkey_start_offset(k.k) - data_offset, k.k->size,
2303                         rbio->pick.crc.csum_type)) {
2304                 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
2305                 ret = 0;
2306                 goto out;
2307         }
2308
2309         /*
2310          * going to be temporarily appending another checksum entry:
2311          */
2312         new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
2313                                  sizeof(struct bch_extent_crc128));
2314         if ((ret = PTR_ERR_OR_ZERO(new)))
2315                 goto out;
2316
2317         bkey_reassemble(new, k);
2318
2319         if (!bch2_bkey_narrow_crcs(new, new_crc))
2320                 goto out;
2321
2322         ret = bch2_trans_update(trans, &iter, new,
2323                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
2324 out:
2325         bch2_trans_iter_exit(trans, &iter);
2326         return ret;
2327 }
2328
2329 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
2330 {
2331         bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
2332                       __bch2_rbio_narrow_crcs(&trans, rbio));
2333 }
2334
2335 /* Inner part that may run in process context */
2336 static void __bch2_read_endio(struct work_struct *work)
2337 {
2338         struct bch_read_bio *rbio =
2339                 container_of(work, struct bch_read_bio, work);
2340         struct bch_fs *c        = rbio->c;
2341         struct bch_dev *ca      = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2342         struct bio *src         = &rbio->bio;
2343         struct bio *dst         = &bch2_rbio_parent(rbio)->bio;
2344         struct bvec_iter dst_iter = rbio->bvec_iter;
2345         struct bch_extent_crc_unpacked crc = rbio->pick.crc;
2346         struct nonce nonce = extent_nonce(rbio->version, crc);
2347         unsigned nofs_flags;
2348         struct bch_csum csum;
2349         int ret;
2350
2351         nofs_flags = memalloc_nofs_save();
2352
2353         /* Reset iterator for checksumming and copying bounced data: */
2354         if (rbio->bounce) {
2355                 src->bi_iter.bi_size            = crc.compressed_size << 9;
2356                 src->bi_iter.bi_idx             = 0;
2357                 src->bi_iter.bi_bvec_done       = 0;
2358         } else {
2359                 src->bi_iter                    = rbio->bvec_iter;
2360         }
2361
2362         csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
2363         if (bch2_crc_cmp(csum, rbio->pick.crc.csum) && !c->opts.no_data_io)
2364                 goto csum_err;
2365
2366         /*
2367          * XXX
2368          * We need to rework the narrow_crcs path to deliver the read completion
2369          * first, and then punt to a different workqueue, otherwise we're
2370          * holding up reads while doing btree updates which is bad for memory
2371          * reclaim.
2372          */
2373         if (unlikely(rbio->narrow_crcs))
2374                 bch2_rbio_narrow_crcs(rbio);
2375
2376         if (rbio->flags & BCH_READ_NODECODE)
2377                 goto nodecode;
2378
2379         /* Adjust crc to point to subset of data we want: */
2380         crc.offset     += rbio->offset_into_extent;
2381         crc.live_size   = bvec_iter_sectors(rbio->bvec_iter);
2382
2383         if (crc_is_compressed(crc)) {
2384                 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2385                 if (ret)
2386                         goto decrypt_err;
2387
2388                 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
2389                         goto decompression_err;
2390         } else {
2391                 /* don't need to decrypt the entire bio: */
2392                 nonce = nonce_add(nonce, crc.offset << 9);
2393                 bio_advance(src, crc.offset << 9);
2394
2395                 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
2396                 src->bi_iter.bi_size = dst_iter.bi_size;
2397
2398                 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2399                 if (ret)
2400                         goto decrypt_err;
2401
2402                 if (rbio->bounce) {
2403                         struct bvec_iter src_iter = src->bi_iter;
2404                         bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
2405                 }
2406         }
2407
2408         if (rbio->promote) {
2409                 /*
2410                  * Re encrypt data we decrypted, so it's consistent with
2411                  * rbio->crc:
2412                  */
2413                 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2414                 if (ret)
2415                         goto decrypt_err;
2416
2417                 promote_start(rbio->promote, rbio);
2418                 rbio->promote = NULL;
2419         }
2420 nodecode:
2421         if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
2422                 rbio = bch2_rbio_free(rbio);
2423                 bch2_rbio_done(rbio);
2424         }
2425 out:
2426         memalloc_nofs_restore(nofs_flags);
2427         return;
2428 csum_err:
2429         /*
2430          * Checksum error: if the bio wasn't bounced, we may have been
2431          * reading into buffers owned by userspace (that userspace can
2432          * scribble over) - retry the read, bouncing it this time:
2433          */
2434         if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
2435                 rbio->flags |= BCH_READ_MUST_BOUNCE;
2436                 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
2437                 goto out;
2438         }
2439
2440         bch_err_inum_offset_ratelimited(ca,
2441                 rbio->read_pos.inode,
2442                 rbio->read_pos.offset << 9,
2443                 "data checksum error: expected %0llx:%0llx got %0llx:%0llx (type %s)",
2444                 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
2445                 csum.hi, csum.lo, bch2_csum_types[crc.csum_type]);
2446         bch2_io_error(ca);
2447         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2448         goto out;
2449 decompression_err:
2450         bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2451                                         rbio->read_pos.offset << 9,
2452                                         "decompression error");
2453         bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2454         goto out;
2455 decrypt_err:
2456         bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2457                                         rbio->read_pos.offset << 9,
2458                                         "decrypt error");
2459         bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2460         goto out;
2461 }
2462
2463 static void bch2_read_endio(struct bio *bio)
2464 {
2465         struct bch_read_bio *rbio =
2466                 container_of(bio, struct bch_read_bio, bio);
2467         struct bch_fs *c        = rbio->c;
2468         struct bch_dev *ca      = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2469         struct workqueue_struct *wq = NULL;
2470         enum rbio_context context = RBIO_CONTEXT_NULL;
2471
2472         if (rbio->have_ioref) {
2473                 bch2_latency_acct(ca, rbio->submit_time, READ);
2474                 percpu_ref_put(&ca->io_ref);
2475         }
2476
2477         if (!rbio->split)
2478                 rbio->bio.bi_end_io = rbio->end_io;
2479
2480         if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
2481                                     rbio->read_pos.inode,
2482                                     rbio->read_pos.offset,
2483                                     "data read error: %s",
2484                                bch2_blk_status_to_str(bio->bi_status))) {
2485                 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
2486                 return;
2487         }
2488
2489         if (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
2490             ptr_stale(ca, &rbio->pick.ptr)) {
2491                 trace_and_count(c, read_reuse_race, &rbio->bio);
2492
2493                 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
2494                         bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
2495                 else
2496                         bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
2497                 return;
2498         }
2499
2500         if (rbio->narrow_crcs ||
2501             rbio->promote ||
2502             crc_is_compressed(rbio->pick.crc) ||
2503             bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
2504                 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
2505         else if (rbio->pick.crc.csum_type)
2506                 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
2507
2508         bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
2509 }
2510
2511 int __bch2_read_indirect_extent(struct btree_trans *trans,
2512                                 unsigned *offset_into_extent,
2513                                 struct bkey_buf *orig_k)
2514 {
2515         struct btree_iter iter;
2516         struct bkey_s_c k;
2517         u64 reflink_offset;
2518         int ret;
2519
2520         reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
2521                 *offset_into_extent;
2522
2523         bch2_trans_iter_init(trans, &iter, BTREE_ID_reflink,
2524                              POS(0, reflink_offset),
2525                              BTREE_ITER_SLOTS);
2526         k = bch2_btree_iter_peek_slot(&iter);
2527         ret = bkey_err(k);
2528         if (ret)
2529                 goto err;
2530
2531         if (k.k->type != KEY_TYPE_reflink_v &&
2532             k.k->type != KEY_TYPE_indirect_inline_data) {
2533                 bch_err_inum_offset_ratelimited(trans->c,
2534                         orig_k->k->k.p.inode,
2535                         orig_k->k->k.p.offset << 9,
2536                         "%llu len %u points to nonexistent indirect extent %llu",
2537                         orig_k->k->k.p.offset,
2538                         orig_k->k->k.size,
2539                         reflink_offset);
2540                 bch2_inconsistent_error(trans->c);
2541                 ret = -EIO;
2542                 goto err;
2543         }
2544
2545         *offset_into_extent = iter.pos.offset - bkey_start_offset(k.k);
2546         bch2_bkey_buf_reassemble(orig_k, trans->c, k);
2547 err:
2548         bch2_trans_iter_exit(trans, &iter);
2549         return ret;
2550 }
2551
2552 static noinline void read_from_stale_dirty_pointer(struct btree_trans *trans,
2553                                                    struct bkey_s_c k,
2554                                                    struct bch_extent_ptr ptr)
2555 {
2556         struct bch_fs *c = trans->c;
2557         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr.dev);
2558         struct btree_iter iter;
2559         struct printbuf buf = PRINTBUF;
2560         int ret;
2561
2562         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
2563                              PTR_BUCKET_POS(c, &ptr),
2564                              BTREE_ITER_CACHED);
2565
2566         prt_printf(&buf, "Attempting to read from stale dirty pointer:");
2567         printbuf_indent_add(&buf, 2);
2568         prt_newline(&buf);
2569
2570         bch2_bkey_val_to_text(&buf, c, k);
2571         prt_newline(&buf);
2572
2573         prt_printf(&buf, "memory gen: %u", *bucket_gen(ca, iter.pos.offset));
2574
2575         ret = lockrestart_do(trans, bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
2576         if (!ret) {
2577                 prt_newline(&buf);
2578                 bch2_bkey_val_to_text(&buf, c, k);
2579         }
2580
2581         bch2_fs_inconsistent(c, "%s", buf.buf);
2582
2583         bch2_trans_iter_exit(trans, &iter);
2584         printbuf_exit(&buf);
2585 }
2586
2587 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2588                        struct bvec_iter iter, struct bpos read_pos,
2589                        enum btree_id data_btree, struct bkey_s_c k,
2590                        unsigned offset_into_extent,
2591                        struct bch_io_failures *failed, unsigned flags)
2592 {
2593         struct bch_fs *c = trans->c;
2594         struct extent_ptr_decoded pick;
2595         struct bch_read_bio *rbio = NULL;
2596         struct bch_dev *ca = NULL;
2597         struct promote_op *promote = NULL;
2598         bool bounce = false, read_full = false, narrow_crcs = false;
2599         struct bpos data_pos = bkey_start_pos(k.k);
2600         int pick_ret;
2601
2602         if (bkey_extent_is_inline_data(k.k)) {
2603                 unsigned bytes = min_t(unsigned, iter.bi_size,
2604                                        bkey_inline_data_bytes(k.k));
2605
2606                 swap(iter.bi_size, bytes);
2607                 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2608                 swap(iter.bi_size, bytes);
2609                 bio_advance_iter(&orig->bio, &iter, bytes);
2610                 zero_fill_bio_iter(&orig->bio, iter);
2611                 goto out_read_done;
2612         }
2613 retry_pick:
2614         pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2615
2616         /* hole or reservation - just zero fill: */
2617         if (!pick_ret)
2618                 goto hole;
2619
2620         if (pick_ret < 0) {
2621                 bch_err_inum_offset_ratelimited(c,
2622                                 read_pos.inode, read_pos.offset << 9,
2623                                 "no device to read from");
2624                 goto err;
2625         }
2626
2627         ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2628
2629         /*
2630          * Stale dirty pointers are treated as IO errors, but @failed isn't
2631          * allocated unless we're in the retry path - so if we're not in the
2632          * retry path, don't check here, it'll be caught in bch2_read_endio()
2633          * and we'll end up in the retry path:
2634          */
2635         if ((flags & BCH_READ_IN_RETRY) &&
2636             !pick.ptr.cached &&
2637             unlikely(ptr_stale(ca, &pick.ptr))) {
2638                 read_from_stale_dirty_pointer(trans, k, pick.ptr);
2639                 bch2_mark_io_failure(failed, &pick);
2640                 goto retry_pick;
2641         }
2642
2643         /*
2644          * Unlock the iterator while the btree node's lock is still in
2645          * cache, before doing the IO:
2646          */
2647         bch2_trans_unlock(trans);
2648
2649         if (flags & BCH_READ_NODECODE) {
2650                 /*
2651                  * can happen if we retry, and the extent we were going to read
2652                  * has been merged in the meantime:
2653                  */
2654                 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2655                         goto hole;
2656
2657                 iter.bi_size    = pick.crc.compressed_size << 9;
2658                 goto get_bio;
2659         }
2660
2661         if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2662             bio_flagged(&orig->bio, BIO_CHAIN))
2663                 flags |= BCH_READ_MUST_CLONE;
2664
2665         narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2666                 bch2_can_narrow_extent_crcs(k, pick.crc);
2667
2668         if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2669                 flags |= BCH_READ_MUST_BOUNCE;
2670
2671         EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2672
2673         if (crc_is_compressed(pick.crc) ||
2674             (pick.crc.csum_type != BCH_CSUM_none &&
2675              (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2676               (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2677                (flags & BCH_READ_USER_MAPPED)) ||
2678               (flags & BCH_READ_MUST_BOUNCE)))) {
2679                 read_full = true;
2680                 bounce = true;
2681         }
2682
2683         if (orig->opts.promote_target)
2684                 promote = promote_alloc(trans, iter, k, &pick, orig->opts, flags,
2685                                         &rbio, &bounce, &read_full);
2686
2687         if (!read_full) {
2688                 EBUG_ON(crc_is_compressed(pick.crc));
2689                 EBUG_ON(pick.crc.csum_type &&
2690                         (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2691                          bvec_iter_sectors(iter) != pick.crc.live_size ||
2692                          pick.crc.offset ||
2693                          offset_into_extent));
2694
2695                 data_pos.offset += offset_into_extent;
2696                 pick.ptr.offset += pick.crc.offset +
2697                         offset_into_extent;
2698                 offset_into_extent              = 0;
2699                 pick.crc.compressed_size        = bvec_iter_sectors(iter);
2700                 pick.crc.uncompressed_size      = bvec_iter_sectors(iter);
2701                 pick.crc.offset                 = 0;
2702                 pick.crc.live_size              = bvec_iter_sectors(iter);
2703                 offset_into_extent              = 0;
2704         }
2705 get_bio:
2706         if (rbio) {
2707                 /*
2708                  * promote already allocated bounce rbio:
2709                  * promote needs to allocate a bio big enough for uncompressing
2710                  * data in the write path, but we're not going to use it all
2711                  * here:
2712                  */
2713                 EBUG_ON(rbio->bio.bi_iter.bi_size <
2714                        pick.crc.compressed_size << 9);
2715                 rbio->bio.bi_iter.bi_size =
2716                         pick.crc.compressed_size << 9;
2717         } else if (bounce) {
2718                 unsigned sectors = pick.crc.compressed_size;
2719
2720                 rbio = rbio_init(bio_alloc_bioset(NULL,
2721                                                   DIV_ROUND_UP(sectors, PAGE_SECTORS),
2722                                                   0,
2723                                                   GFP_NOIO,
2724                                                   &c->bio_read_split),
2725                                  orig->opts);
2726
2727                 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2728                 rbio->bounce    = true;
2729                 rbio->split     = true;
2730         } else if (flags & BCH_READ_MUST_CLONE) {
2731                 /*
2732                  * Have to clone if there were any splits, due to error
2733                  * reporting issues (if a split errored, and retrying didn't
2734                  * work, when it reports the error to its parent (us) we don't
2735                  * know if the error was from our bio, and we should retry, or
2736                  * from the whole bio, in which case we don't want to retry and
2737                  * lose the error)
2738                  */
2739                 rbio = rbio_init(bio_alloc_clone(NULL, &orig->bio, GFP_NOIO,
2740                                                  &c->bio_read_split),
2741                                  orig->opts);
2742                 rbio->bio.bi_iter = iter;
2743                 rbio->split     = true;
2744         } else {
2745                 rbio = orig;
2746                 rbio->bio.bi_iter = iter;
2747                 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2748         }
2749
2750         EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2751
2752         rbio->c                 = c;
2753         rbio->submit_time       = local_clock();
2754         if (rbio->split)
2755                 rbio->parent    = orig;
2756         else
2757                 rbio->end_io    = orig->bio.bi_end_io;
2758         rbio->bvec_iter         = iter;
2759         rbio->offset_into_extent= offset_into_extent;
2760         rbio->flags             = flags;
2761         rbio->have_ioref        = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2762         rbio->narrow_crcs       = narrow_crcs;
2763         rbio->hole              = 0;
2764         rbio->retry             = 0;
2765         rbio->context           = 0;
2766         /* XXX: only initialize this if needed */
2767         rbio->devs_have         = bch2_bkey_devs(k);
2768         rbio->pick              = pick;
2769         rbio->subvol            = orig->subvol;
2770         rbio->read_pos          = read_pos;
2771         rbio->data_btree        = data_btree;
2772         rbio->data_pos          = data_pos;
2773         rbio->version           = k.k->version;
2774         rbio->promote           = promote;
2775         INIT_WORK(&rbio->work, NULL);
2776
2777         rbio->bio.bi_opf        = orig->bio.bi_opf;
2778         rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2779         rbio->bio.bi_end_io     = bch2_read_endio;
2780
2781         if (rbio->bounce)
2782                 trace_and_count(c, read_bounce, &rbio->bio);
2783
2784         this_cpu_add(c->counters[BCH_COUNTER_io_read], bio_sectors(&rbio->bio));
2785         bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2786
2787         /*
2788          * If it's being moved internally, we don't want to flag it as a cache
2789          * hit:
2790          */
2791         if (pick.ptr.cached && !(flags & BCH_READ_NODECODE))
2792                 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2793                         PTR_BUCKET_NR(ca, &pick.ptr), READ);
2794
2795         if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2796                 bio_inc_remaining(&orig->bio);
2797                 trace_and_count(c, read_split, &orig->bio);
2798         }
2799
2800         if (!rbio->pick.idx) {
2801                 if (!rbio->have_ioref) {
2802                         bch_err_inum_offset_ratelimited(c,
2803                                         read_pos.inode,
2804                                         read_pos.offset << 9,
2805                                         "no device to read from");
2806                         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2807                         goto out;
2808                 }
2809
2810                 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2811                              bio_sectors(&rbio->bio));
2812                 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2813
2814                 if (unlikely(c->opts.no_data_io)) {
2815                         if (likely(!(flags & BCH_READ_IN_RETRY)))
2816                                 bio_endio(&rbio->bio);
2817                 } else {
2818                         if (likely(!(flags & BCH_READ_IN_RETRY)))
2819                                 submit_bio(&rbio->bio);
2820                         else
2821                                 submit_bio_wait(&rbio->bio);
2822                 }
2823
2824                 /*
2825                  * We just submitted IO which may block, we expect relock fail
2826                  * events and shouldn't count them:
2827                  */
2828                 trans->notrace_relock_fail = true;
2829         } else {
2830                 /* Attempting reconstruct read: */
2831                 if (bch2_ec_read_extent(c, rbio)) {
2832                         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2833                         goto out;
2834                 }
2835
2836                 if (likely(!(flags & BCH_READ_IN_RETRY)))
2837                         bio_endio(&rbio->bio);
2838         }
2839 out:
2840         if (likely(!(flags & BCH_READ_IN_RETRY))) {
2841                 return 0;
2842         } else {
2843                 int ret;
2844
2845                 rbio->context = RBIO_CONTEXT_UNBOUND;
2846                 bch2_read_endio(&rbio->bio);
2847
2848                 ret = rbio->retry;
2849                 rbio = bch2_rbio_free(rbio);
2850
2851                 if (ret == READ_RETRY_AVOID) {
2852                         bch2_mark_io_failure(failed, &pick);
2853                         ret = READ_RETRY;
2854                 }
2855
2856                 if (!ret)
2857                         goto out_read_done;
2858
2859                 return ret;
2860         }
2861
2862 err:
2863         if (flags & BCH_READ_IN_RETRY)
2864                 return READ_ERR;
2865
2866         orig->bio.bi_status = BLK_STS_IOERR;
2867         goto out_read_done;
2868
2869 hole:
2870         /*
2871          * won't normally happen in the BCH_READ_NODECODE
2872          * (bch2_move_extent()) path, but if we retry and the extent we wanted
2873          * to read no longer exists we have to signal that:
2874          */
2875         if (flags & BCH_READ_NODECODE)
2876                 orig->hole = true;
2877
2878         zero_fill_bio_iter(&orig->bio, iter);
2879 out_read_done:
2880         if (flags & BCH_READ_LAST_FRAGMENT)
2881                 bch2_rbio_done(orig);
2882         return 0;
2883 }
2884
2885 void __bch2_read(struct bch_fs *c, struct bch_read_bio *rbio,
2886                  struct bvec_iter bvec_iter, subvol_inum inum,
2887                  struct bch_io_failures *failed, unsigned flags)
2888 {
2889         struct btree_trans trans;
2890         struct btree_iter iter;
2891         struct bkey_buf sk;
2892         struct bkey_s_c k;
2893         u32 snapshot;
2894         int ret;
2895
2896         BUG_ON(flags & BCH_READ_NODECODE);
2897
2898         bch2_bkey_buf_init(&sk);
2899         bch2_trans_init(&trans, c, 0, 0);
2900 retry:
2901         bch2_trans_begin(&trans);
2902         iter = (struct btree_iter) { NULL };
2903
2904         ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
2905         if (ret)
2906                 goto err;
2907
2908         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2909                              SPOS(inum.inum, bvec_iter.bi_sector, snapshot),
2910                              BTREE_ITER_SLOTS);
2911         while (1) {
2912                 unsigned bytes, sectors, offset_into_extent;
2913                 enum btree_id data_btree = BTREE_ID_extents;
2914
2915                 /*
2916                  * read_extent -> io_time_reset may cause a transaction restart
2917                  * without returning an error, we need to check for that here:
2918                  */
2919                 ret = bch2_trans_relock(&trans);
2920                 if (ret)
2921                         break;
2922
2923                 bch2_btree_iter_set_pos(&iter,
2924                                 POS(inum.inum, bvec_iter.bi_sector));
2925
2926                 k = bch2_btree_iter_peek_slot(&iter);
2927                 ret = bkey_err(k);
2928                 if (ret)
2929                         break;
2930
2931                 offset_into_extent = iter.pos.offset -
2932                         bkey_start_offset(k.k);
2933                 sectors = k.k->size - offset_into_extent;
2934
2935                 bch2_bkey_buf_reassemble(&sk, c, k);
2936
2937                 ret = bch2_read_indirect_extent(&trans, &data_btree,
2938                                         &offset_into_extent, &sk);
2939                 if (ret)
2940                         break;
2941
2942                 k = bkey_i_to_s_c(sk.k);
2943
2944                 /*
2945                  * With indirect extents, the amount of data to read is the min
2946                  * of the original extent and the indirect extent:
2947                  */
2948                 sectors = min(sectors, k.k->size - offset_into_extent);
2949
2950                 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
2951                 swap(bvec_iter.bi_size, bytes);
2952
2953                 if (bvec_iter.bi_size == bytes)
2954                         flags |= BCH_READ_LAST_FRAGMENT;
2955
2956                 ret = __bch2_read_extent(&trans, rbio, bvec_iter, iter.pos,
2957                                          data_btree, k,
2958                                          offset_into_extent, failed, flags);
2959                 if (ret)
2960                         break;
2961
2962                 if (flags & BCH_READ_LAST_FRAGMENT)
2963                         break;
2964
2965                 swap(bvec_iter.bi_size, bytes);
2966                 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
2967
2968                 ret = btree_trans_too_many_iters(&trans);
2969                 if (ret)
2970                         break;
2971         }
2972 err:
2973         bch2_trans_iter_exit(&trans, &iter);
2974
2975         if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
2976             ret == READ_RETRY ||
2977             ret == READ_RETRY_AVOID)
2978                 goto retry;
2979
2980         bch2_trans_exit(&trans);
2981         bch2_bkey_buf_exit(&sk, c);
2982
2983         if (ret) {
2984                 bch_err_inum_offset_ratelimited(c, inum.inum,
2985                                                 bvec_iter.bi_sector << 9,
2986                                                 "read error %i from btree lookup", ret);
2987                 rbio->bio.bi_status = BLK_STS_IOERR;
2988                 bch2_rbio_done(rbio);
2989         }
2990 }
2991
2992 void bch2_fs_io_exit(struct bch_fs *c)
2993 {
2994         if (c->promote_table.tbl)
2995                 rhashtable_destroy(&c->promote_table);
2996         mempool_exit(&c->bio_bounce_pages);
2997         bioset_exit(&c->bio_write);
2998         bioset_exit(&c->bio_read_split);
2999         bioset_exit(&c->bio_read);
3000 }
3001
3002 int bch2_fs_io_init(struct bch_fs *c)
3003 {
3004         if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
3005                         BIOSET_NEED_BVECS) ||
3006             bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
3007                         BIOSET_NEED_BVECS) ||
3008             bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
3009                         BIOSET_NEED_BVECS) ||
3010             mempool_init_page_pool(&c->bio_bounce_pages,
3011                                    max_t(unsigned,
3012                                          c->opts.btree_node_size,
3013                                          c->opts.encoded_extent_max) /
3014                                    PAGE_SIZE, 0) ||
3015             rhashtable_init(&c->promote_table, &bch_promote_params))
3016                 return -ENOMEM;
3017
3018         return 0;
3019 }