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