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"
14 #include "btree_update.h"
20 #include "disk_groups.h"
23 #include "extent_update.h"
29 #include "rebalance.h"
30 #include "subvolume.h"
34 #include <linux/blkdev.h>
35 #include <linux/random.h>
36 #include <linux/sched/mm.h>
38 #include <trace/events/bcachefs.h>
40 const char *bch2_blk_status_to_str(blk_status_t status)
42 if (status == BLK_STS_REMOVED)
43 return "device removed";
44 return blk_status_to_str(status);
47 static bool bch2_target_congested(struct bch_fs *c, u16 target)
49 const struct bch_devs_mask *devs;
50 unsigned d, nr = 0, total = 0;
51 u64 now = local_clock(), last;
59 devs = bch2_target_to_mask(c, target) ?:
60 &c->rw_devs[BCH_DATA_user];
62 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
63 ca = rcu_dereference(c->devs[d]);
67 congested = atomic_read(&ca->congested);
68 last = READ_ONCE(ca->congested_last);
69 if (time_after64(now, last))
70 congested -= (now - last) >> 12;
72 total += max(congested, 0LL);
77 return bch2_rand_range(nr * CONGESTED_MAX) < total;
80 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
84 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
85 /* ideally we'd be taking into account the device's variance here: */
86 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
87 s64 latency_over = io_latency - latency_threshold;
89 if (latency_threshold && latency_over > 0) {
91 * bump up congested by approximately latency_over * 4 /
92 * latency_threshold - we don't need much accuracy here so don't
93 * bother with the divide:
95 if (atomic_read(&ca->congested) < CONGESTED_MAX)
96 atomic_add(latency_over >>
97 max_t(int, ilog2(latency_threshold) - 2, 0),
100 ca->congested_last = now;
101 } else if (atomic_read(&ca->congested) > 0) {
102 atomic_dec(&ca->congested);
106 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
108 atomic64_t *latency = &ca->cur_latency[rw];
109 u64 now = local_clock();
110 u64 io_latency = time_after64(now, submit_time)
113 u64 old, new, v = atomic64_read(latency);
119 * If the io latency was reasonably close to the current
120 * latency, skip doing the update and atomic operation - most of
123 if (abs((int) (old - io_latency)) < (old >> 1) &&
127 new = ewma_add(old, io_latency, 5);
128 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
130 bch2_congested_acct(ca, io_latency, now, rw);
132 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
135 /* Allocate, free from mempool: */
137 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
139 struct bvec_iter_all iter;
142 bio_for_each_segment_all(bv, bio, iter)
143 if (bv->bv_page != ZERO_PAGE(0))
144 mempool_free(bv->bv_page, &c->bio_bounce_pages);
148 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
152 if (likely(!*using_mempool)) {
153 page = alloc_page(GFP_NOIO);
154 if (unlikely(!page)) {
155 mutex_lock(&c->bio_bounce_pages_lock);
156 *using_mempool = true;
162 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
168 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
171 bool using_mempool = false;
174 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
175 unsigned len = min_t(size_t, PAGE_SIZE, size);
177 BUG_ON(!bio_add_page(bio, page, len, 0));
182 mutex_unlock(&c->bio_bounce_pages_lock);
185 /* Extent update path: */
187 int bch2_sum_sector_overwrites(struct btree_trans *trans,
188 struct btree_iter *extent_iter,
190 bool *usage_increasing,
191 s64 *i_sectors_delta,
192 s64 *disk_sectors_delta)
194 struct bch_fs *c = trans->c;
195 struct btree_iter iter;
197 unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
198 bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
201 *usage_increasing = false;
202 *i_sectors_delta = 0;
203 *disk_sectors_delta = 0;
205 bch2_trans_copy_iter(&iter, extent_iter);
207 for_each_btree_key_continue_norestart(iter, BTREE_ITER_SLOTS, old, ret) {
208 s64 sectors = min(new->k.p.offset, old.k->p.offset) -
209 max(bkey_start_offset(&new->k),
210 bkey_start_offset(old.k));
212 *i_sectors_delta += sectors *
213 (bkey_extent_is_allocation(&new->k) -
214 bkey_extent_is_allocation(old.k));
216 *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
217 *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
218 ? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
221 if (!*usage_increasing &&
222 (new->k.p.snapshot != old.k->p.snapshot ||
223 new_replicas > bch2_bkey_replicas(c, old) ||
224 (!new_compressed && bch2_bkey_sectors_compressed(old))))
225 *usage_increasing = true;
227 if (bkey_cmp(old.k->p, new->k.p) >= 0)
231 bch2_trans_iter_exit(trans, &iter);
235 int bch2_extent_update(struct btree_trans *trans,
237 struct btree_iter *iter,
239 struct disk_reservation *disk_res,
242 s64 *i_sectors_delta_total,
245 struct btree_iter inode_iter;
246 struct bch_inode_unpacked inode_u;
247 struct bpos next_pos;
248 bool usage_increasing;
249 s64 i_sectors_delta = 0, disk_sectors_delta = 0;
253 * This traverses us the iterator without changing iter->path->pos to
254 * search_key() (which is pos + 1 for extents): we want there to be a
255 * path already traversed at iter->pos because
256 * bch2_trans_extent_update() will use it to attempt extent merging
258 ret = __bch2_btree_iter_traverse(iter);
262 ret = bch2_extent_trim_atomic(trans, iter, k);
266 new_i_size = min(k->k.p.offset << 9, new_i_size);
269 ret = bch2_sum_sector_overwrites(trans, iter, k,
272 &disk_sectors_delta);
277 disk_sectors_delta > (s64) disk_res->sectors) {
278 ret = bch2_disk_reservation_add(trans->c, disk_res,
279 disk_sectors_delta - disk_res->sectors,
280 !check_enospc || !usage_increasing
281 ? BCH_DISK_RESERVATION_NOFAIL : 0);
286 ret = bch2_inode_peek(trans, &inode_iter, &inode_u, inum,
291 if (!(inode_u.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
292 new_i_size > inode_u.bi_size)
293 inode_u.bi_size = new_i_size;
295 inode_u.bi_sectors += i_sectors_delta;
297 ret = bch2_trans_update(trans, iter, k, 0) ?:
298 bch2_inode_write(trans, &inode_iter, &inode_u) ?:
299 bch2_trans_commit(trans, disk_res, journal_seq,
300 BTREE_INSERT_NOCHECK_RW|
301 BTREE_INSERT_NOFAIL);
302 bch2_trans_iter_exit(trans, &inode_iter);
307 if (i_sectors_delta_total)
308 *i_sectors_delta_total += i_sectors_delta;
309 bch2_btree_iter_set_pos(iter, next_pos);
315 * Returns -EINTR if we had to drop locks:
317 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
318 subvol_inum inum, u64 end,
319 s64 *i_sectors_delta)
321 struct bch_fs *c = trans->c;
322 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
323 struct bpos end_pos = POS(inum.inum, end);
325 int ret = 0, ret2 = 0;
328 while (!ret || ret == -EINTR) {
329 struct disk_reservation disk_res =
330 bch2_disk_reservation_init(c, 0);
331 struct bkey_i delete;
336 bch2_trans_begin(trans);
338 ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
342 bch2_btree_iter_set_snapshot(iter, snapshot);
344 k = bch2_btree_iter_peek(iter);
345 if (bkey_cmp(iter->pos, end_pos) >= 0) {
346 bch2_btree_iter_set_pos(iter, end_pos);
354 bkey_init(&delete.k);
355 delete.k.p = iter->pos;
357 /* create the biggest key we can */
358 bch2_key_resize(&delete.k, max_sectors);
359 bch2_cut_back(end_pos, &delete);
361 ret = bch2_extent_update(trans, inum, iter, &delete,
363 0, i_sectors_delta, false);
364 bch2_disk_reservation_put(c, &disk_res);
370 int bch2_fpunch(struct bch_fs *c, subvol_inum inum, u64 start, u64 end,
371 s64 *i_sectors_delta)
373 struct btree_trans trans;
374 struct btree_iter iter;
377 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
378 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
379 POS(inum.inum, start),
382 ret = bch2_fpunch_at(&trans, &iter, inum, end, i_sectors_delta);
384 bch2_trans_iter_exit(&trans, &iter);
385 bch2_trans_exit(&trans);
387 return ret == -EINTR ? 0 : ret;
390 int bch2_write_index_default(struct bch_write_op *op)
392 struct bch_fs *c = op->c;
394 struct open_bucket *ec_ob = ec_open_bucket(c, &op->open_buckets);
395 struct keylist *keys = &op->insert_keys;
396 struct bkey_i *k = bch2_keylist_front(keys);
397 struct btree_trans trans;
398 struct btree_iter iter;
400 .subvol = op->subvol,
401 .inum = k->k.p.inode,
405 BUG_ON(!inum.subvol);
407 bch2_bkey_buf_init(&sk);
408 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
411 bch2_trans_begin(&trans);
413 k = bch2_keylist_front(keys);
414 bch2_bkey_buf_copy(&sk, c, k);
416 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol,
417 &sk.k->k.p.snapshot);
423 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
424 bkey_start_pos(&sk.k->k),
425 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
427 ret = bch2_extent_update(&trans, inum, &iter, sk.k,
428 &op->res, op_journal_seq(op),
429 op->new_i_size, &op->i_sectors_delta,
430 op->flags & BCH_WRITE_CHECK_ENOSPC);
431 bch2_trans_iter_exit(&trans, &iter);
439 bch2_ob_add_backpointer(c, ec_ob, &sk.k->k);
441 if (bkey_cmp(iter.pos, k->k.p) >= 0)
442 bch2_keylist_pop_front(&op->insert_keys);
444 bch2_cut_front(iter.pos, k);
445 } while (!bch2_keylist_empty(keys));
447 bch2_trans_exit(&trans);
448 bch2_bkey_buf_exit(&sk, c);
455 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
456 enum bch_data_type type,
457 const struct bkey_i *k)
459 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
460 const struct bch_extent_ptr *ptr;
461 struct bch_write_bio *n;
464 BUG_ON(c->opts.nochanges);
466 bkey_for_each_ptr(ptrs, ptr) {
467 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
470 ca = bch_dev_bkey_exists(c, ptr->dev);
472 if (to_entry(ptr + 1) < ptrs.end) {
473 n = to_wbio(bio_clone_fast(&wbio->bio, GFP_NOIO,
476 n->bio.bi_end_io = wbio->bio.bi_end_io;
477 n->bio.bi_private = wbio->bio.bi_private;
482 n->bio.bi_opf = wbio->bio.bi_opf;
483 bio_inc_remaining(&wbio->bio);
491 n->have_ioref = bch2_dev_get_ioref(ca,
492 type == BCH_DATA_btree ? READ : WRITE);
493 n->submit_time = local_clock();
494 n->bio.bi_iter.bi_sector = ptr->offset;
496 if (likely(n->have_ioref)) {
497 this_cpu_add(ca->io_done->sectors[WRITE][type],
498 bio_sectors(&n->bio));
500 bio_set_dev(&n->bio, ca->disk_sb.bdev);
503 n->bio.bi_status = BLK_STS_REMOVED;
509 static void __bch2_write(struct closure *);
511 static void bch2_write_done(struct closure *cl)
513 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
514 struct bch_fs *c = op->c;
516 if (!op->error && (op->flags & BCH_WRITE_FLUSH))
517 op->error = bch2_journal_error(&c->journal);
519 bch2_disk_reservation_put(c, &op->res);
520 percpu_ref_put(&c->writes);
521 bch2_keylist_free(&op->insert_keys, op->inline_keys);
523 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
527 closure_debug_destroy(cl);
535 * bch_write_index - after a write, update index to point to new data
537 static void __bch2_write_index(struct bch_write_op *op)
539 struct bch_fs *c = op->c;
540 struct keylist *keys = &op->insert_keys;
541 struct bch_extent_ptr *ptr;
542 struct bkey_i *src, *dst = keys->keys, *n, *k;
546 for (src = keys->keys; src != keys->top; src = n) {
549 if (bkey_extent_is_direct_data(&src->k)) {
550 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
551 test_bit(ptr->dev, op->failed.d));
553 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src))) {
560 memmove_u64s_down(dst, src, src->u64s);
561 dst = bkey_next(dst);
567 * probably not the ideal place to hook this in, but I don't
568 * particularly want to plumb io_opts all the way through the btree
569 * update stack right now
571 for_each_keylist_key(keys, k) {
572 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
574 if (bch2_bkey_is_incompressible(bkey_i_to_s_c(k)))
575 bch2_check_set_feature(op->c, BCH_FEATURE_incompressible);
579 if (!bch2_keylist_empty(keys)) {
580 u64 sectors_start = keylist_sectors(keys);
581 int ret = op->index_update_fn(op);
583 BUG_ON(ret == -EINTR);
584 BUG_ON(keylist_sectors(keys) && !ret);
586 op->written += sectors_start - keylist_sectors(keys);
589 bch_err_inum_ratelimited(c, op->pos.inode,
590 "write error %i from btree update", ret);
595 /* If some a bucket wasn't written, we can't erasure code it: */
596 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
597 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
599 bch2_open_buckets_put(c, &op->open_buckets);
602 keys->top = keys->keys;
607 static void bch2_write_index(struct closure *cl)
609 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
610 struct bch_fs *c = op->c;
612 __bch2_write_index(op);
614 if (!(op->flags & BCH_WRITE_DONE)) {
615 continue_at(cl, __bch2_write, index_update_wq(op));
616 } else if (!op->error && (op->flags & BCH_WRITE_FLUSH)) {
617 bch2_journal_flush_seq_async(&c->journal,
620 continue_at(cl, bch2_write_done, index_update_wq(op));
622 continue_at_nobarrier(cl, bch2_write_done, NULL);
626 static void bch2_write_endio(struct bio *bio)
628 struct closure *cl = bio->bi_private;
629 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
630 struct bch_write_bio *wbio = to_wbio(bio);
631 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
632 struct bch_fs *c = wbio->c;
633 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
635 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
637 op->pos.offset - bio_sectors(bio), /* XXX definitely wrong */
638 "data write error: %s",
639 bch2_blk_status_to_str(bio->bi_status)))
640 set_bit(wbio->dev, op->failed.d);
642 if (wbio->have_ioref) {
643 bch2_latency_acct(ca, wbio->submit_time, WRITE);
644 percpu_ref_put(&ca->io_ref);
648 bch2_bio_free_pages_pool(c, bio);
654 bio_endio(&parent->bio);
655 else if (!(op->flags & BCH_WRITE_SKIP_CLOSURE_PUT))
658 continue_at_nobarrier(cl, bch2_write_index, index_update_wq(op));
661 static void init_append_extent(struct bch_write_op *op,
662 struct write_point *wp,
663 struct bversion version,
664 struct bch_extent_crc_unpacked crc)
666 struct bch_fs *c = op->c;
667 struct bkey_i_extent *e;
668 struct open_bucket *ob;
671 BUG_ON(crc.compressed_size > wp->sectors_free);
672 wp->sectors_free -= crc.compressed_size;
673 op->pos.offset += crc.uncompressed_size;
675 e = bkey_extent_init(op->insert_keys.top);
677 e->k.size = crc.uncompressed_size;
678 e->k.version = version;
681 crc.compression_type ||
683 bch2_extent_crc_append(&e->k_i, crc);
685 open_bucket_for_each(c, &wp->ptrs, ob, i) {
686 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
687 union bch_extent_entry *end =
688 bkey_val_end(bkey_i_to_s(&e->k_i));
691 end->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
692 end->ptr.cached = !ca->mi.durability ||
693 (op->flags & BCH_WRITE_CACHED) != 0;
694 end->ptr.offset += ca->mi.bucket_size - ob->sectors_free;
698 BUG_ON(crc.compressed_size > ob->sectors_free);
699 ob->sectors_free -= crc.compressed_size;
702 bch2_keylist_push(&op->insert_keys);
705 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
706 struct write_point *wp,
708 bool *page_alloc_failed,
711 struct bch_write_bio *wbio;
713 unsigned output_available =
714 min(wp->sectors_free << 9, src->bi_iter.bi_size);
715 unsigned pages = DIV_ROUND_UP(output_available +
717 ? ((unsigned long) buf & (PAGE_SIZE - 1))
720 pages = min(pages, BIO_MAX_VECS);
722 bio = bio_alloc_bioset(GFP_NOIO, pages, &c->bio_write);
723 wbio = wbio_init(bio);
724 wbio->put_bio = true;
725 /* copy WRITE_SYNC flag */
726 wbio->bio.bi_opf = src->bi_opf;
729 bch2_bio_map(bio, buf, output_available);
736 * We can't use mempool for more than c->sb.encoded_extent_max
737 * worth of pages, but we'd like to allocate more if we can:
739 bch2_bio_alloc_pages_pool(c, bio,
740 min_t(unsigned, output_available,
741 c->opts.encoded_extent_max));
743 if (bio->bi_iter.bi_size < output_available)
745 bch2_bio_alloc_pages(bio,
747 bio->bi_iter.bi_size,
753 static int bch2_write_rechecksum(struct bch_fs *c,
754 struct bch_write_op *op,
755 unsigned new_csum_type)
757 struct bio *bio = &op->wbio.bio;
758 struct bch_extent_crc_unpacked new_crc;
761 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
763 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
764 bch2_csum_type_is_encryption(new_csum_type))
765 new_csum_type = op->crc.csum_type;
767 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
769 op->crc.offset, op->crc.live_size,
774 bio_advance(bio, op->crc.offset << 9);
775 bio->bi_iter.bi_size = op->crc.live_size << 9;
780 static int bch2_write_decrypt(struct bch_write_op *op)
782 struct bch_fs *c = op->c;
783 struct nonce nonce = extent_nonce(op->version, op->crc);
784 struct bch_csum csum;
786 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
790 * If we need to decrypt data in the write path, we'll no longer be able
791 * to verify the existing checksum (poly1305 mac, in this case) after
792 * it's decrypted - this is the last point we'll be able to reverify the
795 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
796 if (bch2_crc_cmp(op->crc.csum, csum))
799 bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
800 op->crc.csum_type = 0;
801 op->crc.csum = (struct bch_csum) { 0, 0 };
805 static enum prep_encoded_ret {
808 PREP_ENCODED_CHECKSUM_ERR,
809 PREP_ENCODED_DO_WRITE,
810 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
812 struct bch_fs *c = op->c;
813 struct bio *bio = &op->wbio.bio;
815 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
816 return PREP_ENCODED_OK;
818 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
820 /* Can we just write the entire extent as is? */
821 if (op->crc.uncompressed_size == op->crc.live_size &&
822 op->crc.compressed_size <= wp->sectors_free &&
823 (op->crc.compression_type == op->compression_type ||
824 op->incompressible)) {
825 if (!crc_is_compressed(op->crc) &&
826 op->csum_type != op->crc.csum_type &&
827 bch2_write_rechecksum(c, op, op->csum_type))
828 return PREP_ENCODED_CHECKSUM_ERR;
830 return PREP_ENCODED_DO_WRITE;
834 * If the data is compressed and we couldn't write the entire extent as
835 * is, we have to decompress it:
837 if (crc_is_compressed(op->crc)) {
838 struct bch_csum csum;
840 if (bch2_write_decrypt(op))
841 return PREP_ENCODED_CHECKSUM_ERR;
843 /* Last point we can still verify checksum: */
844 csum = bch2_checksum_bio(c, op->crc.csum_type,
845 extent_nonce(op->version, op->crc),
847 if (bch2_crc_cmp(op->crc.csum, csum))
848 return PREP_ENCODED_CHECKSUM_ERR;
850 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
851 return PREP_ENCODED_ERR;
855 * No longer have compressed data after this point - data might be
860 * If the data is checksummed and we're only writing a subset,
861 * rechecksum and adjust bio to point to currently live data:
863 if ((op->crc.live_size != op->crc.uncompressed_size ||
864 op->crc.csum_type != op->csum_type) &&
865 bch2_write_rechecksum(c, op, op->csum_type))
866 return PREP_ENCODED_CHECKSUM_ERR;
869 * If we want to compress the data, it has to be decrypted:
871 if ((op->compression_type ||
872 bch2_csum_type_is_encryption(op->crc.csum_type) !=
873 bch2_csum_type_is_encryption(op->csum_type)) &&
874 bch2_write_decrypt(op))
875 return PREP_ENCODED_CHECKSUM_ERR;
877 return PREP_ENCODED_OK;
880 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
883 struct bch_fs *c = op->c;
884 struct bio *src = &op->wbio.bio, *dst = src;
885 struct bvec_iter saved_iter;
887 unsigned total_output = 0, total_input = 0;
889 bool page_alloc_failed = false;
892 BUG_ON(!bio_sectors(src));
894 ec_buf = bch2_writepoint_ec_buf(c, wp);
896 switch (bch2_write_prep_encoded_data(op, wp)) {
897 case PREP_ENCODED_OK:
899 case PREP_ENCODED_ERR:
902 case PREP_ENCODED_CHECKSUM_ERR:
904 case PREP_ENCODED_DO_WRITE:
905 /* XXX look for bug here */
907 dst = bch2_write_bio_alloc(c, wp, src,
910 bio_copy_data(dst, src);
913 init_append_extent(op, wp, op->version, op->crc);
918 op->compression_type ||
920 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
921 (bch2_csum_type_is_encryption(op->csum_type) &&
922 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
923 dst = bch2_write_bio_alloc(c, wp, src,
929 saved_iter = dst->bi_iter;
932 struct bch_extent_crc_unpacked crc =
933 (struct bch_extent_crc_unpacked) { 0 };
934 struct bversion version = op->version;
935 size_t dst_len, src_len;
937 if (page_alloc_failed &&
938 dst->bi_iter.bi_size < (wp->sectors_free << 9) &&
939 dst->bi_iter.bi_size < c->opts.encoded_extent_max)
942 BUG_ON(op->compression_type &&
943 (op->flags & BCH_WRITE_DATA_ENCODED) &&
944 bch2_csum_type_is_encryption(op->crc.csum_type));
945 BUG_ON(op->compression_type && !bounce);
947 crc.compression_type = op->incompressible
948 ? BCH_COMPRESSION_TYPE_incompressible
949 : op->compression_type
950 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
951 op->compression_type)
953 if (!crc_is_compressed(crc)) {
954 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
955 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
958 dst_len = min_t(unsigned, dst_len,
959 c->opts.encoded_extent_max);
962 swap(dst->bi_iter.bi_size, dst_len);
963 bio_copy_data(dst, src);
964 swap(dst->bi_iter.bi_size, dst_len);
970 BUG_ON(!src_len || !dst_len);
972 if (bch2_csum_type_is_encryption(op->csum_type)) {
973 if (bversion_zero(version)) {
974 version.lo = atomic64_inc_return(&c->key_version);
976 crc.nonce = op->nonce;
977 op->nonce += src_len >> 9;
981 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
982 !crc_is_compressed(crc) &&
983 bch2_csum_type_is_encryption(op->crc.csum_type) ==
984 bch2_csum_type_is_encryption(op->csum_type)) {
986 * Note: when we're using rechecksum(), we need to be
987 * checksumming @src because it has all the data our
988 * existing checksum covers - if we bounced (because we
989 * were trying to compress), @dst will only have the
990 * part of the data the new checksum will cover.
992 * But normally we want to be checksumming post bounce,
993 * because part of the reason for bouncing is so the
994 * data can't be modified (by userspace) while it's in
997 if (bch2_rechecksum_bio(c, src, version, op->crc,
1000 bio_sectors(src) - (src_len >> 9),
1004 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1005 bch2_rechecksum_bio(c, src, version, op->crc,
1008 bio_sectors(src) - (src_len >> 9),
1012 crc.compressed_size = dst_len >> 9;
1013 crc.uncompressed_size = src_len >> 9;
1014 crc.live_size = src_len >> 9;
1016 swap(dst->bi_iter.bi_size, dst_len);
1017 bch2_encrypt_bio(c, op->csum_type,
1018 extent_nonce(version, crc), dst);
1019 crc.csum = bch2_checksum_bio(c, op->csum_type,
1020 extent_nonce(version, crc), dst);
1021 crc.csum_type = op->csum_type;
1022 swap(dst->bi_iter.bi_size, dst_len);
1025 init_append_extent(op, wp, version, crc);
1028 bio_advance(dst, dst_len);
1029 bio_advance(src, src_len);
1030 total_output += dst_len;
1031 total_input += src_len;
1032 } while (dst->bi_iter.bi_size &&
1033 src->bi_iter.bi_size &&
1035 !bch2_keylist_realloc(&op->insert_keys,
1037 ARRAY_SIZE(op->inline_keys),
1038 BKEY_EXTENT_U64s_MAX));
1040 more = src->bi_iter.bi_size != 0;
1042 dst->bi_iter = saved_iter;
1044 if (dst == src && more) {
1045 BUG_ON(total_output != total_input);
1047 dst = bio_split(src, total_input >> 9,
1048 GFP_NOIO, &c->bio_write);
1049 wbio_init(dst)->put_bio = true;
1050 /* copy WRITE_SYNC flag */
1051 dst->bi_opf = src->bi_opf;
1054 dst->bi_iter.bi_size = total_output;
1059 bch_err(c, "error verifying existing checksum while "
1060 "rewriting existing data (memory corruption?)");
1063 if (to_wbio(dst)->bounce)
1064 bch2_bio_free_pages_pool(c, dst);
1065 if (to_wbio(dst)->put_bio)
1071 static void __bch2_write(struct closure *cl)
1073 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1074 struct bch_fs *c = op->c;
1075 struct write_point *wp;
1077 bool skip_put = true;
1078 unsigned nofs_flags;
1081 nofs_flags = memalloc_nofs_save();
1083 memset(&op->failed, 0, sizeof(op->failed));
1086 struct bkey_i *key_to_write;
1087 unsigned key_to_write_offset = op->insert_keys.top_p -
1088 op->insert_keys.keys_p;
1090 /* +1 for possible cache device: */
1091 if (op->open_buckets.nr + op->nr_replicas + 1 >
1092 ARRAY_SIZE(op->open_buckets.v))
1095 if (bch2_keylist_realloc(&op->insert_keys,
1097 ARRAY_SIZE(op->inline_keys),
1098 BKEY_EXTENT_U64s_MAX))
1101 if ((op->flags & BCH_WRITE_FROM_INTERNAL) &&
1102 percpu_ref_is_dying(&c->writes)) {
1108 * The copygc thread is now global, which means it's no longer
1109 * freeing up space on specific disks, which means that
1110 * allocations for specific disks may hang arbitrarily long:
1112 wp = bch2_alloc_sectors_start(c,
1114 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1118 op->nr_replicas_required,
1121 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1122 BCH_WRITE_ONLY_SPECIFIED_DEVS)) ? NULL : cl);
1125 if (unlikely(IS_ERR(wp))) {
1126 if (unlikely(PTR_ERR(wp) != -EAGAIN)) {
1135 * It's possible for the allocator to fail, put us on the
1136 * freelist waitlist, and then succeed in one of various retry
1137 * paths: if that happens, we need to disable the skip_put
1138 * optimization because otherwise there won't necessarily be a
1139 * barrier before we free the bch_write_op:
1141 if (atomic_read(&cl->remaining) & CLOSURE_WAITING)
1144 bch2_open_bucket_get(c, wp, &op->open_buckets);
1145 ret = bch2_write_extent(op, wp, &bio);
1146 bch2_alloc_sectors_done(c, wp);
1155 * for the skip_put optimization this has to be set
1156 * before we submit the bio:
1158 op->flags |= BCH_WRITE_DONE;
1161 bio->bi_end_io = bch2_write_endio;
1162 bio->bi_private = &op->cl;
1163 bio->bi_opf |= REQ_OP_WRITE;
1166 closure_get(bio->bi_private);
1168 op->flags |= BCH_WRITE_SKIP_CLOSURE_PUT;
1170 key_to_write = (void *) (op->insert_keys.keys_p +
1171 key_to_write_offset);
1173 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1178 continue_at(cl, bch2_write_index, index_update_wq(op));
1180 memalloc_nofs_restore(nofs_flags);
1184 op->flags |= BCH_WRITE_DONE;
1186 continue_at(cl, bch2_write_index, index_update_wq(op));
1190 * If the write can't all be submitted at once, we generally want to
1191 * block synchronously as that signals backpressure to the caller.
1193 * However, if we're running out of a workqueue, we can't block here
1194 * because we'll be blocking other work items from completing:
1196 if (current->flags & PF_WQ_WORKER) {
1197 continue_at(cl, bch2_write_index, index_update_wq(op));
1203 if (!bch2_keylist_empty(&op->insert_keys)) {
1204 __bch2_write_index(op);
1207 op->flags |= BCH_WRITE_DONE;
1208 continue_at_nobarrier(cl, bch2_write_done, NULL);
1216 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1218 struct closure *cl = &op->cl;
1219 struct bio *bio = &op->wbio.bio;
1220 struct bvec_iter iter;
1221 struct bkey_i_inline_data *id;
1225 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1227 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1228 ARRAY_SIZE(op->inline_keys),
1229 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1235 sectors = bio_sectors(bio);
1236 op->pos.offset += sectors;
1238 id = bkey_inline_data_init(op->insert_keys.top);
1240 id->k.version = op->version;
1241 id->k.size = sectors;
1243 iter = bio->bi_iter;
1244 iter.bi_size = data_len;
1245 memcpy_from_bio(id->v.data, bio, iter);
1247 while (data_len & 7)
1248 id->v.data[data_len++] = '\0';
1249 set_bkey_val_bytes(&id->k, data_len);
1250 bch2_keylist_push(&op->insert_keys);
1252 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1253 op->flags |= BCH_WRITE_DONE;
1255 continue_at_nobarrier(cl, bch2_write_index, NULL);
1258 bch2_write_done(&op->cl);
1262 * bch_write - handle a write to a cache device or flash only volume
1264 * This is the starting point for any data to end up in a cache device; it could
1265 * be from a normal write, or a writeback write, or a write to a flash only
1266 * volume - it's also used by the moving garbage collector to compact data in
1267 * mostly empty buckets.
1269 * It first writes the data to the cache, creating a list of keys to be inserted
1270 * (if the data won't fit in a single open bucket, there will be multiple keys);
1271 * after the data is written it calls bch_journal, and after the keys have been
1272 * added to the next journal write they're inserted into the btree.
1274 * If op->discard is true, instead of inserting the data it invalidates the
1275 * region of the cache represented by op->bio and op->inode.
1277 void bch2_write(struct closure *cl)
1279 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1280 struct bio *bio = &op->wbio.bio;
1281 struct bch_fs *c = op->c;
1284 BUG_ON(!op->nr_replicas);
1285 BUG_ON(!op->write_point.v);
1286 BUG_ON(!bkey_cmp(op->pos, POS_MAX));
1288 op->start_time = local_clock();
1289 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1290 wbio_init(bio)->put_bio = false;
1292 if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1293 bch_err_inum_ratelimited(c, op->pos.inode,
1294 "misaligned write");
1299 if (c->opts.nochanges ||
1300 !percpu_ref_tryget(&c->writes)) {
1305 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1307 data_len = min_t(u64, bio->bi_iter.bi_size,
1308 op->new_i_size - (op->pos.offset << 9));
1310 if (c->opts.inline_data &&
1311 data_len <= min(block_bytes(c) / 2, 1024U)) {
1312 bch2_write_data_inline(op, data_len);
1316 continue_at_nobarrier(cl, __bch2_write, NULL);
1319 bch2_disk_reservation_put(c, &op->res);
1322 EBUG_ON(cl->parent);
1323 closure_debug_destroy(cl);
1330 /* Cache promotion on read */
1334 struct rcu_head rcu;
1337 struct rhash_head hash;
1340 struct migrate_write write;
1341 struct bio_vec bi_inline_vecs[0]; /* must be last */
1344 static const struct rhashtable_params bch_promote_params = {
1345 .head_offset = offsetof(struct promote_op, hash),
1346 .key_offset = offsetof(struct promote_op, pos),
1347 .key_len = sizeof(struct bpos),
1350 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1352 struct bch_io_opts opts,
1355 if (!(flags & BCH_READ_MAY_PROMOTE))
1358 if (!opts.promote_target)
1361 if (bch2_bkey_has_target(c, k, opts.promote_target))
1364 if (bch2_target_congested(c, opts.promote_target)) {
1365 /* XXX trace this */
1369 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1370 bch_promote_params))
1376 static void promote_free(struct bch_fs *c, struct promote_op *op)
1380 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1381 bch_promote_params);
1383 percpu_ref_put(&c->writes);
1387 static void promote_done(struct closure *cl)
1389 struct promote_op *op =
1390 container_of(cl, struct promote_op, cl);
1391 struct bch_fs *c = op->write.op.c;
1393 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1396 bch2_bio_free_pages_pool(c, &op->write.op.wbio.bio);
1397 promote_free(c, op);
1400 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1402 struct bch_fs *c = rbio->c;
1403 struct closure *cl = &op->cl;
1404 struct bio *bio = &op->write.op.wbio.bio;
1406 trace_promote(&rbio->bio);
1408 /* we now own pages: */
1409 BUG_ON(!rbio->bounce);
1410 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1412 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1413 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1414 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1416 bch2_migrate_read_done(&op->write, rbio);
1418 closure_init(cl, NULL);
1419 closure_call(&op->write.op.cl, bch2_write, c->btree_update_wq, cl);
1420 closure_return_with_destructor(cl, promote_done);
1423 static struct promote_op *__promote_alloc(struct bch_fs *c,
1424 enum btree_id btree_id,
1427 struct extent_ptr_decoded *pick,
1428 struct bch_io_opts opts,
1430 struct bch_read_bio **rbio)
1432 struct promote_op *op = NULL;
1434 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1437 if (!percpu_ref_tryget(&c->writes))
1440 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1444 op->start_time = local_clock();
1448 * We don't use the mempool here because extents that aren't
1449 * checksummed or compressed can be too big for the mempool:
1451 *rbio = kzalloc(sizeof(struct bch_read_bio) +
1452 sizeof(struct bio_vec) * pages,
1457 rbio_init(&(*rbio)->bio, opts);
1458 bio_init(&(*rbio)->bio, (*rbio)->bio.bi_inline_vecs, pages);
1460 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1464 (*rbio)->bounce = true;
1465 (*rbio)->split = true;
1466 (*rbio)->kmalloc = true;
1468 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1469 bch_promote_params))
1472 bio = &op->write.op.wbio.bio;
1473 bio_init(bio, bio->bi_inline_vecs, pages);
1475 ret = bch2_migrate_write_init(c, &op->write,
1476 writepoint_hashed((unsigned long) current),
1479 (struct data_opts) {
1480 .target = opts.promote_target,
1489 bio_free_pages(&(*rbio)->bio);
1493 percpu_ref_put(&c->writes);
1498 static struct promote_op *promote_alloc(struct bch_fs *c,
1499 struct bvec_iter iter,
1501 struct extent_ptr_decoded *pick,
1502 struct bch_io_opts opts,
1504 struct bch_read_bio **rbio,
1508 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1509 /* data might have to be decompressed in the write path: */
1510 unsigned sectors = promote_full
1511 ? max(pick->crc.compressed_size, pick->crc.live_size)
1512 : bvec_iter_sectors(iter);
1513 struct bpos pos = promote_full
1514 ? bkey_start_pos(k.k)
1515 : POS(k.k->p.inode, iter.bi_sector);
1516 struct promote_op *promote;
1518 if (!should_promote(c, k, pos, opts, flags))
1521 promote = __promote_alloc(c,
1522 k.k->type == KEY_TYPE_reflink_v
1525 k, pos, pick, opts, sectors, rbio);
1530 *read_full = promote_full;
1536 #define READ_RETRY_AVOID 1
1537 #define READ_RETRY 2
1542 RBIO_CONTEXT_HIGHPRI,
1543 RBIO_CONTEXT_UNBOUND,
1546 static inline struct bch_read_bio *
1547 bch2_rbio_parent(struct bch_read_bio *rbio)
1549 return rbio->split ? rbio->parent : rbio;
1553 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
1554 enum rbio_context context,
1555 struct workqueue_struct *wq)
1557 if (context <= rbio->context) {
1560 rbio->work.func = fn;
1561 rbio->context = context;
1562 queue_work(wq, &rbio->work);
1566 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
1568 BUG_ON(rbio->bounce && !rbio->split);
1571 promote_free(rbio->c, rbio->promote);
1572 rbio->promote = NULL;
1575 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
1578 struct bch_read_bio *parent = rbio->parent;
1583 bio_put(&rbio->bio);
1592 * Only called on a top level bch_read_bio to complete an entire read request,
1595 static void bch2_rbio_done(struct bch_read_bio *rbio)
1597 if (rbio->start_time)
1598 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
1600 bio_endio(&rbio->bio);
1603 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
1604 struct bvec_iter bvec_iter,
1605 struct bch_io_failures *failed,
1608 struct btree_trans trans;
1609 struct btree_iter iter;
1614 flags &= ~BCH_READ_LAST_FRAGMENT;
1615 flags |= BCH_READ_MUST_CLONE;
1617 bch2_bkey_buf_init(&sk);
1618 bch2_trans_init(&trans, c, 0, 0);
1620 bch2_trans_iter_init(&trans, &iter, rbio->data_btree,
1621 rbio->read_pos, BTREE_ITER_SLOTS);
1623 rbio->bio.bi_status = 0;
1625 k = bch2_btree_iter_peek_slot(&iter);
1629 bch2_bkey_buf_reassemble(&sk, c, k);
1630 k = bkey_i_to_s_c(sk.k);
1631 bch2_trans_unlock(&trans);
1633 if (!bch2_bkey_matches_ptr(c, k,
1635 rbio->data_pos.offset -
1636 rbio->pick.crc.offset)) {
1637 /* extent we wanted to read no longer exists: */
1642 ret = __bch2_read_extent(&trans, rbio, bvec_iter,
1645 k, 0, failed, flags);
1646 if (ret == READ_RETRY)
1651 bch2_rbio_done(rbio);
1652 bch2_trans_iter_exit(&trans, &iter);
1653 bch2_trans_exit(&trans);
1654 bch2_bkey_buf_exit(&sk, c);
1657 rbio->bio.bi_status = BLK_STS_IOERR;
1661 static void bch2_rbio_retry(struct work_struct *work)
1663 struct bch_read_bio *rbio =
1664 container_of(work, struct bch_read_bio, work);
1665 struct bch_fs *c = rbio->c;
1666 struct bvec_iter iter = rbio->bvec_iter;
1667 unsigned flags = rbio->flags;
1668 subvol_inum inum = {
1669 .subvol = rbio->subvol,
1670 .inum = rbio->read_pos.inode,
1672 struct bch_io_failures failed = { .nr = 0 };
1674 trace_read_retry(&rbio->bio);
1676 if (rbio->retry == READ_RETRY_AVOID)
1677 bch2_mark_io_failure(&failed, &rbio->pick);
1679 rbio->bio.bi_status = 0;
1681 rbio = bch2_rbio_free(rbio);
1683 flags |= BCH_READ_IN_RETRY;
1684 flags &= ~BCH_READ_MAY_PROMOTE;
1686 if (flags & BCH_READ_NODECODE) {
1687 bch2_read_retry_nodecode(c, rbio, iter, &failed, flags);
1689 flags &= ~BCH_READ_LAST_FRAGMENT;
1690 flags |= BCH_READ_MUST_CLONE;
1692 __bch2_read(c, rbio, iter, inum, &failed, flags);
1696 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
1699 rbio->retry = retry;
1701 if (rbio->flags & BCH_READ_IN_RETRY)
1704 if (retry == READ_ERR) {
1705 rbio = bch2_rbio_free(rbio);
1707 rbio->bio.bi_status = error;
1708 bch2_rbio_done(rbio);
1710 bch2_rbio_punt(rbio, bch2_rbio_retry,
1711 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
1715 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
1716 struct bch_read_bio *rbio)
1718 struct bch_fs *c = rbio->c;
1719 u64 data_offset = rbio->data_pos.offset - rbio->pick.crc.offset;
1720 struct bch_extent_crc_unpacked new_crc;
1721 struct btree_iter iter;
1726 if (crc_is_compressed(rbio->pick.crc))
1729 bch2_trans_iter_init(trans, &iter, rbio->data_btree, rbio->data_pos,
1730 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
1731 k = bch2_btree_iter_peek_slot(&iter);
1732 if ((ret = bkey_err(k)))
1735 if (bversion_cmp(k.k->version, rbio->version) ||
1736 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
1739 /* Extent was merged? */
1740 if (bkey_start_offset(k.k) < data_offset ||
1741 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
1744 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
1745 rbio->pick.crc, NULL, &new_crc,
1746 bkey_start_offset(k.k) - data_offset, k.k->size,
1747 rbio->pick.crc.csum_type)) {
1748 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
1754 * going to be temporarily appending another checksum entry:
1756 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
1757 sizeof(struct bch_extent_crc128));
1758 if ((ret = PTR_ERR_OR_ZERO(new)))
1761 bkey_reassemble(new, k);
1763 if (!bch2_bkey_narrow_crcs(new, new_crc))
1766 ret = bch2_trans_update(trans, &iter, new,
1767 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1769 bch2_trans_iter_exit(trans, &iter);
1773 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
1775 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
1776 __bch2_rbio_narrow_crcs(&trans, rbio));
1779 /* Inner part that may run in process context */
1780 static void __bch2_read_endio(struct work_struct *work)
1782 struct bch_read_bio *rbio =
1783 container_of(work, struct bch_read_bio, work);
1784 struct bch_fs *c = rbio->c;
1785 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1786 struct bio *src = &rbio->bio;
1787 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
1788 struct bvec_iter dst_iter = rbio->bvec_iter;
1789 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
1790 struct nonce nonce = extent_nonce(rbio->version, crc);
1791 unsigned nofs_flags;
1792 struct bch_csum csum;
1794 nofs_flags = memalloc_nofs_save();
1796 /* Reset iterator for checksumming and copying bounced data: */
1798 src->bi_iter.bi_size = crc.compressed_size << 9;
1799 src->bi_iter.bi_idx = 0;
1800 src->bi_iter.bi_bvec_done = 0;
1802 src->bi_iter = rbio->bvec_iter;
1805 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
1806 if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
1811 * We need to rework the narrow_crcs path to deliver the read completion
1812 * first, and then punt to a different workqueue, otherwise we're
1813 * holding up reads while doing btree updates which is bad for memory
1816 if (unlikely(rbio->narrow_crcs))
1817 bch2_rbio_narrow_crcs(rbio);
1819 if (rbio->flags & BCH_READ_NODECODE)
1822 /* Adjust crc to point to subset of data we want: */
1823 crc.offset += rbio->offset_into_extent;
1824 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
1826 if (crc_is_compressed(crc)) {
1827 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1828 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
1829 goto decompression_err;
1831 /* don't need to decrypt the entire bio: */
1832 nonce = nonce_add(nonce, crc.offset << 9);
1833 bio_advance(src, crc.offset << 9);
1835 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
1836 src->bi_iter.bi_size = dst_iter.bi_size;
1838 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1841 struct bvec_iter src_iter = src->bi_iter;
1842 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
1846 if (rbio->promote) {
1848 * Re encrypt data we decrypted, so it's consistent with
1851 bch2_encrypt_bio(c, crc.csum_type, nonce, src);
1852 promote_start(rbio->promote, rbio);
1853 rbio->promote = NULL;
1856 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
1857 rbio = bch2_rbio_free(rbio);
1858 bch2_rbio_done(rbio);
1861 memalloc_nofs_restore(nofs_flags);
1865 * Checksum error: if the bio wasn't bounced, we may have been
1866 * reading into buffers owned by userspace (that userspace can
1867 * scribble over) - retry the read, bouncing it this time:
1869 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
1870 rbio->flags |= BCH_READ_MUST_BOUNCE;
1871 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
1875 bch2_dev_inum_io_error(ca, rbio->read_pos.inode, (u64) rbio->bvec_iter.bi_sector,
1876 "data checksum error: expected %0llx:%0llx got %0llx:%0llx (type %u)",
1877 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
1878 csum.hi, csum.lo, crc.csum_type);
1879 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
1882 bch_err_inum_ratelimited(c, rbio->read_pos.inode,
1883 "decompression error");
1884 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
1888 static void bch2_read_endio(struct bio *bio)
1890 struct bch_read_bio *rbio =
1891 container_of(bio, struct bch_read_bio, bio);
1892 struct bch_fs *c = rbio->c;
1893 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
1894 struct workqueue_struct *wq = NULL;
1895 enum rbio_context context = RBIO_CONTEXT_NULL;
1897 if (rbio->have_ioref) {
1898 bch2_latency_acct(ca, rbio->submit_time, READ);
1899 percpu_ref_put(&ca->io_ref);
1903 rbio->bio.bi_end_io = rbio->end_io;
1905 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
1906 rbio->read_pos.inode,
1907 rbio->read_pos.offset,
1908 "data read error: %s",
1909 bch2_blk_status_to_str(bio->bi_status))) {
1910 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
1914 if (rbio->pick.ptr.cached &&
1915 (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
1916 ptr_stale(ca, &rbio->pick.ptr))) {
1917 atomic_long_inc(&c->read_realloc_races);
1919 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
1920 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
1922 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
1926 if (rbio->narrow_crcs ||
1927 crc_is_compressed(rbio->pick.crc) ||
1928 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
1929 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
1930 else if (rbio->pick.crc.csum_type)
1931 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
1933 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
1936 int __bch2_read_indirect_extent(struct btree_trans *trans,
1937 unsigned *offset_into_extent,
1938 struct bkey_buf *orig_k)
1940 struct btree_iter iter;
1945 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
1946 *offset_into_extent;
1948 bch2_trans_iter_init(trans, &iter, BTREE_ID_reflink,
1949 POS(0, reflink_offset),
1951 k = bch2_btree_iter_peek_slot(&iter);
1956 if (k.k->type != KEY_TYPE_reflink_v &&
1957 k.k->type != KEY_TYPE_indirect_inline_data) {
1958 bch_err_inum_ratelimited(trans->c, orig_k->k->k.p.inode,
1959 "%llu len %u points to nonexistent indirect extent %llu",
1960 orig_k->k->k.p.offset,
1963 bch2_inconsistent_error(trans->c);
1968 *offset_into_extent = iter.pos.offset - bkey_start_offset(k.k);
1969 bch2_bkey_buf_reassemble(orig_k, trans->c, k);
1971 bch2_trans_iter_exit(trans, &iter);
1975 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
1976 struct bvec_iter iter, struct bpos read_pos,
1977 enum btree_id data_btree, struct bkey_s_c k,
1978 unsigned offset_into_extent,
1979 struct bch_io_failures *failed, unsigned flags)
1981 struct bch_fs *c = trans->c;
1982 struct extent_ptr_decoded pick;
1983 struct bch_read_bio *rbio = NULL;
1985 struct promote_op *promote = NULL;
1986 bool bounce = false, read_full = false, narrow_crcs = false;
1987 struct bpos data_pos = bkey_start_pos(k.k);
1990 if (bkey_extent_is_inline_data(k.k)) {
1991 unsigned bytes = min_t(unsigned, iter.bi_size,
1992 bkey_inline_data_bytes(k.k));
1994 swap(iter.bi_size, bytes);
1995 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
1996 swap(iter.bi_size, bytes);
1997 bio_advance_iter(&orig->bio, &iter, bytes);
1998 zero_fill_bio_iter(&orig->bio, iter);
2002 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2004 /* hole or reservation - just zero fill: */
2009 bch_err_inum_ratelimited(c, k.k->p.inode,
2010 "no device to read from");
2015 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2017 if (flags & BCH_READ_NODECODE) {
2019 * can happen if we retry, and the extent we were going to read
2020 * has been merged in the meantime:
2022 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2025 iter.bi_size = pick.crc.compressed_size << 9;
2029 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2030 bio_flagged(&orig->bio, BIO_CHAIN))
2031 flags |= BCH_READ_MUST_CLONE;
2033 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2034 bch2_can_narrow_extent_crcs(k, pick.crc);
2036 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2037 flags |= BCH_READ_MUST_BOUNCE;
2039 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2041 if (crc_is_compressed(pick.crc) ||
2042 (pick.crc.csum_type != BCH_CSUM_none &&
2043 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2044 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2045 (flags & BCH_READ_USER_MAPPED)) ||
2046 (flags & BCH_READ_MUST_BOUNCE)))) {
2051 if (orig->opts.promote_target)
2052 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2053 &rbio, &bounce, &read_full);
2056 EBUG_ON(crc_is_compressed(pick.crc));
2057 EBUG_ON(pick.crc.csum_type &&
2058 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2059 bvec_iter_sectors(iter) != pick.crc.live_size ||
2061 offset_into_extent));
2063 data_pos.offset += offset_into_extent;
2064 pick.ptr.offset += pick.crc.offset +
2066 offset_into_extent = 0;
2067 pick.crc.compressed_size = bvec_iter_sectors(iter);
2068 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2069 pick.crc.offset = 0;
2070 pick.crc.live_size = bvec_iter_sectors(iter);
2071 offset_into_extent = 0;
2076 * promote already allocated bounce rbio:
2077 * promote needs to allocate a bio big enough for uncompressing
2078 * data in the write path, but we're not going to use it all
2081 EBUG_ON(rbio->bio.bi_iter.bi_size <
2082 pick.crc.compressed_size << 9);
2083 rbio->bio.bi_iter.bi_size =
2084 pick.crc.compressed_size << 9;
2085 } else if (bounce) {
2086 unsigned sectors = pick.crc.compressed_size;
2088 rbio = rbio_init(bio_alloc_bioset(GFP_NOIO,
2089 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2090 &c->bio_read_split),
2093 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2094 rbio->bounce = true;
2096 } else if (flags & BCH_READ_MUST_CLONE) {
2098 * Have to clone if there were any splits, due to error
2099 * reporting issues (if a split errored, and retrying didn't
2100 * work, when it reports the error to its parent (us) we don't
2101 * know if the error was from our bio, and we should retry, or
2102 * from the whole bio, in which case we don't want to retry and
2105 rbio = rbio_init(bio_clone_fast(&orig->bio, GFP_NOIO,
2106 &c->bio_read_split),
2108 rbio->bio.bi_iter = iter;
2112 rbio->bio.bi_iter = iter;
2113 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2116 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2119 rbio->submit_time = local_clock();
2121 rbio->parent = orig;
2123 rbio->end_io = orig->bio.bi_end_io;
2124 rbio->bvec_iter = iter;
2125 rbio->offset_into_extent= offset_into_extent;
2126 rbio->flags = flags;
2127 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2128 rbio->narrow_crcs = narrow_crcs;
2132 /* XXX: only initialize this if needed */
2133 rbio->devs_have = bch2_bkey_devs(k);
2135 rbio->subvol = orig->subvol;
2136 rbio->read_pos = read_pos;
2137 rbio->data_btree = data_btree;
2138 rbio->data_pos = data_pos;
2139 rbio->version = k.k->version;
2140 rbio->promote = promote;
2141 INIT_WORK(&rbio->work, NULL);
2143 rbio->bio.bi_opf = orig->bio.bi_opf;
2144 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2145 rbio->bio.bi_end_io = bch2_read_endio;
2148 trace_read_bounce(&rbio->bio);
2150 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2153 * If it's being moved internally, we don't want to flag it as a cache
2156 if (pick.ptr.cached && !(flags & BCH_READ_NODECODE))
2157 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2158 PTR_BUCKET_NR(ca, &pick.ptr), READ);
2160 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2161 bio_inc_remaining(&orig->bio);
2162 trace_read_split(&orig->bio);
2165 if (!rbio->pick.idx) {
2166 if (!rbio->have_ioref) {
2167 bch_err_inum_ratelimited(c, k.k->p.inode,
2168 "no device to read from");
2169 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2173 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2174 bio_sectors(&rbio->bio));
2175 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2177 if (likely(!(flags & BCH_READ_IN_RETRY)))
2178 submit_bio(&rbio->bio);
2180 submit_bio_wait(&rbio->bio);
2182 /* Attempting reconstruct read: */
2183 if (bch2_ec_read_extent(c, rbio)) {
2184 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2188 if (likely(!(flags & BCH_READ_IN_RETRY)))
2189 bio_endio(&rbio->bio);
2192 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2197 rbio->context = RBIO_CONTEXT_UNBOUND;
2198 bch2_read_endio(&rbio->bio);
2201 rbio = bch2_rbio_free(rbio);
2203 if (ret == READ_RETRY_AVOID) {
2204 bch2_mark_io_failure(failed, &pick);
2215 if (flags & BCH_READ_IN_RETRY)
2218 orig->bio.bi_status = BLK_STS_IOERR;
2223 * won't normally happen in the BCH_READ_NODECODE
2224 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2225 * to read no longer exists we have to signal that:
2227 if (flags & BCH_READ_NODECODE)
2230 zero_fill_bio_iter(&orig->bio, iter);
2232 if (flags & BCH_READ_LAST_FRAGMENT)
2233 bch2_rbio_done(orig);
2237 void __bch2_read(struct bch_fs *c, struct bch_read_bio *rbio,
2238 struct bvec_iter bvec_iter, subvol_inum inum,
2239 struct bch_io_failures *failed, unsigned flags)
2241 struct btree_trans trans;
2242 struct btree_iter iter;
2248 BUG_ON(flags & BCH_READ_NODECODE);
2250 bch2_bkey_buf_init(&sk);
2251 bch2_trans_init(&trans, c, 0, 0);
2253 bch2_trans_begin(&trans);
2254 iter = (struct btree_iter) { NULL };
2256 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
2260 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2261 SPOS(inum.inum, bvec_iter.bi_sector, snapshot),
2262 BTREE_ITER_SLOTS|BTREE_ITER_FILTER_SNAPSHOTS);
2264 unsigned bytes, sectors, offset_into_extent;
2265 enum btree_id data_btree = BTREE_ID_extents;
2268 * read_extent -> io_time_reset may cause a transaction restart
2269 * without returning an error, we need to check for that here:
2271 if (!bch2_trans_relock(&trans)) {
2276 bch2_btree_iter_set_pos(&iter,
2277 POS(inum.inum, bvec_iter.bi_sector));
2279 k = bch2_btree_iter_peek_slot(&iter);
2284 offset_into_extent = iter.pos.offset -
2285 bkey_start_offset(k.k);
2286 sectors = k.k->size - offset_into_extent;
2288 bch2_bkey_buf_reassemble(&sk, c, k);
2290 ret = bch2_read_indirect_extent(&trans, &data_btree,
2291 &offset_into_extent, &sk);
2295 k = bkey_i_to_s_c(sk.k);
2298 * With indirect extents, the amount of data to read is the min
2299 * of the original extent and the indirect extent:
2301 sectors = min(sectors, k.k->size - offset_into_extent);
2304 * Unlock the iterator while the btree node's lock is still in
2305 * cache, before doing the IO:
2307 bch2_trans_unlock(&trans);
2309 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
2310 swap(bvec_iter.bi_size, bytes);
2312 if (bvec_iter.bi_size == bytes)
2313 flags |= BCH_READ_LAST_FRAGMENT;
2315 ret = __bch2_read_extent(&trans, rbio, bvec_iter, iter.pos,
2317 offset_into_extent, failed, flags);
2321 if (flags & BCH_READ_LAST_FRAGMENT)
2324 swap(bvec_iter.bi_size, bytes);
2325 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
2327 ret = btree_trans_too_many_iters(&trans);
2332 bch2_trans_iter_exit(&trans, &iter);
2334 if (ret == -EINTR || ret == READ_RETRY || ret == READ_RETRY_AVOID)
2337 bch2_trans_exit(&trans);
2338 bch2_bkey_buf_exit(&sk, c);
2341 bch_err_inum_ratelimited(c, inum.inum,
2342 "read error %i from btree lookup", ret);
2343 rbio->bio.bi_status = BLK_STS_IOERR;
2344 bch2_rbio_done(rbio);
2348 void bch2_fs_io_exit(struct bch_fs *c)
2350 if (c->promote_table.tbl)
2351 rhashtable_destroy(&c->promote_table);
2352 mempool_exit(&c->bio_bounce_pages);
2353 bioset_exit(&c->bio_write);
2354 bioset_exit(&c->bio_read_split);
2355 bioset_exit(&c->bio_read);
2358 int bch2_fs_io_init(struct bch_fs *c)
2360 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2361 BIOSET_NEED_BVECS) ||
2362 bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2363 BIOSET_NEED_BVECS) ||
2364 bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2365 BIOSET_NEED_BVECS) ||
2366 mempool_init_page_pool(&c->bio_bounce_pages,
2368 c->opts.btree_node_size,
2369 c->opts.encoded_extent_max) /
2371 rhashtable_init(&c->promote_table, &bch_promote_params))