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"
19 #include "data_update.h"
21 #include "disk_groups.h"
24 #include "extent_update.h"
30 #include "nocow_locking.h"
31 #include "rebalance.h"
32 #include "subvolume.h"
36 #include <linux/blkdev.h>
37 #include <linux/random.h>
38 #include <linux/sched/mm.h>
40 #include <trace/events/bcachefs.h>
42 const char *bch2_blk_status_to_str(blk_status_t status)
44 if (status == BLK_STS_REMOVED)
45 return "device removed";
46 return blk_status_to_str(status);
49 static bool bch2_target_congested(struct bch_fs *c, u16 target)
51 const struct bch_devs_mask *devs;
52 unsigned d, nr = 0, total = 0;
53 u64 now = local_clock(), last;
61 devs = bch2_target_to_mask(c, target) ?:
62 &c->rw_devs[BCH_DATA_user];
64 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
65 ca = rcu_dereference(c->devs[d]);
69 congested = atomic_read(&ca->congested);
70 last = READ_ONCE(ca->congested_last);
71 if (time_after64(now, last))
72 congested -= (now - last) >> 12;
74 total += max(congested, 0LL);
79 return bch2_rand_range(nr * CONGESTED_MAX) < total;
82 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
86 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
87 /* ideally we'd be taking into account the device's variance here: */
88 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
89 s64 latency_over = io_latency - latency_threshold;
91 if (latency_threshold && latency_over > 0) {
93 * bump up congested by approximately latency_over * 4 /
94 * latency_threshold - we don't need much accuracy here so don't
95 * bother with the divide:
97 if (atomic_read(&ca->congested) < CONGESTED_MAX)
98 atomic_add(latency_over >>
99 max_t(int, ilog2(latency_threshold) - 2, 0),
102 ca->congested_last = now;
103 } else if (atomic_read(&ca->congested) > 0) {
104 atomic_dec(&ca->congested);
108 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
110 atomic64_t *latency = &ca->cur_latency[rw];
111 u64 now = local_clock();
112 u64 io_latency = time_after64(now, submit_time)
115 u64 old, new, v = atomic64_read(latency);
121 * If the io latency was reasonably close to the current
122 * latency, skip doing the update and atomic operation - most of
125 if (abs((int) (old - io_latency)) < (old >> 1) &&
129 new = ewma_add(old, io_latency, 5);
130 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
132 bch2_congested_acct(ca, io_latency, now, rw);
134 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
137 /* Allocate, free from mempool: */
139 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
141 struct bvec_iter_all iter;
144 bio_for_each_segment_all(bv, bio, iter)
145 if (bv->bv_page != ZERO_PAGE(0))
146 mempool_free(bv->bv_page, &c->bio_bounce_pages);
150 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
154 if (likely(!*using_mempool)) {
155 page = alloc_page(GFP_NOIO);
156 if (unlikely(!page)) {
157 mutex_lock(&c->bio_bounce_pages_lock);
158 *using_mempool = true;
164 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
170 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
173 bool using_mempool = false;
176 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
177 unsigned len = min_t(size_t, PAGE_SIZE, size);
179 BUG_ON(!bio_add_page(bio, page, len, 0));
184 mutex_unlock(&c->bio_bounce_pages_lock);
187 /* Extent update path: */
189 int bch2_sum_sector_overwrites(struct btree_trans *trans,
190 struct btree_iter *extent_iter,
192 bool *usage_increasing,
193 s64 *i_sectors_delta,
194 s64 *disk_sectors_delta)
196 struct bch_fs *c = trans->c;
197 struct btree_iter iter;
199 unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
200 bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
203 *usage_increasing = false;
204 *i_sectors_delta = 0;
205 *disk_sectors_delta = 0;
207 bch2_trans_copy_iter(&iter, extent_iter);
209 for_each_btree_key_continue_norestart(iter, BTREE_ITER_SLOTS, old, ret) {
210 s64 sectors = min(new->k.p.offset, old.k->p.offset) -
211 max(bkey_start_offset(&new->k),
212 bkey_start_offset(old.k));
214 *i_sectors_delta += sectors *
215 (bkey_extent_is_allocation(&new->k) -
216 bkey_extent_is_allocation(old.k));
218 *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
219 *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
220 ? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
223 if (!*usage_increasing &&
224 (new->k.p.snapshot != old.k->p.snapshot ||
225 new_replicas > bch2_bkey_replicas(c, old) ||
226 (!new_compressed && bch2_bkey_sectors_compressed(old))))
227 *usage_increasing = true;
229 if (bkey_ge(old.k->p, new->k.p))
233 bch2_trans_iter_exit(trans, &iter);
237 static inline int bch2_extent_update_i_size_sectors(struct btree_trans *trans,
238 struct btree_iter *extent_iter,
242 struct btree_iter iter;
244 struct bkey_i_inode_v3 *inode;
247 bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes,
249 extent_iter->pos.inode,
250 extent_iter->snapshot),
251 BTREE_ITER_INTENT|BTREE_ITER_CACHED);
252 k = bch2_bkey_get_mut(trans, &iter);
253 ret = PTR_ERR_OR_ZERO(k);
257 if (unlikely(k->k.type != KEY_TYPE_inode_v3)) {
258 k = bch2_inode_to_v3(trans, k);
259 ret = PTR_ERR_OR_ZERO(k);
264 inode = bkey_i_to_inode_v3(k);
266 if (!(le64_to_cpu(inode->v.bi_flags) & BCH_INODE_I_SIZE_DIRTY) &&
267 new_i_size > le64_to_cpu(inode->v.bi_size))
268 inode->v.bi_size = cpu_to_le64(new_i_size);
270 le64_add_cpu(&inode->v.bi_sectors, i_sectors_delta);
272 inode->k.p.snapshot = iter.snapshot;
274 ret = bch2_trans_update(trans, &iter, &inode->k_i,
275 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
277 bch2_trans_iter_exit(trans, &iter);
281 int bch2_extent_update(struct btree_trans *trans,
283 struct btree_iter *iter,
285 struct disk_reservation *disk_res,
287 s64 *i_sectors_delta_total,
290 struct bpos next_pos;
291 bool usage_increasing;
292 s64 i_sectors_delta = 0, disk_sectors_delta = 0;
296 * This traverses us the iterator without changing iter->path->pos to
297 * search_key() (which is pos + 1 for extents): we want there to be a
298 * path already traversed at iter->pos because
299 * bch2_trans_extent_update() will use it to attempt extent merging
301 ret = __bch2_btree_iter_traverse(iter);
305 ret = bch2_extent_trim_atomic(trans, iter, k);
311 ret = bch2_sum_sector_overwrites(trans, iter, k,
314 &disk_sectors_delta);
319 disk_sectors_delta > (s64) disk_res->sectors) {
320 ret = bch2_disk_reservation_add(trans->c, disk_res,
321 disk_sectors_delta - disk_res->sectors,
322 !check_enospc || !usage_increasing
323 ? BCH_DISK_RESERVATION_NOFAIL : 0);
330 * We always have to do an inode update - even when i_size/i_sectors
331 * aren't changing - for fsync to work properly; fsync relies on
332 * inode->bi_journal_seq which is updated by the trigger code:
334 ret = bch2_extent_update_i_size_sectors(trans, iter,
335 min(k->k.p.offset << 9, new_i_size),
337 bch2_trans_update(trans, iter, k, 0) ?:
338 bch2_trans_commit(trans, disk_res, NULL,
339 BTREE_INSERT_NOCHECK_RW|
340 BTREE_INSERT_NOFAIL);
344 if (i_sectors_delta_total)
345 *i_sectors_delta_total += i_sectors_delta;
346 bch2_btree_iter_set_pos(iter, next_pos);
350 /* Overwrites whatever was present with zeroes: */
351 int bch2_extent_fallocate(struct btree_trans *trans,
353 struct btree_iter *iter,
355 struct bch_io_opts opts,
356 s64 *i_sectors_delta,
357 struct write_point_specifier write_point)
359 struct bch_fs *c = trans->c;
360 struct disk_reservation disk_res = { 0 };
362 struct open_buckets open_buckets;
364 struct bkey_buf old, new;
365 bool have_reservation = false;
366 bool unwritten = opts.nocow &&
367 c->sb.version >= bcachefs_metadata_version_unwritten_extents;
370 bch2_bkey_buf_init(&old);
371 bch2_bkey_buf_init(&new);
372 closure_init_stack(&cl);
375 k = bch2_btree_iter_peek_slot(iter);
380 sectors = min_t(u64, sectors, k.k->p.offset - iter->pos.offset);
382 if (!have_reservation) {
383 unsigned new_replicas =
384 max(0, (int) opts.data_replicas -
385 (int) bch2_bkey_nr_ptrs_fully_allocated(k));
387 * Get a disk reservation before (in the nocow case) calling
388 * into the allocator:
390 ret = bch2_disk_reservation_get(c, &disk_res, sectors, new_replicas, 0);
394 bch2_bkey_buf_reassemble(&old, c, k);
397 if (have_reservation) {
398 if (!bch2_extents_match(k, bkey_i_to_s_c(old.k)))
401 bch2_key_resize(&new.k->k, sectors);
402 } else if (!unwritten) {
403 struct bkey_i_reservation *reservation;
405 bch2_bkey_buf_realloc(&new, c, sizeof(*reservation) / sizeof(u64));
406 reservation = bkey_reservation_init(new.k);
407 reservation->k.p = iter->pos;
408 bch2_key_resize(&reservation->k, sectors);
409 reservation->v.nr_replicas = opts.data_replicas;
411 struct bkey_i_extent *e;
412 struct bch_devs_list devs_have;
413 struct write_point *wp;
414 struct bch_extent_ptr *ptr;
418 bch2_bkey_buf_realloc(&new, c, BKEY_EXTENT_U64s_MAX);
420 e = bkey_extent_init(new.k);
423 ret = bch2_alloc_sectors_start_trans(trans,
424 opts.foreground_target,
430 RESERVE_none, 0, &cl, &wp);
431 if (bch2_err_matches(ret, BCH_ERR_operation_blocked)) {
432 bch2_trans_unlock(trans);
439 sectors = min(sectors, wp->sectors_free);
441 bch2_key_resize(&e->k, sectors);
443 bch2_open_bucket_get(c, wp, &open_buckets);
444 bch2_alloc_sectors_append_ptrs(c, wp, &e->k_i, sectors, false);
445 bch2_alloc_sectors_done(c, wp);
447 extent_for_each_ptr(extent_i_to_s(e), ptr)
448 ptr->unwritten = true;
451 have_reservation = true;
453 ret = bch2_extent_update(trans, inum, iter, new.k, &disk_res,
454 0, i_sectors_delta, true);
456 if ((atomic_read(&cl.remaining) & CLOSURE_REMAINING_MASK) != 1) {
457 bch2_trans_unlock(trans);
461 if (bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
462 bch2_trans_begin(trans);
466 bch2_open_buckets_put(c, &open_buckets);
467 bch2_disk_reservation_put(c, &disk_res);
468 bch2_bkey_buf_exit(&new, c);
469 bch2_bkey_buf_exit(&old, c);
475 * Returns -BCH_ERR_transacton_restart if we had to drop locks:
477 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
478 subvol_inum inum, u64 end,
479 s64 *i_sectors_delta)
481 struct bch_fs *c = trans->c;
482 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
483 struct bpos end_pos = POS(inum.inum, end);
485 int ret = 0, ret2 = 0;
489 bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
490 struct disk_reservation disk_res =
491 bch2_disk_reservation_init(c, 0);
492 struct bkey_i delete;
497 bch2_trans_begin(trans);
499 ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
503 bch2_btree_iter_set_snapshot(iter, snapshot);
506 * peek_upto() doesn't have ideal semantics for extents:
508 k = bch2_btree_iter_peek_upto(iter, end_pos);
516 BUG_ON(bkey_ge(iter->pos, end_pos));
518 bkey_init(&delete.k);
519 delete.k.p = iter->pos;
521 /* create the biggest key we can */
522 bch2_key_resize(&delete.k, max_sectors);
523 bch2_cut_back(end_pos, &delete);
525 ret = bch2_extent_update(trans, inum, iter, &delete,
526 &disk_res, 0, i_sectors_delta, false);
527 bch2_disk_reservation_put(c, &disk_res);
530 BUG_ON(bkey_gt(iter->pos, end_pos));
535 int bch2_fpunch(struct bch_fs *c, subvol_inum inum, u64 start, u64 end,
536 s64 *i_sectors_delta)
538 struct btree_trans trans;
539 struct btree_iter iter;
542 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
543 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
544 POS(inum.inum, start),
547 ret = bch2_fpunch_at(&trans, &iter, inum, end, i_sectors_delta);
549 bch2_trans_iter_exit(&trans, &iter);
550 bch2_trans_exit(&trans);
552 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
558 static int bch2_write_index_default(struct bch_write_op *op)
560 struct bch_fs *c = op->c;
562 struct keylist *keys = &op->insert_keys;
563 struct bkey_i *k = bch2_keylist_front(keys);
564 struct btree_trans trans;
565 struct btree_iter iter;
567 .subvol = op->subvol,
568 .inum = k->k.p.inode,
572 BUG_ON(!inum.subvol);
574 bch2_bkey_buf_init(&sk);
575 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
578 bch2_trans_begin(&trans);
580 k = bch2_keylist_front(keys);
581 bch2_bkey_buf_copy(&sk, c, k);
583 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol,
584 &sk.k->k.p.snapshot);
585 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
590 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
591 bkey_start_pos(&sk.k->k),
592 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
594 ret = bch2_extent_update(&trans, inum, &iter, sk.k,
596 op->new_i_size, &op->i_sectors_delta,
597 op->flags & BCH_WRITE_CHECK_ENOSPC);
598 bch2_trans_iter_exit(&trans, &iter);
600 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
605 if (bkey_ge(iter.pos, k->k.p))
606 bch2_keylist_pop_front(&op->insert_keys);
608 bch2_cut_front(iter.pos, k);
609 } while (!bch2_keylist_empty(keys));
611 bch2_trans_exit(&trans);
612 bch2_bkey_buf_exit(&sk, c);
619 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
620 enum bch_data_type type,
621 const struct bkey_i *k,
624 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
625 const struct bch_extent_ptr *ptr;
626 struct bch_write_bio *n;
629 BUG_ON(c->opts.nochanges);
631 bkey_for_each_ptr(ptrs, ptr) {
632 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
635 ca = bch_dev_bkey_exists(c, ptr->dev);
637 if (to_entry(ptr + 1) < ptrs.end) {
638 n = to_wbio(bio_alloc_clone(NULL, &wbio->bio,
639 GFP_NOIO, &ca->replica_set));
641 n->bio.bi_end_io = wbio->bio.bi_end_io;
642 n->bio.bi_private = wbio->bio.bi_private;
647 n->bio.bi_opf = wbio->bio.bi_opf;
648 bio_inc_remaining(&wbio->bio);
656 n->have_ioref = nocow || bch2_dev_get_ioref(ca,
657 type == BCH_DATA_btree ? READ : WRITE);
659 n->submit_time = local_clock();
660 n->inode_offset = bkey_start_offset(&k->k);
661 n->bio.bi_iter.bi_sector = ptr->offset;
663 if (likely(n->have_ioref)) {
664 this_cpu_add(ca->io_done->sectors[WRITE][type],
665 bio_sectors(&n->bio));
667 bio_set_dev(&n->bio, ca->disk_sb.bdev);
670 n->bio.bi_status = BLK_STS_REMOVED;
676 static void __bch2_write(struct bch_write_op *);
678 static void bch2_write_done(struct closure *cl)
680 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
681 struct bch_fs *c = op->c;
683 bch2_disk_reservation_put(c, &op->res);
684 percpu_ref_put(&c->writes);
685 bch2_keylist_free(&op->insert_keys, op->inline_keys);
687 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
689 closure_debug_destroy(cl);
694 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
696 struct keylist *keys = &op->insert_keys;
697 struct bch_extent_ptr *ptr;
698 struct bkey_i *src, *dst = keys->keys, *n;
700 for (src = keys->keys; src != keys->top; src = n) {
703 if (bkey_extent_is_direct_data(&src->k)) {
704 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
705 test_bit(ptr->dev, op->failed.d));
707 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
712 memmove_u64s_down(dst, src, src->u64s);
713 dst = bkey_next(dst);
721 * bch_write_index - after a write, update index to point to new data
723 static void __bch2_write_index(struct bch_write_op *op)
725 struct bch_fs *c = op->c;
726 struct keylist *keys = &op->insert_keys;
731 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
732 ret = bch2_write_drop_io_error_ptrs(op);
738 * probably not the ideal place to hook this in, but I don't
739 * particularly want to plumb io_opts all the way through the btree
740 * update stack right now
742 for_each_keylist_key(keys, k)
743 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
745 if (!bch2_keylist_empty(keys)) {
746 u64 sectors_start = keylist_sectors(keys);
748 ret = !(op->flags & BCH_WRITE_MOVE)
749 ? bch2_write_index_default(op)
750 : bch2_data_update_index_update(op);
752 BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
753 BUG_ON(keylist_sectors(keys) && !ret);
755 op->written += sectors_start - keylist_sectors(keys);
757 if (ret && !bch2_err_matches(ret, EROFS)) {
758 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
760 bch_err_inum_offset_ratelimited(c,
761 k->k.p.inode, k->k.p.offset << 9,
762 "write error while doing btree update: %s",
770 /* If some a bucket wasn't written, we can't erasure code it: */
771 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
772 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
774 bch2_open_buckets_put(c, &op->open_buckets);
777 keys->top = keys->keys;
779 op->flags |= BCH_WRITE_DONE;
783 static void bch2_write_index(struct closure *cl)
785 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
786 struct write_point *wp = op->wp;
787 struct workqueue_struct *wq = index_update_wq(op);
790 op->btree_update_ready = true;
791 queue_work(wq, &wp->index_update_work);
794 void bch2_write_point_do_index_updates(struct work_struct *work)
796 struct write_point *wp =
797 container_of(work, struct write_point, index_update_work);
798 struct bch_write_op *op;
801 spin_lock(&wp->writes_lock);
802 op = list_first_entry_or_null(&wp->writes, struct bch_write_op, wp_list);
803 if (op && !op->btree_update_ready)
806 list_del(&op->wp_list);
807 spin_unlock(&wp->writes_lock);
812 __bch2_write_index(op);
814 if (!(op->flags & BCH_WRITE_DONE))
817 bch2_write_done(&op->cl);
821 static void bch2_write_endio(struct bio *bio)
823 struct closure *cl = bio->bi_private;
824 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
825 struct bch_write_bio *wbio = to_wbio(bio);
826 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
827 struct bch_fs *c = wbio->c;
828 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
830 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
832 wbio->inode_offset << 9,
833 "data write error: %s",
834 bch2_blk_status_to_str(bio->bi_status))) {
835 set_bit(wbio->dev, op->failed.d);
836 op->flags |= BCH_WRITE_IO_ERROR;
840 set_bit(wbio->dev, op->devs_need_flush->d);
842 if (wbio->have_ioref) {
843 bch2_latency_acct(ca, wbio->submit_time, WRITE);
844 percpu_ref_put(&ca->io_ref);
848 bch2_bio_free_pages_pool(c, bio);
854 bio_endio(&parent->bio);
861 static void init_append_extent(struct bch_write_op *op,
862 struct write_point *wp,
863 struct bversion version,
864 struct bch_extent_crc_unpacked crc)
866 struct bch_fs *c = op->c;
867 struct bkey_i_extent *e;
869 op->pos.offset += crc.uncompressed_size;
871 e = bkey_extent_init(op->insert_keys.top);
873 e->k.size = crc.uncompressed_size;
874 e->k.version = version;
877 crc.compression_type ||
879 bch2_extent_crc_append(&e->k_i, crc);
881 bch2_alloc_sectors_append_ptrs_inlined(c, wp, &e->k_i, crc.compressed_size,
882 op->flags & BCH_WRITE_CACHED);
884 bch2_keylist_push(&op->insert_keys);
887 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
888 struct write_point *wp,
890 bool *page_alloc_failed,
893 struct bch_write_bio *wbio;
895 unsigned output_available =
896 min(wp->sectors_free << 9, src->bi_iter.bi_size);
897 unsigned pages = DIV_ROUND_UP(output_available +
899 ? ((unsigned long) buf & (PAGE_SIZE - 1))
902 pages = min(pages, BIO_MAX_VECS);
904 bio = bio_alloc_bioset(NULL, pages, 0,
905 GFP_NOIO, &c->bio_write);
906 wbio = wbio_init(bio);
907 wbio->put_bio = true;
908 /* copy WRITE_SYNC flag */
909 wbio->bio.bi_opf = src->bi_opf;
912 bch2_bio_map(bio, buf, output_available);
919 * We can't use mempool for more than c->sb.encoded_extent_max
920 * worth of pages, but we'd like to allocate more if we can:
922 bch2_bio_alloc_pages_pool(c, bio,
923 min_t(unsigned, output_available,
924 c->opts.encoded_extent_max));
926 if (bio->bi_iter.bi_size < output_available)
928 bch2_bio_alloc_pages(bio,
930 bio->bi_iter.bi_size,
936 static int bch2_write_rechecksum(struct bch_fs *c,
937 struct bch_write_op *op,
938 unsigned new_csum_type)
940 struct bio *bio = &op->wbio.bio;
941 struct bch_extent_crc_unpacked new_crc;
944 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
946 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
947 bch2_csum_type_is_encryption(new_csum_type))
948 new_csum_type = op->crc.csum_type;
950 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
952 op->crc.offset, op->crc.live_size,
957 bio_advance(bio, op->crc.offset << 9);
958 bio->bi_iter.bi_size = op->crc.live_size << 9;
963 static int bch2_write_decrypt(struct bch_write_op *op)
965 struct bch_fs *c = op->c;
966 struct nonce nonce = extent_nonce(op->version, op->crc);
967 struct bch_csum csum;
970 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
974 * If we need to decrypt data in the write path, we'll no longer be able
975 * to verify the existing checksum (poly1305 mac, in this case) after
976 * it's decrypted - this is the last point we'll be able to reverify the
979 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
980 if (bch2_crc_cmp(op->crc.csum, csum))
983 ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
984 op->crc.csum_type = 0;
985 op->crc.csum = (struct bch_csum) { 0, 0 };
989 static enum prep_encoded_ret {
992 PREP_ENCODED_CHECKSUM_ERR,
993 PREP_ENCODED_DO_WRITE,
994 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
996 struct bch_fs *c = op->c;
997 struct bio *bio = &op->wbio.bio;
999 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
1000 return PREP_ENCODED_OK;
1002 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
1004 /* Can we just write the entire extent as is? */
1005 if (op->crc.uncompressed_size == op->crc.live_size &&
1006 op->crc.compressed_size <= wp->sectors_free &&
1007 (op->crc.compression_type == op->compression_type ||
1008 op->incompressible)) {
1009 if (!crc_is_compressed(op->crc) &&
1010 op->csum_type != op->crc.csum_type &&
1011 bch2_write_rechecksum(c, op, op->csum_type))
1012 return PREP_ENCODED_CHECKSUM_ERR;
1014 return PREP_ENCODED_DO_WRITE;
1018 * If the data is compressed and we couldn't write the entire extent as
1019 * is, we have to decompress it:
1021 if (crc_is_compressed(op->crc)) {
1022 struct bch_csum csum;
1024 if (bch2_write_decrypt(op))
1025 return PREP_ENCODED_CHECKSUM_ERR;
1027 /* Last point we can still verify checksum: */
1028 csum = bch2_checksum_bio(c, op->crc.csum_type,
1029 extent_nonce(op->version, op->crc),
1031 if (bch2_crc_cmp(op->crc.csum, csum))
1032 return PREP_ENCODED_CHECKSUM_ERR;
1034 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
1035 return PREP_ENCODED_ERR;
1039 * No longer have compressed data after this point - data might be
1044 * If the data is checksummed and we're only writing a subset,
1045 * rechecksum and adjust bio to point to currently live data:
1047 if ((op->crc.live_size != op->crc.uncompressed_size ||
1048 op->crc.csum_type != op->csum_type) &&
1049 bch2_write_rechecksum(c, op, op->csum_type))
1050 return PREP_ENCODED_CHECKSUM_ERR;
1053 * If we want to compress the data, it has to be decrypted:
1055 if ((op->compression_type ||
1056 bch2_csum_type_is_encryption(op->crc.csum_type) !=
1057 bch2_csum_type_is_encryption(op->csum_type)) &&
1058 bch2_write_decrypt(op))
1059 return PREP_ENCODED_CHECKSUM_ERR;
1061 return PREP_ENCODED_OK;
1064 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
1067 struct bch_fs *c = op->c;
1068 struct bio *src = &op->wbio.bio, *dst = src;
1069 struct bvec_iter saved_iter;
1071 unsigned total_output = 0, total_input = 0;
1072 bool bounce = false;
1073 bool page_alloc_failed = false;
1076 BUG_ON(!bio_sectors(src));
1078 ec_buf = bch2_writepoint_ec_buf(c, wp);
1080 switch (bch2_write_prep_encoded_data(op, wp)) {
1081 case PREP_ENCODED_OK:
1083 case PREP_ENCODED_ERR:
1086 case PREP_ENCODED_CHECKSUM_ERR:
1088 case PREP_ENCODED_DO_WRITE:
1089 /* XXX look for bug here */
1091 dst = bch2_write_bio_alloc(c, wp, src,
1094 bio_copy_data(dst, src);
1097 init_append_extent(op, wp, op->version, op->crc);
1102 op->compression_type ||
1104 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
1105 (bch2_csum_type_is_encryption(op->csum_type) &&
1106 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
1107 dst = bch2_write_bio_alloc(c, wp, src,
1113 saved_iter = dst->bi_iter;
1116 struct bch_extent_crc_unpacked crc = { 0 };
1117 struct bversion version = op->version;
1118 size_t dst_len, src_len;
1120 if (page_alloc_failed &&
1121 dst->bi_iter.bi_size < (wp->sectors_free << 9) &&
1122 dst->bi_iter.bi_size < c->opts.encoded_extent_max)
1125 BUG_ON(op->compression_type &&
1126 (op->flags & BCH_WRITE_DATA_ENCODED) &&
1127 bch2_csum_type_is_encryption(op->crc.csum_type));
1128 BUG_ON(op->compression_type && !bounce);
1130 crc.compression_type = op->incompressible
1131 ? BCH_COMPRESSION_TYPE_incompressible
1132 : op->compression_type
1133 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
1134 op->compression_type)
1136 if (!crc_is_compressed(crc)) {
1137 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
1138 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
1141 dst_len = min_t(unsigned, dst_len,
1142 c->opts.encoded_extent_max);
1145 swap(dst->bi_iter.bi_size, dst_len);
1146 bio_copy_data(dst, src);
1147 swap(dst->bi_iter.bi_size, dst_len);
1153 BUG_ON(!src_len || !dst_len);
1155 if (bch2_csum_type_is_encryption(op->csum_type)) {
1156 if (bversion_zero(version)) {
1157 version.lo = atomic64_inc_return(&c->key_version);
1159 crc.nonce = op->nonce;
1160 op->nonce += src_len >> 9;
1164 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1165 !crc_is_compressed(crc) &&
1166 bch2_csum_type_is_encryption(op->crc.csum_type) ==
1167 bch2_csum_type_is_encryption(op->csum_type)) {
1168 u8 compression_type = crc.compression_type;
1169 u16 nonce = crc.nonce;
1171 * Note: when we're using rechecksum(), we need to be
1172 * checksumming @src because it has all the data our
1173 * existing checksum covers - if we bounced (because we
1174 * were trying to compress), @dst will only have the
1175 * part of the data the new checksum will cover.
1177 * But normally we want to be checksumming post bounce,
1178 * because part of the reason for bouncing is so the
1179 * data can't be modified (by userspace) while it's in
1182 if (bch2_rechecksum_bio(c, src, version, op->crc,
1185 bio_sectors(src) - (src_len >> 9),
1189 * rchecksum_bio sets compression_type on crc from op->crc,
1190 * this isn't always correct as sometimes we're changing
1191 * an extent from uncompressed to incompressible.
1193 crc.compression_type = compression_type;
1196 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1197 bch2_rechecksum_bio(c, src, version, op->crc,
1200 bio_sectors(src) - (src_len >> 9),
1204 crc.compressed_size = dst_len >> 9;
1205 crc.uncompressed_size = src_len >> 9;
1206 crc.live_size = src_len >> 9;
1208 swap(dst->bi_iter.bi_size, dst_len);
1209 ret = bch2_encrypt_bio(c, op->csum_type,
1210 extent_nonce(version, crc), dst);
1214 crc.csum = bch2_checksum_bio(c, op->csum_type,
1215 extent_nonce(version, crc), dst);
1216 crc.csum_type = op->csum_type;
1217 swap(dst->bi_iter.bi_size, dst_len);
1220 init_append_extent(op, wp, version, crc);
1223 bio_advance(dst, dst_len);
1224 bio_advance(src, src_len);
1225 total_output += dst_len;
1226 total_input += src_len;
1227 } while (dst->bi_iter.bi_size &&
1228 src->bi_iter.bi_size &&
1230 !bch2_keylist_realloc(&op->insert_keys,
1232 ARRAY_SIZE(op->inline_keys),
1233 BKEY_EXTENT_U64s_MAX));
1235 more = src->bi_iter.bi_size != 0;
1237 dst->bi_iter = saved_iter;
1239 if (dst == src && more) {
1240 BUG_ON(total_output != total_input);
1242 dst = bio_split(src, total_input >> 9,
1243 GFP_NOIO, &c->bio_write);
1244 wbio_init(dst)->put_bio = true;
1245 /* copy WRITE_SYNC flag */
1246 dst->bi_opf = src->bi_opf;
1249 dst->bi_iter.bi_size = total_output;
1254 bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1257 if (to_wbio(dst)->bounce)
1258 bch2_bio_free_pages_pool(c, dst);
1259 if (to_wbio(dst)->put_bio)
1265 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1268 struct bch_fs *c = op->c;
1269 struct bkey_s_c_extent e;
1270 struct extent_ptr_decoded p;
1271 const union bch_extent_entry *entry;
1272 unsigned replicas = 0;
1274 if (k.k->type != KEY_TYPE_extent)
1277 e = bkey_s_c_to_extent(k);
1278 extent_for_each_ptr_decode(e, p, entry) {
1279 if (p.crc.csum_type ||
1280 crc_is_compressed(p.crc) ||
1284 replicas += bch2_extent_ptr_durability(c, &p);
1287 return replicas >= op->opts.data_replicas;
1290 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1292 struct bch_fs *c = op->c;
1293 const struct bch_extent_ptr *ptr;
1296 for_each_keylist_key(&op->insert_keys, k) {
1297 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1299 bkey_for_each_ptr(ptrs, ptr)
1300 bch2_bucket_nocow_unlock(&c->nocow_locks,
1301 PTR_BUCKET_POS(c, ptr),
1302 BUCKET_NOCOW_LOCK_UPDATE);
1306 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1307 struct btree_iter *iter,
1308 struct bkey_i *orig,
1313 struct bkey_ptrs ptrs;
1314 struct bch_extent_ptr *ptr;
1317 if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1322 new = bch2_bkey_make_mut(trans, k);
1323 ret = PTR_ERR_OR_ZERO(new);
1327 bch2_cut_front(bkey_start_pos(&orig->k), new);
1328 bch2_cut_back(orig->k.p, new);
1330 ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1331 bkey_for_each_ptr(ptrs, ptr)
1335 * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1336 * that was done when we kicked off the write, and here it's important
1337 * that we update the extent that we wrote to - even if a snapshot has
1338 * since been created. The write is still outstanding, so we're ok
1339 * w.r.t. snapshot atomicity:
1341 return bch2_extent_update_i_size_sectors(trans, iter,
1342 min(new->k.p.offset << 9, new_i_size), 0) ?:
1343 bch2_trans_update(trans, iter, new,
1344 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1347 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1349 struct bch_fs *c = op->c;
1350 struct btree_trans trans;
1351 struct btree_iter iter;
1352 struct bkey_i *orig;
1356 bch2_trans_init(&trans, c, 0, 0);
1358 for_each_keylist_key(&op->insert_keys, orig) {
1359 ret = for_each_btree_key_upto_commit(&trans, iter, BTREE_ID_extents,
1360 bkey_start_pos(&orig->k), orig->k.p,
1361 BTREE_ITER_INTENT, k,
1362 NULL, NULL, BTREE_INSERT_NOFAIL, ({
1363 BUG_ON(bkey_ge(bkey_start_pos(k.k), orig->k.p));
1365 bch2_nocow_write_convert_one_unwritten(&trans, &iter, orig, k, op->new_i_size);
1368 if (ret && !bch2_err_matches(ret, EROFS)) {
1369 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
1371 bch_err_inum_offset_ratelimited(c,
1372 k->k.p.inode, k->k.p.offset << 9,
1373 "write error while doing btree update: %s",
1383 bch2_trans_exit(&trans);
1386 static void __bch2_nocow_write_done(struct bch_write_op *op)
1388 bch2_nocow_write_unlock(op);
1390 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1392 } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1393 bch2_nocow_write_convert_unwritten(op);
1396 static void bch2_nocow_write_done(struct closure *cl)
1398 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1400 __bch2_nocow_write_done(op);
1401 bch2_write_done(cl);
1404 static void bch2_nocow_write(struct bch_write_op *op)
1406 struct bch_fs *c = op->c;
1407 struct btree_trans trans;
1408 struct btree_iter iter;
1410 struct bkey_ptrs_c ptrs;
1411 const struct bch_extent_ptr *ptr, *ptr2;
1415 struct nocow_lock_bucket *l;
1416 } buckets[BCH_REPLICAS_MAX];
1417 unsigned nr_buckets = 0;
1421 if (op->flags & BCH_WRITE_MOVE)
1424 bch2_trans_init(&trans, c, 0, 0);
1426 bch2_trans_begin(&trans);
1428 ret = bch2_subvolume_get_snapshot(&trans, op->subvol, &snapshot);
1432 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1433 SPOS(op->pos.inode, op->pos.offset, snapshot),
1436 struct bio *bio = &op->wbio.bio;
1440 k = bch2_btree_iter_peek_slot(&iter);
1445 /* fall back to normal cow write path? */
1446 if (unlikely(k.k->p.snapshot != snapshot ||
1447 !bch2_extent_is_writeable(op, k)))
1450 if (bch2_keylist_realloc(&op->insert_keys,
1452 ARRAY_SIZE(op->inline_keys),
1456 /* Get iorefs before dropping btree locks: */
1457 ptrs = bch2_bkey_ptrs_c(k);
1458 bkey_for_each_ptr(ptrs, ptr) {
1459 buckets[nr_buckets].b = PTR_BUCKET_POS(c, ptr);
1460 buckets[nr_buckets].gen = ptr->gen;
1461 buckets[nr_buckets].l =
1462 bucket_nocow_lock(&c->nocow_locks,
1463 bucket_to_u64(buckets[nr_buckets].b));
1465 prefetch(buckets[nr_buckets].l);
1468 if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1472 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1475 /* Unlock before taking nocow locks, doing IO: */
1476 bkey_reassemble(op->insert_keys.top, k);
1477 bch2_trans_unlock(&trans);
1479 bch2_cut_front(op->pos, op->insert_keys.top);
1480 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1481 bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1483 for (i = 0; i < nr_buckets; i++) {
1484 struct bch_dev *ca = bch_dev_bkey_exists(c, buckets[i].b.inode);
1485 struct nocow_lock_bucket *l = buckets[i].l;
1488 __bch2_bucket_nocow_lock(&c->nocow_locks, l,
1489 bucket_to_u64(buckets[i].b),
1490 BUCKET_NOCOW_LOCK_UPDATE);
1493 stale = gen_after(*bucket_gen(ca, buckets[i].b.offset), buckets[i].gen);
1496 if (unlikely(stale))
1497 goto err_bucket_stale;
1500 bio = &op->wbio.bio;
1501 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1502 bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1503 GFP_KERNEL, &c->bio_write);
1504 wbio_init(bio)->put_bio = true;
1505 bio->bi_opf = op->wbio.bio.bi_opf;
1507 op->flags |= BCH_WRITE_DONE;
1510 op->pos.offset += bio_sectors(bio);
1511 op->written += bio_sectors(bio);
1513 bio->bi_end_io = bch2_write_endio;
1514 bio->bi_private = &op->cl;
1515 bio->bi_opf |= REQ_OP_WRITE;
1516 closure_get(&op->cl);
1517 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1518 op->insert_keys.top, true);
1520 bch2_keylist_push(&op->insert_keys);
1521 if (op->flags & BCH_WRITE_DONE)
1523 bch2_btree_iter_advance(&iter);
1526 bch2_trans_iter_exit(&trans, &iter);
1528 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1532 bch_err_inum_offset_ratelimited(c,
1534 op->pos.offset << 9,
1535 "%s: btree lookup error %s",
1536 __func__, bch2_err_str(ret));
1538 op->flags |= BCH_WRITE_DONE;
1541 bch2_trans_exit(&trans);
1543 /* fallback to cow write path? */
1544 if (!(op->flags & BCH_WRITE_DONE)) {
1545 closure_sync(&op->cl);
1546 __bch2_nocow_write_done(op);
1547 op->insert_keys.top = op->insert_keys.keys;
1548 } else if (op->flags & BCH_WRITE_SYNC) {
1549 closure_sync(&op->cl);
1550 bch2_nocow_write_done(&op->cl);
1554 * needs to run out of process context because ei_quota_lock is
1557 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1561 bkey_for_each_ptr(ptrs, ptr2) {
1565 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1568 /* Fall back to COW path: */
1572 bch2_bucket_nocow_unlock(&c->nocow_locks,
1574 BUCKET_NOCOW_LOCK_UPDATE);
1576 bkey_for_each_ptr(ptrs, ptr2)
1577 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1579 /* We can retry this: */
1580 ret = BCH_ERR_transaction_restart;
1584 static void __bch2_write(struct bch_write_op *op)
1586 struct bch_fs *c = op->c;
1587 struct write_point *wp = NULL;
1588 struct bio *bio = NULL;
1589 unsigned nofs_flags;
1592 nofs_flags = memalloc_nofs_save();
1594 if (unlikely(op->opts.nocow)) {
1595 bch2_nocow_write(op);
1596 if (op->flags & BCH_WRITE_DONE)
1597 goto out_nofs_restore;
1600 memset(&op->failed, 0, sizeof(op->failed));
1601 op->btree_update_ready = false;
1604 struct bkey_i *key_to_write;
1605 unsigned key_to_write_offset = op->insert_keys.top_p -
1606 op->insert_keys.keys_p;
1608 /* +1 for possible cache device: */
1609 if (op->open_buckets.nr + op->nr_replicas + 1 >
1610 ARRAY_SIZE(op->open_buckets.v))
1613 if (bch2_keylist_realloc(&op->insert_keys,
1615 ARRAY_SIZE(op->inline_keys),
1616 BKEY_EXTENT_U64s_MAX))
1620 * The copygc thread is now global, which means it's no longer
1621 * freeing up space on specific disks, which means that
1622 * allocations for specific disks may hang arbitrarily long:
1624 ret = bch2_trans_do(c, NULL, NULL, 0,
1625 bch2_alloc_sectors_start_trans(&trans,
1627 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1631 op->nr_replicas_required,
1634 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1635 BCH_WRITE_ONLY_SPECIFIED_DEVS))
1636 ? NULL : &op->cl, &wp));
1637 if (unlikely(ret)) {
1638 if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1644 ret = bch2_write_extent(op, wp, &bio);
1647 bch2_open_bucket_get(c, wp, &op->open_buckets);
1648 bch2_alloc_sectors_done_inlined(c, wp);
1651 if (!(op->flags & BCH_WRITE_SYNC)) {
1652 spin_lock(&wp->writes_lock);
1654 list_add_tail(&op->wp_list, &wp->writes);
1655 spin_unlock(&wp->writes_lock);
1658 op->flags |= BCH_WRITE_DONE;
1666 bio->bi_end_io = bch2_write_endio;
1667 bio->bi_private = &op->cl;
1668 bio->bi_opf |= REQ_OP_WRITE;
1670 closure_get(bio->bi_private);
1672 key_to_write = (void *) (op->insert_keys.keys_p +
1673 key_to_write_offset);
1675 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1676 key_to_write, false);
1682 * If we're running asynchronously, wne may still want to block
1683 * synchronously here if we weren't able to submit all of the IO at
1684 * once, as that signals backpressure to the caller.
1686 if ((op->flags & BCH_WRITE_SYNC) || !(op->flags & BCH_WRITE_DONE)) {
1687 closure_sync(&op->cl);
1688 __bch2_write_index(op);
1690 if (!(op->flags & BCH_WRITE_DONE))
1692 bch2_write_done(&op->cl);
1694 continue_at(&op->cl, bch2_write_index, NULL);
1697 memalloc_nofs_restore(nofs_flags);
1700 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1702 struct bio *bio = &op->wbio.bio;
1703 struct bvec_iter iter;
1704 struct bkey_i_inline_data *id;
1708 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1710 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1711 ARRAY_SIZE(op->inline_keys),
1712 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1718 sectors = bio_sectors(bio);
1719 op->pos.offset += sectors;
1721 id = bkey_inline_data_init(op->insert_keys.top);
1723 id->k.version = op->version;
1724 id->k.size = sectors;
1726 iter = bio->bi_iter;
1727 iter.bi_size = data_len;
1728 memcpy_from_bio(id->v.data, bio, iter);
1730 while (data_len & 7)
1731 id->v.data[data_len++] = '\0';
1732 set_bkey_val_bytes(&id->k, data_len);
1733 bch2_keylist_push(&op->insert_keys);
1735 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1736 op->flags |= BCH_WRITE_DONE;
1738 __bch2_write_index(op);
1740 bch2_write_done(&op->cl);
1744 * bch_write - handle a write to a cache device or flash only volume
1746 * This is the starting point for any data to end up in a cache device; it could
1747 * be from a normal write, or a writeback write, or a write to a flash only
1748 * volume - it's also used by the moving garbage collector to compact data in
1749 * mostly empty buckets.
1751 * It first writes the data to the cache, creating a list of keys to be inserted
1752 * (if the data won't fit in a single open bucket, there will be multiple keys);
1753 * after the data is written it calls bch_journal, and after the keys have been
1754 * added to the next journal write they're inserted into the btree.
1756 * If op->discard is true, instead of inserting the data it invalidates the
1757 * region of the cache represented by op->bio and op->inode.
1759 void bch2_write(struct closure *cl)
1761 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1762 struct bio *bio = &op->wbio.bio;
1763 struct bch_fs *c = op->c;
1766 EBUG_ON(op->cl.parent);
1767 BUG_ON(!op->nr_replicas);
1768 BUG_ON(!op->write_point.v);
1769 BUG_ON(bkey_eq(op->pos, POS_MAX));
1771 op->start_time = local_clock();
1772 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1773 wbio_init(bio)->put_bio = false;
1775 if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1776 bch_err_inum_offset_ratelimited(c,
1778 op->pos.offset << 9,
1779 "misaligned write");
1784 if (c->opts.nochanges ||
1785 !percpu_ref_tryget_live(&c->writes)) {
1786 op->error = -BCH_ERR_erofs_no_writes;
1790 this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1791 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1793 data_len = min_t(u64, bio->bi_iter.bi_size,
1794 op->new_i_size - (op->pos.offset << 9));
1796 if (c->opts.inline_data &&
1797 data_len <= min(block_bytes(c) / 2, 1024U)) {
1798 bch2_write_data_inline(op, data_len);
1805 bch2_disk_reservation_put(c, &op->res);
1807 closure_debug_destroy(&op->cl);
1812 /* Cache promotion on read */
1815 struct rcu_head rcu;
1818 struct rhash_head hash;
1821 struct data_update write;
1822 struct bio_vec bi_inline_vecs[0]; /* must be last */
1825 static const struct rhashtable_params bch_promote_params = {
1826 .head_offset = offsetof(struct promote_op, hash),
1827 .key_offset = offsetof(struct promote_op, pos),
1828 .key_len = sizeof(struct bpos),
1831 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1833 struct bch_io_opts opts,
1836 if (!(flags & BCH_READ_MAY_PROMOTE))
1839 if (!opts.promote_target)
1842 if (bch2_bkey_has_target(c, k, opts.promote_target))
1845 if (bkey_extent_is_unwritten(k))
1848 if (bch2_target_congested(c, opts.promote_target)) {
1849 /* XXX trace this */
1853 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1854 bch_promote_params))
1860 static void promote_free(struct bch_fs *c, struct promote_op *op)
1864 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1865 bch_promote_params);
1867 percpu_ref_put(&c->writes);
1871 static void promote_done(struct bch_write_op *wop)
1873 struct promote_op *op =
1874 container_of(wop, struct promote_op, write.op);
1875 struct bch_fs *c = op->write.op.c;
1877 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1880 bch2_data_update_exit(&op->write);
1881 promote_free(c, op);
1884 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1886 struct bio *bio = &op->write.op.wbio.bio;
1888 trace_and_count(op->write.op.c, read_promote, &rbio->bio);
1890 /* we now own pages: */
1891 BUG_ON(!rbio->bounce);
1892 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1894 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1895 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1896 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1898 bch2_data_update_read_done(&op->write, rbio->pick.crc);
1901 static struct promote_op *__promote_alloc(struct bch_fs *c,
1902 enum btree_id btree_id,
1905 struct extent_ptr_decoded *pick,
1906 struct bch_io_opts opts,
1908 struct bch_read_bio **rbio)
1910 struct promote_op *op = NULL;
1912 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1915 if (!percpu_ref_tryget_live(&c->writes))
1918 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1922 op->start_time = local_clock();
1926 * We don't use the mempool here because extents that aren't
1927 * checksummed or compressed can be too big for the mempool:
1929 *rbio = kzalloc(sizeof(struct bch_read_bio) +
1930 sizeof(struct bio_vec) * pages,
1935 rbio_init(&(*rbio)->bio, opts);
1936 bio_init(&(*rbio)->bio, NULL, (*rbio)->bio.bi_inline_vecs, pages, 0);
1938 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1942 (*rbio)->bounce = true;
1943 (*rbio)->split = true;
1944 (*rbio)->kmalloc = true;
1946 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1947 bch_promote_params))
1950 bio = &op->write.op.wbio.bio;
1951 bio_init(bio, NULL, bio->bi_inline_vecs, pages, 0);
1953 ret = bch2_data_update_init(c, &op->write,
1954 writepoint_hashed((unsigned long) current),
1956 (struct data_update_opts) {
1957 .target = opts.promote_target,
1958 .extra_replicas = 1,
1959 .write_flags = BCH_WRITE_ALLOC_NOWAIT|BCH_WRITE_CACHED,
1963 op->write.op.end_io = promote_done;
1968 bio_free_pages(&(*rbio)->bio);
1972 percpu_ref_put(&c->writes);
1977 static struct promote_op *promote_alloc(struct bch_fs *c,
1978 struct bvec_iter iter,
1980 struct extent_ptr_decoded *pick,
1981 struct bch_io_opts opts,
1983 struct bch_read_bio **rbio,
1987 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1988 /* data might have to be decompressed in the write path: */
1989 unsigned sectors = promote_full
1990 ? max(pick->crc.compressed_size, pick->crc.live_size)
1991 : bvec_iter_sectors(iter);
1992 struct bpos pos = promote_full
1993 ? bkey_start_pos(k.k)
1994 : POS(k.k->p.inode, iter.bi_sector);
1995 struct promote_op *promote;
1997 if (!should_promote(c, k, pos, opts, flags))
2000 promote = __promote_alloc(c,
2001 k.k->type == KEY_TYPE_reflink_v
2004 k, pos, pick, opts, sectors, rbio);
2009 *read_full = promote_full;
2015 #define READ_RETRY_AVOID 1
2016 #define READ_RETRY 2
2021 RBIO_CONTEXT_HIGHPRI,
2022 RBIO_CONTEXT_UNBOUND,
2025 static inline struct bch_read_bio *
2026 bch2_rbio_parent(struct bch_read_bio *rbio)
2028 return rbio->split ? rbio->parent : rbio;
2032 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
2033 enum rbio_context context,
2034 struct workqueue_struct *wq)
2036 if (context <= rbio->context) {
2039 rbio->work.func = fn;
2040 rbio->context = context;
2041 queue_work(wq, &rbio->work);
2045 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
2047 BUG_ON(rbio->bounce && !rbio->split);
2050 promote_free(rbio->c, rbio->promote);
2051 rbio->promote = NULL;
2054 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
2057 struct bch_read_bio *parent = rbio->parent;
2062 bio_put(&rbio->bio);
2071 * Only called on a top level bch_read_bio to complete an entire read request,
2074 static void bch2_rbio_done(struct bch_read_bio *rbio)
2076 if (rbio->start_time)
2077 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
2079 bio_endio(&rbio->bio);
2082 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
2083 struct bvec_iter bvec_iter,
2084 struct bch_io_failures *failed,
2087 struct btree_trans trans;
2088 struct btree_iter iter;
2093 flags &= ~BCH_READ_LAST_FRAGMENT;
2094 flags |= BCH_READ_MUST_CLONE;
2096 bch2_bkey_buf_init(&sk);
2097 bch2_trans_init(&trans, c, 0, 0);
2099 bch2_trans_iter_init(&trans, &iter, rbio->data_btree,
2100 rbio->read_pos, BTREE_ITER_SLOTS);
2102 rbio->bio.bi_status = 0;
2104 k = bch2_btree_iter_peek_slot(&iter);
2108 bch2_bkey_buf_reassemble(&sk, c, k);
2109 k = bkey_i_to_s_c(sk.k);
2110 bch2_trans_unlock(&trans);
2112 if (!bch2_bkey_matches_ptr(c, k,
2114 rbio->data_pos.offset -
2115 rbio->pick.crc.offset)) {
2116 /* extent we wanted to read no longer exists: */
2121 ret = __bch2_read_extent(&trans, rbio, bvec_iter,
2124 k, 0, failed, flags);
2125 if (ret == READ_RETRY)
2130 bch2_rbio_done(rbio);
2131 bch2_trans_iter_exit(&trans, &iter);
2132 bch2_trans_exit(&trans);
2133 bch2_bkey_buf_exit(&sk, c);
2136 rbio->bio.bi_status = BLK_STS_IOERR;
2140 static void bch2_rbio_retry(struct work_struct *work)
2142 struct bch_read_bio *rbio =
2143 container_of(work, struct bch_read_bio, work);
2144 struct bch_fs *c = rbio->c;
2145 struct bvec_iter iter = rbio->bvec_iter;
2146 unsigned flags = rbio->flags;
2147 subvol_inum inum = {
2148 .subvol = rbio->subvol,
2149 .inum = rbio->read_pos.inode,
2151 struct bch_io_failures failed = { .nr = 0 };
2153 trace_and_count(c, read_retry, &rbio->bio);
2155 if (rbio->retry == READ_RETRY_AVOID)
2156 bch2_mark_io_failure(&failed, &rbio->pick);
2158 rbio->bio.bi_status = 0;
2160 rbio = bch2_rbio_free(rbio);
2162 flags |= BCH_READ_IN_RETRY;
2163 flags &= ~BCH_READ_MAY_PROMOTE;
2165 if (flags & BCH_READ_NODECODE) {
2166 bch2_read_retry_nodecode(c, rbio, iter, &failed, flags);
2168 flags &= ~BCH_READ_LAST_FRAGMENT;
2169 flags |= BCH_READ_MUST_CLONE;
2171 __bch2_read(c, rbio, iter, inum, &failed, flags);
2175 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
2178 rbio->retry = retry;
2180 if (rbio->flags & BCH_READ_IN_RETRY)
2183 if (retry == READ_ERR) {
2184 rbio = bch2_rbio_free(rbio);
2186 rbio->bio.bi_status = error;
2187 bch2_rbio_done(rbio);
2189 bch2_rbio_punt(rbio, bch2_rbio_retry,
2190 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
2194 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
2195 struct bch_read_bio *rbio)
2197 struct bch_fs *c = rbio->c;
2198 u64 data_offset = rbio->data_pos.offset - rbio->pick.crc.offset;
2199 struct bch_extent_crc_unpacked new_crc;
2200 struct btree_iter iter;
2205 if (crc_is_compressed(rbio->pick.crc))
2208 bch2_trans_iter_init(trans, &iter, rbio->data_btree, rbio->data_pos,
2209 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2210 k = bch2_btree_iter_peek_slot(&iter);
2211 if ((ret = bkey_err(k)))
2214 if (bversion_cmp(k.k->version, rbio->version) ||
2215 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
2218 /* Extent was merged? */
2219 if (bkey_start_offset(k.k) < data_offset ||
2220 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
2223 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
2224 rbio->pick.crc, NULL, &new_crc,
2225 bkey_start_offset(k.k) - data_offset, k.k->size,
2226 rbio->pick.crc.csum_type)) {
2227 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
2233 * going to be temporarily appending another checksum entry:
2235 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
2236 sizeof(struct bch_extent_crc128));
2237 if ((ret = PTR_ERR_OR_ZERO(new)))
2240 bkey_reassemble(new, k);
2242 if (!bch2_bkey_narrow_crcs(new, new_crc))
2245 ret = bch2_trans_update(trans, &iter, new,
2246 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
2248 bch2_trans_iter_exit(trans, &iter);
2252 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
2254 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
2255 __bch2_rbio_narrow_crcs(&trans, rbio));
2258 /* Inner part that may run in process context */
2259 static void __bch2_read_endio(struct work_struct *work)
2261 struct bch_read_bio *rbio =
2262 container_of(work, struct bch_read_bio, work);
2263 struct bch_fs *c = rbio->c;
2264 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2265 struct bio *src = &rbio->bio;
2266 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
2267 struct bvec_iter dst_iter = rbio->bvec_iter;
2268 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
2269 struct nonce nonce = extent_nonce(rbio->version, crc);
2270 unsigned nofs_flags;
2271 struct bch_csum csum;
2274 nofs_flags = memalloc_nofs_save();
2276 /* Reset iterator for checksumming and copying bounced data: */
2278 src->bi_iter.bi_size = crc.compressed_size << 9;
2279 src->bi_iter.bi_idx = 0;
2280 src->bi_iter.bi_bvec_done = 0;
2282 src->bi_iter = rbio->bvec_iter;
2285 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
2286 if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
2291 * We need to rework the narrow_crcs path to deliver the read completion
2292 * first, and then punt to a different workqueue, otherwise we're
2293 * holding up reads while doing btree updates which is bad for memory
2296 if (unlikely(rbio->narrow_crcs))
2297 bch2_rbio_narrow_crcs(rbio);
2299 if (rbio->flags & BCH_READ_NODECODE)
2302 /* Adjust crc to point to subset of data we want: */
2303 crc.offset += rbio->offset_into_extent;
2304 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
2306 if (crc_is_compressed(crc)) {
2307 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2311 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
2312 goto decompression_err;
2314 /* don't need to decrypt the entire bio: */
2315 nonce = nonce_add(nonce, crc.offset << 9);
2316 bio_advance(src, crc.offset << 9);
2318 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
2319 src->bi_iter.bi_size = dst_iter.bi_size;
2321 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2326 struct bvec_iter src_iter = src->bi_iter;
2327 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
2331 if (rbio->promote) {
2333 * Re encrypt data we decrypted, so it's consistent with
2336 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2340 promote_start(rbio->promote, rbio);
2341 rbio->promote = NULL;
2344 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
2345 rbio = bch2_rbio_free(rbio);
2346 bch2_rbio_done(rbio);
2349 memalloc_nofs_restore(nofs_flags);
2353 * Checksum error: if the bio wasn't bounced, we may have been
2354 * reading into buffers owned by userspace (that userspace can
2355 * scribble over) - retry the read, bouncing it this time:
2357 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
2358 rbio->flags |= BCH_READ_MUST_BOUNCE;
2359 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
2363 bch_err_inum_offset_ratelimited(ca,
2364 rbio->read_pos.inode,
2365 rbio->read_pos.offset << 9,
2366 "data checksum error: expected %0llx:%0llx got %0llx:%0llx (type %s)",
2367 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
2368 csum.hi, csum.lo, bch2_csum_types[crc.csum_type]);
2370 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2373 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2374 rbio->read_pos.offset << 9,
2375 "decompression error");
2376 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2379 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2380 rbio->read_pos.offset << 9,
2382 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2386 static void bch2_read_endio(struct bio *bio)
2388 struct bch_read_bio *rbio =
2389 container_of(bio, struct bch_read_bio, bio);
2390 struct bch_fs *c = rbio->c;
2391 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2392 struct workqueue_struct *wq = NULL;
2393 enum rbio_context context = RBIO_CONTEXT_NULL;
2395 if (rbio->have_ioref) {
2396 bch2_latency_acct(ca, rbio->submit_time, READ);
2397 percpu_ref_put(&ca->io_ref);
2401 rbio->bio.bi_end_io = rbio->end_io;
2403 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
2404 rbio->read_pos.inode,
2405 rbio->read_pos.offset,
2406 "data read error: %s",
2407 bch2_blk_status_to_str(bio->bi_status))) {
2408 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
2412 if (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
2413 ptr_stale(ca, &rbio->pick.ptr)) {
2414 trace_and_count(c, read_reuse_race, &rbio->bio);
2416 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
2417 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
2419 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
2423 if (rbio->narrow_crcs ||
2425 crc_is_compressed(rbio->pick.crc) ||
2426 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
2427 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
2428 else if (rbio->pick.crc.csum_type)
2429 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
2431 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
2434 int __bch2_read_indirect_extent(struct btree_trans *trans,
2435 unsigned *offset_into_extent,
2436 struct bkey_buf *orig_k)
2438 struct btree_iter iter;
2443 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
2444 *offset_into_extent;
2446 bch2_trans_iter_init(trans, &iter, BTREE_ID_reflink,
2447 POS(0, reflink_offset),
2449 k = bch2_btree_iter_peek_slot(&iter);
2454 if (k.k->type != KEY_TYPE_reflink_v &&
2455 k.k->type != KEY_TYPE_indirect_inline_data) {
2456 bch_err_inum_offset_ratelimited(trans->c,
2457 orig_k->k->k.p.inode,
2458 orig_k->k->k.p.offset << 9,
2459 "%llu len %u points to nonexistent indirect extent %llu",
2460 orig_k->k->k.p.offset,
2463 bch2_inconsistent_error(trans->c);
2468 *offset_into_extent = iter.pos.offset - bkey_start_offset(k.k);
2469 bch2_bkey_buf_reassemble(orig_k, trans->c, k);
2471 bch2_trans_iter_exit(trans, &iter);
2475 static noinline void read_from_stale_dirty_pointer(struct btree_trans *trans,
2477 struct bch_extent_ptr ptr)
2479 struct bch_fs *c = trans->c;
2480 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr.dev);
2481 struct btree_iter iter;
2482 struct printbuf buf = PRINTBUF;
2485 bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
2486 PTR_BUCKET_POS(c, &ptr),
2489 prt_printf(&buf, "Attempting to read from stale dirty pointer:");
2490 printbuf_indent_add(&buf, 2);
2493 bch2_bkey_val_to_text(&buf, c, k);
2496 prt_printf(&buf, "memory gen: %u", *bucket_gen(ca, iter.pos.offset));
2498 ret = lockrestart_do(trans, bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
2501 bch2_bkey_val_to_text(&buf, c, k);
2504 bch2_fs_inconsistent(c, "%s", buf.buf);
2506 bch2_trans_iter_exit(trans, &iter);
2507 printbuf_exit(&buf);
2510 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2511 struct bvec_iter iter, struct bpos read_pos,
2512 enum btree_id data_btree, struct bkey_s_c k,
2513 unsigned offset_into_extent,
2514 struct bch_io_failures *failed, unsigned flags)
2516 struct bch_fs *c = trans->c;
2517 struct extent_ptr_decoded pick;
2518 struct bch_read_bio *rbio = NULL;
2519 struct bch_dev *ca = NULL;
2520 struct promote_op *promote = NULL;
2521 bool bounce = false, read_full = false, narrow_crcs = false;
2522 struct bpos data_pos = bkey_start_pos(k.k);
2525 if (bkey_extent_is_inline_data(k.k)) {
2526 unsigned bytes = min_t(unsigned, iter.bi_size,
2527 bkey_inline_data_bytes(k.k));
2529 swap(iter.bi_size, bytes);
2530 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2531 swap(iter.bi_size, bytes);
2532 bio_advance_iter(&orig->bio, &iter, bytes);
2533 zero_fill_bio_iter(&orig->bio, iter);
2537 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2539 /* hole or reservation - just zero fill: */
2544 bch_err_inum_offset_ratelimited(c,
2545 read_pos.inode, read_pos.offset << 9,
2546 "no device to read from");
2550 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2553 * Stale dirty pointers are treated as IO errors, but @failed isn't
2554 * allocated unless we're in the retry path - so if we're not in the
2555 * retry path, don't check here, it'll be caught in bch2_read_endio()
2556 * and we'll end up in the retry path:
2558 if ((flags & BCH_READ_IN_RETRY) &&
2560 unlikely(ptr_stale(ca, &pick.ptr))) {
2561 read_from_stale_dirty_pointer(trans, k, pick.ptr);
2562 bch2_mark_io_failure(failed, &pick);
2567 * Unlock the iterator while the btree node's lock is still in
2568 * cache, before doing the IO:
2570 bch2_trans_unlock(trans);
2572 if (flags & BCH_READ_NODECODE) {
2574 * can happen if we retry, and the extent we were going to read
2575 * has been merged in the meantime:
2577 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2580 iter.bi_size = pick.crc.compressed_size << 9;
2584 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2585 bio_flagged(&orig->bio, BIO_CHAIN))
2586 flags |= BCH_READ_MUST_CLONE;
2588 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2589 bch2_can_narrow_extent_crcs(k, pick.crc);
2591 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2592 flags |= BCH_READ_MUST_BOUNCE;
2594 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2596 if (crc_is_compressed(pick.crc) ||
2597 (pick.crc.csum_type != BCH_CSUM_none &&
2598 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2599 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2600 (flags & BCH_READ_USER_MAPPED)) ||
2601 (flags & BCH_READ_MUST_BOUNCE)))) {
2606 if (orig->opts.promote_target)
2607 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2608 &rbio, &bounce, &read_full);
2611 EBUG_ON(crc_is_compressed(pick.crc));
2612 EBUG_ON(pick.crc.csum_type &&
2613 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2614 bvec_iter_sectors(iter) != pick.crc.live_size ||
2616 offset_into_extent));
2618 data_pos.offset += offset_into_extent;
2619 pick.ptr.offset += pick.crc.offset +
2621 offset_into_extent = 0;
2622 pick.crc.compressed_size = bvec_iter_sectors(iter);
2623 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2624 pick.crc.offset = 0;
2625 pick.crc.live_size = bvec_iter_sectors(iter);
2626 offset_into_extent = 0;
2631 * promote already allocated bounce rbio:
2632 * promote needs to allocate a bio big enough for uncompressing
2633 * data in the write path, but we're not going to use it all
2636 EBUG_ON(rbio->bio.bi_iter.bi_size <
2637 pick.crc.compressed_size << 9);
2638 rbio->bio.bi_iter.bi_size =
2639 pick.crc.compressed_size << 9;
2640 } else if (bounce) {
2641 unsigned sectors = pick.crc.compressed_size;
2643 rbio = rbio_init(bio_alloc_bioset(NULL,
2644 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2647 &c->bio_read_split),
2650 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2651 rbio->bounce = true;
2653 } else if (flags & BCH_READ_MUST_CLONE) {
2655 * Have to clone if there were any splits, due to error
2656 * reporting issues (if a split errored, and retrying didn't
2657 * work, when it reports the error to its parent (us) we don't
2658 * know if the error was from our bio, and we should retry, or
2659 * from the whole bio, in which case we don't want to retry and
2662 rbio = rbio_init(bio_alloc_clone(NULL, &orig->bio, GFP_NOIO,
2663 &c->bio_read_split),
2665 rbio->bio.bi_iter = iter;
2669 rbio->bio.bi_iter = iter;
2670 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2673 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2676 rbio->submit_time = local_clock();
2678 rbio->parent = orig;
2680 rbio->end_io = orig->bio.bi_end_io;
2681 rbio->bvec_iter = iter;
2682 rbio->offset_into_extent= offset_into_extent;
2683 rbio->flags = flags;
2684 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2685 rbio->narrow_crcs = narrow_crcs;
2689 /* XXX: only initialize this if needed */
2690 rbio->devs_have = bch2_bkey_devs(k);
2692 rbio->subvol = orig->subvol;
2693 rbio->read_pos = read_pos;
2694 rbio->data_btree = data_btree;
2695 rbio->data_pos = data_pos;
2696 rbio->version = k.k->version;
2697 rbio->promote = promote;
2698 INIT_WORK(&rbio->work, NULL);
2700 rbio->bio.bi_opf = orig->bio.bi_opf;
2701 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2702 rbio->bio.bi_end_io = bch2_read_endio;
2705 trace_and_count(c, read_bounce, &rbio->bio);
2707 this_cpu_add(c->counters[BCH_COUNTER_io_read], bio_sectors(&rbio->bio));
2708 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2711 * If it's being moved internally, we don't want to flag it as a cache
2714 if (pick.ptr.cached && !(flags & BCH_READ_NODECODE))
2715 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2716 PTR_BUCKET_NR(ca, &pick.ptr), READ);
2718 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2719 bio_inc_remaining(&orig->bio);
2720 trace_and_count(c, read_split, &orig->bio);
2723 if (!rbio->pick.idx) {
2724 if (!rbio->have_ioref) {
2725 bch_err_inum_offset_ratelimited(c,
2727 read_pos.offset << 9,
2728 "no device to read from");
2729 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2733 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2734 bio_sectors(&rbio->bio));
2735 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2737 if (likely(!(flags & BCH_READ_IN_RETRY)))
2738 submit_bio(&rbio->bio);
2740 submit_bio_wait(&rbio->bio);
2742 /* Attempting reconstruct read: */
2743 if (bch2_ec_read_extent(c, rbio)) {
2744 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2748 if (likely(!(flags & BCH_READ_IN_RETRY)))
2749 bio_endio(&rbio->bio);
2752 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2757 rbio->context = RBIO_CONTEXT_UNBOUND;
2758 bch2_read_endio(&rbio->bio);
2761 rbio = bch2_rbio_free(rbio);
2763 if (ret == READ_RETRY_AVOID) {
2764 bch2_mark_io_failure(failed, &pick);
2775 if (flags & BCH_READ_IN_RETRY)
2778 orig->bio.bi_status = BLK_STS_IOERR;
2783 * won't normally happen in the BCH_READ_NODECODE
2784 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2785 * to read no longer exists we have to signal that:
2787 if (flags & BCH_READ_NODECODE)
2790 zero_fill_bio_iter(&orig->bio, iter);
2792 if (flags & BCH_READ_LAST_FRAGMENT)
2793 bch2_rbio_done(orig);
2797 void __bch2_read(struct bch_fs *c, struct bch_read_bio *rbio,
2798 struct bvec_iter bvec_iter, subvol_inum inum,
2799 struct bch_io_failures *failed, unsigned flags)
2801 struct btree_trans trans;
2802 struct btree_iter iter;
2808 BUG_ON(flags & BCH_READ_NODECODE);
2810 bch2_bkey_buf_init(&sk);
2811 bch2_trans_init(&trans, c, 0, 0);
2813 bch2_trans_begin(&trans);
2814 iter = (struct btree_iter) { NULL };
2816 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
2820 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2821 SPOS(inum.inum, bvec_iter.bi_sector, snapshot),
2824 unsigned bytes, sectors, offset_into_extent;
2825 enum btree_id data_btree = BTREE_ID_extents;
2828 * read_extent -> io_time_reset may cause a transaction restart
2829 * without returning an error, we need to check for that here:
2831 ret = bch2_trans_relock(&trans);
2835 bch2_btree_iter_set_pos(&iter,
2836 POS(inum.inum, bvec_iter.bi_sector));
2838 k = bch2_btree_iter_peek_slot(&iter);
2843 offset_into_extent = iter.pos.offset -
2844 bkey_start_offset(k.k);
2845 sectors = k.k->size - offset_into_extent;
2847 bch2_bkey_buf_reassemble(&sk, c, k);
2849 ret = bch2_read_indirect_extent(&trans, &data_btree,
2850 &offset_into_extent, &sk);
2854 k = bkey_i_to_s_c(sk.k);
2857 * With indirect extents, the amount of data to read is the min
2858 * of the original extent and the indirect extent:
2860 sectors = min(sectors, k.k->size - offset_into_extent);
2862 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
2863 swap(bvec_iter.bi_size, bytes);
2865 if (bvec_iter.bi_size == bytes)
2866 flags |= BCH_READ_LAST_FRAGMENT;
2868 ret = __bch2_read_extent(&trans, rbio, bvec_iter, iter.pos,
2870 offset_into_extent, failed, flags);
2874 if (flags & BCH_READ_LAST_FRAGMENT)
2877 swap(bvec_iter.bi_size, bytes);
2878 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
2880 ret = btree_trans_too_many_iters(&trans);
2885 bch2_trans_iter_exit(&trans, &iter);
2887 if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
2888 ret == READ_RETRY ||
2889 ret == READ_RETRY_AVOID)
2892 bch2_trans_exit(&trans);
2893 bch2_bkey_buf_exit(&sk, c);
2896 bch_err_inum_offset_ratelimited(c, inum.inum,
2897 bvec_iter.bi_sector << 9,
2898 "read error %i from btree lookup", ret);
2899 rbio->bio.bi_status = BLK_STS_IOERR;
2900 bch2_rbio_done(rbio);
2904 void bch2_fs_io_exit(struct bch_fs *c)
2906 if (c->promote_table.tbl)
2907 rhashtable_destroy(&c->promote_table);
2908 mempool_exit(&c->bio_bounce_pages);
2909 bioset_exit(&c->bio_write);
2910 bioset_exit(&c->bio_read_split);
2911 bioset_exit(&c->bio_read);
2914 int bch2_fs_io_init(struct bch_fs *c)
2916 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2917 BIOSET_NEED_BVECS) ||
2918 bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2919 BIOSET_NEED_BVECS) ||
2920 bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2921 BIOSET_NEED_BVECS) ||
2922 mempool_init_page_pool(&c->bio_bounce_pages,
2924 c->opts.btree_node_size,
2925 c->opts.encoded_extent_max) /
2927 rhashtable_init(&c->promote_table, &bch_promote_params))