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/prefetch.h>
38 #include <linux/random.h>
39 #include <linux/sched/mm.h>
41 #include <trace/events/bcachefs.h>
43 const char *bch2_blk_status_to_str(blk_status_t status)
45 if (status == BLK_STS_REMOVED)
46 return "device removed";
47 return blk_status_to_str(status);
50 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
52 static bool bch2_target_congested(struct bch_fs *c, u16 target)
54 const struct bch_devs_mask *devs;
55 unsigned d, nr = 0, total = 0;
56 u64 now = local_clock(), last;
64 devs = bch2_target_to_mask(c, target) ?:
65 &c->rw_devs[BCH_DATA_user];
67 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
68 ca = rcu_dereference(c->devs[d]);
72 congested = atomic_read(&ca->congested);
73 last = READ_ONCE(ca->congested_last);
74 if (time_after64(now, last))
75 congested -= (now - last) >> 12;
77 total += max(congested, 0LL);
82 return bch2_rand_range(nr * CONGESTED_MAX) < total;
85 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
89 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
90 /* ideally we'd be taking into account the device's variance here: */
91 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
92 s64 latency_over = io_latency - latency_threshold;
94 if (latency_threshold && latency_over > 0) {
96 * bump up congested by approximately latency_over * 4 /
97 * latency_threshold - we don't need much accuracy here so don't
98 * bother with the divide:
100 if (atomic_read(&ca->congested) < CONGESTED_MAX)
101 atomic_add(latency_over >>
102 max_t(int, ilog2(latency_threshold) - 2, 0),
105 ca->congested_last = now;
106 } else if (atomic_read(&ca->congested) > 0) {
107 atomic_dec(&ca->congested);
111 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
113 atomic64_t *latency = &ca->cur_latency[rw];
114 u64 now = local_clock();
115 u64 io_latency = time_after64(now, submit_time)
118 u64 old, new, v = atomic64_read(latency);
124 * If the io latency was reasonably close to the current
125 * latency, skip doing the update and atomic operation - most of
128 if (abs((int) (old - io_latency)) < (old >> 1) &&
132 new = ewma_add(old, io_latency, 5);
133 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
135 bch2_congested_acct(ca, io_latency, now, rw);
137 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
142 static bool bch2_target_congested(struct bch_fs *c, u16 target)
149 /* Allocate, free from mempool: */
151 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
153 struct bvec_iter_all iter;
156 bio_for_each_segment_all(bv, bio, iter)
157 if (bv->bv_page != ZERO_PAGE(0))
158 mempool_free(bv->bv_page, &c->bio_bounce_pages);
162 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
166 if (likely(!*using_mempool)) {
167 page = alloc_page(GFP_NOIO);
168 if (unlikely(!page)) {
169 mutex_lock(&c->bio_bounce_pages_lock);
170 *using_mempool = true;
176 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
182 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
185 bool using_mempool = false;
188 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
189 unsigned len = min_t(size_t, PAGE_SIZE, size);
191 BUG_ON(!bio_add_page(bio, page, len, 0));
196 mutex_unlock(&c->bio_bounce_pages_lock);
199 /* Extent update path: */
201 int bch2_sum_sector_overwrites(struct btree_trans *trans,
202 struct btree_iter *extent_iter,
204 bool *usage_increasing,
205 s64 *i_sectors_delta,
206 s64 *disk_sectors_delta)
208 struct bch_fs *c = trans->c;
209 struct btree_iter iter;
211 unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
212 bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
215 *usage_increasing = false;
216 *i_sectors_delta = 0;
217 *disk_sectors_delta = 0;
219 bch2_trans_copy_iter(&iter, extent_iter);
221 for_each_btree_key_continue_norestart(iter, BTREE_ITER_SLOTS, old, ret) {
222 s64 sectors = min(new->k.p.offset, old.k->p.offset) -
223 max(bkey_start_offset(&new->k),
224 bkey_start_offset(old.k));
226 *i_sectors_delta += sectors *
227 (bkey_extent_is_allocation(&new->k) -
228 bkey_extent_is_allocation(old.k));
230 *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
231 *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
232 ? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
235 if (!*usage_increasing &&
236 (new->k.p.snapshot != old.k->p.snapshot ||
237 new_replicas > bch2_bkey_replicas(c, old) ||
238 (!new_compressed && bch2_bkey_sectors_compressed(old))))
239 *usage_increasing = true;
241 if (bkey_ge(old.k->p, new->k.p))
245 bch2_trans_iter_exit(trans, &iter);
249 static inline int bch2_extent_update_i_size_sectors(struct btree_trans *trans,
250 struct btree_iter *extent_iter,
254 struct btree_iter iter;
256 struct bkey_i_inode_v3 *inode;
257 unsigned inode_update_flags = BTREE_UPDATE_NOJOURNAL;
260 bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes,
262 extent_iter->pos.inode,
263 extent_iter->snapshot),
264 BTREE_ITER_INTENT|BTREE_ITER_CACHED);
265 k = bch2_bkey_get_mut(trans, &iter);
266 ret = PTR_ERR_OR_ZERO(k);
270 if (unlikely(k->k.type != KEY_TYPE_inode_v3)) {
271 k = bch2_inode_to_v3(trans, k);
272 ret = PTR_ERR_OR_ZERO(k);
277 inode = bkey_i_to_inode_v3(k);
279 if (!(le64_to_cpu(inode->v.bi_flags) & BCH_INODE_I_SIZE_DIRTY) &&
280 new_i_size > le64_to_cpu(inode->v.bi_size)) {
281 inode->v.bi_size = cpu_to_le64(new_i_size);
282 inode_update_flags = 0;
285 if (i_sectors_delta) {
286 le64_add_cpu(&inode->v.bi_sectors, i_sectors_delta);
287 inode_update_flags = 0;
290 if (inode->k.p.snapshot != iter.snapshot) {
291 inode->k.p.snapshot = iter.snapshot;
292 inode_update_flags = 0;
295 ret = bch2_trans_update(trans, &iter, &inode->k_i,
296 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
299 bch2_trans_iter_exit(trans, &iter);
303 int bch2_extent_update(struct btree_trans *trans,
305 struct btree_iter *iter,
307 struct disk_reservation *disk_res,
309 s64 *i_sectors_delta_total,
312 struct bpos next_pos;
313 bool usage_increasing;
314 s64 i_sectors_delta = 0, disk_sectors_delta = 0;
318 * This traverses us the iterator without changing iter->path->pos to
319 * search_key() (which is pos + 1 for extents): we want there to be a
320 * path already traversed at iter->pos because
321 * bch2_trans_extent_update() will use it to attempt extent merging
323 ret = __bch2_btree_iter_traverse(iter);
327 ret = bch2_extent_trim_atomic(trans, iter, k);
333 ret = bch2_sum_sector_overwrites(trans, iter, k,
336 &disk_sectors_delta);
341 disk_sectors_delta > (s64) disk_res->sectors) {
342 ret = bch2_disk_reservation_add(trans->c, disk_res,
343 disk_sectors_delta - disk_res->sectors,
344 !check_enospc || !usage_increasing
345 ? BCH_DISK_RESERVATION_NOFAIL : 0);
352 * We always have to do an inode update - even when i_size/i_sectors
353 * aren't changing - for fsync to work properly; fsync relies on
354 * inode->bi_journal_seq which is updated by the trigger code:
356 ret = bch2_extent_update_i_size_sectors(trans, iter,
357 min(k->k.p.offset << 9, new_i_size),
359 bch2_trans_update(trans, iter, k, 0) ?:
360 bch2_trans_commit(trans, disk_res, NULL,
361 BTREE_INSERT_NOCHECK_RW|
362 BTREE_INSERT_NOFAIL);
366 if (i_sectors_delta_total)
367 *i_sectors_delta_total += i_sectors_delta;
368 bch2_btree_iter_set_pos(iter, next_pos);
372 /* Overwrites whatever was present with zeroes: */
373 int bch2_extent_fallocate(struct btree_trans *trans,
375 struct btree_iter *iter,
377 struct bch_io_opts opts,
378 s64 *i_sectors_delta,
379 struct write_point_specifier write_point)
381 struct bch_fs *c = trans->c;
382 struct disk_reservation disk_res = { 0 };
384 struct open_buckets open_buckets;
386 struct bkey_buf old, new;
387 bool have_reservation = false;
388 bool unwritten = opts.nocow &&
389 c->sb.version >= bcachefs_metadata_version_unwritten_extents;
392 bch2_bkey_buf_init(&old);
393 bch2_bkey_buf_init(&new);
394 closure_init_stack(&cl);
397 k = bch2_btree_iter_peek_slot(iter);
402 sectors = min_t(u64, sectors, k.k->p.offset - iter->pos.offset);
404 if (!have_reservation) {
405 unsigned new_replicas =
406 max(0, (int) opts.data_replicas -
407 (int) bch2_bkey_nr_ptrs_fully_allocated(k));
409 * Get a disk reservation before (in the nocow case) calling
410 * into the allocator:
412 ret = bch2_disk_reservation_get(c, &disk_res, sectors, new_replicas, 0);
416 bch2_bkey_buf_reassemble(&old, c, k);
419 if (have_reservation) {
420 if (!bch2_extents_match(k, bkey_i_to_s_c(old.k)))
423 bch2_key_resize(&new.k->k, sectors);
424 } else if (!unwritten) {
425 struct bkey_i_reservation *reservation;
427 bch2_bkey_buf_realloc(&new, c, sizeof(*reservation) / sizeof(u64));
428 reservation = bkey_reservation_init(new.k);
429 reservation->k.p = iter->pos;
430 bch2_key_resize(&reservation->k, sectors);
431 reservation->v.nr_replicas = opts.data_replicas;
433 struct bkey_i_extent *e;
434 struct bch_devs_list devs_have;
435 struct write_point *wp;
436 struct bch_extent_ptr *ptr;
440 bch2_bkey_buf_realloc(&new, c, BKEY_EXTENT_U64s_MAX);
442 e = bkey_extent_init(new.k);
445 ret = bch2_alloc_sectors_start_trans(trans,
446 opts.foreground_target,
452 RESERVE_none, 0, &cl, &wp);
453 if (bch2_err_matches(ret, BCH_ERR_operation_blocked)) {
454 bch2_trans_unlock(trans);
461 sectors = min(sectors, wp->sectors_free);
463 bch2_key_resize(&e->k, sectors);
465 bch2_open_bucket_get(c, wp, &open_buckets);
466 bch2_alloc_sectors_append_ptrs(c, wp, &e->k_i, sectors, false);
467 bch2_alloc_sectors_done(c, wp);
469 extent_for_each_ptr(extent_i_to_s(e), ptr)
470 ptr->unwritten = true;
473 have_reservation = true;
475 ret = bch2_extent_update(trans, inum, iter, new.k, &disk_res,
476 0, i_sectors_delta, true);
478 if ((atomic_read(&cl.remaining) & CLOSURE_REMAINING_MASK) != 1) {
479 bch2_trans_unlock(trans);
483 if (bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
484 bch2_trans_begin(trans);
488 bch2_open_buckets_put(c, &open_buckets);
489 bch2_disk_reservation_put(c, &disk_res);
490 bch2_bkey_buf_exit(&new, c);
491 bch2_bkey_buf_exit(&old, c);
497 * Returns -BCH_ERR_transacton_restart if we had to drop locks:
499 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
500 subvol_inum inum, u64 end,
501 s64 *i_sectors_delta)
503 struct bch_fs *c = trans->c;
504 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
505 struct bpos end_pos = POS(inum.inum, end);
507 int ret = 0, ret2 = 0;
511 bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
512 struct disk_reservation disk_res =
513 bch2_disk_reservation_init(c, 0);
514 struct bkey_i delete;
519 bch2_trans_begin(trans);
521 ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
525 bch2_btree_iter_set_snapshot(iter, snapshot);
528 * peek_upto() doesn't have ideal semantics for extents:
530 k = bch2_btree_iter_peek_upto(iter, end_pos);
538 bkey_init(&delete.k);
539 delete.k.p = iter->pos;
541 /* create the biggest key we can */
542 bch2_key_resize(&delete.k, max_sectors);
543 bch2_cut_back(end_pos, &delete);
545 ret = bch2_extent_update(trans, inum, iter, &delete,
546 &disk_res, 0, i_sectors_delta, false);
547 bch2_disk_reservation_put(c, &disk_res);
553 int bch2_fpunch(struct bch_fs *c, subvol_inum inum, u64 start, u64 end,
554 s64 *i_sectors_delta)
556 struct btree_trans trans;
557 struct btree_iter iter;
560 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
561 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
562 POS(inum.inum, start),
565 ret = bch2_fpunch_at(&trans, &iter, inum, end, i_sectors_delta);
567 bch2_trans_iter_exit(&trans, &iter);
568 bch2_trans_exit(&trans);
570 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
576 static int bch2_write_index_default(struct bch_write_op *op)
578 struct bch_fs *c = op->c;
580 struct keylist *keys = &op->insert_keys;
581 struct bkey_i *k = bch2_keylist_front(keys);
582 struct btree_trans trans;
583 struct btree_iter iter;
585 .subvol = op->subvol,
586 .inum = k->k.p.inode,
590 BUG_ON(!inum.subvol);
592 bch2_bkey_buf_init(&sk);
593 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
596 bch2_trans_begin(&trans);
598 k = bch2_keylist_front(keys);
599 bch2_bkey_buf_copy(&sk, c, k);
601 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol,
602 &sk.k->k.p.snapshot);
603 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
608 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
609 bkey_start_pos(&sk.k->k),
610 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
612 ret = bch2_extent_update(&trans, inum, &iter, sk.k,
614 op->new_i_size, &op->i_sectors_delta,
615 op->flags & BCH_WRITE_CHECK_ENOSPC);
616 bch2_trans_iter_exit(&trans, &iter);
618 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
623 if (bkey_ge(iter.pos, k->k.p))
624 bch2_keylist_pop_front(&op->insert_keys);
626 bch2_cut_front(iter.pos, k);
627 } while (!bch2_keylist_empty(keys));
629 bch2_trans_exit(&trans);
630 bch2_bkey_buf_exit(&sk, c);
637 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
638 enum bch_data_type type,
639 const struct bkey_i *k,
642 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
643 const struct bch_extent_ptr *ptr;
644 struct bch_write_bio *n;
647 BUG_ON(c->opts.nochanges);
649 bkey_for_each_ptr(ptrs, ptr) {
650 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
653 ca = bch_dev_bkey_exists(c, ptr->dev);
655 if (to_entry(ptr + 1) < ptrs.end) {
656 n = to_wbio(bio_alloc_clone(NULL, &wbio->bio,
657 GFP_NOIO, &ca->replica_set));
659 n->bio.bi_end_io = wbio->bio.bi_end_io;
660 n->bio.bi_private = wbio->bio.bi_private;
665 n->bio.bi_opf = wbio->bio.bi_opf;
666 bio_inc_remaining(&wbio->bio);
674 n->have_ioref = nocow || bch2_dev_get_ioref(ca,
675 type == BCH_DATA_btree ? READ : WRITE);
677 n->submit_time = local_clock();
678 n->inode_offset = bkey_start_offset(&k->k);
679 n->bio.bi_iter.bi_sector = ptr->offset;
681 if (likely(n->have_ioref)) {
682 this_cpu_add(ca->io_done->sectors[WRITE][type],
683 bio_sectors(&n->bio));
685 bio_set_dev(&n->bio, ca->disk_sb.bdev);
687 if (IS_ENABLED(CONFIG_BCACHEFS_NO_IO) && type != BCH_DATA_btree) {
694 n->bio.bi_status = BLK_STS_REMOVED;
700 static void __bch2_write(struct bch_write_op *);
702 static void bch2_write_done(struct closure *cl)
704 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
705 struct bch_fs *c = op->c;
707 bch2_disk_reservation_put(c, &op->res);
708 bch2_write_ref_put(c, BCH_WRITE_REF_write);
709 bch2_keylist_free(&op->insert_keys, op->inline_keys);
711 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
714 closure_debug_destroy(cl);
719 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
721 struct keylist *keys = &op->insert_keys;
722 struct bch_extent_ptr *ptr;
723 struct bkey_i *src, *dst = keys->keys, *n;
725 for (src = keys->keys; src != keys->top; src = n) {
728 if (bkey_extent_is_direct_data(&src->k)) {
729 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
730 test_bit(ptr->dev, op->failed.d));
732 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
737 memmove_u64s_down(dst, src, src->u64s);
738 dst = bkey_next(dst);
746 * bch_write_index - after a write, update index to point to new data
748 static void __bch2_write_index(struct bch_write_op *op)
750 struct bch_fs *c = op->c;
751 struct keylist *keys = &op->insert_keys;
756 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
757 ret = bch2_write_drop_io_error_ptrs(op);
763 * probably not the ideal place to hook this in, but I don't
764 * particularly want to plumb io_opts all the way through the btree
765 * update stack right now
767 for_each_keylist_key(keys, k)
768 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
770 if (!bch2_keylist_empty(keys)) {
771 u64 sectors_start = keylist_sectors(keys);
773 ret = !(op->flags & BCH_WRITE_MOVE)
774 ? bch2_write_index_default(op)
775 : bch2_data_update_index_update(op);
777 BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
778 BUG_ON(keylist_sectors(keys) && !ret);
780 op->written += sectors_start - keylist_sectors(keys);
782 if (ret && !bch2_err_matches(ret, EROFS)) {
783 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
785 bch_err_inum_offset_ratelimited(c,
786 k->k.p.inode, k->k.p.offset << 9,
787 "write error while doing btree update: %s",
795 /* If some a bucket wasn't written, we can't erasure code it: */
796 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
797 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
799 bch2_open_buckets_put(c, &op->open_buckets);
802 keys->top = keys->keys;
804 op->flags |= BCH_WRITE_DONE;
808 static inline void __wp_update_state(struct write_point *wp, enum write_point_state state)
810 if (state != wp->state) {
811 u64 now = ktime_get_ns();
813 if (wp->last_state_change &&
814 time_after64(now, wp->last_state_change))
815 wp->time[wp->state] += now - wp->last_state_change;
817 wp->last_state_change = now;
821 static inline void wp_update_state(struct write_point *wp, bool running)
823 enum write_point_state state;
825 state = running ? WRITE_POINT_running :
826 !list_empty(&wp->writes) ? WRITE_POINT_waiting_io
827 : WRITE_POINT_stopped;
829 __wp_update_state(wp, state);
832 static void bch2_write_index(struct closure *cl)
834 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
835 struct write_point *wp = op->wp;
836 struct workqueue_struct *wq = index_update_wq(op);
841 * We're not using wp->writes_lock here, so this is racey: that's ok,
842 * because this is just for diagnostic purposes, and we're running out
843 * of interrupt context here so if we were to take the log we'd have to
844 * switch to spin_lock_irq()/irqsave(), which is not free:
846 if (wp->state == WRITE_POINT_waiting_io)
847 __wp_update_state(wp, WRITE_POINT_waiting_work);
849 op->btree_update_ready = true;
850 queue_work(wq, &wp->index_update_work);
853 void bch2_write_point_do_index_updates(struct work_struct *work)
855 struct write_point *wp =
856 container_of(work, struct write_point, index_update_work);
857 struct bch_write_op *op;
860 spin_lock(&wp->writes_lock);
861 list_for_each_entry(op, &wp->writes, wp_list)
862 if (op->btree_update_ready) {
863 list_del(&op->wp_list);
868 wp_update_state(wp, op != NULL);
869 spin_unlock(&wp->writes_lock);
874 op->flags |= BCH_WRITE_IN_WORKER;
876 __bch2_write_index(op);
878 if (!(op->flags & BCH_WRITE_DONE))
881 bch2_write_done(&op->cl);
885 static void bch2_write_endio(struct bio *bio)
887 struct closure *cl = bio->bi_private;
888 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
889 struct bch_write_bio *wbio = to_wbio(bio);
890 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
891 struct bch_fs *c = wbio->c;
892 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
894 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
896 wbio->inode_offset << 9,
897 "data write error: %s",
898 bch2_blk_status_to_str(bio->bi_status))) {
899 set_bit(wbio->dev, op->failed.d);
900 op->flags |= BCH_WRITE_IO_ERROR;
904 set_bit(wbio->dev, op->devs_need_flush->d);
906 if (wbio->have_ioref) {
907 bch2_latency_acct(ca, wbio->submit_time, WRITE);
908 percpu_ref_put(&ca->io_ref);
912 bch2_bio_free_pages_pool(c, bio);
918 bio_endio(&parent->bio);
923 static void init_append_extent(struct bch_write_op *op,
924 struct write_point *wp,
925 struct bversion version,
926 struct bch_extent_crc_unpacked crc)
928 struct bkey_i_extent *e;
930 op->pos.offset += crc.uncompressed_size;
932 e = bkey_extent_init(op->insert_keys.top);
934 e->k.size = crc.uncompressed_size;
935 e->k.version = version;
938 crc.compression_type ||
940 bch2_extent_crc_append(&e->k_i, crc);
942 bch2_alloc_sectors_append_ptrs_inlined(op->c, wp, &e->k_i, crc.compressed_size,
943 op->flags & BCH_WRITE_CACHED);
945 bch2_keylist_push(&op->insert_keys);
948 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
949 struct write_point *wp,
951 bool *page_alloc_failed,
954 struct bch_write_bio *wbio;
956 unsigned output_available =
957 min(wp->sectors_free << 9, src->bi_iter.bi_size);
958 unsigned pages = DIV_ROUND_UP(output_available +
960 ? ((unsigned long) buf & (PAGE_SIZE - 1))
963 pages = min(pages, BIO_MAX_VECS);
965 bio = bio_alloc_bioset(NULL, pages, 0,
966 GFP_NOIO, &c->bio_write);
967 wbio = wbio_init(bio);
968 wbio->put_bio = true;
969 /* copy WRITE_SYNC flag */
970 wbio->bio.bi_opf = src->bi_opf;
973 bch2_bio_map(bio, buf, output_available);
980 * We can't use mempool for more than c->sb.encoded_extent_max
981 * worth of pages, but we'd like to allocate more if we can:
983 bch2_bio_alloc_pages_pool(c, bio,
984 min_t(unsigned, output_available,
985 c->opts.encoded_extent_max));
987 if (bio->bi_iter.bi_size < output_available)
989 bch2_bio_alloc_pages(bio,
991 bio->bi_iter.bi_size,
997 static int bch2_write_rechecksum(struct bch_fs *c,
998 struct bch_write_op *op,
999 unsigned new_csum_type)
1001 struct bio *bio = &op->wbio.bio;
1002 struct bch_extent_crc_unpacked new_crc;
1005 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
1007 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
1008 bch2_csum_type_is_encryption(new_csum_type))
1009 new_csum_type = op->crc.csum_type;
1011 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
1013 op->crc.offset, op->crc.live_size,
1018 bio_advance(bio, op->crc.offset << 9);
1019 bio->bi_iter.bi_size = op->crc.live_size << 9;
1024 static int bch2_write_decrypt(struct bch_write_op *op)
1026 struct bch_fs *c = op->c;
1027 struct nonce nonce = extent_nonce(op->version, op->crc);
1028 struct bch_csum csum;
1031 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
1035 * If we need to decrypt data in the write path, we'll no longer be able
1036 * to verify the existing checksum (poly1305 mac, in this case) after
1037 * it's decrypted - this is the last point we'll be able to reverify the
1040 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
1041 if (bch2_crc_cmp(op->crc.csum, csum))
1044 ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
1045 op->crc.csum_type = 0;
1046 op->crc.csum = (struct bch_csum) { 0, 0 };
1050 static enum prep_encoded_ret {
1053 PREP_ENCODED_CHECKSUM_ERR,
1054 PREP_ENCODED_DO_WRITE,
1055 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
1057 struct bch_fs *c = op->c;
1058 struct bio *bio = &op->wbio.bio;
1060 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
1061 return PREP_ENCODED_OK;
1063 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
1065 /* Can we just write the entire extent as is? */
1066 if (op->crc.uncompressed_size == op->crc.live_size &&
1067 op->crc.compressed_size <= wp->sectors_free &&
1068 (op->crc.compression_type == op->compression_type ||
1069 op->incompressible)) {
1070 if (!crc_is_compressed(op->crc) &&
1071 op->csum_type != op->crc.csum_type &&
1072 bch2_write_rechecksum(c, op, op->csum_type))
1073 return PREP_ENCODED_CHECKSUM_ERR;
1075 return PREP_ENCODED_DO_WRITE;
1079 * If the data is compressed and we couldn't write the entire extent as
1080 * is, we have to decompress it:
1082 if (crc_is_compressed(op->crc)) {
1083 struct bch_csum csum;
1085 if (bch2_write_decrypt(op))
1086 return PREP_ENCODED_CHECKSUM_ERR;
1088 /* Last point we can still verify checksum: */
1089 csum = bch2_checksum_bio(c, op->crc.csum_type,
1090 extent_nonce(op->version, op->crc),
1092 if (bch2_crc_cmp(op->crc.csum, csum))
1093 return PREP_ENCODED_CHECKSUM_ERR;
1095 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
1096 return PREP_ENCODED_ERR;
1100 * No longer have compressed data after this point - data might be
1105 * If the data is checksummed and we're only writing a subset,
1106 * rechecksum and adjust bio to point to currently live data:
1108 if ((op->crc.live_size != op->crc.uncompressed_size ||
1109 op->crc.csum_type != op->csum_type) &&
1110 bch2_write_rechecksum(c, op, op->csum_type))
1111 return PREP_ENCODED_CHECKSUM_ERR;
1114 * If we want to compress the data, it has to be decrypted:
1116 if ((op->compression_type ||
1117 bch2_csum_type_is_encryption(op->crc.csum_type) !=
1118 bch2_csum_type_is_encryption(op->csum_type)) &&
1119 bch2_write_decrypt(op))
1120 return PREP_ENCODED_CHECKSUM_ERR;
1122 return PREP_ENCODED_OK;
1125 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
1128 struct bch_fs *c = op->c;
1129 struct bio *src = &op->wbio.bio, *dst = src;
1130 struct bvec_iter saved_iter;
1132 unsigned total_output = 0, total_input = 0;
1133 bool bounce = false;
1134 bool page_alloc_failed = false;
1137 BUG_ON(!bio_sectors(src));
1139 ec_buf = bch2_writepoint_ec_buf(c, wp);
1141 switch (bch2_write_prep_encoded_data(op, wp)) {
1142 case PREP_ENCODED_OK:
1144 case PREP_ENCODED_ERR:
1147 case PREP_ENCODED_CHECKSUM_ERR:
1149 case PREP_ENCODED_DO_WRITE:
1150 /* XXX look for bug here */
1152 dst = bch2_write_bio_alloc(c, wp, src,
1155 bio_copy_data(dst, src);
1158 init_append_extent(op, wp, op->version, op->crc);
1163 op->compression_type ||
1165 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
1166 (bch2_csum_type_is_encryption(op->csum_type) &&
1167 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
1168 dst = bch2_write_bio_alloc(c, wp, src,
1174 saved_iter = dst->bi_iter;
1177 struct bch_extent_crc_unpacked crc = { 0 };
1178 struct bversion version = op->version;
1179 size_t dst_len, src_len;
1181 if (page_alloc_failed &&
1182 dst->bi_iter.bi_size < (wp->sectors_free << 9) &&
1183 dst->bi_iter.bi_size < c->opts.encoded_extent_max)
1186 BUG_ON(op->compression_type &&
1187 (op->flags & BCH_WRITE_DATA_ENCODED) &&
1188 bch2_csum_type_is_encryption(op->crc.csum_type));
1189 BUG_ON(op->compression_type && !bounce);
1191 crc.compression_type = op->incompressible
1192 ? BCH_COMPRESSION_TYPE_incompressible
1193 : op->compression_type
1194 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
1195 op->compression_type)
1197 if (!crc_is_compressed(crc)) {
1198 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
1199 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
1202 dst_len = min_t(unsigned, dst_len,
1203 c->opts.encoded_extent_max);
1206 swap(dst->bi_iter.bi_size, dst_len);
1207 bio_copy_data(dst, src);
1208 swap(dst->bi_iter.bi_size, dst_len);
1214 BUG_ON(!src_len || !dst_len);
1216 if (bch2_csum_type_is_encryption(op->csum_type)) {
1217 if (bversion_zero(version)) {
1218 version.lo = atomic64_inc_return(&c->key_version);
1220 crc.nonce = op->nonce;
1221 op->nonce += src_len >> 9;
1225 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1226 !crc_is_compressed(crc) &&
1227 bch2_csum_type_is_encryption(op->crc.csum_type) ==
1228 bch2_csum_type_is_encryption(op->csum_type)) {
1229 u8 compression_type = crc.compression_type;
1230 u16 nonce = crc.nonce;
1232 * Note: when we're using rechecksum(), we need to be
1233 * checksumming @src because it has all the data our
1234 * existing checksum covers - if we bounced (because we
1235 * were trying to compress), @dst will only have the
1236 * part of the data the new checksum will cover.
1238 * But normally we want to be checksumming post bounce,
1239 * because part of the reason for bouncing is so the
1240 * data can't be modified (by userspace) while it's in
1243 if (bch2_rechecksum_bio(c, src, version, op->crc,
1246 bio_sectors(src) - (src_len >> 9),
1250 * rchecksum_bio sets compression_type on crc from op->crc,
1251 * this isn't always correct as sometimes we're changing
1252 * an extent from uncompressed to incompressible.
1254 crc.compression_type = compression_type;
1257 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1258 bch2_rechecksum_bio(c, src, version, op->crc,
1261 bio_sectors(src) - (src_len >> 9),
1265 crc.compressed_size = dst_len >> 9;
1266 crc.uncompressed_size = src_len >> 9;
1267 crc.live_size = src_len >> 9;
1269 swap(dst->bi_iter.bi_size, dst_len);
1270 ret = bch2_encrypt_bio(c, op->csum_type,
1271 extent_nonce(version, crc), dst);
1275 crc.csum = bch2_checksum_bio(c, op->csum_type,
1276 extent_nonce(version, crc), dst);
1277 crc.csum_type = op->csum_type;
1278 swap(dst->bi_iter.bi_size, dst_len);
1281 init_append_extent(op, wp, version, crc);
1284 bio_advance(dst, dst_len);
1285 bio_advance(src, src_len);
1286 total_output += dst_len;
1287 total_input += src_len;
1288 } while (dst->bi_iter.bi_size &&
1289 src->bi_iter.bi_size &&
1291 !bch2_keylist_realloc(&op->insert_keys,
1293 ARRAY_SIZE(op->inline_keys),
1294 BKEY_EXTENT_U64s_MAX));
1296 more = src->bi_iter.bi_size != 0;
1298 dst->bi_iter = saved_iter;
1300 if (dst == src && more) {
1301 BUG_ON(total_output != total_input);
1303 dst = bio_split(src, total_input >> 9,
1304 GFP_NOIO, &c->bio_write);
1305 wbio_init(dst)->put_bio = true;
1306 /* copy WRITE_SYNC flag */
1307 dst->bi_opf = src->bi_opf;
1310 dst->bi_iter.bi_size = total_output;
1315 bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1318 if (to_wbio(dst)->bounce)
1319 bch2_bio_free_pages_pool(c, dst);
1320 if (to_wbio(dst)->put_bio)
1326 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1329 struct bch_fs *c = op->c;
1330 struct bkey_s_c_extent e;
1331 struct extent_ptr_decoded p;
1332 const union bch_extent_entry *entry;
1333 unsigned replicas = 0;
1335 if (k.k->type != KEY_TYPE_extent)
1338 e = bkey_s_c_to_extent(k);
1339 extent_for_each_ptr_decode(e, p, entry) {
1340 if (p.crc.csum_type ||
1341 crc_is_compressed(p.crc) ||
1345 replicas += bch2_extent_ptr_durability(c, &p);
1348 return replicas >= op->opts.data_replicas;
1351 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1353 struct bch_fs *c = op->c;
1354 const struct bch_extent_ptr *ptr;
1357 for_each_keylist_key(&op->insert_keys, k) {
1358 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1360 bkey_for_each_ptr(ptrs, ptr)
1361 bch2_bucket_nocow_unlock(&c->nocow_locks,
1362 PTR_BUCKET_POS(c, ptr),
1363 BUCKET_NOCOW_LOCK_UPDATE);
1367 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1368 struct btree_iter *iter,
1369 struct bkey_i *orig,
1374 struct bkey_ptrs ptrs;
1375 struct bch_extent_ptr *ptr;
1378 if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1383 new = bch2_bkey_make_mut(trans, k);
1384 ret = PTR_ERR_OR_ZERO(new);
1388 bch2_cut_front(bkey_start_pos(&orig->k), new);
1389 bch2_cut_back(orig->k.p, new);
1391 ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1392 bkey_for_each_ptr(ptrs, ptr)
1396 * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1397 * that was done when we kicked off the write, and here it's important
1398 * that we update the extent that we wrote to - even if a snapshot has
1399 * since been created. The write is still outstanding, so we're ok
1400 * w.r.t. snapshot atomicity:
1402 return bch2_extent_update_i_size_sectors(trans, iter,
1403 min(new->k.p.offset << 9, new_i_size), 0) ?:
1404 bch2_trans_update(trans, iter, new,
1405 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1408 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1410 struct bch_fs *c = op->c;
1411 struct btree_trans trans;
1412 struct btree_iter iter;
1413 struct bkey_i *orig;
1417 bch2_trans_init(&trans, c, 0, 0);
1419 for_each_keylist_key(&op->insert_keys, orig) {
1420 ret = for_each_btree_key_upto_commit(&trans, iter, BTREE_ID_extents,
1421 bkey_start_pos(&orig->k), orig->k.p,
1422 BTREE_ITER_INTENT, k,
1423 NULL, NULL, BTREE_INSERT_NOFAIL, ({
1424 bch2_nocow_write_convert_one_unwritten(&trans, &iter, orig, k, op->new_i_size);
1427 if (ret && !bch2_err_matches(ret, EROFS)) {
1428 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
1430 bch_err_inum_offset_ratelimited(c,
1431 k->k.p.inode, k->k.p.offset << 9,
1432 "write error while doing btree update: %s",
1442 bch2_trans_exit(&trans);
1445 static void __bch2_nocow_write_done(struct bch_write_op *op)
1447 bch2_nocow_write_unlock(op);
1449 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1451 } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1452 bch2_nocow_write_convert_unwritten(op);
1455 static void bch2_nocow_write_done(struct closure *cl)
1457 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1459 __bch2_nocow_write_done(op);
1460 bch2_write_done(cl);
1463 static void bch2_nocow_write(struct bch_write_op *op)
1465 struct bch_fs *c = op->c;
1466 struct btree_trans trans;
1467 struct btree_iter iter;
1469 struct bkey_ptrs_c ptrs;
1470 const struct bch_extent_ptr *ptr, *ptr2;
1474 struct nocow_lock_bucket *l;
1475 } buckets[BCH_REPLICAS_MAX];
1476 unsigned nr_buckets = 0;
1480 if (op->flags & BCH_WRITE_MOVE)
1483 bch2_trans_init(&trans, c, 0, 0);
1485 bch2_trans_begin(&trans);
1487 ret = bch2_subvolume_get_snapshot(&trans, op->subvol, &snapshot);
1491 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1492 SPOS(op->pos.inode, op->pos.offset, snapshot),
1495 struct bio *bio = &op->wbio.bio;
1499 k = bch2_btree_iter_peek_slot(&iter);
1504 /* fall back to normal cow write path? */
1505 if (unlikely(k.k->p.snapshot != snapshot ||
1506 !bch2_extent_is_writeable(op, k)))
1509 if (bch2_keylist_realloc(&op->insert_keys,
1511 ARRAY_SIZE(op->inline_keys),
1515 /* Get iorefs before dropping btree locks: */
1516 ptrs = bch2_bkey_ptrs_c(k);
1517 bkey_for_each_ptr(ptrs, ptr) {
1518 buckets[nr_buckets].b = PTR_BUCKET_POS(c, ptr);
1519 buckets[nr_buckets].gen = ptr->gen;
1520 buckets[nr_buckets].l =
1521 bucket_nocow_lock(&c->nocow_locks,
1522 bucket_to_u64(buckets[nr_buckets].b));
1524 prefetch(buckets[nr_buckets].l);
1527 if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1531 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1534 /* Unlock before taking nocow locks, doing IO: */
1535 bkey_reassemble(op->insert_keys.top, k);
1536 bch2_trans_unlock(&trans);
1538 bch2_cut_front(op->pos, op->insert_keys.top);
1539 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1540 bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1542 for (i = 0; i < nr_buckets; i++) {
1543 struct bch_dev *ca = bch_dev_bkey_exists(c, buckets[i].b.inode);
1544 struct nocow_lock_bucket *l = buckets[i].l;
1547 __bch2_bucket_nocow_lock(&c->nocow_locks, l,
1548 bucket_to_u64(buckets[i].b),
1549 BUCKET_NOCOW_LOCK_UPDATE);
1552 stale = gen_after(*bucket_gen(ca, buckets[i].b.offset), buckets[i].gen);
1555 if (unlikely(stale))
1556 goto err_bucket_stale;
1559 bio = &op->wbio.bio;
1560 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1561 bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1562 GFP_KERNEL, &c->bio_write);
1563 wbio_init(bio)->put_bio = true;
1564 bio->bi_opf = op->wbio.bio.bi_opf;
1566 op->flags |= BCH_WRITE_DONE;
1569 op->pos.offset += bio_sectors(bio);
1570 op->written += bio_sectors(bio);
1572 bio->bi_end_io = bch2_write_endio;
1573 bio->bi_private = &op->cl;
1574 bio->bi_opf |= REQ_OP_WRITE;
1575 closure_get(&op->cl);
1576 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1577 op->insert_keys.top, true);
1579 bch2_keylist_push(&op->insert_keys);
1580 if (op->flags & BCH_WRITE_DONE)
1582 bch2_btree_iter_advance(&iter);
1585 bch2_trans_iter_exit(&trans, &iter);
1587 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1591 bch_err_inum_offset_ratelimited(c,
1593 op->pos.offset << 9,
1594 "%s: btree lookup error %s",
1595 __func__, bch2_err_str(ret));
1597 op->flags |= BCH_WRITE_DONE;
1600 bch2_trans_exit(&trans);
1602 /* fallback to cow write path? */
1603 if (!(op->flags & BCH_WRITE_DONE)) {
1604 closure_sync(&op->cl);
1605 __bch2_nocow_write_done(op);
1606 op->insert_keys.top = op->insert_keys.keys;
1607 } else if (op->flags & BCH_WRITE_SYNC) {
1608 closure_sync(&op->cl);
1609 bch2_nocow_write_done(&op->cl);
1613 * needs to run out of process context because ei_quota_lock is
1616 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1620 bkey_for_each_ptr(ptrs, ptr2) {
1624 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1627 /* Fall back to COW path: */
1631 bch2_bucket_nocow_unlock(&c->nocow_locks,
1633 BUCKET_NOCOW_LOCK_UPDATE);
1635 bkey_for_each_ptr(ptrs, ptr2)
1636 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1638 /* We can retry this: */
1639 ret = BCH_ERR_transaction_restart;
1643 static void __bch2_write(struct bch_write_op *op)
1645 struct bch_fs *c = op->c;
1646 struct write_point *wp = NULL;
1647 struct bio *bio = NULL;
1648 unsigned nofs_flags;
1651 nofs_flags = memalloc_nofs_save();
1653 if (unlikely(op->opts.nocow)) {
1654 bch2_nocow_write(op);
1655 if (op->flags & BCH_WRITE_DONE)
1656 goto out_nofs_restore;
1659 memset(&op->failed, 0, sizeof(op->failed));
1660 op->btree_update_ready = false;
1663 struct bkey_i *key_to_write;
1664 unsigned key_to_write_offset = op->insert_keys.top_p -
1665 op->insert_keys.keys_p;
1667 /* +1 for possible cache device: */
1668 if (op->open_buckets.nr + op->nr_replicas + 1 >
1669 ARRAY_SIZE(op->open_buckets.v))
1672 if (bch2_keylist_realloc(&op->insert_keys,
1674 ARRAY_SIZE(op->inline_keys),
1675 BKEY_EXTENT_U64s_MAX))
1679 * The copygc thread is now global, which means it's no longer
1680 * freeing up space on specific disks, which means that
1681 * allocations for specific disks may hang arbitrarily long:
1683 ret = bch2_trans_do(c, NULL, NULL, 0,
1684 bch2_alloc_sectors_start_trans(&trans,
1686 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1690 op->nr_replicas_required,
1693 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1694 BCH_WRITE_ONLY_SPECIFIED_DEVS))
1695 ? NULL : &op->cl, &wp));
1696 if (unlikely(ret)) {
1697 if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1705 bch2_open_bucket_get(c, wp, &op->open_buckets);
1706 ret = bch2_write_extent(op, wp, &bio);
1708 bch2_alloc_sectors_done_inlined(c, wp);
1711 if (!(op->flags & BCH_WRITE_SYNC)) {
1712 spin_lock(&wp->writes_lock);
1714 list_add_tail(&op->wp_list, &wp->writes);
1715 if (wp->state == WRITE_POINT_stopped)
1716 __wp_update_state(wp, WRITE_POINT_waiting_io);
1717 spin_unlock(&wp->writes_lock);
1720 op->flags |= BCH_WRITE_DONE;
1728 bio->bi_end_io = bch2_write_endio;
1729 bio->bi_private = &op->cl;
1730 bio->bi_opf |= REQ_OP_WRITE;
1732 closure_get(bio->bi_private);
1734 key_to_write = (void *) (op->insert_keys.keys_p +
1735 key_to_write_offset);
1737 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1738 key_to_write, false);
1744 * If we're running asynchronously, wne may still want to block
1745 * synchronously here if we weren't able to submit all of the IO at
1746 * once, as that signals backpressure to the caller.
1748 if ((op->flags & BCH_WRITE_SYNC) ||
1749 (!(op->flags & BCH_WRITE_DONE) &&
1750 !(op->flags & BCH_WRITE_IN_WORKER))) {
1751 closure_sync(&op->cl);
1752 __bch2_write_index(op);
1754 if (!(op->flags & BCH_WRITE_DONE))
1756 bch2_write_done(&op->cl);
1758 continue_at(&op->cl, bch2_write_index, NULL);
1761 memalloc_nofs_restore(nofs_flags);
1764 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1766 struct bio *bio = &op->wbio.bio;
1767 struct bvec_iter iter;
1768 struct bkey_i_inline_data *id;
1772 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1773 op->flags |= BCH_WRITE_DONE;
1775 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1777 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1778 ARRAY_SIZE(op->inline_keys),
1779 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1785 sectors = bio_sectors(bio);
1786 op->pos.offset += sectors;
1788 id = bkey_inline_data_init(op->insert_keys.top);
1790 id->k.version = op->version;
1791 id->k.size = sectors;
1793 iter = bio->bi_iter;
1794 iter.bi_size = data_len;
1795 memcpy_from_bio(id->v.data, bio, iter);
1797 while (data_len & 7)
1798 id->v.data[data_len++] = '\0';
1799 set_bkey_val_bytes(&id->k, data_len);
1800 bch2_keylist_push(&op->insert_keys);
1802 __bch2_write_index(op);
1804 bch2_write_done(&op->cl);
1808 * bch_write - handle a write to a cache device or flash only volume
1810 * This is the starting point for any data to end up in a cache device; it could
1811 * be from a normal write, or a writeback write, or a write to a flash only
1812 * volume - it's also used by the moving garbage collector to compact data in
1813 * mostly empty buckets.
1815 * It first writes the data to the cache, creating a list of keys to be inserted
1816 * (if the data won't fit in a single open bucket, there will be multiple keys);
1817 * after the data is written it calls bch_journal, and after the keys have been
1818 * added to the next journal write they're inserted into the btree.
1820 * If op->discard is true, instead of inserting the data it invalidates the
1821 * region of the cache represented by op->bio and op->inode.
1823 void bch2_write(struct closure *cl)
1825 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1826 struct bio *bio = &op->wbio.bio;
1827 struct bch_fs *c = op->c;
1830 EBUG_ON(op->cl.parent);
1831 BUG_ON(!op->nr_replicas);
1832 BUG_ON(!op->write_point.v);
1833 BUG_ON(bkey_eq(op->pos, POS_MAX));
1835 op->start_time = local_clock();
1836 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1837 wbio_init(bio)->put_bio = false;
1839 if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1840 bch_err_inum_offset_ratelimited(c,
1842 op->pos.offset << 9,
1843 "misaligned write");
1848 if (c->opts.nochanges ||
1849 !bch2_write_ref_tryget(c, BCH_WRITE_REF_write)) {
1850 op->error = -BCH_ERR_erofs_no_writes;
1854 this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1855 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1857 data_len = min_t(u64, bio->bi_iter.bi_size,
1858 op->new_i_size - (op->pos.offset << 9));
1860 if (c->opts.inline_data &&
1861 data_len <= min(block_bytes(c) / 2, 1024U)) {
1862 bch2_write_data_inline(op, data_len);
1869 bch2_disk_reservation_put(c, &op->res);
1871 closure_debug_destroy(&op->cl);
1876 /* Cache promotion on read */
1879 struct rcu_head rcu;
1882 struct rhash_head hash;
1885 struct data_update write;
1886 struct bio_vec bi_inline_vecs[0]; /* must be last */
1889 static const struct rhashtable_params bch_promote_params = {
1890 .head_offset = offsetof(struct promote_op, hash),
1891 .key_offset = offsetof(struct promote_op, pos),
1892 .key_len = sizeof(struct bpos),
1895 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1897 struct bch_io_opts opts,
1900 if (!(flags & BCH_READ_MAY_PROMOTE))
1903 if (!opts.promote_target)
1906 if (bch2_bkey_has_target(c, k, opts.promote_target))
1909 if (bkey_extent_is_unwritten(k))
1912 if (bch2_target_congested(c, opts.promote_target)) {
1913 /* XXX trace this */
1917 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1918 bch_promote_params))
1924 static void promote_free(struct bch_fs *c, struct promote_op *op)
1928 bch2_data_update_exit(&op->write);
1930 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1931 bch_promote_params);
1933 bch2_write_ref_put(c, BCH_WRITE_REF_promote);
1937 static void promote_done(struct bch_write_op *wop)
1939 struct promote_op *op =
1940 container_of(wop, struct promote_op, write.op);
1941 struct bch_fs *c = op->write.op.c;
1943 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1945 promote_free(c, op);
1948 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1950 struct bio *bio = &op->write.op.wbio.bio;
1952 trace_and_count(op->write.op.c, read_promote, &rbio->bio);
1954 /* we now own pages: */
1955 BUG_ON(!rbio->bounce);
1956 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1958 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1959 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1960 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1962 bch2_data_update_read_done(&op->write, rbio->pick.crc);
1965 static struct promote_op *__promote_alloc(struct btree_trans *trans,
1966 enum btree_id btree_id,
1969 struct extent_ptr_decoded *pick,
1970 struct bch_io_opts opts,
1972 struct bch_read_bio **rbio)
1974 struct bch_fs *c = trans->c;
1975 struct promote_op *op = NULL;
1977 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1980 if (!bch2_write_ref_tryget(c, BCH_WRITE_REF_promote))
1983 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1987 op->start_time = local_clock();
1991 * We don't use the mempool here because extents that aren't
1992 * checksummed or compressed can be too big for the mempool:
1994 *rbio = kzalloc(sizeof(struct bch_read_bio) +
1995 sizeof(struct bio_vec) * pages,
2000 rbio_init(&(*rbio)->bio, opts);
2001 bio_init(&(*rbio)->bio, NULL, (*rbio)->bio.bi_inline_vecs, pages, 0);
2003 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
2007 (*rbio)->bounce = true;
2008 (*rbio)->split = true;
2009 (*rbio)->kmalloc = true;
2011 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
2012 bch_promote_params))
2015 bio = &op->write.op.wbio.bio;
2016 bio_init(bio, NULL, bio->bi_inline_vecs, pages, 0);
2018 ret = bch2_data_update_init(trans, NULL, &op->write,
2019 writepoint_hashed((unsigned long) current),
2021 (struct data_update_opts) {
2022 .target = opts.promote_target,
2023 .extra_replicas = 1,
2024 .write_flags = BCH_WRITE_ALLOC_NOWAIT|BCH_WRITE_CACHED,
2027 if (ret == -BCH_ERR_nocow_lock_blocked) {
2028 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
2029 bch_promote_params);
2035 op->write.op.end_io = promote_done;
2040 bio_free_pages(&(*rbio)->bio);
2044 bch2_write_ref_put(c, BCH_WRITE_REF_promote);
2049 static struct promote_op *promote_alloc(struct btree_trans *trans,
2050 struct bvec_iter iter,
2052 struct extent_ptr_decoded *pick,
2053 struct bch_io_opts opts,
2055 struct bch_read_bio **rbio,
2059 struct bch_fs *c = trans->c;
2060 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
2061 /* data might have to be decompressed in the write path: */
2062 unsigned sectors = promote_full
2063 ? max(pick->crc.compressed_size, pick->crc.live_size)
2064 : bvec_iter_sectors(iter);
2065 struct bpos pos = promote_full
2066 ? bkey_start_pos(k.k)
2067 : POS(k.k->p.inode, iter.bi_sector);
2068 struct promote_op *promote;
2070 if (!should_promote(c, k, pos, opts, flags))
2073 promote = __promote_alloc(trans,
2074 k.k->type == KEY_TYPE_reflink_v
2077 k, pos, pick, opts, sectors, rbio);
2082 *read_full = promote_full;
2088 #define READ_RETRY_AVOID 1
2089 #define READ_RETRY 2
2094 RBIO_CONTEXT_HIGHPRI,
2095 RBIO_CONTEXT_UNBOUND,
2098 static inline struct bch_read_bio *
2099 bch2_rbio_parent(struct bch_read_bio *rbio)
2101 return rbio->split ? rbio->parent : rbio;
2105 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
2106 enum rbio_context context,
2107 struct workqueue_struct *wq)
2109 if (context <= rbio->context) {
2112 rbio->work.func = fn;
2113 rbio->context = context;
2114 queue_work(wq, &rbio->work);
2118 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
2120 BUG_ON(rbio->bounce && !rbio->split);
2123 promote_free(rbio->c, rbio->promote);
2124 rbio->promote = NULL;
2127 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
2130 struct bch_read_bio *parent = rbio->parent;
2135 bio_put(&rbio->bio);
2144 * Only called on a top level bch_read_bio to complete an entire read request,
2147 static void bch2_rbio_done(struct bch_read_bio *rbio)
2149 if (rbio->start_time)
2150 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
2152 bio_endio(&rbio->bio);
2155 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
2156 struct bvec_iter bvec_iter,
2157 struct bch_io_failures *failed,
2160 struct btree_trans trans;
2161 struct btree_iter iter;
2166 flags &= ~BCH_READ_LAST_FRAGMENT;
2167 flags |= BCH_READ_MUST_CLONE;
2169 bch2_bkey_buf_init(&sk);
2170 bch2_trans_init(&trans, c, 0, 0);
2172 bch2_trans_iter_init(&trans, &iter, rbio->data_btree,
2173 rbio->read_pos, BTREE_ITER_SLOTS);
2175 rbio->bio.bi_status = 0;
2177 k = bch2_btree_iter_peek_slot(&iter);
2181 bch2_bkey_buf_reassemble(&sk, c, k);
2182 k = bkey_i_to_s_c(sk.k);
2183 bch2_trans_unlock(&trans);
2185 if (!bch2_bkey_matches_ptr(c, k,
2187 rbio->data_pos.offset -
2188 rbio->pick.crc.offset)) {
2189 /* extent we wanted to read no longer exists: */
2194 ret = __bch2_read_extent(&trans, rbio, bvec_iter,
2197 k, 0, failed, flags);
2198 if (ret == READ_RETRY)
2203 bch2_rbio_done(rbio);
2204 bch2_trans_iter_exit(&trans, &iter);
2205 bch2_trans_exit(&trans);
2206 bch2_bkey_buf_exit(&sk, c);
2209 rbio->bio.bi_status = BLK_STS_IOERR;
2213 static void bch2_rbio_retry(struct work_struct *work)
2215 struct bch_read_bio *rbio =
2216 container_of(work, struct bch_read_bio, work);
2217 struct bch_fs *c = rbio->c;
2218 struct bvec_iter iter = rbio->bvec_iter;
2219 unsigned flags = rbio->flags;
2220 subvol_inum inum = {
2221 .subvol = rbio->subvol,
2222 .inum = rbio->read_pos.inode,
2224 struct bch_io_failures failed = { .nr = 0 };
2226 trace_and_count(c, read_retry, &rbio->bio);
2228 if (rbio->retry == READ_RETRY_AVOID)
2229 bch2_mark_io_failure(&failed, &rbio->pick);
2231 rbio->bio.bi_status = 0;
2233 rbio = bch2_rbio_free(rbio);
2235 flags |= BCH_READ_IN_RETRY;
2236 flags &= ~BCH_READ_MAY_PROMOTE;
2238 if (flags & BCH_READ_NODECODE) {
2239 bch2_read_retry_nodecode(c, rbio, iter, &failed, flags);
2241 flags &= ~BCH_READ_LAST_FRAGMENT;
2242 flags |= BCH_READ_MUST_CLONE;
2244 __bch2_read(c, rbio, iter, inum, &failed, flags);
2248 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
2251 rbio->retry = retry;
2253 if (rbio->flags & BCH_READ_IN_RETRY)
2256 if (retry == READ_ERR) {
2257 rbio = bch2_rbio_free(rbio);
2259 rbio->bio.bi_status = error;
2260 bch2_rbio_done(rbio);
2262 bch2_rbio_punt(rbio, bch2_rbio_retry,
2263 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
2267 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
2268 struct bch_read_bio *rbio)
2270 struct bch_fs *c = rbio->c;
2271 u64 data_offset = rbio->data_pos.offset - rbio->pick.crc.offset;
2272 struct bch_extent_crc_unpacked new_crc;
2273 struct btree_iter iter;
2278 if (crc_is_compressed(rbio->pick.crc))
2281 bch2_trans_iter_init(trans, &iter, rbio->data_btree, rbio->data_pos,
2282 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2283 k = bch2_btree_iter_peek_slot(&iter);
2284 if ((ret = bkey_err(k)))
2287 if (bversion_cmp(k.k->version, rbio->version) ||
2288 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
2291 /* Extent was merged? */
2292 if (bkey_start_offset(k.k) < data_offset ||
2293 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
2296 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
2297 rbio->pick.crc, NULL, &new_crc,
2298 bkey_start_offset(k.k) - data_offset, k.k->size,
2299 rbio->pick.crc.csum_type)) {
2300 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
2306 * going to be temporarily appending another checksum entry:
2308 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
2309 sizeof(struct bch_extent_crc128));
2310 if ((ret = PTR_ERR_OR_ZERO(new)))
2313 bkey_reassemble(new, k);
2315 if (!bch2_bkey_narrow_crcs(new, new_crc))
2318 ret = bch2_trans_update(trans, &iter, new,
2319 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
2321 bch2_trans_iter_exit(trans, &iter);
2325 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
2327 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
2328 __bch2_rbio_narrow_crcs(&trans, rbio));
2331 /* Inner part that may run in process context */
2332 static void __bch2_read_endio(struct work_struct *work)
2334 struct bch_read_bio *rbio =
2335 container_of(work, struct bch_read_bio, work);
2336 struct bch_fs *c = rbio->c;
2337 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2338 struct bio *src = &rbio->bio;
2339 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
2340 struct bvec_iter dst_iter = rbio->bvec_iter;
2341 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
2342 struct nonce nonce = extent_nonce(rbio->version, crc);
2343 unsigned nofs_flags;
2344 struct bch_csum csum;
2347 nofs_flags = memalloc_nofs_save();
2349 /* Reset iterator for checksumming and copying bounced data: */
2351 src->bi_iter.bi_size = crc.compressed_size << 9;
2352 src->bi_iter.bi_idx = 0;
2353 src->bi_iter.bi_bvec_done = 0;
2355 src->bi_iter = rbio->bvec_iter;
2358 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
2359 if (bch2_crc_cmp(csum, rbio->pick.crc.csum) &&
2360 !IS_ENABLED(CONFIG_BCACHEFS_NO_IO))
2365 * We need to rework the narrow_crcs path to deliver the read completion
2366 * first, and then punt to a different workqueue, otherwise we're
2367 * holding up reads while doing btree updates which is bad for memory
2370 if (unlikely(rbio->narrow_crcs))
2371 bch2_rbio_narrow_crcs(rbio);
2373 if (rbio->flags & BCH_READ_NODECODE)
2376 /* Adjust crc to point to subset of data we want: */
2377 crc.offset += rbio->offset_into_extent;
2378 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
2380 if (crc_is_compressed(crc)) {
2381 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2385 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
2386 goto decompression_err;
2388 /* don't need to decrypt the entire bio: */
2389 nonce = nonce_add(nonce, crc.offset << 9);
2390 bio_advance(src, crc.offset << 9);
2392 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
2393 src->bi_iter.bi_size = dst_iter.bi_size;
2395 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2400 struct bvec_iter src_iter = src->bi_iter;
2401 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
2405 if (rbio->promote) {
2407 * Re encrypt data we decrypted, so it's consistent with
2410 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2414 promote_start(rbio->promote, rbio);
2415 rbio->promote = NULL;
2418 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
2419 rbio = bch2_rbio_free(rbio);
2420 bch2_rbio_done(rbio);
2423 memalloc_nofs_restore(nofs_flags);
2427 * Checksum error: if the bio wasn't bounced, we may have been
2428 * reading into buffers owned by userspace (that userspace can
2429 * scribble over) - retry the read, bouncing it this time:
2431 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
2432 rbio->flags |= BCH_READ_MUST_BOUNCE;
2433 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
2437 bch_err_inum_offset_ratelimited(ca,
2438 rbio->read_pos.inode,
2439 rbio->read_pos.offset << 9,
2440 "data checksum error: expected %0llx:%0llx got %0llx:%0llx (type %s)",
2441 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
2442 csum.hi, csum.lo, bch2_csum_types[crc.csum_type]);
2444 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2447 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2448 rbio->read_pos.offset << 9,
2449 "decompression error");
2450 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2453 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2454 rbio->read_pos.offset << 9,
2456 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2460 static void bch2_read_endio(struct bio *bio)
2462 struct bch_read_bio *rbio =
2463 container_of(bio, struct bch_read_bio, bio);
2464 struct bch_fs *c = rbio->c;
2465 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2466 struct workqueue_struct *wq = NULL;
2467 enum rbio_context context = RBIO_CONTEXT_NULL;
2469 if (rbio->have_ioref) {
2470 bch2_latency_acct(ca, rbio->submit_time, READ);
2471 percpu_ref_put(&ca->io_ref);
2475 rbio->bio.bi_end_io = rbio->end_io;
2477 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
2478 rbio->read_pos.inode,
2479 rbio->read_pos.offset,
2480 "data read error: %s",
2481 bch2_blk_status_to_str(bio->bi_status))) {
2482 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
2486 if (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
2487 ptr_stale(ca, &rbio->pick.ptr)) {
2488 trace_and_count(c, read_reuse_race, &rbio->bio);
2490 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
2491 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
2493 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
2497 if (rbio->narrow_crcs ||
2499 crc_is_compressed(rbio->pick.crc) ||
2500 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
2501 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
2502 else if (rbio->pick.crc.csum_type)
2503 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
2505 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
2508 int __bch2_read_indirect_extent(struct btree_trans *trans,
2509 unsigned *offset_into_extent,
2510 struct bkey_buf *orig_k)
2512 struct btree_iter iter;
2517 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
2518 *offset_into_extent;
2520 bch2_trans_iter_init(trans, &iter, BTREE_ID_reflink,
2521 POS(0, reflink_offset),
2523 k = bch2_btree_iter_peek_slot(&iter);
2528 if (k.k->type != KEY_TYPE_reflink_v &&
2529 k.k->type != KEY_TYPE_indirect_inline_data) {
2530 bch_err_inum_offset_ratelimited(trans->c,
2531 orig_k->k->k.p.inode,
2532 orig_k->k->k.p.offset << 9,
2533 "%llu len %u points to nonexistent indirect extent %llu",
2534 orig_k->k->k.p.offset,
2537 bch2_inconsistent_error(trans->c);
2542 *offset_into_extent = iter.pos.offset - bkey_start_offset(k.k);
2543 bch2_bkey_buf_reassemble(orig_k, trans->c, k);
2545 bch2_trans_iter_exit(trans, &iter);
2549 static noinline void read_from_stale_dirty_pointer(struct btree_trans *trans,
2551 struct bch_extent_ptr ptr)
2553 struct bch_fs *c = trans->c;
2554 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr.dev);
2555 struct btree_iter iter;
2556 struct printbuf buf = PRINTBUF;
2559 bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
2560 PTR_BUCKET_POS(c, &ptr),
2563 prt_printf(&buf, "Attempting to read from stale dirty pointer:");
2564 printbuf_indent_add(&buf, 2);
2567 bch2_bkey_val_to_text(&buf, c, k);
2570 prt_printf(&buf, "memory gen: %u", *bucket_gen(ca, iter.pos.offset));
2572 ret = lockrestart_do(trans, bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
2575 bch2_bkey_val_to_text(&buf, c, k);
2578 bch2_fs_inconsistent(c, "%s", buf.buf);
2580 bch2_trans_iter_exit(trans, &iter);
2581 printbuf_exit(&buf);
2584 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2585 struct bvec_iter iter, struct bpos read_pos,
2586 enum btree_id data_btree, struct bkey_s_c k,
2587 unsigned offset_into_extent,
2588 struct bch_io_failures *failed, unsigned flags)
2590 struct bch_fs *c = trans->c;
2591 struct extent_ptr_decoded pick;
2592 struct bch_read_bio *rbio = NULL;
2593 struct bch_dev *ca = NULL;
2594 struct promote_op *promote = NULL;
2595 bool bounce = false, read_full = false, narrow_crcs = false;
2596 struct bpos data_pos = bkey_start_pos(k.k);
2599 if (bkey_extent_is_inline_data(k.k)) {
2600 unsigned bytes = min_t(unsigned, iter.bi_size,
2601 bkey_inline_data_bytes(k.k));
2603 swap(iter.bi_size, bytes);
2604 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2605 swap(iter.bi_size, bytes);
2606 bio_advance_iter(&orig->bio, &iter, bytes);
2607 zero_fill_bio_iter(&orig->bio, iter);
2611 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2613 /* hole or reservation - just zero fill: */
2618 bch_err_inum_offset_ratelimited(c,
2619 read_pos.inode, read_pos.offset << 9,
2620 "no device to read from");
2624 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2627 * Stale dirty pointers are treated as IO errors, but @failed isn't
2628 * allocated unless we're in the retry path - so if we're not in the
2629 * retry path, don't check here, it'll be caught in bch2_read_endio()
2630 * and we'll end up in the retry path:
2632 if ((flags & BCH_READ_IN_RETRY) &&
2634 unlikely(ptr_stale(ca, &pick.ptr))) {
2635 read_from_stale_dirty_pointer(trans, k, pick.ptr);
2636 bch2_mark_io_failure(failed, &pick);
2641 * Unlock the iterator while the btree node's lock is still in
2642 * cache, before doing the IO:
2644 bch2_trans_unlock(trans);
2646 if (flags & BCH_READ_NODECODE) {
2648 * can happen if we retry, and the extent we were going to read
2649 * has been merged in the meantime:
2651 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2654 iter.bi_size = pick.crc.compressed_size << 9;
2658 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2659 bio_flagged(&orig->bio, BIO_CHAIN))
2660 flags |= BCH_READ_MUST_CLONE;
2662 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2663 bch2_can_narrow_extent_crcs(k, pick.crc);
2665 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2666 flags |= BCH_READ_MUST_BOUNCE;
2668 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2670 if (crc_is_compressed(pick.crc) ||
2671 (pick.crc.csum_type != BCH_CSUM_none &&
2672 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2673 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2674 (flags & BCH_READ_USER_MAPPED)) ||
2675 (flags & BCH_READ_MUST_BOUNCE)))) {
2680 if (orig->opts.promote_target)
2681 promote = promote_alloc(trans, iter, k, &pick, orig->opts, flags,
2682 &rbio, &bounce, &read_full);
2685 EBUG_ON(crc_is_compressed(pick.crc));
2686 EBUG_ON(pick.crc.csum_type &&
2687 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2688 bvec_iter_sectors(iter) != pick.crc.live_size ||
2690 offset_into_extent));
2692 data_pos.offset += offset_into_extent;
2693 pick.ptr.offset += pick.crc.offset +
2695 offset_into_extent = 0;
2696 pick.crc.compressed_size = bvec_iter_sectors(iter);
2697 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2698 pick.crc.offset = 0;
2699 pick.crc.live_size = bvec_iter_sectors(iter);
2700 offset_into_extent = 0;
2705 * promote already allocated bounce rbio:
2706 * promote needs to allocate a bio big enough for uncompressing
2707 * data in the write path, but we're not going to use it all
2710 EBUG_ON(rbio->bio.bi_iter.bi_size <
2711 pick.crc.compressed_size << 9);
2712 rbio->bio.bi_iter.bi_size =
2713 pick.crc.compressed_size << 9;
2714 } else if (bounce) {
2715 unsigned sectors = pick.crc.compressed_size;
2717 rbio = rbio_init(bio_alloc_bioset(NULL,
2718 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2721 &c->bio_read_split),
2724 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2725 rbio->bounce = true;
2727 } else if (flags & BCH_READ_MUST_CLONE) {
2729 * Have to clone if there were any splits, due to error
2730 * reporting issues (if a split errored, and retrying didn't
2731 * work, when it reports the error to its parent (us) we don't
2732 * know if the error was from our bio, and we should retry, or
2733 * from the whole bio, in which case we don't want to retry and
2736 rbio = rbio_init(bio_alloc_clone(NULL, &orig->bio, GFP_NOIO,
2737 &c->bio_read_split),
2739 rbio->bio.bi_iter = iter;
2743 rbio->bio.bi_iter = iter;
2744 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2747 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2750 rbio->submit_time = local_clock();
2752 rbio->parent = orig;
2754 rbio->end_io = orig->bio.bi_end_io;
2755 rbio->bvec_iter = iter;
2756 rbio->offset_into_extent= offset_into_extent;
2757 rbio->flags = flags;
2758 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2759 rbio->narrow_crcs = narrow_crcs;
2763 /* XXX: only initialize this if needed */
2764 rbio->devs_have = bch2_bkey_devs(k);
2766 rbio->subvol = orig->subvol;
2767 rbio->read_pos = read_pos;
2768 rbio->data_btree = data_btree;
2769 rbio->data_pos = data_pos;
2770 rbio->version = k.k->version;
2771 rbio->promote = promote;
2772 INIT_WORK(&rbio->work, NULL);
2774 rbio->bio.bi_opf = orig->bio.bi_opf;
2775 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2776 rbio->bio.bi_end_io = bch2_read_endio;
2779 trace_and_count(c, read_bounce, &rbio->bio);
2781 this_cpu_add(c->counters[BCH_COUNTER_io_read], bio_sectors(&rbio->bio));
2782 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2785 * If it's being moved internally, we don't want to flag it as a cache
2788 if (pick.ptr.cached && !(flags & BCH_READ_NODECODE))
2789 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2790 PTR_BUCKET_NR(ca, &pick.ptr), READ);
2792 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2793 bio_inc_remaining(&orig->bio);
2794 trace_and_count(c, read_split, &orig->bio);
2797 if (!rbio->pick.idx) {
2798 if (!rbio->have_ioref) {
2799 bch_err_inum_offset_ratelimited(c,
2801 read_pos.offset << 9,
2802 "no device to read from");
2803 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2807 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2808 bio_sectors(&rbio->bio));
2809 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2811 if (IS_ENABLED(CONFIG_BCACHEFS_NO_IO)) {
2812 if (likely(!(flags & BCH_READ_IN_RETRY)))
2813 bio_endio(&rbio->bio);
2815 if (likely(!(flags & BCH_READ_IN_RETRY)))
2816 submit_bio(&rbio->bio);
2818 submit_bio_wait(&rbio->bio);
2822 * We just submitted IO which may block, we expect relock fail
2823 * events and shouldn't count them:
2825 trans->notrace_relock_fail = true;
2827 /* Attempting reconstruct read: */
2828 if (bch2_ec_read_extent(c, rbio)) {
2829 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2833 if (likely(!(flags & BCH_READ_IN_RETRY)))
2834 bio_endio(&rbio->bio);
2837 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2842 rbio->context = RBIO_CONTEXT_UNBOUND;
2843 bch2_read_endio(&rbio->bio);
2846 rbio = bch2_rbio_free(rbio);
2848 if (ret == READ_RETRY_AVOID) {
2849 bch2_mark_io_failure(failed, &pick);
2860 if (flags & BCH_READ_IN_RETRY)
2863 orig->bio.bi_status = BLK_STS_IOERR;
2868 * won't normally happen in the BCH_READ_NODECODE
2869 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2870 * to read no longer exists we have to signal that:
2872 if (flags & BCH_READ_NODECODE)
2875 zero_fill_bio_iter(&orig->bio, iter);
2877 if (flags & BCH_READ_LAST_FRAGMENT)
2878 bch2_rbio_done(orig);
2882 void __bch2_read(struct bch_fs *c, struct bch_read_bio *rbio,
2883 struct bvec_iter bvec_iter, subvol_inum inum,
2884 struct bch_io_failures *failed, unsigned flags)
2886 struct btree_trans trans;
2887 struct btree_iter iter;
2893 BUG_ON(flags & BCH_READ_NODECODE);
2895 bch2_bkey_buf_init(&sk);
2896 bch2_trans_init(&trans, c, 0, 0);
2898 bch2_trans_begin(&trans);
2899 iter = (struct btree_iter) { NULL };
2901 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
2905 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2906 SPOS(inum.inum, bvec_iter.bi_sector, snapshot),
2909 unsigned bytes, sectors, offset_into_extent;
2910 enum btree_id data_btree = BTREE_ID_extents;
2913 * read_extent -> io_time_reset may cause a transaction restart
2914 * without returning an error, we need to check for that here:
2916 ret = bch2_trans_relock(&trans);
2920 bch2_btree_iter_set_pos(&iter,
2921 POS(inum.inum, bvec_iter.bi_sector));
2923 k = bch2_btree_iter_peek_slot(&iter);
2928 offset_into_extent = iter.pos.offset -
2929 bkey_start_offset(k.k);
2930 sectors = k.k->size - offset_into_extent;
2932 bch2_bkey_buf_reassemble(&sk, c, k);
2934 ret = bch2_read_indirect_extent(&trans, &data_btree,
2935 &offset_into_extent, &sk);
2939 k = bkey_i_to_s_c(sk.k);
2942 * With indirect extents, the amount of data to read is the min
2943 * of the original extent and the indirect extent:
2945 sectors = min(sectors, k.k->size - offset_into_extent);
2947 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
2948 swap(bvec_iter.bi_size, bytes);
2950 if (bvec_iter.bi_size == bytes)
2951 flags |= BCH_READ_LAST_FRAGMENT;
2953 ret = __bch2_read_extent(&trans, rbio, bvec_iter, iter.pos,
2955 offset_into_extent, failed, flags);
2959 if (flags & BCH_READ_LAST_FRAGMENT)
2962 swap(bvec_iter.bi_size, bytes);
2963 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
2965 ret = btree_trans_too_many_iters(&trans);
2970 bch2_trans_iter_exit(&trans, &iter);
2972 if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
2973 ret == READ_RETRY ||
2974 ret == READ_RETRY_AVOID)
2977 bch2_trans_exit(&trans);
2978 bch2_bkey_buf_exit(&sk, c);
2981 bch_err_inum_offset_ratelimited(c, inum.inum,
2982 bvec_iter.bi_sector << 9,
2983 "read error %i from btree lookup", ret);
2984 rbio->bio.bi_status = BLK_STS_IOERR;
2985 bch2_rbio_done(rbio);
2989 void bch2_fs_io_exit(struct bch_fs *c)
2991 if (c->promote_table.tbl)
2992 rhashtable_destroy(&c->promote_table);
2993 mempool_exit(&c->bio_bounce_pages);
2994 bioset_exit(&c->bio_write);
2995 bioset_exit(&c->bio_read_split);
2996 bioset_exit(&c->bio_read);
2999 int bch2_fs_io_init(struct bch_fs *c)
3001 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
3002 BIOSET_NEED_BVECS) ||
3003 bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
3004 BIOSET_NEED_BVECS) ||
3005 bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
3006 BIOSET_NEED_BVECS) ||
3007 mempool_init_page_pool(&c->bio_bounce_pages,
3009 c->opts.btree_node_size,
3010 c->opts.encoded_extent_max) /
3012 rhashtable_init(&c->promote_table, &bch_promote_params))