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