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_foreground.h"
11 #include "bkey_on_stack.h"
13 #include "btree_update.h"
19 #include "disk_groups.h"
22 #include "extent_update.h"
28 #include "rebalance.h"
32 #include <linux/blkdev.h>
33 #include <linux/random.h>
35 #include <trace/events/bcachefs.h>
37 static bool bch2_target_congested(struct bch_fs *c, u16 target)
39 const struct bch_devs_mask *devs;
40 unsigned d, nr = 0, total = 0;
41 u64 now = local_clock(), last;
49 devs = bch2_target_to_mask(c, target);
50 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
51 ca = rcu_dereference(c->devs[d]);
55 congested = atomic_read(&ca->congested);
56 last = READ_ONCE(ca->congested_last);
57 if (time_after64(now, last))
58 congested -= (now - last) >> 12;
60 total += max(congested, 0LL);
65 return bch2_rand_range(nr * CONGESTED_MAX) < total;
68 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
72 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
73 /* ideally we'd be taking into account the device's variance here: */
74 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
75 s64 latency_over = io_latency - latency_threshold;
77 if (latency_threshold && latency_over > 0) {
79 * bump up congested by approximately latency_over * 4 /
80 * latency_threshold - we don't need much accuracy here so don't
81 * bother with the divide:
83 if (atomic_read(&ca->congested) < CONGESTED_MAX)
84 atomic_add(latency_over >>
85 max_t(int, ilog2(latency_threshold) - 2, 0),
88 ca->congested_last = now;
89 } else if (atomic_read(&ca->congested) > 0) {
90 atomic_dec(&ca->congested);
94 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
96 atomic64_t *latency = &ca->cur_latency[rw];
97 u64 now = local_clock();
98 u64 io_latency = time_after64(now, submit_time)
101 u64 old, new, v = atomic64_read(latency);
107 * If the io latency was reasonably close to the current
108 * latency, skip doing the update and atomic operation - most of
111 if (abs((int) (old - io_latency)) < (old >> 1) &&
115 new = ewma_add(old, io_latency, 5);
116 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
118 bch2_congested_acct(ca, io_latency, now, rw);
120 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
123 /* Allocate, free from mempool: */
125 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
127 struct bvec_iter_all iter;
130 bio_for_each_segment_all(bv, bio, iter)
131 if (bv->bv_page != ZERO_PAGE(0))
132 mempool_free(bv->bv_page, &c->bio_bounce_pages);
136 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
140 if (likely(!*using_mempool)) {
141 page = alloc_page(GFP_NOIO);
142 if (unlikely(!page)) {
143 mutex_lock(&c->bio_bounce_pages_lock);
144 *using_mempool = true;
150 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
156 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
159 bool using_mempool = false;
162 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
163 unsigned len = min(PAGE_SIZE, size);
165 BUG_ON(!bio_add_page(bio, page, len, 0));
170 mutex_unlock(&c->bio_bounce_pages_lock);
173 /* Extent update path: */
175 static int sum_sector_overwrites(struct btree_trans *trans,
176 struct btree_iter *extent_iter,
179 bool *maybe_extending,
182 struct btree_iter *iter;
186 *maybe_extending = true;
189 iter = bch2_trans_copy_iter(trans, extent_iter);
191 return PTR_ERR(iter);
193 for_each_btree_key_continue(iter, BTREE_ITER_SLOTS, old, ret) {
195 bch2_bkey_nr_ptrs_fully_allocated(old) <
196 bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new))) {
201 *delta += (min(new->k.p.offset,
203 max(bkey_start_offset(&new->k),
204 bkey_start_offset(old.k))) *
205 (bkey_extent_is_allocation(&new->k) -
206 bkey_extent_is_allocation(old.k));
208 if (bkey_cmp(old.k->p, new->k.p) >= 0) {
210 * Check if there's already data above where we're
211 * going to be writing to - this means we're definitely
212 * not extending the file:
214 * Note that it's not sufficient to check if there's
215 * data up to the sector offset we're going to be
216 * writing to, because i_size could be up to one block
219 if (!bkey_cmp(old.k->p, new->k.p))
220 old = bch2_btree_iter_next(iter);
222 if (old.k && !bkey_err(old) &&
223 old.k->p.inode == extent_iter->pos.inode &&
224 bkey_extent_is_data(old.k))
225 *maybe_extending = false;
231 bch2_trans_iter_put(trans, iter);
235 int bch2_extent_update(struct btree_trans *trans,
236 struct btree_iter *iter,
238 struct disk_reservation *disk_res,
241 s64 *i_sectors_delta)
243 /* this must live until after bch2_trans_commit(): */
244 struct bkey_inode_buf inode_p;
245 bool extending = false;
249 ret = bch2_extent_trim_atomic(k, iter);
253 ret = sum_sector_overwrites(trans, iter, k,
254 disk_res && disk_res->sectors != 0,
259 new_i_size = extending
260 ? min(k->k.p.offset << 9, new_i_size)
263 if (delta || new_i_size) {
264 struct btree_iter *inode_iter;
265 struct bch_inode_unpacked inode_u;
267 inode_iter = bch2_inode_peek(trans, &inode_u,
268 k->k.p.inode, BTREE_ITER_INTENT);
269 if (IS_ERR(inode_iter))
270 return PTR_ERR(inode_iter);
274 * writeback can race a bit with truncate, because truncate
275 * first updates the inode then truncates the pagecache. This is
276 * ugly, but lets us preserve the invariant that the in memory
277 * i_size is always >= the on disk i_size.
279 BUG_ON(new_i_size > inode_u.bi_size &&
280 (inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY));
282 BUG_ON(new_i_size > inode_u.bi_size && !extending);
284 if (!(inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
285 new_i_size > inode_u.bi_size)
286 inode_u.bi_size = new_i_size;
290 inode_u.bi_sectors += delta;
292 if (delta || new_i_size) {
293 bch2_inode_pack(&inode_p, &inode_u);
294 bch2_trans_update(trans, inode_iter,
295 &inode_p.inode.k_i, 0);
298 bch2_trans_iter_put(trans, inode_iter);
301 bch2_trans_update(trans, iter, k, 0);
303 ret = bch2_trans_commit(trans, disk_res, journal_seq,
304 BTREE_INSERT_NOCHECK_RW|
306 BTREE_INSERT_USE_RESERVE);
307 if (!ret && i_sectors_delta)
308 *i_sectors_delta += delta;
313 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
314 struct bpos end, u64 *journal_seq,
315 s64 *i_sectors_delta)
317 struct bch_fs *c = trans->c;
318 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
320 int ret = 0, ret2 = 0;
322 while ((k = bch2_btree_iter_peek(iter)).k &&
323 bkey_cmp(iter->pos, end) < 0) {
324 struct disk_reservation disk_res =
325 bch2_disk_reservation_init(c, 0);
326 struct bkey_i delete;
328 bch2_trans_begin(trans);
334 bkey_init(&delete.k);
335 delete.k.p = iter->pos;
337 /* create the biggest key we can */
338 bch2_key_resize(&delete.k, max_sectors);
339 bch2_cut_back(end, &delete);
341 ret = bch2_extent_update(trans, iter, &delete,
342 &disk_res, journal_seq,
344 bch2_disk_reservation_put(c, &disk_res);
354 if (bkey_cmp(iter->pos, end) > 0) {
355 bch2_btree_iter_set_pos(iter, end);
356 ret = bch2_btree_iter_traverse(iter);
362 int bch2_fpunch(struct bch_fs *c, u64 inum, u64 start, u64 end,
363 u64 *journal_seq, s64 *i_sectors_delta)
365 struct btree_trans trans;
366 struct btree_iter *iter;
369 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
370 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
374 ret = bch2_fpunch_at(&trans, iter, POS(inum, end),
375 journal_seq, i_sectors_delta);
376 bch2_trans_exit(&trans);
384 int bch2_write_index_default(struct bch_write_op *op)
386 struct bch_fs *c = op->c;
387 struct bkey_on_stack sk;
388 struct keylist *keys = &op->insert_keys;
389 struct bkey_i *k = bch2_keylist_front(keys);
390 struct btree_trans trans;
391 struct btree_iter *iter;
394 bkey_on_stack_init(&sk);
395 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
397 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
398 bkey_start_pos(&k->k),
399 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
402 bch2_trans_begin(&trans);
404 k = bch2_keylist_front(keys);
406 bkey_on_stack_realloc(&sk, c, k->k.u64s);
408 bch2_cut_front(iter->pos, sk.k);
410 ret = bch2_extent_update(&trans, iter, sk.k,
411 &op->res, op_journal_seq(op),
412 op->new_i_size, &op->i_sectors_delta);
418 if (bkey_cmp(iter->pos, k->k.p) >= 0)
419 bch2_keylist_pop_front(keys);
420 } while (!bch2_keylist_empty(keys));
422 bch2_trans_exit(&trans);
423 bkey_on_stack_exit(&sk, c);
430 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
431 enum bch_data_type type,
432 const struct bkey_i *k)
434 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
435 const struct bch_extent_ptr *ptr;
436 struct bch_write_bio *n;
439 BUG_ON(c->opts.nochanges);
441 bkey_for_each_ptr(ptrs, ptr) {
442 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
445 ca = bch_dev_bkey_exists(c, ptr->dev);
447 if (to_entry(ptr + 1) < ptrs.end) {
448 n = to_wbio(bio_clone_fast(&wbio->bio, GFP_NOIO,
451 n->bio.bi_end_io = wbio->bio.bi_end_io;
452 n->bio.bi_private = wbio->bio.bi_private;
457 n->bio.bi_opf = wbio->bio.bi_opf;
458 bio_inc_remaining(&wbio->bio);
466 n->have_ioref = bch2_dev_get_ioref(ca, WRITE);
467 n->submit_time = local_clock();
468 n->bio.bi_iter.bi_sector = ptr->offset;
470 if (!journal_flushes_device(ca))
471 n->bio.bi_opf |= REQ_FUA;
473 if (likely(n->have_ioref)) {
474 this_cpu_add(ca->io_done->sectors[WRITE][type],
475 bio_sectors(&n->bio));
477 bio_set_dev(&n->bio, ca->disk_sb.bdev);
480 n->bio.bi_status = BLK_STS_REMOVED;
486 static void __bch2_write(struct closure *);
488 static void bch2_write_done(struct closure *cl)
490 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
491 struct bch_fs *c = op->c;
493 if (!op->error && (op->flags & BCH_WRITE_FLUSH))
494 op->error = bch2_journal_error(&c->journal);
496 if (!(op->flags & BCH_WRITE_NOPUT_RESERVATION))
497 bch2_disk_reservation_put(c, &op->res);
498 percpu_ref_put(&c->writes);
499 bch2_keylist_free(&op->insert_keys, op->inline_keys);
501 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
503 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
504 up(&c->io_in_flight);
508 closure_debug_destroy(cl);
516 * bch_write_index - after a write, update index to point to new data
518 static void __bch2_write_index(struct bch_write_op *op)
520 struct bch_fs *c = op->c;
521 struct keylist *keys = &op->insert_keys;
522 struct bch_extent_ptr *ptr;
523 struct bkey_i *src, *dst = keys->keys, *n, *k;
527 for (src = keys->keys; src != keys->top; src = n) {
530 if (bkey_extent_is_direct_data(&src->k)) {
531 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
532 test_bit(ptr->dev, op->failed.d));
534 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src))) {
541 memmove_u64s_down(dst, src, src->u64s);
542 dst = bkey_next(dst);
548 * probably not the ideal place to hook this in, but I don't
549 * particularly want to plumb io_opts all the way through the btree
550 * update stack right now
552 for_each_keylist_key(keys, k) {
553 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
555 if (bch2_bkey_is_incompressible(bkey_i_to_s_c(k)))
556 bch2_check_set_feature(op->c, BCH_FEATURE_incompressible);
560 if (!bch2_keylist_empty(keys)) {
561 u64 sectors_start = keylist_sectors(keys);
562 int ret = op->index_update_fn(op);
564 BUG_ON(ret == -EINTR);
565 BUG_ON(keylist_sectors(keys) && !ret);
567 op->written += sectors_start - keylist_sectors(keys);
570 __bcache_io_error(c, "btree IO error %i", ret);
575 /* If some a bucket wasn't written, we can't erasure code it: */
576 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
577 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
579 bch2_open_buckets_put(c, &op->open_buckets);
582 keys->top = keys->keys;
587 static void bch2_write_index(struct closure *cl)
589 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
590 struct bch_fs *c = op->c;
592 __bch2_write_index(op);
594 if (!(op->flags & BCH_WRITE_DONE)) {
595 continue_at(cl, __bch2_write, index_update_wq(op));
596 } else if (!op->error && (op->flags & BCH_WRITE_FLUSH)) {
597 bch2_journal_flush_seq_async(&c->journal,
600 continue_at(cl, bch2_write_done, index_update_wq(op));
602 continue_at_nobarrier(cl, bch2_write_done, NULL);
606 static void bch2_write_endio(struct bio *bio)
608 struct closure *cl = bio->bi_private;
609 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
610 struct bch_write_bio *wbio = to_wbio(bio);
611 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
612 struct bch_fs *c = wbio->c;
613 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
615 if (bch2_dev_io_err_on(bio->bi_status, ca, "data write"))
616 set_bit(wbio->dev, op->failed.d);
618 if (wbio->have_ioref) {
619 bch2_latency_acct(ca, wbio->submit_time, WRITE);
620 percpu_ref_put(&ca->io_ref);
624 bch2_bio_free_pages_pool(c, bio);
630 bio_endio(&parent->bio);
631 else if (!(op->flags & BCH_WRITE_SKIP_CLOSURE_PUT))
634 continue_at_nobarrier(cl, bch2_write_index, index_update_wq(op));
637 static void init_append_extent(struct bch_write_op *op,
638 struct write_point *wp,
639 struct bversion version,
640 struct bch_extent_crc_unpacked crc)
642 struct bch_fs *c = op->c;
643 struct bkey_i_extent *e;
644 struct open_bucket *ob;
647 BUG_ON(crc.compressed_size > wp->sectors_free);
648 wp->sectors_free -= crc.compressed_size;
649 op->pos.offset += crc.uncompressed_size;
651 e = bkey_extent_init(op->insert_keys.top);
653 e->k.size = crc.uncompressed_size;
654 e->k.version = version;
657 crc.compression_type ||
659 bch2_extent_crc_append(&e->k_i, crc);
661 open_bucket_for_each(c, &wp->ptrs, ob, i) {
662 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
663 union bch_extent_entry *end =
664 bkey_val_end(bkey_i_to_s(&e->k_i));
667 end->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
668 end->ptr.cached = !ca->mi.durability ||
669 (op->flags & BCH_WRITE_CACHED) != 0;
670 end->ptr.offset += ca->mi.bucket_size - ob->sectors_free;
674 BUG_ON(crc.compressed_size > ob->sectors_free);
675 ob->sectors_free -= crc.compressed_size;
678 bch2_keylist_push(&op->insert_keys);
681 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
682 struct write_point *wp,
684 bool *page_alloc_failed,
687 struct bch_write_bio *wbio;
689 unsigned output_available =
690 min(wp->sectors_free << 9, src->bi_iter.bi_size);
691 unsigned pages = DIV_ROUND_UP(output_available +
693 ? ((unsigned long) buf & (PAGE_SIZE - 1))
696 bio = bio_alloc_bioset(GFP_NOIO, pages, &c->bio_write);
697 wbio = wbio_init(bio);
698 wbio->put_bio = true;
699 /* copy WRITE_SYNC flag */
700 wbio->bio.bi_opf = src->bi_opf;
703 bch2_bio_map(bio, buf, output_available);
710 * We can't use mempool for more than c->sb.encoded_extent_max
711 * worth of pages, but we'd like to allocate more if we can:
713 bch2_bio_alloc_pages_pool(c, bio,
714 min_t(unsigned, output_available,
715 c->sb.encoded_extent_max << 9));
717 if (bio->bi_iter.bi_size < output_available)
719 bch2_bio_alloc_pages(bio,
721 bio->bi_iter.bi_size,
727 static int bch2_write_rechecksum(struct bch_fs *c,
728 struct bch_write_op *op,
729 unsigned new_csum_type)
731 struct bio *bio = &op->wbio.bio;
732 struct bch_extent_crc_unpacked new_crc;
735 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
737 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
738 bch2_csum_type_is_encryption(new_csum_type))
739 new_csum_type = op->crc.csum_type;
741 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
743 op->crc.offset, op->crc.live_size,
748 bio_advance(bio, op->crc.offset << 9);
749 bio->bi_iter.bi_size = op->crc.live_size << 9;
754 static int bch2_write_decrypt(struct bch_write_op *op)
756 struct bch_fs *c = op->c;
757 struct nonce nonce = extent_nonce(op->version, op->crc);
758 struct bch_csum csum;
760 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
764 * If we need to decrypt data in the write path, we'll no longer be able
765 * to verify the existing checksum (poly1305 mac, in this case) after
766 * it's decrypted - this is the last point we'll be able to reverify the
769 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
770 if (bch2_crc_cmp(op->crc.csum, csum))
773 bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
774 op->crc.csum_type = 0;
775 op->crc.csum = (struct bch_csum) { 0, 0 };
779 static enum prep_encoded_ret {
782 PREP_ENCODED_CHECKSUM_ERR,
783 PREP_ENCODED_DO_WRITE,
784 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
786 struct bch_fs *c = op->c;
787 struct bio *bio = &op->wbio.bio;
789 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
790 return PREP_ENCODED_OK;
792 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
794 /* Can we just write the entire extent as is? */
795 if (op->crc.uncompressed_size == op->crc.live_size &&
796 op->crc.compressed_size <= wp->sectors_free &&
797 (op->crc.compression_type == op->compression_type ||
798 op->incompressible)) {
799 if (!crc_is_compressed(op->crc) &&
800 op->csum_type != op->crc.csum_type &&
801 bch2_write_rechecksum(c, op, op->csum_type))
802 return PREP_ENCODED_CHECKSUM_ERR;
804 return PREP_ENCODED_DO_WRITE;
808 * If the data is compressed and we couldn't write the entire extent as
809 * is, we have to decompress it:
811 if (crc_is_compressed(op->crc)) {
812 struct bch_csum csum;
814 if (bch2_write_decrypt(op))
815 return PREP_ENCODED_CHECKSUM_ERR;
817 /* Last point we can still verify checksum: */
818 csum = bch2_checksum_bio(c, op->crc.csum_type,
819 extent_nonce(op->version, op->crc),
821 if (bch2_crc_cmp(op->crc.csum, csum))
822 return PREP_ENCODED_CHECKSUM_ERR;
824 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
825 return PREP_ENCODED_ERR;
829 * No longer have compressed data after this point - data might be
834 * If the data is checksummed and we're only writing a subset,
835 * rechecksum and adjust bio to point to currently live data:
837 if ((op->crc.live_size != op->crc.uncompressed_size ||
838 op->crc.csum_type != op->csum_type) &&
839 bch2_write_rechecksum(c, op, op->csum_type))
840 return PREP_ENCODED_CHECKSUM_ERR;
843 * If we want to compress the data, it has to be decrypted:
845 if ((op->compression_type ||
846 bch2_csum_type_is_encryption(op->crc.csum_type) !=
847 bch2_csum_type_is_encryption(op->csum_type)) &&
848 bch2_write_decrypt(op))
849 return PREP_ENCODED_CHECKSUM_ERR;
851 return PREP_ENCODED_OK;
854 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
857 struct bch_fs *c = op->c;
858 struct bio *src = &op->wbio.bio, *dst = src;
859 struct bvec_iter saved_iter;
861 struct bpos ec_pos = op->pos;
862 unsigned total_output = 0, total_input = 0;
864 bool page_alloc_failed = false;
867 BUG_ON(!bio_sectors(src));
869 ec_buf = bch2_writepoint_ec_buf(c, wp);
871 switch (bch2_write_prep_encoded_data(op, wp)) {
872 case PREP_ENCODED_OK:
874 case PREP_ENCODED_ERR:
877 case PREP_ENCODED_CHECKSUM_ERR:
880 case PREP_ENCODED_DO_WRITE:
881 /* XXX look for bug here */
883 dst = bch2_write_bio_alloc(c, wp, src,
886 bio_copy_data(dst, src);
889 init_append_extent(op, wp, op->version, op->crc);
894 op->compression_type ||
896 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
897 (bch2_csum_type_is_encryption(op->csum_type) &&
898 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
899 dst = bch2_write_bio_alloc(c, wp, src,
905 saved_iter = dst->bi_iter;
908 struct bch_extent_crc_unpacked crc =
909 (struct bch_extent_crc_unpacked) { 0 };
910 struct bversion version = op->version;
911 size_t dst_len, src_len;
913 if (page_alloc_failed &&
914 bio_sectors(dst) < wp->sectors_free &&
915 bio_sectors(dst) < c->sb.encoded_extent_max)
918 BUG_ON(op->compression_type &&
919 (op->flags & BCH_WRITE_DATA_ENCODED) &&
920 bch2_csum_type_is_encryption(op->crc.csum_type));
921 BUG_ON(op->compression_type && !bounce);
923 crc.compression_type = op->incompressible
924 ? BCH_COMPRESSION_TYPE_incompressible
925 : op->compression_type
926 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
927 op->compression_type)
929 if (!crc_is_compressed(crc)) {
930 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
931 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
934 dst_len = min_t(unsigned, dst_len,
935 c->sb.encoded_extent_max << 9);
938 swap(dst->bi_iter.bi_size, dst_len);
939 bio_copy_data(dst, src);
940 swap(dst->bi_iter.bi_size, dst_len);
946 BUG_ON(!src_len || !dst_len);
948 if (bch2_csum_type_is_encryption(op->csum_type)) {
949 if (bversion_zero(version)) {
950 version.lo = atomic64_inc_return(&c->key_version);
952 crc.nonce = op->nonce;
953 op->nonce += src_len >> 9;
957 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
958 !crc_is_compressed(crc) &&
959 bch2_csum_type_is_encryption(op->crc.csum_type) ==
960 bch2_csum_type_is_encryption(op->csum_type)) {
962 * Note: when we're using rechecksum(), we need to be
963 * checksumming @src because it has all the data our
964 * existing checksum covers - if we bounced (because we
965 * were trying to compress), @dst will only have the
966 * part of the data the new checksum will cover.
968 * But normally we want to be checksumming post bounce,
969 * because part of the reason for bouncing is so the
970 * data can't be modified (by userspace) while it's in
973 if (bch2_rechecksum_bio(c, src, version, op->crc,
976 bio_sectors(src) - (src_len >> 9),
980 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
981 bch2_rechecksum_bio(c, src, version, op->crc,
984 bio_sectors(src) - (src_len >> 9),
988 crc.compressed_size = dst_len >> 9;
989 crc.uncompressed_size = src_len >> 9;
990 crc.live_size = src_len >> 9;
992 swap(dst->bi_iter.bi_size, dst_len);
993 bch2_encrypt_bio(c, op->csum_type,
994 extent_nonce(version, crc), dst);
995 crc.csum = bch2_checksum_bio(c, op->csum_type,
996 extent_nonce(version, crc), dst);
997 crc.csum_type = op->csum_type;
998 swap(dst->bi_iter.bi_size, dst_len);
1001 init_append_extent(op, wp, version, crc);
1004 bio_advance(dst, dst_len);
1005 bio_advance(src, src_len);
1006 total_output += dst_len;
1007 total_input += src_len;
1008 } while (dst->bi_iter.bi_size &&
1009 src->bi_iter.bi_size &&
1011 !bch2_keylist_realloc(&op->insert_keys,
1013 ARRAY_SIZE(op->inline_keys),
1014 BKEY_EXTENT_U64s_MAX));
1016 more = src->bi_iter.bi_size != 0;
1018 dst->bi_iter = saved_iter;
1020 if (dst == src && more) {
1021 BUG_ON(total_output != total_input);
1023 dst = bio_split(src, total_input >> 9,
1024 GFP_NOIO, &c->bio_write);
1025 wbio_init(dst)->put_bio = true;
1026 /* copy WRITE_SYNC flag */
1027 dst->bi_opf = src->bi_opf;
1030 dst->bi_iter.bi_size = total_output;
1032 /* might have done a realloc... */
1033 bch2_ec_add_backpointer(c, wp, ec_pos, total_input >> 9);
1038 bch_err(c, "error verifying existing checksum while "
1039 "rewriting existing data (memory corruption?)");
1042 if (to_wbio(dst)->bounce)
1043 bch2_bio_free_pages_pool(c, dst);
1044 if (to_wbio(dst)->put_bio)
1050 static void __bch2_write(struct closure *cl)
1052 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1053 struct bch_fs *c = op->c;
1054 struct write_point *wp;
1056 bool skip_put = true;
1059 memset(&op->failed, 0, sizeof(op->failed));
1062 struct bkey_i *key_to_write;
1063 unsigned key_to_write_offset = op->insert_keys.top_p -
1064 op->insert_keys.keys_p;
1066 /* +1 for possible cache device: */
1067 if (op->open_buckets.nr + op->nr_replicas + 1 >
1068 ARRAY_SIZE(op->open_buckets.v))
1071 if (bch2_keylist_realloc(&op->insert_keys,
1073 ARRAY_SIZE(op->inline_keys),
1074 BKEY_EXTENT_U64s_MAX))
1077 if ((op->flags & BCH_WRITE_FROM_INTERNAL) &&
1078 percpu_ref_is_dying(&c->writes)) {
1083 wp = bch2_alloc_sectors_start(c,
1085 op->opts.erasure_code,
1089 op->nr_replicas_required,
1092 (op->flags & BCH_WRITE_ALLOC_NOWAIT) ? NULL : cl);
1095 if (unlikely(IS_ERR(wp))) {
1096 if (unlikely(PTR_ERR(wp) != -EAGAIN)) {
1104 bch2_open_bucket_get(c, wp, &op->open_buckets);
1105 ret = bch2_write_extent(op, wp, &bio);
1106 bch2_alloc_sectors_done(c, wp);
1115 * for the skip_put optimization this has to be set
1116 * before we submit the bio:
1118 op->flags |= BCH_WRITE_DONE;
1121 bio->bi_end_io = bch2_write_endio;
1122 bio->bi_private = &op->cl;
1123 bio->bi_opf |= REQ_OP_WRITE;
1126 closure_get(bio->bi_private);
1128 op->flags |= BCH_WRITE_SKIP_CLOSURE_PUT;
1130 key_to_write = (void *) (op->insert_keys.keys_p +
1131 key_to_write_offset);
1133 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_USER,
1138 continue_at(cl, bch2_write_index, index_update_wq(op));
1142 op->flags |= BCH_WRITE_DONE;
1144 continue_at(cl, bch2_write_index, index_update_wq(op));
1148 * If the write can't all be submitted at once, we generally want to
1149 * block synchronously as that signals backpressure to the caller.
1151 * However, if we're running out of a workqueue, we can't block here
1152 * because we'll be blocking other work items from completing:
1154 if (current->flags & PF_WQ_WORKER) {
1155 continue_at(cl, bch2_write_index, index_update_wq(op));
1161 if (!bch2_keylist_empty(&op->insert_keys)) {
1162 __bch2_write_index(op);
1165 op->flags |= BCH_WRITE_DONE;
1166 continue_at_nobarrier(cl, bch2_write_done, NULL);
1174 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1176 struct closure *cl = &op->cl;
1177 struct bio *bio = &op->wbio.bio;
1178 struct bvec_iter iter;
1179 struct bkey_i_inline_data *id;
1183 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1185 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1186 ARRAY_SIZE(op->inline_keys),
1187 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1193 sectors = bio_sectors(bio);
1194 op->pos.offset += sectors;
1196 id = bkey_inline_data_init(op->insert_keys.top);
1198 id->k.version = op->version;
1199 id->k.size = sectors;
1201 iter = bio->bi_iter;
1202 iter.bi_size = data_len;
1203 memcpy_from_bio(id->v.data, bio, iter);
1205 while (data_len & 7)
1206 id->v.data[data_len++] = '\0';
1207 set_bkey_val_bytes(&id->k, data_len);
1208 bch2_keylist_push(&op->insert_keys);
1210 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1211 op->flags |= BCH_WRITE_DONE;
1213 continue_at_nobarrier(cl, bch2_write_index, NULL);
1216 bch2_write_done(&op->cl);
1220 * bch_write - handle a write to a cache device or flash only volume
1222 * This is the starting point for any data to end up in a cache device; it could
1223 * be from a normal write, or a writeback write, or a write to a flash only
1224 * volume - it's also used by the moving garbage collector to compact data in
1225 * mostly empty buckets.
1227 * It first writes the data to the cache, creating a list of keys to be inserted
1228 * (if the data won't fit in a single open bucket, there will be multiple keys);
1229 * after the data is written it calls bch_journal, and after the keys have been
1230 * added to the next journal write they're inserted into the btree.
1232 * If op->discard is true, instead of inserting the data it invalidates the
1233 * region of the cache represented by op->bio and op->inode.
1235 void bch2_write(struct closure *cl)
1237 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1238 struct bio *bio = &op->wbio.bio;
1239 struct bch_fs *c = op->c;
1242 BUG_ON(!op->nr_replicas);
1243 BUG_ON(!op->write_point.v);
1244 BUG_ON(!bkey_cmp(op->pos, POS_MAX));
1246 op->start_time = local_clock();
1247 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1248 wbio_init(bio)->put_bio = false;
1250 if (bio_sectors(bio) & (c->opts.block_size - 1)) {
1251 __bcache_io_error(c, "misaligned write");
1256 if (c->opts.nochanges ||
1257 !percpu_ref_tryget(&c->writes)) {
1258 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1259 __bcache_io_error(c, "read only");
1265 * Can't ratelimit copygc - we'd deadlock:
1267 if (!(op->flags & BCH_WRITE_FROM_INTERNAL))
1268 down(&c->io_in_flight);
1270 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1272 data_len = min_t(u64, bio->bi_iter.bi_size,
1273 op->new_i_size - (op->pos.offset << 9));
1275 if (c->opts.inline_data &&
1276 data_len <= min(block_bytes(c) / 2, 1024U)) {
1277 bch2_write_data_inline(op, data_len);
1281 continue_at_nobarrier(cl, __bch2_write, NULL);
1284 if (!(op->flags & BCH_WRITE_NOPUT_RESERVATION))
1285 bch2_disk_reservation_put(c, &op->res);
1288 EBUG_ON(cl->parent);
1289 closure_debug_destroy(cl);
1296 /* Cache promotion on read */
1300 struct rcu_head rcu;
1303 struct rhash_head hash;
1306 struct migrate_write write;
1307 struct bio_vec bi_inline_vecs[0]; /* must be last */
1310 static const struct rhashtable_params bch_promote_params = {
1311 .head_offset = offsetof(struct promote_op, hash),
1312 .key_offset = offsetof(struct promote_op, pos),
1313 .key_len = sizeof(struct bpos),
1316 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1318 struct bch_io_opts opts,
1321 if (!(flags & BCH_READ_MAY_PROMOTE))
1324 if (!opts.promote_target)
1327 if (bch2_bkey_has_target(c, k, opts.promote_target))
1330 if (bch2_target_congested(c, opts.promote_target)) {
1331 /* XXX trace this */
1335 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1336 bch_promote_params))
1342 static void promote_free(struct bch_fs *c, struct promote_op *op)
1346 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1347 bch_promote_params);
1349 percpu_ref_put(&c->writes);
1353 static void promote_done(struct closure *cl)
1355 struct promote_op *op =
1356 container_of(cl, struct promote_op, cl);
1357 struct bch_fs *c = op->write.op.c;
1359 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1362 bch2_bio_free_pages_pool(c, &op->write.op.wbio.bio);
1363 promote_free(c, op);
1366 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1368 struct bch_fs *c = rbio->c;
1369 struct closure *cl = &op->cl;
1370 struct bio *bio = &op->write.op.wbio.bio;
1372 trace_promote(&rbio->bio);
1374 /* we now own pages: */
1375 BUG_ON(!rbio->bounce);
1376 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1378 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1379 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1380 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1382 bch2_migrate_read_done(&op->write, rbio);
1384 closure_init(cl, NULL);
1385 closure_call(&op->write.op.cl, bch2_write, c->wq, cl);
1386 closure_return_with_destructor(cl, promote_done);
1389 static struct promote_op *__promote_alloc(struct bch_fs *c,
1390 enum btree_id btree_id,
1393 struct extent_ptr_decoded *pick,
1394 struct bch_io_opts opts,
1396 struct bch_read_bio **rbio)
1398 struct promote_op *op = NULL;
1400 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1403 if (!percpu_ref_tryget(&c->writes))
1406 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1410 op->start_time = local_clock();
1414 * We don't use the mempool here because extents that aren't
1415 * checksummed or compressed can be too big for the mempool:
1417 *rbio = kzalloc(sizeof(struct bch_read_bio) +
1418 sizeof(struct bio_vec) * pages,
1423 rbio_init(&(*rbio)->bio, opts);
1424 bio_init(&(*rbio)->bio, (*rbio)->bio.bi_inline_vecs, pages);
1426 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1430 (*rbio)->bounce = true;
1431 (*rbio)->split = true;
1432 (*rbio)->kmalloc = true;
1434 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1435 bch_promote_params))
1438 bio = &op->write.op.wbio.bio;
1439 bio_init(bio, bio->bi_inline_vecs, pages);
1441 ret = bch2_migrate_write_init(c, &op->write,
1442 writepoint_hashed((unsigned long) current),
1445 (struct data_opts) {
1446 .target = opts.promote_target
1454 bio_free_pages(&(*rbio)->bio);
1458 percpu_ref_put(&c->writes);
1463 static struct promote_op *promote_alloc(struct bch_fs *c,
1464 struct bvec_iter iter,
1466 struct extent_ptr_decoded *pick,
1467 struct bch_io_opts opts,
1469 struct bch_read_bio **rbio,
1473 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1474 /* data might have to be decompressed in the write path: */
1475 unsigned sectors = promote_full
1476 ? max(pick->crc.compressed_size, pick->crc.live_size)
1477 : bvec_iter_sectors(iter);
1478 struct bpos pos = promote_full
1479 ? bkey_start_pos(k.k)
1480 : POS(k.k->p.inode, iter.bi_sector);
1481 struct promote_op *promote;
1483 if (!should_promote(c, k, pos, opts, flags))
1486 promote = __promote_alloc(c,
1487 k.k->type == KEY_TYPE_reflink_v
1490 k, pos, pick, opts, sectors, rbio);
1495 *read_full = promote_full;
1501 #define READ_RETRY_AVOID 1
1502 #define READ_RETRY 2
1507 RBIO_CONTEXT_HIGHPRI,
1508 RBIO_CONTEXT_UNBOUND,
1511 static inline struct bch_read_bio *
1512 bch2_rbio_parent(struct bch_read_bio *rbio)
1514 return rbio->split ? rbio->parent : rbio;
1518 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
1519 enum rbio_context context,
1520 struct workqueue_struct *wq)
1522 if (context <= rbio->context) {
1525 rbio->work.func = fn;
1526 rbio->context = context;
1527 queue_work(wq, &rbio->work);
1531 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
1533 BUG_ON(rbio->bounce && !rbio->split);
1536 promote_free(rbio->c, rbio->promote);
1537 rbio->promote = NULL;
1540 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
1543 struct bch_read_bio *parent = rbio->parent;
1548 bio_put(&rbio->bio);
1557 * Only called on a top level bch_read_bio to complete an entire read request,
1560 static void bch2_rbio_done(struct bch_read_bio *rbio)
1562 if (rbio->start_time)
1563 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
1565 bio_endio(&rbio->bio);
1568 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
1569 struct bvec_iter bvec_iter, u64 inode,
1570 struct bch_io_failures *failed,
1573 struct btree_trans trans;
1574 struct btree_iter *iter;
1575 struct bkey_on_stack sk;
1579 flags &= ~BCH_READ_LAST_FRAGMENT;
1580 flags |= BCH_READ_MUST_CLONE;
1582 bkey_on_stack_init(&sk);
1583 bch2_trans_init(&trans, c, 0, 0);
1585 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
1586 rbio->pos, BTREE_ITER_SLOTS);
1588 rbio->bio.bi_status = 0;
1590 k = bch2_btree_iter_peek_slot(iter);
1594 bkey_on_stack_reassemble(&sk, c, k);
1595 k = bkey_i_to_s_c(sk.k);
1596 bch2_trans_unlock(&trans);
1598 if (!bch2_bkey_matches_ptr(c, k,
1601 rbio->pick.crc.offset)) {
1602 /* extent we wanted to read no longer exists: */
1607 ret = __bch2_read_extent(c, rbio, bvec_iter, k, 0, failed, flags);
1608 if (ret == READ_RETRY)
1613 bch2_rbio_done(rbio);
1614 bch2_trans_exit(&trans);
1615 bkey_on_stack_exit(&sk, c);
1618 rbio->bio.bi_status = BLK_STS_IOERR;
1622 static void bch2_read_retry(struct bch_fs *c, struct bch_read_bio *rbio,
1623 struct bvec_iter bvec_iter, u64 inode,
1624 struct bch_io_failures *failed, unsigned flags)
1626 struct btree_trans trans;
1627 struct btree_iter *iter;
1628 struct bkey_on_stack sk;
1632 flags &= ~BCH_READ_LAST_FRAGMENT;
1633 flags |= BCH_READ_MUST_CLONE;
1635 bkey_on_stack_init(&sk);
1636 bch2_trans_init(&trans, c, 0, 0);
1638 bch2_trans_begin(&trans);
1640 for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS,
1641 POS(inode, bvec_iter.bi_sector),
1642 BTREE_ITER_SLOTS, k, ret) {
1643 unsigned bytes, sectors, offset_into_extent;
1645 bkey_on_stack_reassemble(&sk, c, k);
1646 k = bkey_i_to_s_c(sk.k);
1648 offset_into_extent = iter->pos.offset -
1649 bkey_start_offset(k.k);
1650 sectors = k.k->size - offset_into_extent;
1652 ret = bch2_read_indirect_extent(&trans,
1653 &offset_into_extent, &sk);
1657 sectors = min(sectors, k.k->size - offset_into_extent);
1659 bch2_trans_unlock(&trans);
1661 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
1662 swap(bvec_iter.bi_size, bytes);
1664 ret = __bch2_read_extent(c, rbio, bvec_iter, k,
1665 offset_into_extent, failed, flags);
1673 if (bytes == bvec_iter.bi_size)
1676 swap(bvec_iter.bi_size, bytes);
1677 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
1683 * If we get here, it better have been because there was an error
1684 * reading a btree node
1687 __bcache_io_error(c, "btree IO error: %i", ret);
1689 rbio->bio.bi_status = BLK_STS_IOERR;
1691 bch2_trans_exit(&trans);
1692 bkey_on_stack_exit(&sk, c);
1693 bch2_rbio_done(rbio);
1696 static void bch2_rbio_retry(struct work_struct *work)
1698 struct bch_read_bio *rbio =
1699 container_of(work, struct bch_read_bio, work);
1700 struct bch_fs *c = rbio->c;
1701 struct bvec_iter iter = rbio->bvec_iter;
1702 unsigned flags = rbio->flags;
1703 u64 inode = rbio->pos.inode;
1704 struct bch_io_failures failed = { .nr = 0 };
1706 trace_read_retry(&rbio->bio);
1708 if (rbio->retry == READ_RETRY_AVOID)
1709 bch2_mark_io_failure(&failed, &rbio->pick);
1711 rbio->bio.bi_status = 0;
1713 rbio = bch2_rbio_free(rbio);
1715 flags |= BCH_READ_IN_RETRY;
1716 flags &= ~BCH_READ_MAY_PROMOTE;
1718 if (flags & BCH_READ_NODECODE)
1719 bch2_read_retry_nodecode(c, rbio, iter, inode, &failed, flags);
1721 bch2_read_retry(c, rbio, iter, inode, &failed, flags);
1724 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
1727 rbio->retry = retry;
1729 if (rbio->flags & BCH_READ_IN_RETRY)
1732 if (retry == READ_ERR) {
1733 rbio = bch2_rbio_free(rbio);
1735 rbio->bio.bi_status = error;
1736 bch2_rbio_done(rbio);
1738 bch2_rbio_punt(rbio, bch2_rbio_retry,
1739 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
1743 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
1744 struct bch_read_bio *rbio)
1746 struct bch_fs *c = rbio->c;
1747 u64 data_offset = rbio->pos.offset - rbio->pick.crc.offset;
1748 struct bch_extent_crc_unpacked new_crc;
1749 struct btree_iter *iter = NULL;
1754 if (crc_is_compressed(rbio->pick.crc))
1757 iter = bch2_trans_get_iter(trans, BTREE_ID_EXTENTS, rbio->pos,
1758 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1759 if ((ret = PTR_ERR_OR_ZERO(iter)))
1762 k = bch2_btree_iter_peek_slot(iter);
1763 if ((ret = bkey_err(k)))
1767 * going to be temporarily appending another checksum entry:
1769 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
1770 BKEY_EXTENT_U64s_MAX * 8);
1771 if ((ret = PTR_ERR_OR_ZERO(new)))
1774 bkey_reassemble(new, k);
1775 k = bkey_i_to_s_c(new);
1777 if (bversion_cmp(k.k->version, rbio->version) ||
1778 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
1781 /* Extent was merged? */
1782 if (bkey_start_offset(k.k) < data_offset ||
1783 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
1786 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
1787 rbio->pick.crc, NULL, &new_crc,
1788 bkey_start_offset(k.k) - data_offset, k.k->size,
1789 rbio->pick.crc.csum_type)) {
1790 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
1795 if (!bch2_bkey_narrow_crcs(new, new_crc))
1798 bch2_trans_update(trans, iter, new, 0);
1800 bch2_trans_iter_put(trans, iter);
1804 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
1806 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
1807 __bch2_rbio_narrow_crcs(&trans, rbio));
1810 /* Inner part that may run in process context */
1811 static void __bch2_read_endio(struct work_struct *work)
1813 struct bch_read_bio *rbio =
1814 container_of(work, struct bch_read_bio, work);
1815 struct bch_fs *c = rbio->c;
1816 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1817 struct bio *src = &rbio->bio;
1818 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
1819 struct bvec_iter dst_iter = rbio->bvec_iter;
1820 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
1821 struct nonce nonce = extent_nonce(rbio->version, crc);
1822 struct bch_csum csum;
1824 /* Reset iterator for checksumming and copying bounced data: */
1826 src->bi_iter.bi_size = crc.compressed_size << 9;
1827 src->bi_iter.bi_idx = 0;
1828 src->bi_iter.bi_bvec_done = 0;
1830 src->bi_iter = rbio->bvec_iter;
1833 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
1834 if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
1837 if (unlikely(rbio->narrow_crcs))
1838 bch2_rbio_narrow_crcs(rbio);
1840 if (rbio->flags & BCH_READ_NODECODE)
1843 /* Adjust crc to point to subset of data we want: */
1844 crc.offset += rbio->offset_into_extent;
1845 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
1847 if (crc_is_compressed(crc)) {
1848 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1849 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
1850 goto decompression_err;
1852 /* don't need to decrypt the entire bio: */
1853 nonce = nonce_add(nonce, crc.offset << 9);
1854 bio_advance(src, crc.offset << 9);
1856 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
1857 src->bi_iter.bi_size = dst_iter.bi_size;
1859 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1862 struct bvec_iter src_iter = src->bi_iter;
1863 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
1867 if (rbio->promote) {
1869 * Re encrypt data we decrypted, so it's consistent with
1872 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1873 promote_start(rbio->promote, rbio);
1874 rbio->promote = NULL;
1877 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
1878 rbio = bch2_rbio_free(rbio);
1879 bch2_rbio_done(rbio);
1884 * Checksum error: if the bio wasn't bounced, we may have been
1885 * reading into buffers owned by userspace (that userspace can
1886 * scribble over) - retry the read, bouncing it this time:
1888 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
1889 rbio->flags |= BCH_READ_MUST_BOUNCE;
1890 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
1894 bch2_dev_io_error(ca,
1895 "data checksum error, inode %llu offset %llu: expected %0llx:%0llx got %0llx:%0llx (type %u)",
1896 rbio->pos.inode, (u64) rbio->bvec_iter.bi_sector,
1897 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
1898 csum.hi, csum.lo, crc.csum_type);
1899 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
1902 __bcache_io_error(c, "decompression error, inode %llu offset %llu",
1904 (u64) rbio->bvec_iter.bi_sector);
1905 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
1909 static void bch2_read_endio(struct bio *bio)
1911 struct bch_read_bio *rbio =
1912 container_of(bio, struct bch_read_bio, bio);
1913 struct bch_fs *c = rbio->c;
1914 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1915 struct workqueue_struct *wq = NULL;
1916 enum rbio_context context = RBIO_CONTEXT_NULL;
1918 if (rbio->have_ioref) {
1919 bch2_latency_acct(ca, rbio->submit_time, READ);
1920 percpu_ref_put(&ca->io_ref);
1924 rbio->bio.bi_end_io = rbio->end_io;
1926 if (bch2_dev_io_err_on(bio->bi_status, ca, "data read")) {
1927 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
1931 if (rbio->pick.ptr.cached &&
1932 (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
1933 ptr_stale(ca, &rbio->pick.ptr))) {
1934 atomic_long_inc(&c->read_realloc_races);
1936 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
1937 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
1939 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
1943 if (rbio->narrow_crcs ||
1944 crc_is_compressed(rbio->pick.crc) ||
1945 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
1946 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
1947 else if (rbio->pick.crc.csum_type)
1948 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
1950 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
1953 int __bch2_read_indirect_extent(struct btree_trans *trans,
1954 unsigned *offset_into_extent,
1955 struct bkey_on_stack *orig_k)
1957 struct btree_iter *iter;
1962 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
1963 *offset_into_extent;
1965 iter = bch2_trans_get_iter(trans, BTREE_ID_REFLINK,
1966 POS(0, reflink_offset),
1968 ret = PTR_ERR_OR_ZERO(iter);
1972 k = bch2_btree_iter_peek_slot(iter);
1977 if (k.k->type != KEY_TYPE_reflink_v) {
1978 __bcache_io_error(trans->c,
1979 "pointer to nonexistent indirect extent");
1984 *offset_into_extent = iter->pos.offset - bkey_start_offset(k.k);
1985 bkey_on_stack_reassemble(orig_k, trans->c, k);
1987 bch2_trans_iter_put(trans, iter);
1991 int __bch2_read_extent(struct bch_fs *c, struct bch_read_bio *orig,
1992 struct bvec_iter iter, struct bkey_s_c k,
1993 unsigned offset_into_extent,
1994 struct bch_io_failures *failed, unsigned flags)
1996 struct extent_ptr_decoded pick;
1997 struct bch_read_bio *rbio = NULL;
1999 struct promote_op *promote = NULL;
2000 bool bounce = false, read_full = false, narrow_crcs = false;
2001 struct bpos pos = bkey_start_pos(k.k);
2004 if (k.k->type == KEY_TYPE_inline_data) {
2005 struct bkey_s_c_inline_data d = bkey_s_c_to_inline_data(k);
2006 unsigned bytes = min_t(unsigned, iter.bi_size,
2007 bkey_val_bytes(d.k));
2009 swap(iter.bi_size, bytes);
2010 memcpy_to_bio(&orig->bio, iter, d.v->data);
2011 swap(iter.bi_size, bytes);
2012 bio_advance_iter(&orig->bio, &iter, bytes);
2013 zero_fill_bio_iter(&orig->bio, iter);
2017 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2019 /* hole or reservation - just zero fill: */
2024 __bcache_io_error(c, "no device to read from");
2029 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2031 if (flags & BCH_READ_NODECODE) {
2033 * can happen if we retry, and the extent we were going to read
2034 * has been merged in the meantime:
2036 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2039 iter.bi_size = pick.crc.compressed_size << 9;
2043 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2044 bio_flagged(&orig->bio, BIO_CHAIN))
2045 flags |= BCH_READ_MUST_CLONE;
2047 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2048 bch2_can_narrow_extent_crcs(k, pick.crc);
2050 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2051 flags |= BCH_READ_MUST_BOUNCE;
2053 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2055 if (crc_is_compressed(pick.crc) ||
2056 (pick.crc.csum_type != BCH_CSUM_NONE &&
2057 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2058 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2059 (flags & BCH_READ_USER_MAPPED)) ||
2060 (flags & BCH_READ_MUST_BOUNCE)))) {
2065 if (orig->opts.promote_target)
2066 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2067 &rbio, &bounce, &read_full);
2070 EBUG_ON(crc_is_compressed(pick.crc));
2071 EBUG_ON(pick.crc.csum_type &&
2072 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2073 bvec_iter_sectors(iter) != pick.crc.live_size ||
2075 offset_into_extent));
2077 pos.offset += offset_into_extent;
2078 pick.ptr.offset += pick.crc.offset +
2080 offset_into_extent = 0;
2081 pick.crc.compressed_size = bvec_iter_sectors(iter);
2082 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2083 pick.crc.offset = 0;
2084 pick.crc.live_size = bvec_iter_sectors(iter);
2085 offset_into_extent = 0;
2090 * promote already allocated bounce rbio:
2091 * promote needs to allocate a bio big enough for uncompressing
2092 * data in the write path, but we're not going to use it all
2095 EBUG_ON(rbio->bio.bi_iter.bi_size <
2096 pick.crc.compressed_size << 9);
2097 rbio->bio.bi_iter.bi_size =
2098 pick.crc.compressed_size << 9;
2099 } else if (bounce) {
2100 unsigned sectors = pick.crc.compressed_size;
2102 rbio = rbio_init(bio_alloc_bioset(GFP_NOIO,
2103 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2104 &c->bio_read_split),
2107 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2108 rbio->bounce = true;
2110 } else if (flags & BCH_READ_MUST_CLONE) {
2112 * Have to clone if there were any splits, due to error
2113 * reporting issues (if a split errored, and retrying didn't
2114 * work, when it reports the error to its parent (us) we don't
2115 * know if the error was from our bio, and we should retry, or
2116 * from the whole bio, in which case we don't want to retry and
2119 rbio = rbio_init(bio_clone_fast(&orig->bio, GFP_NOIO,
2120 &c->bio_read_split),
2122 rbio->bio.bi_iter = iter;
2126 rbio->bio.bi_iter = iter;
2127 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2130 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2133 rbio->submit_time = local_clock();
2135 rbio->parent = orig;
2137 rbio->end_io = orig->bio.bi_end_io;
2138 rbio->bvec_iter = iter;
2139 rbio->offset_into_extent= offset_into_extent;
2140 rbio->flags = flags;
2141 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2142 rbio->narrow_crcs = narrow_crcs;
2146 /* XXX: only initialize this if needed */
2147 rbio->devs_have = bch2_bkey_devs(k);
2150 rbio->version = k.k->version;
2151 rbio->promote = promote;
2152 INIT_WORK(&rbio->work, NULL);
2154 rbio->bio.bi_opf = orig->bio.bi_opf;
2155 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2156 rbio->bio.bi_end_io = bch2_read_endio;
2159 trace_read_bounce(&rbio->bio);
2161 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2164 bucket_io_clock_reset(c, ca, PTR_BUCKET_NR(ca, &pick.ptr), READ);
2167 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2168 bio_inc_remaining(&orig->bio);
2169 trace_read_split(&orig->bio);
2172 if (!rbio->pick.idx) {
2173 if (!rbio->have_ioref) {
2174 __bcache_io_error(c, "no device to read from");
2175 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2179 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_USER],
2180 bio_sectors(&rbio->bio));
2181 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2183 if (likely(!(flags & BCH_READ_IN_RETRY)))
2184 submit_bio(&rbio->bio);
2186 submit_bio_wait(&rbio->bio);
2188 /* Attempting reconstruct read: */
2189 if (bch2_ec_read_extent(c, rbio)) {
2190 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2194 if (likely(!(flags & BCH_READ_IN_RETRY)))
2195 bio_endio(&rbio->bio);
2198 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2203 rbio->context = RBIO_CONTEXT_UNBOUND;
2204 bch2_read_endio(&rbio->bio);
2207 rbio = bch2_rbio_free(rbio);
2209 if (ret == READ_RETRY_AVOID) {
2210 bch2_mark_io_failure(failed, &pick);
2218 if (flags & BCH_READ_IN_RETRY)
2221 orig->bio.bi_status = BLK_STS_IOERR;
2226 * won't normally happen in the BCH_READ_NODECODE
2227 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2228 * to read no longer exists we have to signal that:
2230 if (flags & BCH_READ_NODECODE)
2233 zero_fill_bio_iter(&orig->bio, iter);
2235 if (flags & BCH_READ_LAST_FRAGMENT)
2236 bch2_rbio_done(orig);
2240 void bch2_read(struct bch_fs *c, struct bch_read_bio *rbio, u64 inode)
2242 struct btree_trans trans;
2243 struct btree_iter *iter;
2244 struct bkey_on_stack sk;
2246 unsigned flags = BCH_READ_RETRY_IF_STALE|
2247 BCH_READ_MAY_PROMOTE|
2248 BCH_READ_USER_MAPPED;
2251 BUG_ON(rbio->_state);
2252 BUG_ON(flags & BCH_READ_NODECODE);
2253 BUG_ON(flags & BCH_READ_IN_RETRY);
2256 rbio->start_time = local_clock();
2258 bkey_on_stack_init(&sk);
2259 bch2_trans_init(&trans, c, 0, 0);
2261 bch2_trans_begin(&trans);
2263 iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
2264 POS(inode, rbio->bio.bi_iter.bi_sector),
2267 unsigned bytes, sectors, offset_into_extent;
2269 bch2_btree_iter_set_pos(iter,
2270 POS(inode, rbio->bio.bi_iter.bi_sector));
2272 k = bch2_btree_iter_peek_slot(iter);
2277 offset_into_extent = iter->pos.offset -
2278 bkey_start_offset(k.k);
2279 sectors = k.k->size - offset_into_extent;
2281 bkey_on_stack_reassemble(&sk, c, k);
2282 k = bkey_i_to_s_c(sk.k);
2284 ret = bch2_read_indirect_extent(&trans,
2285 &offset_into_extent, &sk);
2290 * With indirect extents, the amount of data to read is the min
2291 * of the original extent and the indirect extent:
2293 sectors = min(sectors, k.k->size - offset_into_extent);
2296 * Unlock the iterator while the btree node's lock is still in
2297 * cache, before doing the IO:
2299 bch2_trans_unlock(&trans);
2301 bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
2302 swap(rbio->bio.bi_iter.bi_size, bytes);
2304 if (rbio->bio.bi_iter.bi_size == bytes)
2305 flags |= BCH_READ_LAST_FRAGMENT;
2307 bch2_read_extent(c, rbio, k, offset_into_extent, flags);
2309 if (flags & BCH_READ_LAST_FRAGMENT)
2312 swap(rbio->bio.bi_iter.bi_size, bytes);
2313 bio_advance(&rbio->bio, bytes);
2316 bch2_trans_exit(&trans);
2317 bkey_on_stack_exit(&sk, c);
2323 bcache_io_error(c, &rbio->bio, "btree IO error: %i", ret);
2324 bch2_rbio_done(rbio);
2328 void bch2_fs_io_exit(struct bch_fs *c)
2330 if (c->promote_table.tbl)
2331 rhashtable_destroy(&c->promote_table);
2332 mempool_exit(&c->bio_bounce_pages);
2333 bioset_exit(&c->bio_write);
2334 bioset_exit(&c->bio_read_split);
2335 bioset_exit(&c->bio_read);
2338 int bch2_fs_io_init(struct bch_fs *c)
2340 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2341 BIOSET_NEED_BVECS) ||
2342 bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2343 BIOSET_NEED_BVECS) ||
2344 bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2345 BIOSET_NEED_BVECS) ||
2346 mempool_init_page_pool(&c->bio_bounce_pages,
2348 c->opts.btree_node_size,
2349 c->sb.encoded_extent_max) /
2351 rhashtable_init(&c->promote_table, &bch_promote_params))