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