]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/io.c
Merge pull request #38 from jnsaff/patch-1
[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_foreground.h"
11 #include "bkey_on_stack.h"
12 #include "bset.h"
13 #include "btree_update.h"
14 #include "buckets.h"
15 #include "checksum.h"
16 #include "compress.h"
17 #include "clock.h"
18 #include "debug.h"
19 #include "disk_groups.h"
20 #include "ec.h"
21 #include "error.h"
22 #include "extent_update.h"
23 #include "inode.h"
24 #include "io.h"
25 #include "journal.h"
26 #include "keylist.h"
27 #include "move.h"
28 #include "rebalance.h"
29 #include "super.h"
30 #include "super-io.h"
31
32 #include <linux/blkdev.h>
33 #include <linux/random.h>
34 #include <linux/sched/mm.h>
35
36 #include <trace/events/bcachefs.h>
37
38 const char *bch2_blk_status_to_str(blk_status_t status)
39 {
40         if (status == BLK_STS_REMOVED)
41                 return "device removed";
42         return blk_status_to_str(status);
43 }
44
45 static bool bch2_target_congested(struct bch_fs *c, u16 target)
46 {
47         const struct bch_devs_mask *devs;
48         unsigned d, nr = 0, total = 0;
49         u64 now = local_clock(), last;
50         s64 congested;
51         struct bch_dev *ca;
52
53         if (!target)
54                 return false;
55
56         rcu_read_lock();
57         devs = bch2_target_to_mask(c, target) ?:
58                 &c->rw_devs[BCH_DATA_user];
59
60         for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
61                 ca = rcu_dereference(c->devs[d]);
62                 if (!ca)
63                         continue;
64
65                 congested = atomic_read(&ca->congested);
66                 last = READ_ONCE(ca->congested_last);
67                 if (time_after64(now, last))
68                         congested -= (now - last) >> 12;
69
70                 total += max(congested, 0LL);
71                 nr++;
72         }
73         rcu_read_unlock();
74
75         return bch2_rand_range(nr * CONGESTED_MAX) < total;
76 }
77
78 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
79                                        u64 now, int rw)
80 {
81         u64 latency_capable =
82                 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
83         /* ideally we'd be taking into account the device's variance here: */
84         u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
85         s64 latency_over = io_latency - latency_threshold;
86
87         if (latency_threshold && latency_over > 0) {
88                 /*
89                  * bump up congested by approximately latency_over * 4 /
90                  * latency_threshold - we don't need much accuracy here so don't
91                  * bother with the divide:
92                  */
93                 if (atomic_read(&ca->congested) < CONGESTED_MAX)
94                         atomic_add(latency_over >>
95                                    max_t(int, ilog2(latency_threshold) - 2, 0),
96                                    &ca->congested);
97
98                 ca->congested_last = now;
99         } else if (atomic_read(&ca->congested) > 0) {
100                 atomic_dec(&ca->congested);
101         }
102 }
103
104 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
105 {
106         atomic64_t *latency = &ca->cur_latency[rw];
107         u64 now = local_clock();
108         u64 io_latency = time_after64(now, submit_time)
109                 ? now - submit_time
110                 : 0;
111         u64 old, new, v = atomic64_read(latency);
112
113         do {
114                 old = v;
115
116                 /*
117                  * If the io latency was reasonably close to the current
118                  * latency, skip doing the update and atomic operation - most of
119                  * the time:
120                  */
121                 if (abs((int) (old - io_latency)) < (old >> 1) &&
122                     now & ~(~0 << 5))
123                         break;
124
125                 new = ewma_add(old, io_latency, 5);
126         } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
127
128         bch2_congested_acct(ca, io_latency, now, rw);
129
130         __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
131 }
132
133 /* Allocate, free from mempool: */
134
135 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
136 {
137         struct bvec_iter_all iter;
138         struct bio_vec *bv;
139
140         bio_for_each_segment_all(bv, bio, iter)
141                 if (bv->bv_page != ZERO_PAGE(0))
142                         mempool_free(bv->bv_page, &c->bio_bounce_pages);
143         bio->bi_vcnt = 0;
144 }
145
146 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
147 {
148         struct page *page;
149
150         if (likely(!*using_mempool)) {
151                 page = alloc_page(GFP_NOIO);
152                 if (unlikely(!page)) {
153                         mutex_lock(&c->bio_bounce_pages_lock);
154                         *using_mempool = true;
155                         goto pool_alloc;
156
157                 }
158         } else {
159 pool_alloc:
160                 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
161         }
162
163         return page;
164 }
165
166 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
167                                size_t size)
168 {
169         bool using_mempool = false;
170
171         while (size) {
172                 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
173                 unsigned len = min(PAGE_SIZE, size);
174
175                 BUG_ON(!bio_add_page(bio, page, len, 0));
176                 size -= len;
177         }
178
179         if (using_mempool)
180                 mutex_unlock(&c->bio_bounce_pages_lock);
181 }
182
183 /* Extent update path: */
184
185 static int sum_sector_overwrites(struct btree_trans *trans,
186                                  struct btree_iter *extent_iter,
187                                  struct bkey_i *new,
188                                  bool may_allocate,
189                                  bool *maybe_extending,
190                                  s64 *delta)
191 {
192         struct btree_iter *iter;
193         struct bkey_s_c old;
194         int ret = 0;
195
196         *maybe_extending = true;
197         *delta = 0;
198
199         iter = bch2_trans_copy_iter(trans, extent_iter);
200         if (IS_ERR(iter))
201                 return PTR_ERR(iter);
202
203         for_each_btree_key_continue(iter, BTREE_ITER_SLOTS, old, ret) {
204                 if (!may_allocate &&
205                     bch2_bkey_nr_ptrs_fully_allocated(old) <
206                     bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new))) {
207                         ret = -ENOSPC;
208                         break;
209                 }
210
211                 *delta += (min(new->k.p.offset,
212                               old.k->p.offset) -
213                           max(bkey_start_offset(&new->k),
214                               bkey_start_offset(old.k))) *
215                         (bkey_extent_is_allocation(&new->k) -
216                          bkey_extent_is_allocation(old.k));
217
218                 if (bkey_cmp(old.k->p, new->k.p) >= 0) {
219                         /*
220                          * Check if there's already data above where we're
221                          * going to be writing to - this means we're definitely
222                          * not extending the file:
223                          *
224                          * Note that it's not sufficient to check if there's
225                          * data up to the sector offset we're going to be
226                          * writing to, because i_size could be up to one block
227                          * less:
228                          */
229                         if (!bkey_cmp(old.k->p, new->k.p))
230                                 old = bch2_btree_iter_next(iter);
231
232                         if (old.k && !bkey_err(old) &&
233                             old.k->p.inode == extent_iter->pos.inode &&
234                             bkey_extent_is_data(old.k))
235                                 *maybe_extending = false;
236
237                         break;
238                 }
239         }
240
241         bch2_trans_iter_put(trans, iter);
242         return ret;
243 }
244
245 int bch2_extent_update(struct btree_trans *trans,
246                        struct btree_iter *iter,
247                        struct bkey_i *k,
248                        struct disk_reservation *disk_res,
249                        u64 *journal_seq,
250                        u64 new_i_size,
251                        s64 *i_sectors_delta)
252 {
253         /* this must live until after bch2_trans_commit(): */
254         struct bkey_inode_buf inode_p;
255         bool extending = false;
256         s64 delta = 0;
257         int ret;
258
259         ret = bch2_extent_trim_atomic(k, iter);
260         if (ret)
261                 return ret;
262
263         ret = sum_sector_overwrites(trans, iter, k,
264                         disk_res && disk_res->sectors != 0,
265                         &extending, &delta);
266         if (ret)
267                 return ret;
268
269         new_i_size = extending
270                 ? min(k->k.p.offset << 9, new_i_size)
271                 : 0;
272
273         if (delta || new_i_size) {
274                 struct btree_iter *inode_iter;
275                 struct bch_inode_unpacked inode_u;
276
277                 inode_iter = bch2_inode_peek(trans, &inode_u,
278                                 k->k.p.inode, BTREE_ITER_INTENT);
279                 if (IS_ERR(inode_iter))
280                         return PTR_ERR(inode_iter);
281
282                 /*
283                  * XXX:
284                  * writeback can race a bit with truncate, because truncate
285                  * first updates the inode then truncates the pagecache. This is
286                  * ugly, but lets us preserve the invariant that the in memory
287                  * i_size is always >= the on disk i_size.
288                  *
289                 BUG_ON(new_i_size > inode_u.bi_size &&
290                        (inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY));
291                  */
292                 BUG_ON(new_i_size > inode_u.bi_size && !extending);
293
294                 if (!(inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
295                     new_i_size > inode_u.bi_size)
296                         inode_u.bi_size = new_i_size;
297                 else
298                         new_i_size = 0;
299
300                 inode_u.bi_sectors += delta;
301
302                 if (delta || new_i_size) {
303                         bch2_inode_pack(&inode_p, &inode_u);
304                         bch2_trans_update(trans, inode_iter,
305                                           &inode_p.inode.k_i, 0);
306                 }
307
308                 bch2_trans_iter_put(trans, inode_iter);
309         }
310
311         bch2_trans_update(trans, iter, k, 0);
312
313         ret = bch2_trans_commit(trans, disk_res, journal_seq,
314                                 BTREE_INSERT_NOCHECK_RW|
315                                 BTREE_INSERT_NOFAIL|
316                                 BTREE_INSERT_USE_RESERVE);
317         if (!ret && i_sectors_delta)
318                 *i_sectors_delta += delta;
319
320         return ret;
321 }
322
323 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
324                    struct bpos end, u64 *journal_seq,
325                    s64 *i_sectors_delta)
326 {
327         struct bch_fs *c        = trans->c;
328         unsigned max_sectors    = KEY_SIZE_MAX & (~0 << c->block_bits);
329         struct bkey_s_c k;
330         int ret = 0, ret2 = 0;
331
332         while ((k = bch2_btree_iter_peek(iter)).k &&
333                bkey_cmp(iter->pos, end) < 0) {
334                 struct disk_reservation disk_res =
335                         bch2_disk_reservation_init(c, 0);
336                 struct bkey_i delete;
337
338                 bch2_trans_begin(trans);
339
340                 ret = bkey_err(k);
341                 if (ret)
342                         goto btree_err;
343
344                 bkey_init(&delete.k);
345                 delete.k.p = iter->pos;
346
347                 /* create the biggest key we can */
348                 bch2_key_resize(&delete.k, max_sectors);
349                 bch2_cut_back(end, &delete);
350
351                 ret = bch2_extent_update(trans, iter, &delete,
352                                 &disk_res, journal_seq,
353                                 0, i_sectors_delta);
354                 bch2_disk_reservation_put(c, &disk_res);
355 btree_err:
356                 if (ret == -EINTR) {
357                         ret2 = ret;
358                         ret = 0;
359                 }
360                 if (ret)
361                         break;
362         }
363
364         if (bkey_cmp(iter->pos, end) > 0) {
365                 bch2_btree_iter_set_pos(iter, end);
366                 ret = bch2_btree_iter_traverse(iter);
367         }
368
369         return ret ?: ret2;
370 }
371
372 int bch2_fpunch(struct bch_fs *c, u64 inum, u64 start, u64 end,
373                 u64 *journal_seq, s64 *i_sectors_delta)
374 {
375         struct btree_trans trans;
376         struct btree_iter *iter;
377         int ret = 0;
378
379         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
380         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
381                                    POS(inum, start),
382                                    BTREE_ITER_INTENT);
383
384         ret = bch2_fpunch_at(&trans, iter, POS(inum, end),
385                              journal_seq, i_sectors_delta);
386         bch2_trans_exit(&trans);
387
388         if (ret == -EINTR)
389                 ret = 0;
390
391         return ret;
392 }
393
394 int bch2_write_index_default(struct bch_write_op *op)
395 {
396         struct bch_fs *c = op->c;
397         struct bkey_on_stack sk;
398         struct keylist *keys = &op->insert_keys;
399         struct bkey_i *k = bch2_keylist_front(keys);
400         struct btree_trans trans;
401         struct btree_iter *iter;
402         int ret;
403
404         bkey_on_stack_init(&sk);
405         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
406
407         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
408                                    bkey_start_pos(&k->k),
409                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
410
411         do {
412                 bch2_trans_begin(&trans);
413
414                 k = bch2_keylist_front(keys);
415
416                 bkey_on_stack_realloc(&sk, c, k->k.u64s);
417                 bkey_copy(sk.k, k);
418                 bch2_cut_front(iter->pos, sk.k);
419
420                 ret = bch2_extent_update(&trans, iter, sk.k,
421                                          &op->res, op_journal_seq(op),
422                                          op->new_i_size, &op->i_sectors_delta);
423                 if (ret == -EINTR)
424                         continue;
425                 if (ret)
426                         break;
427
428                 if (bkey_cmp(iter->pos, k->k.p) >= 0)
429                         bch2_keylist_pop_front(keys);
430         } while (!bch2_keylist_empty(keys));
431
432         bch2_trans_exit(&trans);
433         bkey_on_stack_exit(&sk, c);
434
435         return ret;
436 }
437
438 /* Writes */
439
440 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
441                                enum bch_data_type type,
442                                const struct bkey_i *k)
443 {
444         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
445         const struct bch_extent_ptr *ptr;
446         struct bch_write_bio *n;
447         struct bch_dev *ca;
448
449         BUG_ON(c->opts.nochanges);
450
451         bkey_for_each_ptr(ptrs, ptr) {
452                 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
453                        !c->devs[ptr->dev]);
454
455                 ca = bch_dev_bkey_exists(c, ptr->dev);
456
457                 if (to_entry(ptr + 1) < ptrs.end) {
458                         n = to_wbio(bio_clone_fast(&wbio->bio, GFP_NOIO,
459                                                    &ca->replica_set));
460
461                         n->bio.bi_end_io        = wbio->bio.bi_end_io;
462                         n->bio.bi_private       = wbio->bio.bi_private;
463                         n->parent               = wbio;
464                         n->split                = true;
465                         n->bounce               = false;
466                         n->put_bio              = true;
467                         n->bio.bi_opf           = wbio->bio.bi_opf;
468                         bio_inc_remaining(&wbio->bio);
469                 } else {
470                         n = wbio;
471                         n->split                = false;
472                 }
473
474                 n->c                    = c;
475                 n->dev                  = ptr->dev;
476                 n->have_ioref           = bch2_dev_get_ioref(ca,
477                                         type == BCH_DATA_btree ? READ : WRITE);
478                 n->submit_time          = local_clock();
479                 n->bio.bi_iter.bi_sector = ptr->offset;
480
481                 if (!journal_flushes_device(ca))
482                         n->bio.bi_opf |= REQ_FUA;
483
484                 if (likely(n->have_ioref)) {
485                         this_cpu_add(ca->io_done->sectors[WRITE][type],
486                                      bio_sectors(&n->bio));
487
488                         bio_set_dev(&n->bio, ca->disk_sb.bdev);
489                         submit_bio(&n->bio);
490                 } else {
491                         n->bio.bi_status        = BLK_STS_REMOVED;
492                         bio_endio(&n->bio);
493                 }
494         }
495 }
496
497 static void __bch2_write(struct closure *);
498
499 static void bch2_write_done(struct closure *cl)
500 {
501         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
502         struct bch_fs *c = op->c;
503
504         if (!op->error && (op->flags & BCH_WRITE_FLUSH))
505                 op->error = bch2_journal_error(&c->journal);
506
507         bch2_disk_reservation_put(c, &op->res);
508         percpu_ref_put(&c->writes);
509         bch2_keylist_free(&op->insert_keys, op->inline_keys);
510
511         bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
512
513         if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
514                 up(&c->io_in_flight);
515
516         if (op->end_io) {
517                 EBUG_ON(cl->parent);
518                 closure_debug_destroy(cl);
519                 op->end_io(op);
520         } else {
521                 closure_return(cl);
522         }
523 }
524
525 /**
526  * bch_write_index - after a write, update index to point to new data
527  */
528 static void __bch2_write_index(struct bch_write_op *op)
529 {
530         struct bch_fs *c = op->c;
531         struct keylist *keys = &op->insert_keys;
532         struct bch_extent_ptr *ptr;
533         struct bkey_i *src, *dst = keys->keys, *n, *k;
534         unsigned dev;
535         int ret;
536
537         for (src = keys->keys; src != keys->top; src = n) {
538                 n = bkey_next(src);
539
540                 if (bkey_extent_is_direct_data(&src->k)) {
541                         bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
542                                             test_bit(ptr->dev, op->failed.d));
543
544                         if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src))) {
545                                 ret = -EIO;
546                                 goto err;
547                         }
548                 }
549
550                 if (dst != src)
551                         memmove_u64s_down(dst, src, src->u64s);
552                 dst = bkey_next(dst);
553         }
554
555         keys->top = dst;
556
557         /*
558          * probably not the ideal place to hook this in, but I don't
559          * particularly want to plumb io_opts all the way through the btree
560          * update stack right now
561          */
562         for_each_keylist_key(keys, k) {
563                 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
564
565                 if (bch2_bkey_is_incompressible(bkey_i_to_s_c(k)))
566                         bch2_check_set_feature(op->c, BCH_FEATURE_incompressible);
567
568         }
569
570         if (!bch2_keylist_empty(keys)) {
571                 u64 sectors_start = keylist_sectors(keys);
572                 int ret = op->index_update_fn(op);
573
574                 BUG_ON(ret == -EINTR);
575                 BUG_ON(keylist_sectors(keys) && !ret);
576
577                 op->written += sectors_start - keylist_sectors(keys);
578
579                 if (ret) {
580                         __bcache_io_error(c, "btree IO error %i", ret);
581                         op->error = ret;
582                 }
583         }
584 out:
585         /* If some a bucket wasn't written, we can't erasure code it: */
586         for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
587                 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
588
589         bch2_open_buckets_put(c, &op->open_buckets);
590         return;
591 err:
592         keys->top = keys->keys;
593         op->error = ret;
594         goto out;
595 }
596
597 static void bch2_write_index(struct closure *cl)
598 {
599         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
600         struct bch_fs *c = op->c;
601
602         __bch2_write_index(op);
603
604         if (!(op->flags & BCH_WRITE_DONE)) {
605                 continue_at(cl, __bch2_write, index_update_wq(op));
606         } else if (!op->error && (op->flags & BCH_WRITE_FLUSH)) {
607                 bch2_journal_flush_seq_async(&c->journal,
608                                              *op_journal_seq(op),
609                                              cl);
610                 continue_at(cl, bch2_write_done, index_update_wq(op));
611         } else {
612                 continue_at_nobarrier(cl, bch2_write_done, NULL);
613         }
614 }
615
616 static void bch2_write_endio(struct bio *bio)
617 {
618         struct closure *cl              = bio->bi_private;
619         struct bch_write_op *op         = container_of(cl, struct bch_write_op, cl);
620         struct bch_write_bio *wbio      = to_wbio(bio);
621         struct bch_write_bio *parent    = wbio->split ? wbio->parent : NULL;
622         struct bch_fs *c                = wbio->c;
623         struct bch_dev *ca              = bch_dev_bkey_exists(c, wbio->dev);
624
625         if (bch2_dev_io_err_on(bio->bi_status, ca, "data write: %s",
626                                bch2_blk_status_to_str(bio->bi_status)))
627                 set_bit(wbio->dev, op->failed.d);
628
629         if (wbio->have_ioref) {
630                 bch2_latency_acct(ca, wbio->submit_time, WRITE);
631                 percpu_ref_put(&ca->io_ref);
632         }
633
634         if (wbio->bounce)
635                 bch2_bio_free_pages_pool(c, bio);
636
637         if (wbio->put_bio)
638                 bio_put(bio);
639
640         if (parent)
641                 bio_endio(&parent->bio);
642         else if (!(op->flags & BCH_WRITE_SKIP_CLOSURE_PUT))
643                 closure_put(cl);
644         else
645                 continue_at_nobarrier(cl, bch2_write_index, index_update_wq(op));
646 }
647
648 static void init_append_extent(struct bch_write_op *op,
649                                struct write_point *wp,
650                                struct bversion version,
651                                struct bch_extent_crc_unpacked crc)
652 {
653         struct bch_fs *c = op->c;
654         struct bkey_i_extent *e;
655         struct open_bucket *ob;
656         unsigned i;
657
658         BUG_ON(crc.compressed_size > wp->sectors_free);
659         wp->sectors_free -= crc.compressed_size;
660         op->pos.offset += crc.uncompressed_size;
661
662         e = bkey_extent_init(op->insert_keys.top);
663         e->k.p          = op->pos;
664         e->k.size       = crc.uncompressed_size;
665         e->k.version    = version;
666
667         if (crc.csum_type ||
668             crc.compression_type ||
669             crc.nonce)
670                 bch2_extent_crc_append(&e->k_i, crc);
671
672         open_bucket_for_each(c, &wp->ptrs, ob, i) {
673                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
674                 union bch_extent_entry *end =
675                         bkey_val_end(bkey_i_to_s(&e->k_i));
676
677                 end->ptr = ob->ptr;
678                 end->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
679                 end->ptr.cached = !ca->mi.durability ||
680                         (op->flags & BCH_WRITE_CACHED) != 0;
681                 end->ptr.offset += ca->mi.bucket_size - ob->sectors_free;
682
683                 e->k.u64s++;
684
685                 BUG_ON(crc.compressed_size > ob->sectors_free);
686                 ob->sectors_free -= crc.compressed_size;
687         }
688
689         bch2_keylist_push(&op->insert_keys);
690 }
691
692 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
693                                         struct write_point *wp,
694                                         struct bio *src,
695                                         bool *page_alloc_failed,
696                                         void *buf)
697 {
698         struct bch_write_bio *wbio;
699         struct bio *bio;
700         unsigned output_available =
701                 min(wp->sectors_free << 9, src->bi_iter.bi_size);
702         unsigned pages = DIV_ROUND_UP(output_available +
703                                       (buf
704                                        ? ((unsigned long) buf & (PAGE_SIZE - 1))
705                                        : 0), PAGE_SIZE);
706
707         bio = bio_alloc_bioset(GFP_NOIO, pages, &c->bio_write);
708         wbio                    = wbio_init(bio);
709         wbio->put_bio           = true;
710         /* copy WRITE_SYNC flag */
711         wbio->bio.bi_opf        = src->bi_opf;
712
713         if (buf) {
714                 bch2_bio_map(bio, buf, output_available);
715                 return bio;
716         }
717
718         wbio->bounce            = true;
719
720         /*
721          * We can't use mempool for more than c->sb.encoded_extent_max
722          * worth of pages, but we'd like to allocate more if we can:
723          */
724         bch2_bio_alloc_pages_pool(c, bio,
725                                   min_t(unsigned, output_available,
726                                         c->sb.encoded_extent_max << 9));
727
728         if (bio->bi_iter.bi_size < output_available)
729                 *page_alloc_failed =
730                         bch2_bio_alloc_pages(bio,
731                                              output_available -
732                                              bio->bi_iter.bi_size,
733                                              GFP_NOFS) != 0;
734
735         return bio;
736 }
737
738 static int bch2_write_rechecksum(struct bch_fs *c,
739                                  struct bch_write_op *op,
740                                  unsigned new_csum_type)
741 {
742         struct bio *bio = &op->wbio.bio;
743         struct bch_extent_crc_unpacked new_crc;
744         int ret;
745
746         /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
747
748         if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
749             bch2_csum_type_is_encryption(new_csum_type))
750                 new_csum_type = op->crc.csum_type;
751
752         ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
753                                   NULL, &new_crc,
754                                   op->crc.offset, op->crc.live_size,
755                                   new_csum_type);
756         if (ret)
757                 return ret;
758
759         bio_advance(bio, op->crc.offset << 9);
760         bio->bi_iter.bi_size = op->crc.live_size << 9;
761         op->crc = new_crc;
762         return 0;
763 }
764
765 static int bch2_write_decrypt(struct bch_write_op *op)
766 {
767         struct bch_fs *c = op->c;
768         struct nonce nonce = extent_nonce(op->version, op->crc);
769         struct bch_csum csum;
770
771         if (!bch2_csum_type_is_encryption(op->crc.csum_type))
772                 return 0;
773
774         /*
775          * If we need to decrypt data in the write path, we'll no longer be able
776          * to verify the existing checksum (poly1305 mac, in this case) after
777          * it's decrypted - this is the last point we'll be able to reverify the
778          * checksum:
779          */
780         csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
781         if (bch2_crc_cmp(op->crc.csum, csum))
782                 return -EIO;
783
784         bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
785         op->crc.csum_type = 0;
786         op->crc.csum = (struct bch_csum) { 0, 0 };
787         return 0;
788 }
789
790 static enum prep_encoded_ret {
791         PREP_ENCODED_OK,
792         PREP_ENCODED_ERR,
793         PREP_ENCODED_CHECKSUM_ERR,
794         PREP_ENCODED_DO_WRITE,
795 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
796 {
797         struct bch_fs *c = op->c;
798         struct bio *bio = &op->wbio.bio;
799
800         if (!(op->flags & BCH_WRITE_DATA_ENCODED))
801                 return PREP_ENCODED_OK;
802
803         BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
804
805         /* Can we just write the entire extent as is? */
806         if (op->crc.uncompressed_size == op->crc.live_size &&
807             op->crc.compressed_size <= wp->sectors_free &&
808             (op->crc.compression_type == op->compression_type ||
809              op->incompressible)) {
810                 if (!crc_is_compressed(op->crc) &&
811                     op->csum_type != op->crc.csum_type &&
812                     bch2_write_rechecksum(c, op, op->csum_type))
813                         return PREP_ENCODED_CHECKSUM_ERR;
814
815                 return PREP_ENCODED_DO_WRITE;
816         }
817
818         /*
819          * If the data is compressed and we couldn't write the entire extent as
820          * is, we have to decompress it:
821          */
822         if (crc_is_compressed(op->crc)) {
823                 struct bch_csum csum;
824
825                 if (bch2_write_decrypt(op))
826                         return PREP_ENCODED_CHECKSUM_ERR;
827
828                 /* Last point we can still verify checksum: */
829                 csum = bch2_checksum_bio(c, op->crc.csum_type,
830                                          extent_nonce(op->version, op->crc),
831                                          bio);
832                 if (bch2_crc_cmp(op->crc.csum, csum))
833                         return PREP_ENCODED_CHECKSUM_ERR;
834
835                 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
836                         return PREP_ENCODED_ERR;
837         }
838
839         /*
840          * No longer have compressed data after this point - data might be
841          * encrypted:
842          */
843
844         /*
845          * If the data is checksummed and we're only writing a subset,
846          * rechecksum and adjust bio to point to currently live data:
847          */
848         if ((op->crc.live_size != op->crc.uncompressed_size ||
849              op->crc.csum_type != op->csum_type) &&
850             bch2_write_rechecksum(c, op, op->csum_type))
851                 return PREP_ENCODED_CHECKSUM_ERR;
852
853         /*
854          * If we want to compress the data, it has to be decrypted:
855          */
856         if ((op->compression_type ||
857              bch2_csum_type_is_encryption(op->crc.csum_type) !=
858              bch2_csum_type_is_encryption(op->csum_type)) &&
859             bch2_write_decrypt(op))
860                 return PREP_ENCODED_CHECKSUM_ERR;
861
862         return PREP_ENCODED_OK;
863 }
864
865 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
866                              struct bio **_dst)
867 {
868         struct bch_fs *c = op->c;
869         struct bio *src = &op->wbio.bio, *dst = src;
870         struct bvec_iter saved_iter;
871         void *ec_buf;
872         struct bpos ec_pos = op->pos;
873         unsigned total_output = 0, total_input = 0;
874         bool bounce = false;
875         bool page_alloc_failed = false;
876         int ret, more = 0;
877
878         BUG_ON(!bio_sectors(src));
879
880         ec_buf = bch2_writepoint_ec_buf(c, wp);
881
882         switch (bch2_write_prep_encoded_data(op, wp)) {
883         case PREP_ENCODED_OK:
884                 break;
885         case PREP_ENCODED_ERR:
886                 ret = -EIO;
887                 goto err;
888         case PREP_ENCODED_CHECKSUM_ERR:
889                 BUG();
890                 goto csum_err;
891         case PREP_ENCODED_DO_WRITE:
892                 /* XXX look for bug here */
893                 if (ec_buf) {
894                         dst = bch2_write_bio_alloc(c, wp, src,
895                                                    &page_alloc_failed,
896                                                    ec_buf);
897                         bio_copy_data(dst, src);
898                         bounce = true;
899                 }
900                 init_append_extent(op, wp, op->version, op->crc);
901                 goto do_write;
902         }
903
904         if (ec_buf ||
905             op->compression_type ||
906             (op->csum_type &&
907              !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
908             (bch2_csum_type_is_encryption(op->csum_type) &&
909              !(op->flags & BCH_WRITE_PAGES_OWNED))) {
910                 dst = bch2_write_bio_alloc(c, wp, src,
911                                            &page_alloc_failed,
912                                            ec_buf);
913                 bounce = true;
914         }
915
916         saved_iter = dst->bi_iter;
917
918         do {
919                 struct bch_extent_crc_unpacked crc =
920                         (struct bch_extent_crc_unpacked) { 0 };
921                 struct bversion version = op->version;
922                 size_t dst_len, src_len;
923
924                 if (page_alloc_failed &&
925                     bio_sectors(dst) < wp->sectors_free &&
926                     bio_sectors(dst) < c->sb.encoded_extent_max)
927                         break;
928
929                 BUG_ON(op->compression_type &&
930                        (op->flags & BCH_WRITE_DATA_ENCODED) &&
931                        bch2_csum_type_is_encryption(op->crc.csum_type));
932                 BUG_ON(op->compression_type && !bounce);
933
934                 crc.compression_type = op->incompressible
935                         ? BCH_COMPRESSION_TYPE_incompressible
936                         : op->compression_type
937                         ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
938                                             op->compression_type)
939                         : 0;
940                 if (!crc_is_compressed(crc)) {
941                         dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
942                         dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
943
944                         if (op->csum_type)
945                                 dst_len = min_t(unsigned, dst_len,
946                                                 c->sb.encoded_extent_max << 9);
947
948                         if (bounce) {
949                                 swap(dst->bi_iter.bi_size, dst_len);
950                                 bio_copy_data(dst, src);
951                                 swap(dst->bi_iter.bi_size, dst_len);
952                         }
953
954                         src_len = dst_len;
955                 }
956
957                 BUG_ON(!src_len || !dst_len);
958
959                 if (bch2_csum_type_is_encryption(op->csum_type)) {
960                         if (bversion_zero(version)) {
961                                 version.lo = atomic64_inc_return(&c->key_version);
962                         } else {
963                                 crc.nonce = op->nonce;
964                                 op->nonce += src_len >> 9;
965                         }
966                 }
967
968                 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
969                     !crc_is_compressed(crc) &&
970                     bch2_csum_type_is_encryption(op->crc.csum_type) ==
971                     bch2_csum_type_is_encryption(op->csum_type)) {
972                         /*
973                          * Note: when we're using rechecksum(), we need to be
974                          * checksumming @src because it has all the data our
975                          * existing checksum covers - if we bounced (because we
976                          * were trying to compress), @dst will only have the
977                          * part of the data the new checksum will cover.
978                          *
979                          * But normally we want to be checksumming post bounce,
980                          * because part of the reason for bouncing is so the
981                          * data can't be modified (by userspace) while it's in
982                          * flight.
983                          */
984                         if (bch2_rechecksum_bio(c, src, version, op->crc,
985                                         &crc, &op->crc,
986                                         src_len >> 9,
987                                         bio_sectors(src) - (src_len >> 9),
988                                         op->csum_type))
989                                 goto csum_err;
990                 } else {
991                         if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
992                             bch2_rechecksum_bio(c, src, version, op->crc,
993                                         NULL, &op->crc,
994                                         src_len >> 9,
995                                         bio_sectors(src) - (src_len >> 9),
996                                         op->crc.csum_type))
997                                 goto csum_err;
998
999                         crc.compressed_size     = dst_len >> 9;
1000                         crc.uncompressed_size   = src_len >> 9;
1001                         crc.live_size           = src_len >> 9;
1002
1003                         swap(dst->bi_iter.bi_size, dst_len);
1004                         bch2_encrypt_bio(c, op->csum_type,
1005                                          extent_nonce(version, crc), dst);
1006                         crc.csum = bch2_checksum_bio(c, op->csum_type,
1007                                          extent_nonce(version, crc), dst);
1008                         crc.csum_type = op->csum_type;
1009                         swap(dst->bi_iter.bi_size, dst_len);
1010                 }
1011
1012                 init_append_extent(op, wp, version, crc);
1013
1014                 if (dst != src)
1015                         bio_advance(dst, dst_len);
1016                 bio_advance(src, src_len);
1017                 total_output    += dst_len;
1018                 total_input     += src_len;
1019         } while (dst->bi_iter.bi_size &&
1020                  src->bi_iter.bi_size &&
1021                  wp->sectors_free &&
1022                  !bch2_keylist_realloc(&op->insert_keys,
1023                                       op->inline_keys,
1024                                       ARRAY_SIZE(op->inline_keys),
1025                                       BKEY_EXTENT_U64s_MAX));
1026
1027         more = src->bi_iter.bi_size != 0;
1028
1029         dst->bi_iter = saved_iter;
1030
1031         if (dst == src && more) {
1032                 BUG_ON(total_output != total_input);
1033
1034                 dst = bio_split(src, total_input >> 9,
1035                                 GFP_NOIO, &c->bio_write);
1036                 wbio_init(dst)->put_bio = true;
1037                 /* copy WRITE_SYNC flag */
1038                 dst->bi_opf             = src->bi_opf;
1039         }
1040
1041         dst->bi_iter.bi_size = total_output;
1042 do_write:
1043         /* might have done a realloc... */
1044         bch2_ec_add_backpointer(c, wp, ec_pos, total_input >> 9);
1045
1046         *_dst = dst;
1047         return more;
1048 csum_err:
1049         bch_err(c, "error verifying existing checksum while "
1050                 "rewriting existing data (memory corruption?)");
1051         ret = -EIO;
1052 err:
1053         if (to_wbio(dst)->bounce)
1054                 bch2_bio_free_pages_pool(c, dst);
1055         if (to_wbio(dst)->put_bio)
1056                 bio_put(dst);
1057
1058         return ret;
1059 }
1060
1061 static void __bch2_write(struct closure *cl)
1062 {
1063         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1064         struct bch_fs *c = op->c;
1065         struct write_point *wp;
1066         struct bio *bio;
1067         bool skip_put = true;
1068         unsigned nofs_flags;
1069         int ret;
1070
1071         nofs_flags = memalloc_nofs_save();
1072 again:
1073         memset(&op->failed, 0, sizeof(op->failed));
1074
1075         do {
1076                 struct bkey_i *key_to_write;
1077                 unsigned key_to_write_offset = op->insert_keys.top_p -
1078                         op->insert_keys.keys_p;
1079
1080                 /* +1 for possible cache device: */
1081                 if (op->open_buckets.nr + op->nr_replicas + 1 >
1082                     ARRAY_SIZE(op->open_buckets.v))
1083                         goto flush_io;
1084
1085                 if (bch2_keylist_realloc(&op->insert_keys,
1086                                         op->inline_keys,
1087                                         ARRAY_SIZE(op->inline_keys),
1088                                         BKEY_EXTENT_U64s_MAX))
1089                         goto flush_io;
1090
1091                 if ((op->flags & BCH_WRITE_FROM_INTERNAL) &&
1092                     percpu_ref_is_dying(&c->writes)) {
1093                         ret = -EROFS;
1094                         goto err;
1095                 }
1096
1097                 /*
1098                  * The copygc thread is now global, which means it's no longer
1099                  * freeing up space on specific disks, which means that
1100                  * allocations for specific disks may hang arbitrarily long:
1101                  */
1102                 wp = bch2_alloc_sectors_start(c,
1103                         op->target,
1104                         op->opts.erasure_code,
1105                         op->write_point,
1106                         &op->devs_have,
1107                         op->nr_replicas,
1108                         op->nr_replicas_required,
1109                         op->alloc_reserve,
1110                         op->flags,
1111                         (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1112                                       BCH_WRITE_ONLY_SPECIFIED_DEVS)) ? NULL : cl);
1113                 EBUG_ON(!wp);
1114
1115                 if (unlikely(IS_ERR(wp))) {
1116                         if (unlikely(PTR_ERR(wp) != -EAGAIN)) {
1117                                 ret = PTR_ERR(wp);
1118                                 goto err;
1119                         }
1120
1121                         goto flush_io;
1122                 }
1123
1124                 /*
1125                  * It's possible for the allocator to fail, put us on the
1126                  * freelist waitlist, and then succeed in one of various retry
1127                  * paths: if that happens, we need to disable the skip_put
1128                  * optimization because otherwise there won't necessarily be a
1129                  * barrier before we free the bch_write_op:
1130                  */
1131                 if (atomic_read(&cl->remaining) & CLOSURE_WAITING)
1132                         skip_put = false;
1133
1134                 bch2_open_bucket_get(c, wp, &op->open_buckets);
1135                 ret = bch2_write_extent(op, wp, &bio);
1136                 bch2_alloc_sectors_done(c, wp);
1137
1138                 if (ret < 0)
1139                         goto err;
1140
1141                 if (ret) {
1142                         skip_put = false;
1143                 } else {
1144                         /*
1145                          * for the skip_put optimization this has to be set
1146                          * before we submit the bio:
1147                          */
1148                         op->flags |= BCH_WRITE_DONE;
1149                 }
1150
1151                 bio->bi_end_io  = bch2_write_endio;
1152                 bio->bi_private = &op->cl;
1153                 bio->bi_opf |= REQ_OP_WRITE;
1154
1155                 if (!skip_put)
1156                         closure_get(bio->bi_private);
1157                 else
1158                         op->flags |= BCH_WRITE_SKIP_CLOSURE_PUT;
1159
1160                 key_to_write = (void *) (op->insert_keys.keys_p +
1161                                          key_to_write_offset);
1162
1163                 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1164                                           key_to_write);
1165         } while (ret);
1166
1167         if (!skip_put)
1168                 continue_at(cl, bch2_write_index, index_update_wq(op));
1169 out:
1170         memalloc_nofs_restore(nofs_flags);
1171         return;
1172 err:
1173         op->error = ret;
1174         op->flags |= BCH_WRITE_DONE;
1175
1176         continue_at(cl, bch2_write_index, index_update_wq(op));
1177         goto out;
1178 flush_io:
1179         /*
1180          * If the write can't all be submitted at once, we generally want to
1181          * block synchronously as that signals backpressure to the caller.
1182          *
1183          * However, if we're running out of a workqueue, we can't block here
1184          * because we'll be blocking other work items from completing:
1185          */
1186         if (current->flags & PF_WQ_WORKER) {
1187                 continue_at(cl, bch2_write_index, index_update_wq(op));
1188                 goto out;
1189         }
1190
1191         closure_sync(cl);
1192
1193         if (!bch2_keylist_empty(&op->insert_keys)) {
1194                 __bch2_write_index(op);
1195
1196                 if (op->error) {
1197                         op->flags |= BCH_WRITE_DONE;
1198                         continue_at_nobarrier(cl, bch2_write_done, NULL);
1199                         goto out;
1200                 }
1201         }
1202
1203         goto again;
1204 }
1205
1206 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1207 {
1208         struct closure *cl = &op->cl;
1209         struct bio *bio = &op->wbio.bio;
1210         struct bvec_iter iter;
1211         struct bkey_i_inline_data *id;
1212         unsigned sectors;
1213         int ret;
1214
1215         bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1216
1217         ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1218                                    ARRAY_SIZE(op->inline_keys),
1219                                    BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1220         if (ret) {
1221                 op->error = ret;
1222                 goto err;
1223         }
1224
1225         sectors = bio_sectors(bio);
1226         op->pos.offset += sectors;
1227
1228         id = bkey_inline_data_init(op->insert_keys.top);
1229         id->k.p         = op->pos;
1230         id->k.version   = op->version;
1231         id->k.size      = sectors;
1232
1233         iter = bio->bi_iter;
1234         iter.bi_size = data_len;
1235         memcpy_from_bio(id->v.data, bio, iter);
1236
1237         while (data_len & 7)
1238                 id->v.data[data_len++] = '\0';
1239         set_bkey_val_bytes(&id->k, data_len);
1240         bch2_keylist_push(&op->insert_keys);
1241
1242         op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1243         op->flags |= BCH_WRITE_DONE;
1244
1245         continue_at_nobarrier(cl, bch2_write_index, NULL);
1246         return;
1247 err:
1248         bch2_write_done(&op->cl);
1249 }
1250
1251 /**
1252  * bch_write - handle a write to a cache device or flash only volume
1253  *
1254  * This is the starting point for any data to end up in a cache device; it could
1255  * be from a normal write, or a writeback write, or a write to a flash only
1256  * volume - it's also used by the moving garbage collector to compact data in
1257  * mostly empty buckets.
1258  *
1259  * It first writes the data to the cache, creating a list of keys to be inserted
1260  * (if the data won't fit in a single open bucket, there will be multiple keys);
1261  * after the data is written it calls bch_journal, and after the keys have been
1262  * added to the next journal write they're inserted into the btree.
1263  *
1264  * If op->discard is true, instead of inserting the data it invalidates the
1265  * region of the cache represented by op->bio and op->inode.
1266  */
1267 void bch2_write(struct closure *cl)
1268 {
1269         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1270         struct bio *bio = &op->wbio.bio;
1271         struct bch_fs *c = op->c;
1272         unsigned data_len;
1273
1274         BUG_ON(!op->nr_replicas);
1275         BUG_ON(!op->write_point.v);
1276         BUG_ON(!bkey_cmp(op->pos, POS_MAX));
1277
1278         op->start_time = local_clock();
1279         bch2_keylist_init(&op->insert_keys, op->inline_keys);
1280         wbio_init(bio)->put_bio = false;
1281
1282         if (bio_sectors(bio) & (c->opts.block_size - 1)) {
1283                 __bcache_io_error(c, "misaligned write");
1284                 op->error = -EIO;
1285                 goto err;
1286         }
1287
1288         if (c->opts.nochanges ||
1289             !percpu_ref_tryget(&c->writes)) {
1290                 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1291                         __bcache_io_error(c, "read only");
1292                 op->error = -EROFS;
1293                 goto err;
1294         }
1295
1296         /*
1297          * Can't ratelimit copygc - we'd deadlock:
1298          */
1299         if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1300                 down(&c->io_in_flight);
1301
1302         bch2_increment_clock(c, bio_sectors(bio), WRITE);
1303
1304         data_len = min_t(u64, bio->bi_iter.bi_size,
1305                          op->new_i_size - (op->pos.offset << 9));
1306
1307         if (c->opts.inline_data &&
1308             data_len <= min(block_bytes(c) / 2, 1024U)) {
1309                 bch2_write_data_inline(op, data_len);
1310                 return;
1311         }
1312
1313         continue_at_nobarrier(cl, __bch2_write, NULL);
1314         return;
1315 err:
1316         bch2_disk_reservation_put(c, &op->res);
1317
1318         if (op->end_io) {
1319                 EBUG_ON(cl->parent);
1320                 closure_debug_destroy(cl);
1321                 op->end_io(op);
1322         } else {
1323                 closure_return(cl);
1324         }
1325 }
1326
1327 /* Cache promotion on read */
1328
1329 struct promote_op {
1330         struct closure          cl;
1331         struct rcu_head         rcu;
1332         u64                     start_time;
1333
1334         struct rhash_head       hash;
1335         struct bpos             pos;
1336
1337         struct migrate_write    write;
1338         struct bio_vec          bi_inline_vecs[0]; /* must be last */
1339 };
1340
1341 static const struct rhashtable_params bch_promote_params = {
1342         .head_offset    = offsetof(struct promote_op, hash),
1343         .key_offset     = offsetof(struct promote_op, pos),
1344         .key_len        = sizeof(struct bpos),
1345 };
1346
1347 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1348                                   struct bpos pos,
1349                                   struct bch_io_opts opts,
1350                                   unsigned flags)
1351 {
1352         if (!(flags & BCH_READ_MAY_PROMOTE))
1353                 return false;
1354
1355         if (!opts.promote_target)
1356                 return false;
1357
1358         if (bch2_bkey_has_target(c, k, opts.promote_target))
1359                 return false;
1360
1361         if (bch2_target_congested(c, opts.promote_target)) {
1362                 /* XXX trace this */
1363                 return false;
1364         }
1365
1366         if (rhashtable_lookup_fast(&c->promote_table, &pos,
1367                                    bch_promote_params))
1368                 return false;
1369
1370         return true;
1371 }
1372
1373 static void promote_free(struct bch_fs *c, struct promote_op *op)
1374 {
1375         int ret;
1376
1377         ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1378                                      bch_promote_params);
1379         BUG_ON(ret);
1380         percpu_ref_put(&c->writes);
1381         kfree_rcu(op, rcu);
1382 }
1383
1384 static void promote_done(struct closure *cl)
1385 {
1386         struct promote_op *op =
1387                 container_of(cl, struct promote_op, cl);
1388         struct bch_fs *c = op->write.op.c;
1389
1390         bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1391                                op->start_time);
1392
1393         bch2_bio_free_pages_pool(c, &op->write.op.wbio.bio);
1394         promote_free(c, op);
1395 }
1396
1397 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1398 {
1399         struct bch_fs *c = rbio->c;
1400         struct closure *cl = &op->cl;
1401         struct bio *bio = &op->write.op.wbio.bio;
1402
1403         trace_promote(&rbio->bio);
1404
1405         /* we now own pages: */
1406         BUG_ON(!rbio->bounce);
1407         BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1408
1409         memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1410                sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1411         swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1412
1413         bch2_migrate_read_done(&op->write, rbio);
1414
1415         closure_init(cl, NULL);
1416         closure_call(&op->write.op.cl, bch2_write, c->wq, cl);
1417         closure_return_with_destructor(cl, promote_done);
1418 }
1419
1420 static struct promote_op *__promote_alloc(struct bch_fs *c,
1421                                           enum btree_id btree_id,
1422                                           struct bkey_s_c k,
1423                                           struct bpos pos,
1424                                           struct extent_ptr_decoded *pick,
1425                                           struct bch_io_opts opts,
1426                                           unsigned sectors,
1427                                           struct bch_read_bio **rbio)
1428 {
1429         struct promote_op *op = NULL;
1430         struct bio *bio;
1431         unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1432         int ret;
1433
1434         if (!percpu_ref_tryget(&c->writes))
1435                 return NULL;
1436
1437         op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1438         if (!op)
1439                 goto err;
1440
1441         op->start_time = local_clock();
1442         op->pos = pos;
1443
1444         /*
1445          * We don't use the mempool here because extents that aren't
1446          * checksummed or compressed can be too big for the mempool:
1447          */
1448         *rbio = kzalloc(sizeof(struct bch_read_bio) +
1449                         sizeof(struct bio_vec) * pages,
1450                         GFP_NOIO);
1451         if (!*rbio)
1452                 goto err;
1453
1454         rbio_init(&(*rbio)->bio, opts);
1455         bio_init(&(*rbio)->bio, (*rbio)->bio.bi_inline_vecs, pages);
1456
1457         if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1458                                  GFP_NOIO))
1459                 goto err;
1460
1461         (*rbio)->bounce         = true;
1462         (*rbio)->split          = true;
1463         (*rbio)->kmalloc        = true;
1464
1465         if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1466                                           bch_promote_params))
1467                 goto err;
1468
1469         bio = &op->write.op.wbio.bio;
1470         bio_init(bio, bio->bi_inline_vecs, pages);
1471
1472         ret = bch2_migrate_write_init(c, &op->write,
1473                         writepoint_hashed((unsigned long) current),
1474                         opts,
1475                         DATA_PROMOTE,
1476                         (struct data_opts) {
1477                                 .target = opts.promote_target
1478                         },
1479                         btree_id, k);
1480         BUG_ON(ret);
1481
1482         return op;
1483 err:
1484         if (*rbio)
1485                 bio_free_pages(&(*rbio)->bio);
1486         kfree(*rbio);
1487         *rbio = NULL;
1488         kfree(op);
1489         percpu_ref_put(&c->writes);
1490         return NULL;
1491 }
1492
1493 noinline
1494 static struct promote_op *promote_alloc(struct bch_fs *c,
1495                                                struct bvec_iter iter,
1496                                                struct bkey_s_c k,
1497                                                struct extent_ptr_decoded *pick,
1498                                                struct bch_io_opts opts,
1499                                                unsigned flags,
1500                                                struct bch_read_bio **rbio,
1501                                                bool *bounce,
1502                                                bool *read_full)
1503 {
1504         bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1505         /* data might have to be decompressed in the write path: */
1506         unsigned sectors = promote_full
1507                 ? max(pick->crc.compressed_size, pick->crc.live_size)
1508                 : bvec_iter_sectors(iter);
1509         struct bpos pos = promote_full
1510                 ? bkey_start_pos(k.k)
1511                 : POS(k.k->p.inode, iter.bi_sector);
1512         struct promote_op *promote;
1513
1514         if (!should_promote(c, k, pos, opts, flags))
1515                 return NULL;
1516
1517         promote = __promote_alloc(c,
1518                                   k.k->type == KEY_TYPE_reflink_v
1519                                   ? BTREE_ID_REFLINK
1520                                   : BTREE_ID_EXTENTS,
1521                                   k, pos, pick, opts, sectors, rbio);
1522         if (!promote)
1523                 return NULL;
1524
1525         *bounce         = true;
1526         *read_full      = promote_full;
1527         return promote;
1528 }
1529
1530 /* Read */
1531
1532 #define READ_RETRY_AVOID        1
1533 #define READ_RETRY              2
1534 #define READ_ERR                3
1535
1536 enum rbio_context {
1537         RBIO_CONTEXT_NULL,
1538         RBIO_CONTEXT_HIGHPRI,
1539         RBIO_CONTEXT_UNBOUND,
1540 };
1541
1542 static inline struct bch_read_bio *
1543 bch2_rbio_parent(struct bch_read_bio *rbio)
1544 {
1545         return rbio->split ? rbio->parent : rbio;
1546 }
1547
1548 __always_inline
1549 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
1550                            enum rbio_context context,
1551                            struct workqueue_struct *wq)
1552 {
1553         if (context <= rbio->context) {
1554                 fn(&rbio->work);
1555         } else {
1556                 rbio->work.func         = fn;
1557                 rbio->context           = context;
1558                 queue_work(wq, &rbio->work);
1559         }
1560 }
1561
1562 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
1563 {
1564         BUG_ON(rbio->bounce && !rbio->split);
1565
1566         if (rbio->promote)
1567                 promote_free(rbio->c, rbio->promote);
1568         rbio->promote = NULL;
1569
1570         if (rbio->bounce)
1571                 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
1572
1573         if (rbio->split) {
1574                 struct bch_read_bio *parent = rbio->parent;
1575
1576                 if (rbio->kmalloc)
1577                         kfree(rbio);
1578                 else
1579                         bio_put(&rbio->bio);
1580
1581                 rbio = parent;
1582         }
1583
1584         return rbio;
1585 }
1586
1587 /*
1588  * Only called on a top level bch_read_bio to complete an entire read request,
1589  * not a split:
1590  */
1591 static void bch2_rbio_done(struct bch_read_bio *rbio)
1592 {
1593         if (rbio->start_time)
1594                 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
1595                                        rbio->start_time);
1596         bio_endio(&rbio->bio);
1597 }
1598
1599 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
1600                                      struct bvec_iter bvec_iter, u64 inode,
1601                                      struct bch_io_failures *failed,
1602                                      unsigned flags)
1603 {
1604         struct btree_trans trans;
1605         struct btree_iter *iter;
1606         struct bkey_on_stack sk;
1607         struct bkey_s_c k;
1608         int ret;
1609
1610         flags &= ~BCH_READ_LAST_FRAGMENT;
1611         flags |= BCH_READ_MUST_CLONE;
1612
1613         bkey_on_stack_init(&sk);
1614         bch2_trans_init(&trans, c, 0, 0);
1615
1616         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
1617                                    rbio->pos, BTREE_ITER_SLOTS);
1618 retry:
1619         rbio->bio.bi_status = 0;
1620
1621         k = bch2_btree_iter_peek_slot(iter);
1622         if (bkey_err(k))
1623                 goto err;
1624
1625         bkey_on_stack_reassemble(&sk, c, k);
1626         k = bkey_i_to_s_c(sk.k);
1627         bch2_trans_unlock(&trans);
1628
1629         if (!bch2_bkey_matches_ptr(c, k,
1630                                    rbio->pick.ptr,
1631                                    rbio->pos.offset -
1632                                    rbio->pick.crc.offset)) {
1633                 /* extent we wanted to read no longer exists: */
1634                 rbio->hole = true;
1635                 goto out;
1636         }
1637
1638         ret = __bch2_read_extent(c, rbio, bvec_iter, k, 0, failed, flags);
1639         if (ret == READ_RETRY)
1640                 goto retry;
1641         if (ret)
1642                 goto err;
1643 out:
1644         bch2_rbio_done(rbio);
1645         bch2_trans_exit(&trans);
1646         bkey_on_stack_exit(&sk, c);
1647         return;
1648 err:
1649         rbio->bio.bi_status = BLK_STS_IOERR;
1650         goto out;
1651 }
1652
1653 static void bch2_read_retry(struct bch_fs *c, struct bch_read_bio *rbio,
1654                             struct bvec_iter bvec_iter, u64 inode,
1655                             struct bch_io_failures *failed, unsigned flags)
1656 {
1657         struct btree_trans trans;
1658         struct btree_iter *iter;
1659         struct bkey_on_stack sk;
1660         struct bkey_s_c k;
1661         int ret;
1662
1663         flags &= ~BCH_READ_LAST_FRAGMENT;
1664         flags |= BCH_READ_MUST_CLONE;
1665
1666         bkey_on_stack_init(&sk);
1667         bch2_trans_init(&trans, c, 0, 0);
1668 retry:
1669         bch2_trans_begin(&trans);
1670
1671         for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS,
1672                            POS(inode, bvec_iter.bi_sector),
1673                            BTREE_ITER_SLOTS, k, ret) {
1674                 unsigned bytes, sectors, offset_into_extent;
1675
1676                 bkey_on_stack_reassemble(&sk, c, k);
1677                 k = bkey_i_to_s_c(sk.k);
1678
1679                 offset_into_extent = iter->pos.offset -
1680                         bkey_start_offset(k.k);
1681                 sectors = k.k->size - offset_into_extent;
1682
1683                 ret = bch2_read_indirect_extent(&trans,
1684                                         &offset_into_extent, &sk);
1685                 if (ret)
1686                         break;
1687
1688                 sectors = min(sectors, k.k->size - offset_into_extent);
1689
1690                 bch2_trans_unlock(&trans);
1691
1692                 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
1693                 swap(bvec_iter.bi_size, bytes);
1694
1695                 ret = __bch2_read_extent(c, rbio, bvec_iter, k,
1696                                 offset_into_extent, failed, flags);
1697                 switch (ret) {
1698                 case READ_RETRY:
1699                         goto retry;
1700                 case READ_ERR:
1701                         goto err;
1702                 };
1703
1704                 if (bytes == bvec_iter.bi_size)
1705                         goto out;
1706
1707                 swap(bvec_iter.bi_size, bytes);
1708                 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
1709         }
1710
1711         if (ret == -EINTR)
1712                 goto retry;
1713         /*
1714          * If we get here, it better have been because there was an error
1715          * reading a btree node
1716          */
1717         BUG_ON(!ret);
1718         __bcache_io_error(c, "btree IO error: %i", ret);
1719 err:
1720         rbio->bio.bi_status = BLK_STS_IOERR;
1721 out:
1722         bch2_trans_exit(&trans);
1723         bkey_on_stack_exit(&sk, c);
1724         bch2_rbio_done(rbio);
1725 }
1726
1727 static void bch2_rbio_retry(struct work_struct *work)
1728 {
1729         struct bch_read_bio *rbio =
1730                 container_of(work, struct bch_read_bio, work);
1731         struct bch_fs *c        = rbio->c;
1732         struct bvec_iter iter   = rbio->bvec_iter;
1733         unsigned flags          = rbio->flags;
1734         u64 inode               = rbio->pos.inode;
1735         struct bch_io_failures failed = { .nr = 0 };
1736
1737         trace_read_retry(&rbio->bio);
1738
1739         if (rbio->retry == READ_RETRY_AVOID)
1740                 bch2_mark_io_failure(&failed, &rbio->pick);
1741
1742         rbio->bio.bi_status = 0;
1743
1744         rbio = bch2_rbio_free(rbio);
1745
1746         flags |= BCH_READ_IN_RETRY;
1747         flags &= ~BCH_READ_MAY_PROMOTE;
1748
1749         if (flags & BCH_READ_NODECODE)
1750                 bch2_read_retry_nodecode(c, rbio, iter, inode, &failed, flags);
1751         else
1752                 bch2_read_retry(c, rbio, iter, inode, &failed, flags);
1753 }
1754
1755 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
1756                             blk_status_t error)
1757 {
1758         rbio->retry = retry;
1759
1760         if (rbio->flags & BCH_READ_IN_RETRY)
1761                 return;
1762
1763         if (retry == READ_ERR) {
1764                 rbio = bch2_rbio_free(rbio);
1765
1766                 rbio->bio.bi_status = error;
1767                 bch2_rbio_done(rbio);
1768         } else {
1769                 bch2_rbio_punt(rbio, bch2_rbio_retry,
1770                                RBIO_CONTEXT_UNBOUND, system_unbound_wq);
1771         }
1772 }
1773
1774 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
1775                                    struct bch_read_bio *rbio)
1776 {
1777         struct bch_fs *c = rbio->c;
1778         u64 data_offset = rbio->pos.offset - rbio->pick.crc.offset;
1779         struct bch_extent_crc_unpacked new_crc;
1780         struct btree_iter *iter = NULL;
1781         struct bkey_i *new;
1782         struct bkey_s_c k;
1783         int ret = 0;
1784
1785         if (crc_is_compressed(rbio->pick.crc))
1786                 return 0;
1787
1788         iter = bch2_trans_get_iter(trans, BTREE_ID_EXTENTS, rbio->pos,
1789                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1790         if ((ret = PTR_ERR_OR_ZERO(iter)))
1791                 goto out;
1792
1793         k = bch2_btree_iter_peek_slot(iter);
1794         if ((ret = bkey_err(k)))
1795                 goto out;
1796
1797         /*
1798          * going to be temporarily appending another checksum entry:
1799          */
1800         new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
1801                                  BKEY_EXTENT_U64s_MAX * 8);
1802         if ((ret = PTR_ERR_OR_ZERO(new)))
1803                 goto out;
1804
1805         bkey_reassemble(new, k);
1806         k = bkey_i_to_s_c(new);
1807
1808         if (bversion_cmp(k.k->version, rbio->version) ||
1809             !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
1810                 goto out;
1811
1812         /* Extent was merged? */
1813         if (bkey_start_offset(k.k) < data_offset ||
1814             k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
1815                 goto out;
1816
1817         if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
1818                         rbio->pick.crc, NULL, &new_crc,
1819                         bkey_start_offset(k.k) - data_offset, k.k->size,
1820                         rbio->pick.crc.csum_type)) {
1821                 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
1822                 ret = 0;
1823                 goto out;
1824         }
1825
1826         if (!bch2_bkey_narrow_crcs(new, new_crc))
1827                 goto out;
1828
1829         bch2_trans_update(trans, iter, new, 0);
1830 out:
1831         bch2_trans_iter_put(trans, iter);
1832         return ret;
1833 }
1834
1835 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
1836 {
1837         bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
1838                       __bch2_rbio_narrow_crcs(&trans, rbio));
1839 }
1840
1841 /* Inner part that may run in process context */
1842 static void __bch2_read_endio(struct work_struct *work)
1843 {
1844         struct bch_read_bio *rbio =
1845                 container_of(work, struct bch_read_bio, work);
1846         struct bch_fs *c        = rbio->c;
1847         struct bch_dev *ca      = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1848         struct bio *src         = &rbio->bio;
1849         struct bio *dst         = &bch2_rbio_parent(rbio)->bio;
1850         struct bvec_iter dst_iter = rbio->bvec_iter;
1851         struct bch_extent_crc_unpacked crc = rbio->pick.crc;
1852         struct nonce nonce = extent_nonce(rbio->version, crc);
1853         struct bch_csum csum;
1854
1855         /* Reset iterator for checksumming and copying bounced data: */
1856         if (rbio->bounce) {
1857                 src->bi_iter.bi_size            = crc.compressed_size << 9;
1858                 src->bi_iter.bi_idx             = 0;
1859                 src->bi_iter.bi_bvec_done       = 0;
1860         } else {
1861                 src->bi_iter                    = rbio->bvec_iter;
1862         }
1863
1864         csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
1865         if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
1866                 goto csum_err;
1867
1868         if (unlikely(rbio->narrow_crcs))
1869                 bch2_rbio_narrow_crcs(rbio);
1870
1871         if (rbio->flags & BCH_READ_NODECODE)
1872                 goto nodecode;
1873
1874         /* Adjust crc to point to subset of data we want: */
1875         crc.offset     += rbio->offset_into_extent;
1876         crc.live_size   = bvec_iter_sectors(rbio->bvec_iter);
1877
1878         if (crc_is_compressed(crc)) {
1879                 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1880                 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
1881                         goto decompression_err;
1882         } else {
1883                 /* don't need to decrypt the entire bio: */
1884                 nonce = nonce_add(nonce, crc.offset << 9);
1885                 bio_advance(src, crc.offset << 9);
1886
1887                 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
1888                 src->bi_iter.bi_size = dst_iter.bi_size;
1889
1890                 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1891
1892                 if (rbio->bounce) {
1893                         struct bvec_iter src_iter = src->bi_iter;
1894                         bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
1895                 }
1896         }
1897
1898         if (rbio->promote) {
1899                 /*
1900                  * Re encrypt data we decrypted, so it's consistent with
1901                  * rbio->crc:
1902                  */
1903                 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1904                 promote_start(rbio->promote, rbio);
1905                 rbio->promote = NULL;
1906         }
1907 nodecode:
1908         if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
1909                 rbio = bch2_rbio_free(rbio);
1910                 bch2_rbio_done(rbio);
1911         }
1912         return;
1913 csum_err:
1914         /*
1915          * Checksum error: if the bio wasn't bounced, we may have been
1916          * reading into buffers owned by userspace (that userspace can
1917          * scribble over) - retry the read, bouncing it this time:
1918          */
1919         if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
1920                 rbio->flags |= BCH_READ_MUST_BOUNCE;
1921                 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
1922                 return;
1923         }
1924
1925         bch2_dev_io_error(ca,
1926                 "data checksum error, inode %llu offset %llu: expected %0llx:%0llx got %0llx:%0llx (type %u)",
1927                 rbio->pos.inode, (u64) rbio->bvec_iter.bi_sector,
1928                 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
1929                 csum.hi, csum.lo, crc.csum_type);
1930         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
1931         return;
1932 decompression_err:
1933         __bcache_io_error(c, "decompression error, inode %llu offset %llu",
1934                           rbio->pos.inode,
1935                           (u64) rbio->bvec_iter.bi_sector);
1936         bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
1937         return;
1938 }
1939
1940 static void bch2_read_endio(struct bio *bio)
1941 {
1942         struct bch_read_bio *rbio =
1943                 container_of(bio, struct bch_read_bio, bio);
1944         struct bch_fs *c        = rbio->c;
1945         struct bch_dev *ca      = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1946         struct workqueue_struct *wq = NULL;
1947         enum rbio_context context = RBIO_CONTEXT_NULL;
1948
1949         if (rbio->have_ioref) {
1950                 bch2_latency_acct(ca, rbio->submit_time, READ);
1951                 percpu_ref_put(&ca->io_ref);
1952         }
1953
1954         if (!rbio->split)
1955                 rbio->bio.bi_end_io = rbio->end_io;
1956
1957         if (bch2_dev_io_err_on(bio->bi_status, ca, "data read; %s",
1958                                bch2_blk_status_to_str(bio->bi_status))) {
1959                 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
1960                 return;
1961         }
1962
1963         if (rbio->pick.ptr.cached &&
1964             (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
1965              ptr_stale(ca, &rbio->pick.ptr))) {
1966                 atomic_long_inc(&c->read_realloc_races);
1967
1968                 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
1969                         bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
1970                 else
1971                         bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
1972                 return;
1973         }
1974
1975         if (rbio->narrow_crcs ||
1976             crc_is_compressed(rbio->pick.crc) ||
1977             bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
1978                 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
1979         else if (rbio->pick.crc.csum_type)
1980                 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
1981
1982         bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
1983 }
1984
1985 int __bch2_read_indirect_extent(struct btree_trans *trans,
1986                                 unsigned *offset_into_extent,
1987                                 struct bkey_on_stack *orig_k)
1988 {
1989         struct btree_iter *iter;
1990         struct bkey_s_c k;
1991         u64 reflink_offset;
1992         int ret;
1993
1994         reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
1995                 *offset_into_extent;
1996
1997         iter = bch2_trans_get_iter(trans, BTREE_ID_REFLINK,
1998                                    POS(0, reflink_offset),
1999                                    BTREE_ITER_SLOTS);
2000         ret = PTR_ERR_OR_ZERO(iter);
2001         if (ret)
2002                 return ret;
2003
2004         k = bch2_btree_iter_peek_slot(iter);
2005         ret = bkey_err(k);
2006         if (ret)
2007                 goto err;
2008
2009         if (k.k->type != KEY_TYPE_reflink_v) {
2010                 __bcache_io_error(trans->c,
2011                                 "pointer to nonexistent indirect extent");
2012                 ret = -EIO;
2013                 goto err;
2014         }
2015
2016         *offset_into_extent = iter->pos.offset - bkey_start_offset(k.k);
2017         bkey_on_stack_reassemble(orig_k, trans->c, k);
2018 err:
2019         bch2_trans_iter_put(trans, iter);
2020         return ret;
2021 }
2022
2023 int __bch2_read_extent(struct bch_fs *c, struct bch_read_bio *orig,
2024                        struct bvec_iter iter, struct bkey_s_c k,
2025                        unsigned offset_into_extent,
2026                        struct bch_io_failures *failed, unsigned flags)
2027 {
2028         struct extent_ptr_decoded pick;
2029         struct bch_read_bio *rbio = NULL;
2030         struct bch_dev *ca;
2031         struct promote_op *promote = NULL;
2032         bool bounce = false, read_full = false, narrow_crcs = false;
2033         struct bpos pos = bkey_start_pos(k.k);
2034         int pick_ret;
2035
2036         if (k.k->type == KEY_TYPE_inline_data) {
2037                 struct bkey_s_c_inline_data d = bkey_s_c_to_inline_data(k);
2038                 unsigned bytes = min_t(unsigned, iter.bi_size,
2039                                        bkey_val_bytes(d.k));
2040
2041                 swap(iter.bi_size, bytes);
2042                 memcpy_to_bio(&orig->bio, iter, d.v->data);
2043                 swap(iter.bi_size, bytes);
2044                 bio_advance_iter(&orig->bio, &iter, bytes);
2045                 zero_fill_bio_iter(&orig->bio, iter);
2046                 goto out_read_done;
2047         }
2048
2049         pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2050
2051         /* hole or reservation - just zero fill: */
2052         if (!pick_ret)
2053                 goto hole;
2054
2055         if (pick_ret < 0) {
2056                 __bcache_io_error(c, "no device to read from");
2057                 goto err;
2058         }
2059
2060         if (pick_ret > 0)
2061                 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2062
2063         if (flags & BCH_READ_NODECODE) {
2064                 /*
2065                  * can happen if we retry, and the extent we were going to read
2066                  * has been merged in the meantime:
2067                  */
2068                 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2069                         goto hole;
2070
2071                 iter.bi_size    = pick.crc.compressed_size << 9;
2072                 goto get_bio;
2073         }
2074
2075         if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2076             bio_flagged(&orig->bio, BIO_CHAIN))
2077                 flags |= BCH_READ_MUST_CLONE;
2078
2079         narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2080                 bch2_can_narrow_extent_crcs(k, pick.crc);
2081
2082         if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2083                 flags |= BCH_READ_MUST_BOUNCE;
2084
2085         EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2086
2087         if (crc_is_compressed(pick.crc) ||
2088             (pick.crc.csum_type != BCH_CSUM_NONE &&
2089              (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2090               (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2091                (flags & BCH_READ_USER_MAPPED)) ||
2092               (flags & BCH_READ_MUST_BOUNCE)))) {
2093                 read_full = true;
2094                 bounce = true;
2095         }
2096
2097         if (orig->opts.promote_target)
2098                 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2099                                         &rbio, &bounce, &read_full);
2100
2101         if (!read_full) {
2102                 EBUG_ON(crc_is_compressed(pick.crc));
2103                 EBUG_ON(pick.crc.csum_type &&
2104                         (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2105                          bvec_iter_sectors(iter) != pick.crc.live_size ||
2106                          pick.crc.offset ||
2107                          offset_into_extent));
2108
2109                 pos.offset += offset_into_extent;
2110                 pick.ptr.offset += pick.crc.offset +
2111                         offset_into_extent;
2112                 offset_into_extent              = 0;
2113                 pick.crc.compressed_size        = bvec_iter_sectors(iter);
2114                 pick.crc.uncompressed_size      = bvec_iter_sectors(iter);
2115                 pick.crc.offset                 = 0;
2116                 pick.crc.live_size              = bvec_iter_sectors(iter);
2117                 offset_into_extent              = 0;
2118         }
2119 get_bio:
2120         if (rbio) {
2121                 /*
2122                  * promote already allocated bounce rbio:
2123                  * promote needs to allocate a bio big enough for uncompressing
2124                  * data in the write path, but we're not going to use it all
2125                  * here:
2126                  */
2127                 EBUG_ON(rbio->bio.bi_iter.bi_size <
2128                        pick.crc.compressed_size << 9);
2129                 rbio->bio.bi_iter.bi_size =
2130                         pick.crc.compressed_size << 9;
2131         } else if (bounce) {
2132                 unsigned sectors = pick.crc.compressed_size;
2133
2134                 rbio = rbio_init(bio_alloc_bioset(GFP_NOIO,
2135                                                   DIV_ROUND_UP(sectors, PAGE_SECTORS),
2136                                                   &c->bio_read_split),
2137                                  orig->opts);
2138
2139                 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2140                 rbio->bounce    = true;
2141                 rbio->split     = true;
2142         } else if (flags & BCH_READ_MUST_CLONE) {
2143                 /*
2144                  * Have to clone if there were any splits, due to error
2145                  * reporting issues (if a split errored, and retrying didn't
2146                  * work, when it reports the error to its parent (us) we don't
2147                  * know if the error was from our bio, and we should retry, or
2148                  * from the whole bio, in which case we don't want to retry and
2149                  * lose the error)
2150                  */
2151                 rbio = rbio_init(bio_clone_fast(&orig->bio, GFP_NOIO,
2152                                                 &c->bio_read_split),
2153                                  orig->opts);
2154                 rbio->bio.bi_iter = iter;
2155                 rbio->split     = true;
2156         } else {
2157                 rbio = orig;
2158                 rbio->bio.bi_iter = iter;
2159                 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2160         }
2161
2162         EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2163
2164         rbio->c                 = c;
2165         rbio->submit_time       = local_clock();
2166         if (rbio->split)
2167                 rbio->parent    = orig;
2168         else
2169                 rbio->end_io    = orig->bio.bi_end_io;
2170         rbio->bvec_iter         = iter;
2171         rbio->offset_into_extent= offset_into_extent;
2172         rbio->flags             = flags;
2173         rbio->have_ioref        = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2174         rbio->narrow_crcs       = narrow_crcs;
2175         rbio->hole              = 0;
2176         rbio->retry             = 0;
2177         rbio->context           = 0;
2178         /* XXX: only initialize this if needed */
2179         rbio->devs_have         = bch2_bkey_devs(k);
2180         rbio->pick              = pick;
2181         rbio->pos               = pos;
2182         rbio->version           = k.k->version;
2183         rbio->promote           = promote;
2184         INIT_WORK(&rbio->work, NULL);
2185
2186         rbio->bio.bi_opf        = orig->bio.bi_opf;
2187         rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2188         rbio->bio.bi_end_io     = bch2_read_endio;
2189
2190         if (rbio->bounce)
2191                 trace_read_bounce(&rbio->bio);
2192
2193         bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2194
2195         rcu_read_lock();
2196         bucket_io_clock_reset(c, ca, PTR_BUCKET_NR(ca, &pick.ptr), READ);
2197         rcu_read_unlock();
2198
2199         if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2200                 bio_inc_remaining(&orig->bio);
2201                 trace_read_split(&orig->bio);
2202         }
2203
2204         if (!rbio->pick.idx) {
2205                 if (!rbio->have_ioref) {
2206                         __bcache_io_error(c, "no device to read from");
2207                         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2208                         goto out;
2209                 }
2210
2211                 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2212                              bio_sectors(&rbio->bio));
2213                 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2214
2215                 if (likely(!(flags & BCH_READ_IN_RETRY)))
2216                         submit_bio(&rbio->bio);
2217                 else
2218                         submit_bio_wait(&rbio->bio);
2219         } else {
2220                 /* Attempting reconstruct read: */
2221                 if (bch2_ec_read_extent(c, rbio)) {
2222                         bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2223                         goto out;
2224                 }
2225
2226                 if (likely(!(flags & BCH_READ_IN_RETRY)))
2227                         bio_endio(&rbio->bio);
2228         }
2229 out:
2230         if (likely(!(flags & BCH_READ_IN_RETRY))) {
2231                 return 0;
2232         } else {
2233                 int ret;
2234
2235                 rbio->context = RBIO_CONTEXT_UNBOUND;
2236                 bch2_read_endio(&rbio->bio);
2237
2238                 ret = rbio->retry;
2239                 rbio = bch2_rbio_free(rbio);
2240
2241                 if (ret == READ_RETRY_AVOID) {
2242                         bch2_mark_io_failure(failed, &pick);
2243                         ret = READ_RETRY;
2244                 }
2245
2246                 return ret;
2247         }
2248
2249 err:
2250         if (flags & BCH_READ_IN_RETRY)
2251                 return READ_ERR;
2252
2253         orig->bio.bi_status = BLK_STS_IOERR;
2254         goto out_read_done;
2255
2256 hole:
2257         /*
2258          * won't normally happen in the BCH_READ_NODECODE
2259          * (bch2_move_extent()) path, but if we retry and the extent we wanted
2260          * to read no longer exists we have to signal that:
2261          */
2262         if (flags & BCH_READ_NODECODE)
2263                 orig->hole = true;
2264
2265         zero_fill_bio_iter(&orig->bio, iter);
2266 out_read_done:
2267         if (flags & BCH_READ_LAST_FRAGMENT)
2268                 bch2_rbio_done(orig);
2269         return 0;
2270 }
2271
2272 void bch2_read(struct bch_fs *c, struct bch_read_bio *rbio, u64 inode)
2273 {
2274         struct btree_trans trans;
2275         struct btree_iter *iter;
2276         struct bkey_on_stack sk;
2277         struct bkey_s_c k;
2278         unsigned flags = BCH_READ_RETRY_IF_STALE|
2279                 BCH_READ_MAY_PROMOTE|
2280                 BCH_READ_USER_MAPPED;
2281         int ret;
2282
2283         BUG_ON(rbio->_state);
2284         BUG_ON(flags & BCH_READ_NODECODE);
2285         BUG_ON(flags & BCH_READ_IN_RETRY);
2286
2287         rbio->c = c;
2288         rbio->start_time = local_clock();
2289
2290         bkey_on_stack_init(&sk);
2291         bch2_trans_init(&trans, c, 0, 0);
2292 retry:
2293         bch2_trans_begin(&trans);
2294
2295         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
2296                                    POS(inode, rbio->bio.bi_iter.bi_sector),
2297                                    BTREE_ITER_SLOTS);
2298         while (1) {
2299                 unsigned bytes, sectors, offset_into_extent;
2300
2301                 bch2_btree_iter_set_pos(iter,
2302                                 POS(inode, rbio->bio.bi_iter.bi_sector));
2303
2304                 k = bch2_btree_iter_peek_slot(iter);
2305                 ret = bkey_err(k);
2306                 if (ret)
2307                         goto err;
2308
2309                 offset_into_extent = iter->pos.offset -
2310                         bkey_start_offset(k.k);
2311                 sectors = k.k->size - offset_into_extent;
2312
2313                 bkey_on_stack_reassemble(&sk, c, k);
2314                 k = bkey_i_to_s_c(sk.k);
2315
2316                 ret = bch2_read_indirect_extent(&trans,
2317                                         &offset_into_extent, &sk);
2318                 if (ret)
2319                         goto err;
2320
2321                 /*
2322                  * With indirect extents, the amount of data to read is the min
2323                  * of the original extent and the indirect extent:
2324                  */
2325                 sectors = min(sectors, k.k->size - offset_into_extent);
2326
2327                 /*
2328                  * Unlock the iterator while the btree node's lock is still in
2329                  * cache, before doing the IO:
2330                  */
2331                 bch2_trans_unlock(&trans);
2332
2333                 bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
2334                 swap(rbio->bio.bi_iter.bi_size, bytes);
2335
2336                 if (rbio->bio.bi_iter.bi_size == bytes)
2337                         flags |= BCH_READ_LAST_FRAGMENT;
2338
2339                 bch2_read_extent(c, rbio, k, offset_into_extent, flags);
2340
2341                 if (flags & BCH_READ_LAST_FRAGMENT)
2342                         break;
2343
2344                 swap(rbio->bio.bi_iter.bi_size, bytes);
2345                 bio_advance(&rbio->bio, bytes);
2346         }
2347 out:
2348         bch2_trans_exit(&trans);
2349         bkey_on_stack_exit(&sk, c);
2350         return;
2351 err:
2352         if (ret == -EINTR)
2353                 goto retry;
2354
2355         bcache_io_error(c, &rbio->bio, "btree IO error: %i", ret);
2356         bch2_rbio_done(rbio);
2357         goto out;
2358 }
2359
2360 void bch2_fs_io_exit(struct bch_fs *c)
2361 {
2362         if (c->promote_table.tbl)
2363                 rhashtable_destroy(&c->promote_table);
2364         mempool_exit(&c->bio_bounce_pages);
2365         bioset_exit(&c->bio_write);
2366         bioset_exit(&c->bio_read_split);
2367         bioset_exit(&c->bio_read);
2368 }
2369
2370 int bch2_fs_io_init(struct bch_fs *c)
2371 {
2372         if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2373                         BIOSET_NEED_BVECS) ||
2374             bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2375                         BIOSET_NEED_BVECS) ||
2376             bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2377                         BIOSET_NEED_BVECS) ||
2378             mempool_init_page_pool(&c->bio_bounce_pages,
2379                                    max_t(unsigned,
2380                                          c->opts.btree_node_size,
2381                                          c->sb.encoded_extent_max) /
2382                                    PAGE_SECTORS, 0) ||
2383             rhashtable_init(&c->promote_table, &bch_promote_params))
2384                 return -ENOMEM;
2385
2386         return 0;
2387 }