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