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