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