1 // SPDX-License-Identifier: GPL-2.0
3 * Some low level IO code, and hacks for various block layer limitations
5 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6 * Copyright 2012 Google, Inc.
10 #include "alloc_background.h"
11 #include "alloc_foreground.h"
12 #include "bkey_on_stack.h"
14 #include "btree_update.h"
20 #include "disk_groups.h"
23 #include "extent_update.h"
29 #include "rebalance.h"
33 #include <linux/blkdev.h>
34 #include <linux/random.h>
35 #include <linux/sched/mm.h>
37 #include <trace/events/bcachefs.h>
39 const char *bch2_blk_status_to_str(blk_status_t status)
41 if (status == BLK_STS_REMOVED)
42 return "device removed";
43 return blk_status_to_str(status);
46 static bool bch2_target_congested(struct bch_fs *c, u16 target)
48 const struct bch_devs_mask *devs;
49 unsigned d, nr = 0, total = 0;
50 u64 now = local_clock(), last;
58 devs = bch2_target_to_mask(c, target) ?:
59 &c->rw_devs[BCH_DATA_user];
61 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
62 ca = rcu_dereference(c->devs[d]);
66 congested = atomic_read(&ca->congested);
67 last = READ_ONCE(ca->congested_last);
68 if (time_after64(now, last))
69 congested -= (now - last) >> 12;
71 total += max(congested, 0LL);
76 return bch2_rand_range(nr * CONGESTED_MAX) < total;
79 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
83 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
84 /* ideally we'd be taking into account the device's variance here: */
85 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
86 s64 latency_over = io_latency - latency_threshold;
88 if (latency_threshold && latency_over > 0) {
90 * bump up congested by approximately latency_over * 4 /
91 * latency_threshold - we don't need much accuracy here so don't
92 * bother with the divide:
94 if (atomic_read(&ca->congested) < CONGESTED_MAX)
95 atomic_add(latency_over >>
96 max_t(int, ilog2(latency_threshold) - 2, 0),
99 ca->congested_last = now;
100 } else if (atomic_read(&ca->congested) > 0) {
101 atomic_dec(&ca->congested);
105 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
107 atomic64_t *latency = &ca->cur_latency[rw];
108 u64 now = local_clock();
109 u64 io_latency = time_after64(now, submit_time)
112 u64 old, new, v = atomic64_read(latency);
118 * If the io latency was reasonably close to the current
119 * latency, skip doing the update and atomic operation - most of
122 if (abs((int) (old - io_latency)) < (old >> 1) &&
126 new = ewma_add(old, io_latency, 5);
127 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
129 bch2_congested_acct(ca, io_latency, now, rw);
131 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
134 /* Allocate, free from mempool: */
136 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
138 struct bvec_iter_all iter;
141 bio_for_each_segment_all(bv, bio, iter)
142 if (bv->bv_page != ZERO_PAGE(0))
143 mempool_free(bv->bv_page, &c->bio_bounce_pages);
147 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
151 if (likely(!*using_mempool)) {
152 page = alloc_page(GFP_NOIO);
153 if (unlikely(!page)) {
154 mutex_lock(&c->bio_bounce_pages_lock);
155 *using_mempool = true;
161 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
167 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
170 bool using_mempool = false;
173 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
174 unsigned len = min_t(size_t, PAGE_SIZE, size);
176 BUG_ON(!bio_add_page(bio, page, len, 0));
181 mutex_unlock(&c->bio_bounce_pages_lock);
184 /* Extent update path: */
186 static int sum_sector_overwrites(struct btree_trans *trans,
187 struct btree_iter *extent_iter,
190 bool *maybe_extending,
193 struct btree_iter *iter;
197 *maybe_extending = true;
200 iter = bch2_trans_copy_iter(trans, extent_iter);
202 for_each_btree_key_continue(iter, BTREE_ITER_SLOTS, old, ret) {
204 bch2_bkey_nr_ptrs_fully_allocated(old) <
205 bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new))) {
210 *delta += (min(new->k.p.offset,
212 max(bkey_start_offset(&new->k),
213 bkey_start_offset(old.k))) *
214 (bkey_extent_is_allocation(&new->k) -
215 bkey_extent_is_allocation(old.k));
217 if (bkey_cmp(old.k->p, new->k.p) >= 0) {
219 * Check if there's already data above where we're
220 * going to be writing to - this means we're definitely
221 * not extending the file:
223 * Note that it's not sufficient to check if there's
224 * data up to the sector offset we're going to be
225 * writing to, because i_size could be up to one block
228 if (!bkey_cmp(old.k->p, new->k.p))
229 old = bch2_btree_iter_next(iter);
231 if (old.k && !bkey_err(old) &&
232 old.k->p.inode == extent_iter->pos.inode &&
233 bkey_extent_is_data(old.k))
234 *maybe_extending = false;
240 bch2_trans_iter_put(trans, iter);
244 int bch2_extent_update(struct btree_trans *trans,
245 struct btree_iter *iter,
247 struct disk_reservation *disk_res,
250 s64 *i_sectors_delta)
252 /* this must live until after bch2_trans_commit(): */
253 struct bkey_inode_buf inode_p;
254 bool extending = false;
258 ret = bch2_extent_trim_atomic(k, iter);
262 ret = sum_sector_overwrites(trans, iter, k,
263 disk_res && disk_res->sectors != 0,
268 new_i_size = extending
269 ? min(k->k.p.offset << 9, new_i_size)
272 if (delta || new_i_size) {
273 struct btree_iter *inode_iter;
274 struct bch_inode_unpacked inode_u;
276 inode_iter = bch2_inode_peek(trans, &inode_u,
277 k->k.p.inode, BTREE_ITER_INTENT);
278 if (IS_ERR(inode_iter))
279 return PTR_ERR(inode_iter);
283 * writeback can race a bit with truncate, because truncate
284 * first updates the inode then truncates the pagecache. This is
285 * ugly, but lets us preserve the invariant that the in memory
286 * i_size is always >= the on disk i_size.
288 BUG_ON(new_i_size > inode_u.bi_size &&
289 (inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY));
291 BUG_ON(new_i_size > inode_u.bi_size && !extending);
293 if (!(inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
294 new_i_size > inode_u.bi_size)
295 inode_u.bi_size = new_i_size;
299 inode_u.bi_sectors += delta;
301 if (delta || new_i_size) {
302 bch2_inode_pack(trans->c, &inode_p, &inode_u);
303 bch2_trans_update(trans, inode_iter,
304 &inode_p.inode.k_i, 0);
307 bch2_trans_iter_put(trans, inode_iter);
310 bch2_trans_update(trans, iter, k, 0);
312 ret = bch2_trans_commit(trans, disk_res, journal_seq,
313 BTREE_INSERT_NOCHECK_RW|
315 BTREE_INSERT_USE_RESERVE);
316 if (!ret && i_sectors_delta)
317 *i_sectors_delta += delta;
322 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
323 struct bpos end, u64 *journal_seq,
324 s64 *i_sectors_delta)
326 struct bch_fs *c = trans->c;
327 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
329 int ret = 0, ret2 = 0;
331 while ((k = bch2_btree_iter_peek(iter)).k &&
332 bkey_cmp(iter->pos, end) < 0) {
333 struct disk_reservation disk_res =
334 bch2_disk_reservation_init(c, 0);
335 struct bkey_i delete;
337 bch2_trans_begin(trans);
343 bkey_init(&delete.k);
344 delete.k.p = iter->pos;
346 /* create the biggest key we can */
347 bch2_key_resize(&delete.k, max_sectors);
348 bch2_cut_back(end, &delete);
350 ret = bch2_extent_update(trans, iter, &delete,
351 &disk_res, journal_seq,
353 bch2_disk_reservation_put(c, &disk_res);
363 if (bkey_cmp(iter->pos, end) > 0) {
364 bch2_btree_iter_set_pos(iter, end);
365 ret = bch2_btree_iter_traverse(iter);
371 int bch2_fpunch(struct bch_fs *c, u64 inum, u64 start, u64 end,
372 u64 *journal_seq, s64 *i_sectors_delta)
374 struct btree_trans trans;
375 struct btree_iter *iter;
378 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
379 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
383 ret = bch2_fpunch_at(&trans, iter, POS(inum, end),
384 journal_seq, i_sectors_delta);
385 bch2_trans_exit(&trans);
393 int bch2_write_index_default(struct bch_write_op *op)
395 struct bch_fs *c = op->c;
396 struct bkey_on_stack sk;
397 struct keylist *keys = &op->insert_keys;
398 struct bkey_i *k = bch2_keylist_front(keys);
399 struct btree_trans trans;
400 struct btree_iter *iter;
403 bkey_on_stack_init(&sk);
404 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
406 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
407 bkey_start_pos(&k->k),
408 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
411 bch2_trans_begin(&trans);
413 k = bch2_keylist_front(keys);
415 bkey_on_stack_realloc(&sk, c, k->k.u64s);
417 bch2_cut_front(iter->pos, sk.k);
419 ret = bch2_extent_update(&trans, iter, sk.k,
420 &op->res, op_journal_seq(op),
421 op->new_i_size, &op->i_sectors_delta);
427 if (bkey_cmp(iter->pos, k->k.p) >= 0)
428 bch2_keylist_pop_front(keys);
429 } while (!bch2_keylist_empty(keys));
431 bch2_trans_exit(&trans);
432 bkey_on_stack_exit(&sk, c);
439 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
440 enum bch_data_type type,
441 const struct bkey_i *k)
443 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
444 const struct bch_extent_ptr *ptr;
445 struct bch_write_bio *n;
448 BUG_ON(c->opts.nochanges);
450 bkey_for_each_ptr(ptrs, ptr) {
451 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
454 ca = bch_dev_bkey_exists(c, ptr->dev);
456 if (to_entry(ptr + 1) < ptrs.end) {
457 n = to_wbio(bio_clone_fast(&wbio->bio, GFP_NOIO,
460 n->bio.bi_end_io = wbio->bio.bi_end_io;
461 n->bio.bi_private = wbio->bio.bi_private;
466 n->bio.bi_opf = wbio->bio.bi_opf;
467 bio_inc_remaining(&wbio->bio);
475 n->have_ioref = bch2_dev_get_ioref(ca,
476 type == BCH_DATA_btree ? READ : WRITE);
477 n->submit_time = local_clock();
478 n->bio.bi_iter.bi_sector = ptr->offset;
480 if (!journal_flushes_device(ca))
481 n->bio.bi_opf |= REQ_FUA;
483 if (likely(n->have_ioref)) {
484 this_cpu_add(ca->io_done->sectors[WRITE][type],
485 bio_sectors(&n->bio));
487 bio_set_dev(&n->bio, ca->disk_sb.bdev);
490 n->bio.bi_status = BLK_STS_REMOVED;
496 static void __bch2_write(struct closure *);
498 static void bch2_write_done(struct closure *cl)
500 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
501 struct bch_fs *c = op->c;
503 if (!op->error && (op->flags & BCH_WRITE_FLUSH))
504 op->error = bch2_journal_error(&c->journal);
506 bch2_disk_reservation_put(c, &op->res);
507 percpu_ref_put(&c->writes);
508 bch2_keylist_free(&op->insert_keys, op->inline_keys);
510 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
512 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
513 up(&c->io_in_flight);
517 closure_debug_destroy(cl);
525 * bch_write_index - after a write, update index to point to new data
527 static void __bch2_write_index(struct bch_write_op *op)
529 struct bch_fs *c = op->c;
530 struct keylist *keys = &op->insert_keys;
531 struct bch_extent_ptr *ptr;
532 struct bkey_i *src, *dst = keys->keys, *n, *k;
536 for (src = keys->keys; src != keys->top; src = n) {
539 if (bkey_extent_is_direct_data(&src->k)) {
540 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
541 test_bit(ptr->dev, op->failed.d));
543 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src))) {
550 memmove_u64s_down(dst, src, src->u64s);
551 dst = bkey_next(dst);
557 * probably not the ideal place to hook this in, but I don't
558 * particularly want to plumb io_opts all the way through the btree
559 * update stack right now
561 for_each_keylist_key(keys, k) {
562 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
564 if (bch2_bkey_is_incompressible(bkey_i_to_s_c(k)))
565 bch2_check_set_feature(op->c, BCH_FEATURE_incompressible);
569 if (!bch2_keylist_empty(keys)) {
570 u64 sectors_start = keylist_sectors(keys);
571 int ret = op->index_update_fn(op);
573 BUG_ON(ret == -EINTR);
574 BUG_ON(keylist_sectors(keys) && !ret);
576 op->written += sectors_start - keylist_sectors(keys);
579 __bcache_io_error(c, "btree IO error %i", ret);
584 /* If some a bucket wasn't written, we can't erasure code it: */
585 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
586 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
588 bch2_open_buckets_put(c, &op->open_buckets);
591 keys->top = keys->keys;
596 static void bch2_write_index(struct closure *cl)
598 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
599 struct bch_fs *c = op->c;
601 __bch2_write_index(op);
603 if (!(op->flags & BCH_WRITE_DONE)) {
604 continue_at(cl, __bch2_write, index_update_wq(op));
605 } else if (!op->error && (op->flags & BCH_WRITE_FLUSH)) {
606 bch2_journal_flush_seq_async(&c->journal,
609 continue_at(cl, bch2_write_done, index_update_wq(op));
611 continue_at_nobarrier(cl, bch2_write_done, NULL);
615 static void bch2_write_endio(struct bio *bio)
617 struct closure *cl = bio->bi_private;
618 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
619 struct bch_write_bio *wbio = to_wbio(bio);
620 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
621 struct bch_fs *c = wbio->c;
622 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
624 if (bch2_dev_io_err_on(bio->bi_status, ca, "data write: %s",
625 bch2_blk_status_to_str(bio->bi_status)))
626 set_bit(wbio->dev, op->failed.d);
628 if (wbio->have_ioref) {
629 bch2_latency_acct(ca, wbio->submit_time, WRITE);
630 percpu_ref_put(&ca->io_ref);
634 bch2_bio_free_pages_pool(c, bio);
640 bio_endio(&parent->bio);
641 else if (!(op->flags & BCH_WRITE_SKIP_CLOSURE_PUT))
644 continue_at_nobarrier(cl, bch2_write_index, index_update_wq(op));
647 static void init_append_extent(struct bch_write_op *op,
648 struct write_point *wp,
649 struct bversion version,
650 struct bch_extent_crc_unpacked crc)
652 struct bch_fs *c = op->c;
653 struct bkey_i_extent *e;
654 struct open_bucket *ob;
657 BUG_ON(crc.compressed_size > wp->sectors_free);
658 wp->sectors_free -= crc.compressed_size;
659 op->pos.offset += crc.uncompressed_size;
661 e = bkey_extent_init(op->insert_keys.top);
663 e->k.size = crc.uncompressed_size;
664 e->k.version = version;
667 crc.compression_type ||
669 bch2_extent_crc_append(&e->k_i, crc);
671 open_bucket_for_each(c, &wp->ptrs, ob, i) {
672 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
673 union bch_extent_entry *end =
674 bkey_val_end(bkey_i_to_s(&e->k_i));
677 end->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
678 end->ptr.cached = !ca->mi.durability ||
679 (op->flags & BCH_WRITE_CACHED) != 0;
680 end->ptr.offset += ca->mi.bucket_size - ob->sectors_free;
684 BUG_ON(crc.compressed_size > ob->sectors_free);
685 ob->sectors_free -= crc.compressed_size;
688 bch2_keylist_push(&op->insert_keys);
691 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
692 struct write_point *wp,
694 bool *page_alloc_failed,
697 struct bch_write_bio *wbio;
699 unsigned output_available =
700 min(wp->sectors_free << 9, src->bi_iter.bi_size);
701 unsigned pages = DIV_ROUND_UP(output_available +
703 ? ((unsigned long) buf & (PAGE_SIZE - 1))
706 bio = bio_alloc_bioset(GFP_NOIO, pages, &c->bio_write);
707 wbio = wbio_init(bio);
708 wbio->put_bio = true;
709 /* copy WRITE_SYNC flag */
710 wbio->bio.bi_opf = src->bi_opf;
713 bch2_bio_map(bio, buf, output_available);
720 * We can't use mempool for more than c->sb.encoded_extent_max
721 * worth of pages, but we'd like to allocate more if we can:
723 bch2_bio_alloc_pages_pool(c, bio,
724 min_t(unsigned, output_available,
725 c->sb.encoded_extent_max << 9));
727 if (bio->bi_iter.bi_size < output_available)
729 bch2_bio_alloc_pages(bio,
731 bio->bi_iter.bi_size,
737 static int bch2_write_rechecksum(struct bch_fs *c,
738 struct bch_write_op *op,
739 unsigned new_csum_type)
741 struct bio *bio = &op->wbio.bio;
742 struct bch_extent_crc_unpacked new_crc;
745 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
747 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
748 bch2_csum_type_is_encryption(new_csum_type))
749 new_csum_type = op->crc.csum_type;
751 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
753 op->crc.offset, op->crc.live_size,
758 bio_advance(bio, op->crc.offset << 9);
759 bio->bi_iter.bi_size = op->crc.live_size << 9;
764 static int bch2_write_decrypt(struct bch_write_op *op)
766 struct bch_fs *c = op->c;
767 struct nonce nonce = extent_nonce(op->version, op->crc);
768 struct bch_csum csum;
770 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
774 * If we need to decrypt data in the write path, we'll no longer be able
775 * to verify the existing checksum (poly1305 mac, in this case) after
776 * it's decrypted - this is the last point we'll be able to reverify the
779 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
780 if (bch2_crc_cmp(op->crc.csum, csum))
783 bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
784 op->crc.csum_type = 0;
785 op->crc.csum = (struct bch_csum) { 0, 0 };
789 static enum prep_encoded_ret {
792 PREP_ENCODED_CHECKSUM_ERR,
793 PREP_ENCODED_DO_WRITE,
794 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
796 struct bch_fs *c = op->c;
797 struct bio *bio = &op->wbio.bio;
799 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
800 return PREP_ENCODED_OK;
802 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
804 /* Can we just write the entire extent as is? */
805 if (op->crc.uncompressed_size == op->crc.live_size &&
806 op->crc.compressed_size <= wp->sectors_free &&
807 (op->crc.compression_type == op->compression_type ||
808 op->incompressible)) {
809 if (!crc_is_compressed(op->crc) &&
810 op->csum_type != op->crc.csum_type &&
811 bch2_write_rechecksum(c, op, op->csum_type))
812 return PREP_ENCODED_CHECKSUM_ERR;
814 return PREP_ENCODED_DO_WRITE;
818 * If the data is compressed and we couldn't write the entire extent as
819 * is, we have to decompress it:
821 if (crc_is_compressed(op->crc)) {
822 struct bch_csum csum;
824 if (bch2_write_decrypt(op))
825 return PREP_ENCODED_CHECKSUM_ERR;
827 /* Last point we can still verify checksum: */
828 csum = bch2_checksum_bio(c, op->crc.csum_type,
829 extent_nonce(op->version, op->crc),
831 if (bch2_crc_cmp(op->crc.csum, csum))
832 return PREP_ENCODED_CHECKSUM_ERR;
834 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
835 return PREP_ENCODED_ERR;
839 * No longer have compressed data after this point - data might be
844 * If the data is checksummed and we're only writing a subset,
845 * rechecksum and adjust bio to point to currently live data:
847 if ((op->crc.live_size != op->crc.uncompressed_size ||
848 op->crc.csum_type != op->csum_type) &&
849 bch2_write_rechecksum(c, op, op->csum_type))
850 return PREP_ENCODED_CHECKSUM_ERR;
853 * If we want to compress the data, it has to be decrypted:
855 if ((op->compression_type ||
856 bch2_csum_type_is_encryption(op->crc.csum_type) !=
857 bch2_csum_type_is_encryption(op->csum_type)) &&
858 bch2_write_decrypt(op))
859 return PREP_ENCODED_CHECKSUM_ERR;
861 return PREP_ENCODED_OK;
864 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
867 struct bch_fs *c = op->c;
868 struct bio *src = &op->wbio.bio, *dst = src;
869 struct bvec_iter saved_iter;
871 struct bpos ec_pos = op->pos;
872 unsigned total_output = 0, total_input = 0;
874 bool page_alloc_failed = false;
877 BUG_ON(!bio_sectors(src));
879 ec_buf = bch2_writepoint_ec_buf(c, wp);
881 switch (bch2_write_prep_encoded_data(op, wp)) {
882 case PREP_ENCODED_OK:
884 case PREP_ENCODED_ERR:
887 case PREP_ENCODED_CHECKSUM_ERR:
890 case PREP_ENCODED_DO_WRITE:
891 /* XXX look for bug here */
893 dst = bch2_write_bio_alloc(c, wp, src,
896 bio_copy_data(dst, src);
899 init_append_extent(op, wp, op->version, op->crc);
904 op->compression_type ||
906 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
907 (bch2_csum_type_is_encryption(op->csum_type) &&
908 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
909 dst = bch2_write_bio_alloc(c, wp, src,
915 saved_iter = dst->bi_iter;
918 struct bch_extent_crc_unpacked crc =
919 (struct bch_extent_crc_unpacked) { 0 };
920 struct bversion version = op->version;
921 size_t dst_len, src_len;
923 if (page_alloc_failed &&
924 bio_sectors(dst) < wp->sectors_free &&
925 bio_sectors(dst) < c->sb.encoded_extent_max)
928 BUG_ON(op->compression_type &&
929 (op->flags & BCH_WRITE_DATA_ENCODED) &&
930 bch2_csum_type_is_encryption(op->crc.csum_type));
931 BUG_ON(op->compression_type && !bounce);
933 crc.compression_type = op->incompressible
934 ? BCH_COMPRESSION_TYPE_incompressible
935 : op->compression_type
936 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
937 op->compression_type)
939 if (!crc_is_compressed(crc)) {
940 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
941 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
944 dst_len = min_t(unsigned, dst_len,
945 c->sb.encoded_extent_max << 9);
948 swap(dst->bi_iter.bi_size, dst_len);
949 bio_copy_data(dst, src);
950 swap(dst->bi_iter.bi_size, dst_len);
956 BUG_ON(!src_len || !dst_len);
958 if (bch2_csum_type_is_encryption(op->csum_type)) {
959 if (bversion_zero(version)) {
960 version.lo = atomic64_inc_return(&c->key_version);
962 crc.nonce = op->nonce;
963 op->nonce += src_len >> 9;
967 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
968 !crc_is_compressed(crc) &&
969 bch2_csum_type_is_encryption(op->crc.csum_type) ==
970 bch2_csum_type_is_encryption(op->csum_type)) {
972 * Note: when we're using rechecksum(), we need to be
973 * checksumming @src because it has all the data our
974 * existing checksum covers - if we bounced (because we
975 * were trying to compress), @dst will only have the
976 * part of the data the new checksum will cover.
978 * But normally we want to be checksumming post bounce,
979 * because part of the reason for bouncing is so the
980 * data can't be modified (by userspace) while it's in
983 if (bch2_rechecksum_bio(c, src, version, op->crc,
986 bio_sectors(src) - (src_len >> 9),
990 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
991 bch2_rechecksum_bio(c, src, version, op->crc,
994 bio_sectors(src) - (src_len >> 9),
998 crc.compressed_size = dst_len >> 9;
999 crc.uncompressed_size = src_len >> 9;
1000 crc.live_size = src_len >> 9;
1002 swap(dst->bi_iter.bi_size, dst_len);
1003 bch2_encrypt_bio(c, op->csum_type,
1004 extent_nonce(version, crc), dst);
1005 crc.csum = bch2_checksum_bio(c, op->csum_type,
1006 extent_nonce(version, crc), dst);
1007 crc.csum_type = op->csum_type;
1008 swap(dst->bi_iter.bi_size, dst_len);
1011 init_append_extent(op, wp, version, crc);
1014 bio_advance(dst, dst_len);
1015 bio_advance(src, src_len);
1016 total_output += dst_len;
1017 total_input += src_len;
1018 } while (dst->bi_iter.bi_size &&
1019 src->bi_iter.bi_size &&
1021 !bch2_keylist_realloc(&op->insert_keys,
1023 ARRAY_SIZE(op->inline_keys),
1024 BKEY_EXTENT_U64s_MAX));
1026 more = src->bi_iter.bi_size != 0;
1028 dst->bi_iter = saved_iter;
1030 if (dst == src && more) {
1031 BUG_ON(total_output != total_input);
1033 dst = bio_split(src, total_input >> 9,
1034 GFP_NOIO, &c->bio_write);
1035 wbio_init(dst)->put_bio = true;
1036 /* copy WRITE_SYNC flag */
1037 dst->bi_opf = src->bi_opf;
1040 dst->bi_iter.bi_size = total_output;
1042 /* might have done a realloc... */
1043 bch2_ec_add_backpointer(c, wp, ec_pos, total_input >> 9);
1048 bch_err(c, "error verifying existing checksum while "
1049 "rewriting existing data (memory corruption?)");
1052 if (to_wbio(dst)->bounce)
1053 bch2_bio_free_pages_pool(c, dst);
1054 if (to_wbio(dst)->put_bio)
1060 static void __bch2_write(struct closure *cl)
1062 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1063 struct bch_fs *c = op->c;
1064 struct write_point *wp;
1066 bool skip_put = true;
1067 unsigned nofs_flags;
1070 nofs_flags = memalloc_nofs_save();
1072 memset(&op->failed, 0, sizeof(op->failed));
1075 struct bkey_i *key_to_write;
1076 unsigned key_to_write_offset = op->insert_keys.top_p -
1077 op->insert_keys.keys_p;
1079 /* +1 for possible cache device: */
1080 if (op->open_buckets.nr + op->nr_replicas + 1 >
1081 ARRAY_SIZE(op->open_buckets.v))
1084 if (bch2_keylist_realloc(&op->insert_keys,
1086 ARRAY_SIZE(op->inline_keys),
1087 BKEY_EXTENT_U64s_MAX))
1090 if ((op->flags & BCH_WRITE_FROM_INTERNAL) &&
1091 percpu_ref_is_dying(&c->writes)) {
1097 * The copygc thread is now global, which means it's no longer
1098 * freeing up space on specific disks, which means that
1099 * allocations for specific disks may hang arbitrarily long:
1101 wp = bch2_alloc_sectors_start(c,
1103 op->opts.erasure_code,
1107 op->nr_replicas_required,
1110 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1111 BCH_WRITE_ONLY_SPECIFIED_DEVS)) ? NULL : cl);
1114 if (unlikely(IS_ERR(wp))) {
1115 if (unlikely(PTR_ERR(wp) != -EAGAIN)) {
1124 * It's possible for the allocator to fail, put us on the
1125 * freelist waitlist, and then succeed in one of various retry
1126 * paths: if that happens, we need to disable the skip_put
1127 * optimization because otherwise there won't necessarily be a
1128 * barrier before we free the bch_write_op:
1130 if (atomic_read(&cl->remaining) & CLOSURE_WAITING)
1133 bch2_open_bucket_get(c, wp, &op->open_buckets);
1134 ret = bch2_write_extent(op, wp, &bio);
1135 bch2_alloc_sectors_done(c, wp);
1144 * for the skip_put optimization this has to be set
1145 * before we submit the bio:
1147 op->flags |= BCH_WRITE_DONE;
1150 bio->bi_end_io = bch2_write_endio;
1151 bio->bi_private = &op->cl;
1152 bio->bi_opf |= REQ_OP_WRITE;
1155 closure_get(bio->bi_private);
1157 op->flags |= BCH_WRITE_SKIP_CLOSURE_PUT;
1159 key_to_write = (void *) (op->insert_keys.keys_p +
1160 key_to_write_offset);
1162 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1167 continue_at(cl, bch2_write_index, index_update_wq(op));
1169 memalloc_nofs_restore(nofs_flags);
1173 op->flags |= BCH_WRITE_DONE;
1175 continue_at(cl, bch2_write_index, index_update_wq(op));
1179 * If the write can't all be submitted at once, we generally want to
1180 * block synchronously as that signals backpressure to the caller.
1182 * However, if we're running out of a workqueue, we can't block here
1183 * because we'll be blocking other work items from completing:
1185 if (current->flags & PF_WQ_WORKER) {
1186 continue_at(cl, bch2_write_index, index_update_wq(op));
1192 if (!bch2_keylist_empty(&op->insert_keys)) {
1193 __bch2_write_index(op);
1196 op->flags |= BCH_WRITE_DONE;
1197 continue_at_nobarrier(cl, bch2_write_done, NULL);
1205 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1207 struct closure *cl = &op->cl;
1208 struct bio *bio = &op->wbio.bio;
1209 struct bvec_iter iter;
1210 struct bkey_i_inline_data *id;
1214 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1216 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1217 ARRAY_SIZE(op->inline_keys),
1218 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1224 sectors = bio_sectors(bio);
1225 op->pos.offset += sectors;
1227 id = bkey_inline_data_init(op->insert_keys.top);
1229 id->k.version = op->version;
1230 id->k.size = sectors;
1232 iter = bio->bi_iter;
1233 iter.bi_size = data_len;
1234 memcpy_from_bio(id->v.data, bio, iter);
1236 while (data_len & 7)
1237 id->v.data[data_len++] = '\0';
1238 set_bkey_val_bytes(&id->k, data_len);
1239 bch2_keylist_push(&op->insert_keys);
1241 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1242 op->flags |= BCH_WRITE_DONE;
1244 continue_at_nobarrier(cl, bch2_write_index, NULL);
1247 bch2_write_done(&op->cl);
1251 * bch_write - handle a write to a cache device or flash only volume
1253 * This is the starting point for any data to end up in a cache device; it could
1254 * be from a normal write, or a writeback write, or a write to a flash only
1255 * volume - it's also used by the moving garbage collector to compact data in
1256 * mostly empty buckets.
1258 * It first writes the data to the cache, creating a list of keys to be inserted
1259 * (if the data won't fit in a single open bucket, there will be multiple keys);
1260 * after the data is written it calls bch_journal, and after the keys have been
1261 * added to the next journal write they're inserted into the btree.
1263 * If op->discard is true, instead of inserting the data it invalidates the
1264 * region of the cache represented by op->bio and op->inode.
1266 void bch2_write(struct closure *cl)
1268 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1269 struct bio *bio = &op->wbio.bio;
1270 struct bch_fs *c = op->c;
1273 BUG_ON(!op->nr_replicas);
1274 BUG_ON(!op->write_point.v);
1275 BUG_ON(!bkey_cmp(op->pos, POS_MAX));
1277 op->start_time = local_clock();
1278 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1279 wbio_init(bio)->put_bio = false;
1281 if (bio_sectors(bio) & (c->opts.block_size - 1)) {
1282 __bcache_io_error(c, "misaligned write");
1287 if (c->opts.nochanges ||
1288 !percpu_ref_tryget(&c->writes)) {
1289 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1290 __bcache_io_error(c, "read only");
1296 * Can't ratelimit copygc - we'd deadlock:
1298 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1299 down(&c->io_in_flight);
1301 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1303 data_len = min_t(u64, bio->bi_iter.bi_size,
1304 op->new_i_size - (op->pos.offset << 9));
1306 if (c->opts.inline_data &&
1307 data_len <= min(block_bytes(c) / 2, 1024U)) {
1308 bch2_write_data_inline(op, data_len);
1312 continue_at_nobarrier(cl, __bch2_write, NULL);
1315 bch2_disk_reservation_put(c, &op->res);
1318 EBUG_ON(cl->parent);
1319 closure_debug_destroy(cl);
1326 /* Cache promotion on read */
1330 struct rcu_head rcu;
1333 struct rhash_head hash;
1336 struct migrate_write write;
1337 struct bio_vec bi_inline_vecs[0]; /* must be last */
1340 static const struct rhashtable_params bch_promote_params = {
1341 .head_offset = offsetof(struct promote_op, hash),
1342 .key_offset = offsetof(struct promote_op, pos),
1343 .key_len = sizeof(struct bpos),
1346 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1348 struct bch_io_opts opts,
1351 if (!(flags & BCH_READ_MAY_PROMOTE))
1354 if (!opts.promote_target)
1357 if (bch2_bkey_has_target(c, k, opts.promote_target))
1360 if (bch2_target_congested(c, opts.promote_target)) {
1361 /* XXX trace this */
1365 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1366 bch_promote_params))
1372 static void promote_free(struct bch_fs *c, struct promote_op *op)
1376 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1377 bch_promote_params);
1379 percpu_ref_put(&c->writes);
1383 static void promote_done(struct closure *cl)
1385 struct promote_op *op =
1386 container_of(cl, struct promote_op, cl);
1387 struct bch_fs *c = op->write.op.c;
1389 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1392 bch2_bio_free_pages_pool(c, &op->write.op.wbio.bio);
1393 promote_free(c, op);
1396 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1398 struct bch_fs *c = rbio->c;
1399 struct closure *cl = &op->cl;
1400 struct bio *bio = &op->write.op.wbio.bio;
1402 trace_promote(&rbio->bio);
1404 /* we now own pages: */
1405 BUG_ON(!rbio->bounce);
1406 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1408 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1409 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1410 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1412 bch2_migrate_read_done(&op->write, rbio);
1414 closure_init(cl, NULL);
1415 closure_call(&op->write.op.cl, bch2_write, c->wq, cl);
1416 closure_return_with_destructor(cl, promote_done);
1419 static struct promote_op *__promote_alloc(struct bch_fs *c,
1420 enum btree_id btree_id,
1423 struct extent_ptr_decoded *pick,
1424 struct bch_io_opts opts,
1426 struct bch_read_bio **rbio)
1428 struct promote_op *op = NULL;
1430 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1433 if (!percpu_ref_tryget(&c->writes))
1436 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1440 op->start_time = local_clock();
1444 * We don't use the mempool here because extents that aren't
1445 * checksummed or compressed can be too big for the mempool:
1447 *rbio = kzalloc(sizeof(struct bch_read_bio) +
1448 sizeof(struct bio_vec) * pages,
1453 rbio_init(&(*rbio)->bio, opts);
1454 bio_init(&(*rbio)->bio, (*rbio)->bio.bi_inline_vecs, pages);
1456 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1460 (*rbio)->bounce = true;
1461 (*rbio)->split = true;
1462 (*rbio)->kmalloc = true;
1464 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1465 bch_promote_params))
1468 bio = &op->write.op.wbio.bio;
1469 bio_init(bio, bio->bi_inline_vecs, pages);
1471 ret = bch2_migrate_write_init(c, &op->write,
1472 writepoint_hashed((unsigned long) current),
1475 (struct data_opts) {
1476 .target = opts.promote_target,
1485 bio_free_pages(&(*rbio)->bio);
1489 percpu_ref_put(&c->writes);
1494 static struct promote_op *promote_alloc(struct bch_fs *c,
1495 struct bvec_iter iter,
1497 struct extent_ptr_decoded *pick,
1498 struct bch_io_opts opts,
1500 struct bch_read_bio **rbio,
1504 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1505 /* data might have to be decompressed in the write path: */
1506 unsigned sectors = promote_full
1507 ? max(pick->crc.compressed_size, pick->crc.live_size)
1508 : bvec_iter_sectors(iter);
1509 struct bpos pos = promote_full
1510 ? bkey_start_pos(k.k)
1511 : POS(k.k->p.inode, iter.bi_sector);
1512 struct promote_op *promote;
1514 if (!should_promote(c, k, pos, opts, flags))
1517 promote = __promote_alloc(c,
1518 k.k->type == KEY_TYPE_reflink_v
1521 k, pos, pick, opts, sectors, rbio);
1526 *read_full = promote_full;
1532 #define READ_RETRY_AVOID 1
1533 #define READ_RETRY 2
1538 RBIO_CONTEXT_HIGHPRI,
1539 RBIO_CONTEXT_UNBOUND,
1542 static inline struct bch_read_bio *
1543 bch2_rbio_parent(struct bch_read_bio *rbio)
1545 return rbio->split ? rbio->parent : rbio;
1549 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
1550 enum rbio_context context,
1551 struct workqueue_struct *wq)
1553 if (context <= rbio->context) {
1556 rbio->work.func = fn;
1557 rbio->context = context;
1558 queue_work(wq, &rbio->work);
1562 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
1564 BUG_ON(rbio->bounce && !rbio->split);
1567 promote_free(rbio->c, rbio->promote);
1568 rbio->promote = NULL;
1571 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
1574 struct bch_read_bio *parent = rbio->parent;
1579 bio_put(&rbio->bio);
1588 * Only called on a top level bch_read_bio to complete an entire read request,
1591 static void bch2_rbio_done(struct bch_read_bio *rbio)
1593 if (rbio->start_time)
1594 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
1596 bio_endio(&rbio->bio);
1599 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
1600 struct bvec_iter bvec_iter, u64 inode,
1601 struct bch_io_failures *failed,
1604 struct btree_trans trans;
1605 struct btree_iter *iter;
1606 struct bkey_on_stack sk;
1610 flags &= ~BCH_READ_LAST_FRAGMENT;
1611 flags |= BCH_READ_MUST_CLONE;
1613 bkey_on_stack_init(&sk);
1614 bch2_trans_init(&trans, c, 0, 0);
1616 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
1617 rbio->pos, BTREE_ITER_SLOTS);
1619 rbio->bio.bi_status = 0;
1621 k = bch2_btree_iter_peek_slot(iter);
1625 bkey_on_stack_reassemble(&sk, c, k);
1626 k = bkey_i_to_s_c(sk.k);
1627 bch2_trans_unlock(&trans);
1629 if (!bch2_bkey_matches_ptr(c, k,
1632 rbio->pick.crc.offset)) {
1633 /* extent we wanted to read no longer exists: */
1638 ret = __bch2_read_extent(&trans, rbio, bvec_iter, k, 0, failed, flags);
1639 if (ret == READ_RETRY)
1644 bch2_rbio_done(rbio);
1645 bch2_trans_exit(&trans);
1646 bkey_on_stack_exit(&sk, c);
1649 rbio->bio.bi_status = BLK_STS_IOERR;
1653 static void bch2_read_retry(struct bch_fs *c, struct bch_read_bio *rbio,
1654 struct bvec_iter bvec_iter, u64 inode,
1655 struct bch_io_failures *failed, unsigned flags)
1657 struct btree_trans trans;
1658 struct btree_iter *iter;
1659 struct bkey_on_stack sk;
1663 flags &= ~BCH_READ_LAST_FRAGMENT;
1664 flags |= BCH_READ_MUST_CLONE;
1666 bkey_on_stack_init(&sk);
1667 bch2_trans_init(&trans, c, 0, 0);
1669 bch2_trans_begin(&trans);
1671 for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS,
1672 POS(inode, bvec_iter.bi_sector),
1673 BTREE_ITER_SLOTS, k, ret) {
1674 unsigned bytes, sectors, offset_into_extent;
1676 bkey_on_stack_reassemble(&sk, c, k);
1678 offset_into_extent = iter->pos.offset -
1679 bkey_start_offset(k.k);
1680 sectors = k.k->size - offset_into_extent;
1682 ret = bch2_read_indirect_extent(&trans,
1683 &offset_into_extent, &sk);
1687 k = bkey_i_to_s_c(sk.k);
1689 sectors = min(sectors, k.k->size - offset_into_extent);
1691 bch2_trans_unlock(&trans);
1693 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
1694 swap(bvec_iter.bi_size, bytes);
1696 ret = __bch2_read_extent(&trans, rbio, bvec_iter, k,
1697 offset_into_extent, failed, flags);
1705 if (bytes == bvec_iter.bi_size)
1708 swap(bvec_iter.bi_size, bytes);
1709 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
1715 * If we get here, it better have been because there was an error
1716 * reading a btree node
1719 __bcache_io_error(c, "btree IO error: %i", ret);
1721 rbio->bio.bi_status = BLK_STS_IOERR;
1723 bch2_trans_exit(&trans);
1724 bkey_on_stack_exit(&sk, c);
1725 bch2_rbio_done(rbio);
1728 static void bch2_rbio_retry(struct work_struct *work)
1730 struct bch_read_bio *rbio =
1731 container_of(work, struct bch_read_bio, work);
1732 struct bch_fs *c = rbio->c;
1733 struct bvec_iter iter = rbio->bvec_iter;
1734 unsigned flags = rbio->flags;
1735 u64 inode = rbio->pos.inode;
1736 struct bch_io_failures failed = { .nr = 0 };
1738 trace_read_retry(&rbio->bio);
1740 if (rbio->retry == READ_RETRY_AVOID)
1741 bch2_mark_io_failure(&failed, &rbio->pick);
1743 rbio->bio.bi_status = 0;
1745 rbio = bch2_rbio_free(rbio);
1747 flags |= BCH_READ_IN_RETRY;
1748 flags &= ~BCH_READ_MAY_PROMOTE;
1750 if (flags & BCH_READ_NODECODE)
1751 bch2_read_retry_nodecode(c, rbio, iter, inode, &failed, flags);
1753 bch2_read_retry(c, rbio, iter, inode, &failed, flags);
1756 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
1759 rbio->retry = retry;
1761 if (rbio->flags & BCH_READ_IN_RETRY)
1764 if (retry == READ_ERR) {
1765 rbio = bch2_rbio_free(rbio);
1767 rbio->bio.bi_status = error;
1768 bch2_rbio_done(rbio);
1770 bch2_rbio_punt(rbio, bch2_rbio_retry,
1771 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
1775 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
1776 struct bch_read_bio *rbio)
1778 struct bch_fs *c = rbio->c;
1779 u64 data_offset = rbio->pos.offset - rbio->pick.crc.offset;
1780 struct bch_extent_crc_unpacked new_crc;
1781 struct btree_iter *iter = NULL;
1786 if (crc_is_compressed(rbio->pick.crc))
1789 iter = bch2_trans_get_iter(trans, BTREE_ID_EXTENTS, rbio->pos,
1790 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1791 k = bch2_btree_iter_peek_slot(iter);
1792 if ((ret = bkey_err(k)))
1796 * going to be temporarily appending another checksum entry:
1798 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
1799 BKEY_EXTENT_U64s_MAX * 8);
1800 if ((ret = PTR_ERR_OR_ZERO(new)))
1803 bkey_reassemble(new, k);
1804 k = bkey_i_to_s_c(new);
1806 if (bversion_cmp(k.k->version, rbio->version) ||
1807 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
1810 /* Extent was merged? */
1811 if (bkey_start_offset(k.k) < data_offset ||
1812 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
1815 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
1816 rbio->pick.crc, NULL, &new_crc,
1817 bkey_start_offset(k.k) - data_offset, k.k->size,
1818 rbio->pick.crc.csum_type)) {
1819 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
1824 if (!bch2_bkey_narrow_crcs(new, new_crc))
1827 bch2_trans_update(trans, iter, new, 0);
1829 bch2_trans_iter_put(trans, iter);
1833 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
1835 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
1836 __bch2_rbio_narrow_crcs(&trans, rbio));
1839 /* Inner part that may run in process context */
1840 static void __bch2_read_endio(struct work_struct *work)
1842 struct bch_read_bio *rbio =
1843 container_of(work, struct bch_read_bio, work);
1844 struct bch_fs *c = rbio->c;
1845 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1846 struct bio *src = &rbio->bio;
1847 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
1848 struct bvec_iter dst_iter = rbio->bvec_iter;
1849 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
1850 struct nonce nonce = extent_nonce(rbio->version, crc);
1851 struct bch_csum csum;
1853 /* Reset iterator for checksumming and copying bounced data: */
1855 src->bi_iter.bi_size = crc.compressed_size << 9;
1856 src->bi_iter.bi_idx = 0;
1857 src->bi_iter.bi_bvec_done = 0;
1859 src->bi_iter = rbio->bvec_iter;
1862 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
1863 if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
1866 if (unlikely(rbio->narrow_crcs))
1867 bch2_rbio_narrow_crcs(rbio);
1869 if (rbio->flags & BCH_READ_NODECODE)
1872 /* Adjust crc to point to subset of data we want: */
1873 crc.offset += rbio->offset_into_extent;
1874 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
1876 if (crc_is_compressed(crc)) {
1877 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1878 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
1879 goto decompression_err;
1881 /* don't need to decrypt the entire bio: */
1882 nonce = nonce_add(nonce, crc.offset << 9);
1883 bio_advance(src, crc.offset << 9);
1885 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
1886 src->bi_iter.bi_size = dst_iter.bi_size;
1888 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1891 struct bvec_iter src_iter = src->bi_iter;
1892 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
1896 if (rbio->promote) {
1898 * Re encrypt data we decrypted, so it's consistent with
1901 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1902 promote_start(rbio->promote, rbio);
1903 rbio->promote = NULL;
1906 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
1907 rbio = bch2_rbio_free(rbio);
1908 bch2_rbio_done(rbio);
1913 * Checksum error: if the bio wasn't bounced, we may have been
1914 * reading into buffers owned by userspace (that userspace can
1915 * scribble over) - retry the read, bouncing it this time:
1917 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
1918 rbio->flags |= BCH_READ_MUST_BOUNCE;
1919 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
1923 bch2_dev_io_error(ca,
1924 "data checksum error, inode %llu offset %llu: expected %0llx:%0llx got %0llx:%0llx (type %u)",
1925 rbio->pos.inode, (u64) rbio->bvec_iter.bi_sector,
1926 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
1927 csum.hi, csum.lo, crc.csum_type);
1928 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
1931 __bcache_io_error(c, "decompression error, inode %llu offset %llu",
1933 (u64) rbio->bvec_iter.bi_sector);
1934 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
1938 static void bch2_read_endio(struct bio *bio)
1940 struct bch_read_bio *rbio =
1941 container_of(bio, struct bch_read_bio, bio);
1942 struct bch_fs *c = rbio->c;
1943 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1944 struct workqueue_struct *wq = NULL;
1945 enum rbio_context context = RBIO_CONTEXT_NULL;
1947 if (rbio->have_ioref) {
1948 bch2_latency_acct(ca, rbio->submit_time, READ);
1949 percpu_ref_put(&ca->io_ref);
1953 rbio->bio.bi_end_io = rbio->end_io;
1955 if (bch2_dev_io_err_on(bio->bi_status, ca, "data read; %s",
1956 bch2_blk_status_to_str(bio->bi_status))) {
1957 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
1961 if (rbio->pick.ptr.cached &&
1962 (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
1963 ptr_stale(ca, &rbio->pick.ptr))) {
1964 atomic_long_inc(&c->read_realloc_races);
1966 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
1967 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
1969 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
1973 if (rbio->narrow_crcs ||
1974 crc_is_compressed(rbio->pick.crc) ||
1975 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
1976 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
1977 else if (rbio->pick.crc.csum_type)
1978 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
1980 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
1983 int __bch2_read_indirect_extent(struct btree_trans *trans,
1984 unsigned *offset_into_extent,
1985 struct bkey_on_stack *orig_k)
1987 struct btree_iter *iter;
1992 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
1993 *offset_into_extent;
1995 iter = bch2_trans_get_iter(trans, BTREE_ID_REFLINK,
1996 POS(0, reflink_offset),
1998 k = bch2_btree_iter_peek_slot(iter);
2003 if (k.k->type != KEY_TYPE_reflink_v &&
2004 k.k->type != KEY_TYPE_indirect_inline_data) {
2005 __bcache_io_error(trans->c,
2006 "pointer to nonexistent indirect extent");
2011 *offset_into_extent = iter->pos.offset - bkey_start_offset(k.k);
2012 bkey_on_stack_reassemble(orig_k, trans->c, k);
2014 bch2_trans_iter_put(trans, iter);
2018 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2019 struct bvec_iter iter, struct bkey_s_c k,
2020 unsigned offset_into_extent,
2021 struct bch_io_failures *failed, unsigned flags)
2023 struct bch_fs *c = trans->c;
2024 struct extent_ptr_decoded pick;
2025 struct bch_read_bio *rbio = NULL;
2027 struct promote_op *promote = NULL;
2028 bool bounce = false, read_full = false, narrow_crcs = false;
2029 struct bpos pos = bkey_start_pos(k.k);
2032 if (bkey_extent_is_inline_data(k.k)) {
2033 unsigned bytes = min_t(unsigned, iter.bi_size,
2034 bkey_inline_data_bytes(k.k));
2036 swap(iter.bi_size, bytes);
2037 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2038 swap(iter.bi_size, bytes);
2039 bio_advance_iter(&orig->bio, &iter, bytes);
2040 zero_fill_bio_iter(&orig->bio, iter);
2044 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2046 /* hole or reservation - just zero fill: */
2051 __bcache_io_error(c, "no device to read from");
2056 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2058 if (flags & BCH_READ_NODECODE) {
2060 * can happen if we retry, and the extent we were going to read
2061 * has been merged in the meantime:
2063 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2066 iter.bi_size = pick.crc.compressed_size << 9;
2070 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2071 bio_flagged(&orig->bio, BIO_CHAIN))
2072 flags |= BCH_READ_MUST_CLONE;
2074 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2075 bch2_can_narrow_extent_crcs(k, pick.crc);
2077 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2078 flags |= BCH_READ_MUST_BOUNCE;
2080 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2082 if (crc_is_compressed(pick.crc) ||
2083 (pick.crc.csum_type != BCH_CSUM_NONE &&
2084 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2085 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2086 (flags & BCH_READ_USER_MAPPED)) ||
2087 (flags & BCH_READ_MUST_BOUNCE)))) {
2092 if (orig->opts.promote_target)
2093 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2094 &rbio, &bounce, &read_full);
2097 EBUG_ON(crc_is_compressed(pick.crc));
2098 EBUG_ON(pick.crc.csum_type &&
2099 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2100 bvec_iter_sectors(iter) != pick.crc.live_size ||
2102 offset_into_extent));
2104 pos.offset += offset_into_extent;
2105 pick.ptr.offset += pick.crc.offset +
2107 offset_into_extent = 0;
2108 pick.crc.compressed_size = bvec_iter_sectors(iter);
2109 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2110 pick.crc.offset = 0;
2111 pick.crc.live_size = bvec_iter_sectors(iter);
2112 offset_into_extent = 0;
2117 * promote already allocated bounce rbio:
2118 * promote needs to allocate a bio big enough for uncompressing
2119 * data in the write path, but we're not going to use it all
2122 EBUG_ON(rbio->bio.bi_iter.bi_size <
2123 pick.crc.compressed_size << 9);
2124 rbio->bio.bi_iter.bi_size =
2125 pick.crc.compressed_size << 9;
2126 } else if (bounce) {
2127 unsigned sectors = pick.crc.compressed_size;
2129 rbio = rbio_init(bio_alloc_bioset(GFP_NOIO,
2130 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2131 &c->bio_read_split),
2134 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2135 rbio->bounce = true;
2137 } else if (flags & BCH_READ_MUST_CLONE) {
2139 * Have to clone if there were any splits, due to error
2140 * reporting issues (if a split errored, and retrying didn't
2141 * work, when it reports the error to its parent (us) we don't
2142 * know if the error was from our bio, and we should retry, or
2143 * from the whole bio, in which case we don't want to retry and
2146 rbio = rbio_init(bio_clone_fast(&orig->bio, GFP_NOIO,
2147 &c->bio_read_split),
2149 rbio->bio.bi_iter = iter;
2153 rbio->bio.bi_iter = iter;
2154 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2157 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2160 rbio->submit_time = local_clock();
2162 rbio->parent = orig;
2164 rbio->end_io = orig->bio.bi_end_io;
2165 rbio->bvec_iter = iter;
2166 rbio->offset_into_extent= offset_into_extent;
2167 rbio->flags = flags;
2168 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2169 rbio->narrow_crcs = narrow_crcs;
2173 /* XXX: only initialize this if needed */
2174 rbio->devs_have = bch2_bkey_devs(k);
2177 rbio->version = k.k->version;
2178 rbio->promote = promote;
2179 INIT_WORK(&rbio->work, NULL);
2181 rbio->bio.bi_opf = orig->bio.bi_opf;
2182 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2183 rbio->bio.bi_end_io = bch2_read_endio;
2186 trace_read_bounce(&rbio->bio);
2188 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2190 if (pick.ptr.cached)
2191 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2192 PTR_BUCKET_NR(ca, &pick.ptr), READ);
2194 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2195 bio_inc_remaining(&orig->bio);
2196 trace_read_split(&orig->bio);
2199 if (!rbio->pick.idx) {
2200 if (!rbio->have_ioref) {
2201 __bcache_io_error(c, "no device to read from");
2202 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2206 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2207 bio_sectors(&rbio->bio));
2208 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2210 if (likely(!(flags & BCH_READ_IN_RETRY)))
2211 submit_bio(&rbio->bio);
2213 submit_bio_wait(&rbio->bio);
2215 /* Attempting reconstruct read: */
2216 if (bch2_ec_read_extent(c, rbio)) {
2217 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2221 if (likely(!(flags & BCH_READ_IN_RETRY)))
2222 bio_endio(&rbio->bio);
2225 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2230 rbio->context = RBIO_CONTEXT_UNBOUND;
2231 bch2_read_endio(&rbio->bio);
2234 rbio = bch2_rbio_free(rbio);
2236 if (ret == READ_RETRY_AVOID) {
2237 bch2_mark_io_failure(failed, &pick);
2245 if (flags & BCH_READ_IN_RETRY)
2248 orig->bio.bi_status = BLK_STS_IOERR;
2253 * won't normally happen in the BCH_READ_NODECODE
2254 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2255 * to read no longer exists we have to signal that:
2257 if (flags & BCH_READ_NODECODE)
2260 zero_fill_bio_iter(&orig->bio, iter);
2262 if (flags & BCH_READ_LAST_FRAGMENT)
2263 bch2_rbio_done(orig);
2267 void bch2_read(struct bch_fs *c, struct bch_read_bio *rbio, u64 inode)
2269 struct btree_trans trans;
2270 struct btree_iter *iter;
2271 struct bkey_on_stack sk;
2273 unsigned flags = BCH_READ_RETRY_IF_STALE|
2274 BCH_READ_MAY_PROMOTE|
2275 BCH_READ_USER_MAPPED;
2278 BUG_ON(rbio->_state);
2279 BUG_ON(flags & BCH_READ_NODECODE);
2280 BUG_ON(flags & BCH_READ_IN_RETRY);
2283 rbio->start_time = local_clock();
2285 bkey_on_stack_init(&sk);
2286 bch2_trans_init(&trans, c, 0, 0);
2288 bch2_trans_begin(&trans);
2290 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
2291 POS(inode, rbio->bio.bi_iter.bi_sector),
2294 unsigned bytes, sectors, offset_into_extent;
2296 bch2_btree_iter_set_pos(iter,
2297 POS(inode, rbio->bio.bi_iter.bi_sector));
2299 k = bch2_btree_iter_peek_slot(iter);
2304 offset_into_extent = iter->pos.offset -
2305 bkey_start_offset(k.k);
2306 sectors = k.k->size - offset_into_extent;
2308 bkey_on_stack_reassemble(&sk, c, k);
2310 ret = bch2_read_indirect_extent(&trans,
2311 &offset_into_extent, &sk);
2315 k = bkey_i_to_s_c(sk.k);
2318 * With indirect extents, the amount of data to read is the min
2319 * of the original extent and the indirect extent:
2321 sectors = min(sectors, k.k->size - offset_into_extent);
2324 * Unlock the iterator while the btree node's lock is still in
2325 * cache, before doing the IO:
2327 bch2_trans_unlock(&trans);
2329 bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
2330 swap(rbio->bio.bi_iter.bi_size, bytes);
2332 if (rbio->bio.bi_iter.bi_size == bytes)
2333 flags |= BCH_READ_LAST_FRAGMENT;
2335 bch2_read_extent(&trans, rbio, k, offset_into_extent, flags);
2337 if (flags & BCH_READ_LAST_FRAGMENT)
2340 swap(rbio->bio.bi_iter.bi_size, bytes);
2341 bio_advance(&rbio->bio, bytes);
2344 bch2_trans_exit(&trans);
2345 bkey_on_stack_exit(&sk, c);
2351 bcache_io_error(c, &rbio->bio, "btree IO error: %i", ret);
2352 bch2_rbio_done(rbio);
2356 void bch2_fs_io_exit(struct bch_fs *c)
2358 if (c->promote_table.tbl)
2359 rhashtable_destroy(&c->promote_table);
2360 mempool_exit(&c->bio_bounce_pages);
2361 bioset_exit(&c->bio_write);
2362 bioset_exit(&c->bio_read_split);
2363 bioset_exit(&c->bio_read);
2366 int bch2_fs_io_init(struct bch_fs *c)
2368 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2369 BIOSET_NEED_BVECS) ||
2370 bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2371 BIOSET_NEED_BVECS) ||
2372 bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2373 BIOSET_NEED_BVECS) ||
2374 mempool_init_page_pool(&c->bio_bounce_pages,
2376 c->opts.btree_node_size,
2377 c->sb.encoded_extent_max) /
2379 rhashtable_init(&c->promote_table, &bch_promote_params))