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"
37 #include <linux/blkdev.h>
38 #include <linux/prefetch.h>
39 #include <linux/random.h>
40 #include <linux/sched/mm.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 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
51 static bool bch2_target_congested(struct bch_fs *c, u16 target)
53 const struct bch_devs_mask *devs;
54 unsigned d, nr = 0, total = 0;
55 u64 now = local_clock(), last;
63 devs = bch2_target_to_mask(c, target) ?:
64 &c->rw_devs[BCH_DATA_user];
66 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
67 ca = rcu_dereference(c->devs[d]);
71 congested = atomic_read(&ca->congested);
72 last = READ_ONCE(ca->congested_last);
73 if (time_after64(now, last))
74 congested -= (now - last) >> 12;
76 total += max(congested, 0LL);
81 return bch2_rand_range(nr * CONGESTED_MAX) < total;
84 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
88 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
89 /* ideally we'd be taking into account the device's variance here: */
90 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
91 s64 latency_over = io_latency - latency_threshold;
93 if (latency_threshold && latency_over > 0) {
95 * bump up congested by approximately latency_over * 4 /
96 * latency_threshold - we don't need much accuracy here so don't
97 * bother with the divide:
99 if (atomic_read(&ca->congested) < CONGESTED_MAX)
100 atomic_add(latency_over >>
101 max_t(int, ilog2(latency_threshold) - 2, 0),
104 ca->congested_last = now;
105 } else if (atomic_read(&ca->congested) > 0) {
106 atomic_dec(&ca->congested);
110 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
112 atomic64_t *latency = &ca->cur_latency[rw];
113 u64 now = local_clock();
114 u64 io_latency = time_after64(now, submit_time)
117 u64 old, new, v = atomic64_read(latency);
123 * If the io latency was reasonably close to the current
124 * latency, skip doing the update and atomic operation - most of
127 if (abs((int) (old - io_latency)) < (old >> 1) &&
131 new = ewma_add(old, io_latency, 5);
132 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
134 bch2_congested_acct(ca, io_latency, now, rw);
136 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
141 static bool bch2_target_congested(struct bch_fs *c, u16 target)
148 /* Allocate, free from mempool: */
150 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
152 struct bvec_iter_all iter;
155 bio_for_each_segment_all(bv, bio, iter)
156 if (bv->bv_page != ZERO_PAGE(0))
157 mempool_free(bv->bv_page, &c->bio_bounce_pages);
161 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
165 if (likely(!*using_mempool)) {
166 page = alloc_page(GFP_NOFS);
167 if (unlikely(!page)) {
168 mutex_lock(&c->bio_bounce_pages_lock);
169 *using_mempool = true;
175 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOFS);
181 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
184 bool using_mempool = false;
187 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
188 unsigned len = min_t(size_t, PAGE_SIZE, size);
190 BUG_ON(!bio_add_page(bio, page, len, 0));
195 mutex_unlock(&c->bio_bounce_pages_lock);
198 /* Extent update path: */
200 int bch2_sum_sector_overwrites(struct btree_trans *trans,
201 struct btree_iter *extent_iter,
203 bool *usage_increasing,
204 s64 *i_sectors_delta,
205 s64 *disk_sectors_delta)
207 struct bch_fs *c = trans->c;
208 struct btree_iter iter;
210 unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
211 bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
214 *usage_increasing = false;
215 *i_sectors_delta = 0;
216 *disk_sectors_delta = 0;
218 bch2_trans_copy_iter(&iter, extent_iter);
220 for_each_btree_key_upto_continue_norestart(iter,
221 new->k.p, 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 k = bch2_bkey_get_mut_noupdate(trans, &iter, BTREE_ID_inodes,
262 extent_iter->pos.inode,
263 extent_iter->snapshot),
265 ret = PTR_ERR_OR_ZERO(k);
269 if (unlikely(k->k.type != KEY_TYPE_inode_v3)) {
270 k = bch2_inode_to_v3(trans, k);
271 ret = PTR_ERR_OR_ZERO(k);
276 inode = bkey_i_to_inode_v3(k);
278 if (!(le64_to_cpu(inode->v.bi_flags) & BCH_INODE_I_SIZE_DIRTY) &&
279 new_i_size > le64_to_cpu(inode->v.bi_size)) {
280 inode->v.bi_size = cpu_to_le64(new_i_size);
281 inode_update_flags = 0;
284 if (i_sectors_delta) {
285 le64_add_cpu(&inode->v.bi_sectors, i_sectors_delta);
286 inode_update_flags = 0;
289 if (inode->k.p.snapshot != iter.snapshot) {
290 inode->k.p.snapshot = iter.snapshot;
291 inode_update_flags = 0;
294 ret = bch2_trans_update(trans, &iter, &inode->k_i,
295 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
298 bch2_trans_iter_exit(trans, &iter);
302 int bch2_extent_update(struct btree_trans *trans,
304 struct btree_iter *iter,
306 struct disk_reservation *disk_res,
308 s64 *i_sectors_delta_total,
311 struct bpos next_pos;
312 bool usage_increasing;
313 s64 i_sectors_delta = 0, disk_sectors_delta = 0;
317 * This traverses us the iterator without changing iter->path->pos to
318 * search_key() (which is pos + 1 for extents): we want there to be a
319 * path already traversed at iter->pos because
320 * bch2_trans_extent_update() will use it to attempt extent merging
322 ret = __bch2_btree_iter_traverse(iter);
326 ret = bch2_extent_trim_atomic(trans, iter, k);
332 ret = bch2_sum_sector_overwrites(trans, iter, k,
335 &disk_sectors_delta);
340 disk_sectors_delta > (s64) disk_res->sectors) {
341 ret = bch2_disk_reservation_add(trans->c, disk_res,
342 disk_sectors_delta - disk_res->sectors,
343 !check_enospc || !usage_increasing
344 ? BCH_DISK_RESERVATION_NOFAIL : 0);
351 * We always have to do an inode update - even when i_size/i_sectors
352 * aren't changing - for fsync to work properly; fsync relies on
353 * inode->bi_journal_seq which is updated by the trigger code:
355 ret = bch2_extent_update_i_size_sectors(trans, iter,
356 min(k->k.p.offset << 9, new_i_size),
358 bch2_trans_update(trans, iter, k, 0) ?:
359 bch2_trans_commit(trans, disk_res, NULL,
360 BTREE_INSERT_NOCHECK_RW|
361 BTREE_INSERT_NOFAIL);
365 if (i_sectors_delta_total)
366 *i_sectors_delta_total += i_sectors_delta;
367 bch2_btree_iter_set_pos(iter, next_pos);
371 /* Overwrites whatever was present with zeroes: */
372 int bch2_extent_fallocate(struct btree_trans *trans,
374 struct btree_iter *iter,
376 struct bch_io_opts opts,
377 s64 *i_sectors_delta,
378 struct write_point_specifier write_point)
380 struct bch_fs *c = trans->c;
381 struct disk_reservation disk_res = { 0 };
383 struct open_buckets open_buckets;
385 struct bkey_buf old, new;
386 unsigned sectors_allocated;
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 sectors_allocated = 0;
399 k = bch2_btree_iter_peek_slot(iter);
404 sectors = min_t(u64, sectors, k.k->p.offset - iter->pos.offset);
406 if (!have_reservation) {
407 unsigned new_replicas =
408 max(0, (int) opts.data_replicas -
409 (int) bch2_bkey_nr_ptrs_fully_allocated(k));
411 * Get a disk reservation before (in the nocow case) calling
412 * into the allocator:
414 ret = bch2_disk_reservation_get(c, &disk_res, sectors, new_replicas, 0);
418 bch2_bkey_buf_reassemble(&old, c, k);
421 if (have_reservation) {
422 if (!bch2_extents_match(k, bkey_i_to_s_c(old.k)))
425 bch2_key_resize(&new.k->k, sectors);
426 } else if (!unwritten) {
427 struct bkey_i_reservation *reservation;
429 bch2_bkey_buf_realloc(&new, c, sizeof(*reservation) / sizeof(u64));
430 reservation = bkey_reservation_init(new.k);
431 reservation->k.p = iter->pos;
432 bch2_key_resize(&reservation->k, sectors);
433 reservation->v.nr_replicas = opts.data_replicas;
435 struct bkey_i_extent *e;
436 struct bch_devs_list devs_have;
437 struct write_point *wp;
438 struct bch_extent_ptr *ptr;
442 bch2_bkey_buf_realloc(&new, c, BKEY_EXTENT_U64s_MAX);
444 e = bkey_extent_init(new.k);
447 ret = bch2_alloc_sectors_start_trans(trans,
448 opts.foreground_target,
454 BCH_WATERMARK_normal, 0, &cl, &wp);
456 bch2_trans_unlock(trans);
458 if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
463 sectors = min(sectors, wp->sectors_free);
464 sectors_allocated = sectors;
466 bch2_key_resize(&e->k, sectors);
468 bch2_open_bucket_get(c, wp, &open_buckets);
469 bch2_alloc_sectors_append_ptrs(c, wp, &e->k_i, sectors, false);
470 bch2_alloc_sectors_done(c, wp);
472 extent_for_each_ptr(extent_i_to_s(e), ptr)
473 ptr->unwritten = true;
476 have_reservation = true;
478 ret = bch2_extent_update(trans, inum, iter, new.k, &disk_res,
479 0, i_sectors_delta, true);
481 if ((atomic_read(&cl.remaining) & CLOSURE_REMAINING_MASK) != 1) {
482 bch2_trans_unlock(trans);
486 if (bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
487 bch2_trans_begin(trans);
491 if (!ret && sectors_allocated)
492 bch2_increment_clock(c, sectors_allocated, WRITE);
494 bch2_open_buckets_put(c, &open_buckets);
495 bch2_disk_reservation_put(c, &disk_res);
496 bch2_bkey_buf_exit(&new, c);
497 bch2_bkey_buf_exit(&old, c);
503 * Returns -BCH_ERR_transacton_restart if we had to drop locks:
505 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
506 subvol_inum inum, u64 end,
507 s64 *i_sectors_delta)
509 struct bch_fs *c = trans->c;
510 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
511 struct bpos end_pos = POS(inum.inum, end);
513 int ret = 0, ret2 = 0;
517 bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
518 struct disk_reservation disk_res =
519 bch2_disk_reservation_init(c, 0);
520 struct bkey_i delete;
525 bch2_trans_begin(trans);
527 ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
531 bch2_btree_iter_set_snapshot(iter, snapshot);
534 * peek_upto() doesn't have ideal semantics for extents:
536 k = bch2_btree_iter_peek_upto(iter, end_pos);
544 bkey_init(&delete.k);
545 delete.k.p = iter->pos;
547 /* create the biggest key we can */
548 bch2_key_resize(&delete.k, max_sectors);
549 bch2_cut_back(end_pos, &delete);
551 ret = bch2_extent_update(trans, inum, iter, &delete,
552 &disk_res, 0, i_sectors_delta, false);
553 bch2_disk_reservation_put(c, &disk_res);
559 int bch2_fpunch(struct bch_fs *c, subvol_inum inum, u64 start, u64 end,
560 s64 *i_sectors_delta)
562 struct btree_trans trans;
563 struct btree_iter iter;
566 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
567 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
568 POS(inum.inum, start),
571 ret = bch2_fpunch_at(&trans, &iter, inum, end, i_sectors_delta);
573 bch2_trans_iter_exit(&trans, &iter);
574 bch2_trans_exit(&trans);
576 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
582 static int bch2_write_index_default(struct bch_write_op *op)
584 struct bch_fs *c = op->c;
586 struct keylist *keys = &op->insert_keys;
587 struct bkey_i *k = bch2_keylist_front(keys);
588 struct btree_trans trans;
589 struct btree_iter iter;
591 .subvol = op->subvol,
592 .inum = k->k.p.inode,
596 BUG_ON(!inum.subvol);
598 bch2_bkey_buf_init(&sk);
599 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
602 bch2_trans_begin(&trans);
604 k = bch2_keylist_front(keys);
605 bch2_bkey_buf_copy(&sk, c, k);
607 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol,
608 &sk.k->k.p.snapshot);
609 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
614 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
615 bkey_start_pos(&sk.k->k),
616 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
618 ret = bch2_extent_update(&trans, inum, &iter, sk.k,
620 op->new_i_size, &op->i_sectors_delta,
621 op->flags & BCH_WRITE_CHECK_ENOSPC);
622 bch2_trans_iter_exit(&trans, &iter);
624 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
629 if (bkey_ge(iter.pos, k->k.p))
630 bch2_keylist_pop_front(&op->insert_keys);
632 bch2_cut_front(iter.pos, k);
633 } while (!bch2_keylist_empty(keys));
635 bch2_trans_exit(&trans);
636 bch2_bkey_buf_exit(&sk, c);
643 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
644 enum bch_data_type type,
645 const struct bkey_i *k,
648 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
649 const struct bch_extent_ptr *ptr;
650 struct bch_write_bio *n;
653 BUG_ON(c->opts.nochanges);
655 bkey_for_each_ptr(ptrs, ptr) {
656 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
659 ca = bch_dev_bkey_exists(c, ptr->dev);
661 if (to_entry(ptr + 1) < ptrs.end) {
662 n = to_wbio(bio_alloc_clone(NULL, &wbio->bio,
663 GFP_NOFS, &ca->replica_set));
665 n->bio.bi_end_io = wbio->bio.bi_end_io;
666 n->bio.bi_private = wbio->bio.bi_private;
671 n->bio.bi_opf = wbio->bio.bi_opf;
672 bio_inc_remaining(&wbio->bio);
680 n->have_ioref = nocow || bch2_dev_get_ioref(ca,
681 type == BCH_DATA_btree ? READ : WRITE);
683 n->submit_time = local_clock();
684 n->inode_offset = bkey_start_offset(&k->k);
685 n->bio.bi_iter.bi_sector = ptr->offset;
687 if (likely(n->have_ioref)) {
688 this_cpu_add(ca->io_done->sectors[WRITE][type],
689 bio_sectors(&n->bio));
691 bio_set_dev(&n->bio, ca->disk_sb.bdev);
693 if (type != BCH_DATA_btree && unlikely(c->opts.no_data_io)) {
700 n->bio.bi_status = BLK_STS_REMOVED;
706 static void __bch2_write(struct bch_write_op *);
708 static void bch2_write_done(struct closure *cl)
710 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
711 struct bch_fs *c = op->c;
713 bch2_disk_reservation_put(c, &op->res);
714 if (!(op->flags & BCH_WRITE_MOVE))
715 bch2_write_ref_put(c, BCH_WRITE_REF_write);
716 bch2_keylist_free(&op->insert_keys, op->inline_keys);
718 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
721 closure_debug_destroy(cl);
726 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
728 struct keylist *keys = &op->insert_keys;
729 struct bch_extent_ptr *ptr;
730 struct bkey_i *src, *dst = keys->keys, *n;
732 for (src = keys->keys; src != keys->top; src = n) {
735 if (bkey_extent_is_direct_data(&src->k)) {
736 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
737 test_bit(ptr->dev, op->failed.d));
739 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
744 memmove_u64s_down(dst, src, src->k.u64s);
745 dst = bkey_next(dst);
753 * bch_write_index - after a write, update index to point to new data
755 static void __bch2_write_index(struct bch_write_op *op)
757 struct bch_fs *c = op->c;
758 struct keylist *keys = &op->insert_keys;
763 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
764 ret = bch2_write_drop_io_error_ptrs(op);
770 * probably not the ideal place to hook this in, but I don't
771 * particularly want to plumb io_opts all the way through the btree
772 * update stack right now
774 for_each_keylist_key(keys, k)
775 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
777 if (!bch2_keylist_empty(keys)) {
778 u64 sectors_start = keylist_sectors(keys);
780 ret = !(op->flags & BCH_WRITE_MOVE)
781 ? bch2_write_index_default(op)
782 : bch2_data_update_index_update(op);
784 BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
785 BUG_ON(keylist_sectors(keys) && !ret);
787 op->written += sectors_start - keylist_sectors(keys);
789 if (ret && !bch2_err_matches(ret, EROFS)) {
790 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
792 bch_err_inum_offset_ratelimited(c,
793 k->k.p.inode, k->k.p.offset << 9,
794 "write error while doing btree update: %s",
802 /* If some a bucket wasn't written, we can't erasure code it: */
803 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
804 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
806 bch2_open_buckets_put(c, &op->open_buckets);
809 keys->top = keys->keys;
811 op->flags |= BCH_WRITE_DONE;
815 static inline void __wp_update_state(struct write_point *wp, enum write_point_state state)
817 if (state != wp->state) {
818 u64 now = ktime_get_ns();
820 if (wp->last_state_change &&
821 time_after64(now, wp->last_state_change))
822 wp->time[wp->state] += now - wp->last_state_change;
824 wp->last_state_change = now;
828 static inline void wp_update_state(struct write_point *wp, bool running)
830 enum write_point_state state;
832 state = running ? WRITE_POINT_running :
833 !list_empty(&wp->writes) ? WRITE_POINT_waiting_io
834 : WRITE_POINT_stopped;
836 __wp_update_state(wp, state);
839 static void bch2_write_index(struct closure *cl)
841 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
842 struct write_point *wp = op->wp;
843 struct workqueue_struct *wq = index_update_wq(op);
846 if ((op->flags & BCH_WRITE_DONE) &&
847 (op->flags & BCH_WRITE_MOVE))
848 bch2_bio_free_pages_pool(op->c, &op->wbio.bio);
850 spin_lock_irqsave(&wp->writes_lock, flags);
851 if (wp->state == WRITE_POINT_waiting_io)
852 __wp_update_state(wp, WRITE_POINT_waiting_work);
853 list_add_tail(&op->wp_list, &wp->writes);
854 spin_unlock_irqrestore (&wp->writes_lock, flags);
856 queue_work(wq, &wp->index_update_work);
859 static inline void bch2_write_queue(struct bch_write_op *op, struct write_point *wp)
863 if (wp->state == WRITE_POINT_stopped) {
864 spin_lock_irq(&wp->writes_lock);
865 __wp_update_state(wp, WRITE_POINT_waiting_io);
866 spin_unlock_irq(&wp->writes_lock);
870 void bch2_write_point_do_index_updates(struct work_struct *work)
872 struct write_point *wp =
873 container_of(work, struct write_point, index_update_work);
874 struct bch_write_op *op;
877 spin_lock_irq(&wp->writes_lock);
878 op = list_first_entry_or_null(&wp->writes, struct bch_write_op, wp_list);
880 list_del(&op->wp_list);
881 wp_update_state(wp, op != NULL);
882 spin_unlock_irq(&wp->writes_lock);
887 op->flags |= BCH_WRITE_IN_WORKER;
889 __bch2_write_index(op);
891 if (!(op->flags & BCH_WRITE_DONE))
894 bch2_write_done(&op->cl);
898 static void bch2_write_endio(struct bio *bio)
900 struct closure *cl = bio->bi_private;
901 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
902 struct bch_write_bio *wbio = to_wbio(bio);
903 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
904 struct bch_fs *c = wbio->c;
905 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
907 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
909 wbio->inode_offset << 9,
910 "data write error: %s",
911 bch2_blk_status_to_str(bio->bi_status))) {
912 set_bit(wbio->dev, op->failed.d);
913 op->flags |= BCH_WRITE_IO_ERROR;
917 set_bit(wbio->dev, op->devs_need_flush->d);
919 if (wbio->have_ioref) {
920 bch2_latency_acct(ca, wbio->submit_time, WRITE);
921 percpu_ref_put(&ca->io_ref);
925 bch2_bio_free_pages_pool(c, bio);
931 bio_endio(&parent->bio);
936 static void init_append_extent(struct bch_write_op *op,
937 struct write_point *wp,
938 struct bversion version,
939 struct bch_extent_crc_unpacked crc)
941 struct bkey_i_extent *e;
943 op->pos.offset += crc.uncompressed_size;
945 e = bkey_extent_init(op->insert_keys.top);
947 e->k.size = crc.uncompressed_size;
948 e->k.version = version;
951 crc.compression_type ||
953 bch2_extent_crc_append(&e->k_i, crc);
955 bch2_alloc_sectors_append_ptrs_inlined(op->c, wp, &e->k_i, crc.compressed_size,
956 op->flags & BCH_WRITE_CACHED);
958 bch2_keylist_push(&op->insert_keys);
961 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
962 struct write_point *wp,
964 bool *page_alloc_failed,
967 struct bch_write_bio *wbio;
969 unsigned output_available =
970 min(wp->sectors_free << 9, src->bi_iter.bi_size);
971 unsigned pages = DIV_ROUND_UP(output_available +
973 ? ((unsigned long) buf & (PAGE_SIZE - 1))
976 pages = min(pages, BIO_MAX_VECS);
978 bio = bio_alloc_bioset(NULL, pages, 0,
979 GFP_NOFS, &c->bio_write);
980 wbio = wbio_init(bio);
981 wbio->put_bio = true;
982 /* copy WRITE_SYNC flag */
983 wbio->bio.bi_opf = src->bi_opf;
986 bch2_bio_map(bio, buf, output_available);
993 * We can't use mempool for more than c->sb.encoded_extent_max
994 * worth of pages, but we'd like to allocate more if we can:
996 bch2_bio_alloc_pages_pool(c, bio,
997 min_t(unsigned, output_available,
998 c->opts.encoded_extent_max));
1000 if (bio->bi_iter.bi_size < output_available)
1001 *page_alloc_failed =
1002 bch2_bio_alloc_pages(bio,
1004 bio->bi_iter.bi_size,
1010 static int bch2_write_rechecksum(struct bch_fs *c,
1011 struct bch_write_op *op,
1012 unsigned new_csum_type)
1014 struct bio *bio = &op->wbio.bio;
1015 struct bch_extent_crc_unpacked new_crc;
1018 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
1020 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
1021 bch2_csum_type_is_encryption(new_csum_type))
1022 new_csum_type = op->crc.csum_type;
1024 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
1026 op->crc.offset, op->crc.live_size,
1031 bio_advance(bio, op->crc.offset << 9);
1032 bio->bi_iter.bi_size = op->crc.live_size << 9;
1037 static int bch2_write_decrypt(struct bch_write_op *op)
1039 struct bch_fs *c = op->c;
1040 struct nonce nonce = extent_nonce(op->version, op->crc);
1041 struct bch_csum csum;
1044 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
1048 * If we need to decrypt data in the write path, we'll no longer be able
1049 * to verify the existing checksum (poly1305 mac, in this case) after
1050 * it's decrypted - this is the last point we'll be able to reverify the
1053 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
1054 if (bch2_crc_cmp(op->crc.csum, csum))
1057 ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
1058 op->crc.csum_type = 0;
1059 op->crc.csum = (struct bch_csum) { 0, 0 };
1063 static enum prep_encoded_ret {
1066 PREP_ENCODED_CHECKSUM_ERR,
1067 PREP_ENCODED_DO_WRITE,
1068 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
1070 struct bch_fs *c = op->c;
1071 struct bio *bio = &op->wbio.bio;
1073 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
1074 return PREP_ENCODED_OK;
1076 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
1078 /* Can we just write the entire extent as is? */
1079 if (op->crc.uncompressed_size == op->crc.live_size &&
1080 op->crc.compressed_size <= wp->sectors_free &&
1081 (op->crc.compression_type == bch2_compression_opt_to_type(op->compression_opt) ||
1082 op->incompressible)) {
1083 if (!crc_is_compressed(op->crc) &&
1084 op->csum_type != op->crc.csum_type &&
1085 bch2_write_rechecksum(c, op, op->csum_type) &&
1086 !c->opts.no_data_io)
1087 return PREP_ENCODED_CHECKSUM_ERR;
1089 return PREP_ENCODED_DO_WRITE;
1093 * If the data is compressed and we couldn't write the entire extent as
1094 * is, we have to decompress it:
1096 if (crc_is_compressed(op->crc)) {
1097 struct bch_csum csum;
1099 if (bch2_write_decrypt(op))
1100 return PREP_ENCODED_CHECKSUM_ERR;
1102 /* Last point we can still verify checksum: */
1103 csum = bch2_checksum_bio(c, op->crc.csum_type,
1104 extent_nonce(op->version, op->crc),
1106 if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
1107 return PREP_ENCODED_CHECKSUM_ERR;
1109 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
1110 return PREP_ENCODED_ERR;
1114 * No longer have compressed data after this point - data might be
1119 * If the data is checksummed and we're only writing a subset,
1120 * rechecksum and adjust bio to point to currently live data:
1122 if ((op->crc.live_size != op->crc.uncompressed_size ||
1123 op->crc.csum_type != op->csum_type) &&
1124 bch2_write_rechecksum(c, op, op->csum_type) &&
1125 !c->opts.no_data_io)
1126 return PREP_ENCODED_CHECKSUM_ERR;
1129 * If we want to compress the data, it has to be decrypted:
1131 if ((op->compression_opt ||
1132 bch2_csum_type_is_encryption(op->crc.csum_type) !=
1133 bch2_csum_type_is_encryption(op->csum_type)) &&
1134 bch2_write_decrypt(op))
1135 return PREP_ENCODED_CHECKSUM_ERR;
1137 return PREP_ENCODED_OK;
1140 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
1143 struct bch_fs *c = op->c;
1144 struct bio *src = &op->wbio.bio, *dst = src;
1145 struct bvec_iter saved_iter;
1147 unsigned total_output = 0, total_input = 0;
1148 bool bounce = false;
1149 bool page_alloc_failed = false;
1152 BUG_ON(!bio_sectors(src));
1154 ec_buf = bch2_writepoint_ec_buf(c, wp);
1156 switch (bch2_write_prep_encoded_data(op, wp)) {
1157 case PREP_ENCODED_OK:
1159 case PREP_ENCODED_ERR:
1162 case PREP_ENCODED_CHECKSUM_ERR:
1164 case PREP_ENCODED_DO_WRITE:
1165 /* XXX look for bug here */
1167 dst = bch2_write_bio_alloc(c, wp, src,
1170 bio_copy_data(dst, src);
1173 init_append_extent(op, wp, op->version, op->crc);
1178 op->compression_opt ||
1180 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
1181 (bch2_csum_type_is_encryption(op->csum_type) &&
1182 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
1183 dst = bch2_write_bio_alloc(c, wp, src,
1189 saved_iter = dst->bi_iter;
1192 struct bch_extent_crc_unpacked crc = { 0 };
1193 struct bversion version = op->version;
1194 size_t dst_len, src_len;
1196 if (page_alloc_failed &&
1197 dst->bi_iter.bi_size < (wp->sectors_free << 9) &&
1198 dst->bi_iter.bi_size < c->opts.encoded_extent_max)
1201 BUG_ON(op->compression_opt &&
1202 (op->flags & BCH_WRITE_DATA_ENCODED) &&
1203 bch2_csum_type_is_encryption(op->crc.csum_type));
1204 BUG_ON(op->compression_opt && !bounce);
1206 crc.compression_type = op->incompressible
1207 ? BCH_COMPRESSION_TYPE_incompressible
1208 : op->compression_opt
1209 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
1210 op->compression_opt)
1212 if (!crc_is_compressed(crc)) {
1213 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
1214 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
1217 dst_len = min_t(unsigned, dst_len,
1218 c->opts.encoded_extent_max);
1221 swap(dst->bi_iter.bi_size, dst_len);
1222 bio_copy_data(dst, src);
1223 swap(dst->bi_iter.bi_size, dst_len);
1229 BUG_ON(!src_len || !dst_len);
1231 if (bch2_csum_type_is_encryption(op->csum_type)) {
1232 if (bversion_zero(version)) {
1233 version.lo = atomic64_inc_return(&c->key_version);
1235 crc.nonce = op->nonce;
1236 op->nonce += src_len >> 9;
1240 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1241 !crc_is_compressed(crc) &&
1242 bch2_csum_type_is_encryption(op->crc.csum_type) ==
1243 bch2_csum_type_is_encryption(op->csum_type)) {
1244 u8 compression_type = crc.compression_type;
1245 u16 nonce = crc.nonce;
1247 * Note: when we're using rechecksum(), we need to be
1248 * checksumming @src because it has all the data our
1249 * existing checksum covers - if we bounced (because we
1250 * were trying to compress), @dst will only have the
1251 * part of the data the new checksum will cover.
1253 * But normally we want to be checksumming post bounce,
1254 * because part of the reason for bouncing is so the
1255 * data can't be modified (by userspace) while it's in
1258 if (bch2_rechecksum_bio(c, src, version, op->crc,
1261 bio_sectors(src) - (src_len >> 9),
1265 * rchecksum_bio sets compression_type on crc from op->crc,
1266 * this isn't always correct as sometimes we're changing
1267 * an extent from uncompressed to incompressible.
1269 crc.compression_type = compression_type;
1272 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1273 bch2_rechecksum_bio(c, src, version, op->crc,
1276 bio_sectors(src) - (src_len >> 9),
1280 crc.compressed_size = dst_len >> 9;
1281 crc.uncompressed_size = src_len >> 9;
1282 crc.live_size = src_len >> 9;
1284 swap(dst->bi_iter.bi_size, dst_len);
1285 ret = bch2_encrypt_bio(c, op->csum_type,
1286 extent_nonce(version, crc), dst);
1290 crc.csum = bch2_checksum_bio(c, op->csum_type,
1291 extent_nonce(version, crc), dst);
1292 crc.csum_type = op->csum_type;
1293 swap(dst->bi_iter.bi_size, dst_len);
1296 init_append_extent(op, wp, version, crc);
1299 bio_advance(dst, dst_len);
1300 bio_advance(src, src_len);
1301 total_output += dst_len;
1302 total_input += src_len;
1303 } while (dst->bi_iter.bi_size &&
1304 src->bi_iter.bi_size &&
1306 !bch2_keylist_realloc(&op->insert_keys,
1308 ARRAY_SIZE(op->inline_keys),
1309 BKEY_EXTENT_U64s_MAX));
1311 more = src->bi_iter.bi_size != 0;
1313 dst->bi_iter = saved_iter;
1315 if (dst == src && more) {
1316 BUG_ON(total_output != total_input);
1318 dst = bio_split(src, total_input >> 9,
1319 GFP_NOFS, &c->bio_write);
1320 wbio_init(dst)->put_bio = true;
1321 /* copy WRITE_SYNC flag */
1322 dst->bi_opf = src->bi_opf;
1325 dst->bi_iter.bi_size = total_output;
1330 bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1333 if (to_wbio(dst)->bounce)
1334 bch2_bio_free_pages_pool(c, dst);
1335 if (to_wbio(dst)->put_bio)
1341 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1344 struct bch_fs *c = op->c;
1345 struct bkey_s_c_extent e;
1346 struct extent_ptr_decoded p;
1347 const union bch_extent_entry *entry;
1348 unsigned replicas = 0;
1350 if (k.k->type != KEY_TYPE_extent)
1353 e = bkey_s_c_to_extent(k);
1354 extent_for_each_ptr_decode(e, p, entry) {
1355 if (p.crc.csum_type ||
1356 crc_is_compressed(p.crc) ||
1360 replicas += bch2_extent_ptr_durability(c, &p);
1363 return replicas >= op->opts.data_replicas;
1366 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1368 struct bch_fs *c = op->c;
1369 const struct bch_extent_ptr *ptr;
1372 for_each_keylist_key(&op->insert_keys, k) {
1373 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1375 bkey_for_each_ptr(ptrs, ptr)
1376 bch2_bucket_nocow_unlock(&c->nocow_locks,
1377 PTR_BUCKET_POS(c, ptr),
1378 BUCKET_NOCOW_LOCK_UPDATE);
1382 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1383 struct btree_iter *iter,
1384 struct bkey_i *orig,
1389 struct bkey_ptrs ptrs;
1390 struct bch_extent_ptr *ptr;
1393 if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1398 new = bch2_bkey_make_mut_noupdate(trans, k);
1399 ret = PTR_ERR_OR_ZERO(new);
1403 bch2_cut_front(bkey_start_pos(&orig->k), new);
1404 bch2_cut_back(orig->k.p, new);
1406 ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1407 bkey_for_each_ptr(ptrs, ptr)
1411 * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1412 * that was done when we kicked off the write, and here it's important
1413 * that we update the extent that we wrote to - even if a snapshot has
1414 * since been created. The write is still outstanding, so we're ok
1415 * w.r.t. snapshot atomicity:
1417 return bch2_extent_update_i_size_sectors(trans, iter,
1418 min(new->k.p.offset << 9, new_i_size), 0) ?:
1419 bch2_trans_update(trans, iter, new,
1420 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1423 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1425 struct bch_fs *c = op->c;
1426 struct btree_trans trans;
1427 struct btree_iter iter;
1428 struct bkey_i *orig;
1432 bch2_trans_init(&trans, c, 0, 0);
1434 for_each_keylist_key(&op->insert_keys, orig) {
1435 ret = for_each_btree_key_upto_commit(&trans, iter, BTREE_ID_extents,
1436 bkey_start_pos(&orig->k), orig->k.p,
1437 BTREE_ITER_INTENT, k,
1438 NULL, NULL, BTREE_INSERT_NOFAIL, ({
1439 bch2_nocow_write_convert_one_unwritten(&trans, &iter, orig, k, op->new_i_size);
1442 if (ret && !bch2_err_matches(ret, EROFS)) {
1443 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
1445 bch_err_inum_offset_ratelimited(c,
1446 k->k.p.inode, k->k.p.offset << 9,
1447 "write error while doing btree update: %s",
1457 bch2_trans_exit(&trans);
1460 static void __bch2_nocow_write_done(struct bch_write_op *op)
1462 bch2_nocow_write_unlock(op);
1464 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1466 } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1467 bch2_nocow_write_convert_unwritten(op);
1470 static void bch2_nocow_write_done(struct closure *cl)
1472 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1474 __bch2_nocow_write_done(op);
1475 bch2_write_done(cl);
1478 static void bch2_nocow_write(struct bch_write_op *op)
1480 struct bch_fs *c = op->c;
1481 struct btree_trans trans;
1482 struct btree_iter iter;
1484 struct bkey_ptrs_c ptrs;
1485 const struct bch_extent_ptr *ptr;
1489 struct nocow_lock_bucket *l;
1490 } buckets[BCH_REPLICAS_MAX];
1491 unsigned nr_buckets = 0;
1495 if (op->flags & BCH_WRITE_MOVE)
1498 bch2_trans_init(&trans, c, 0, 0);
1500 bch2_trans_begin(&trans);
1502 ret = bch2_subvolume_get_snapshot(&trans, op->subvol, &snapshot);
1506 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1507 SPOS(op->pos.inode, op->pos.offset, snapshot),
1510 struct bio *bio = &op->wbio.bio;
1514 k = bch2_btree_iter_peek_slot(&iter);
1519 /* fall back to normal cow write path? */
1520 if (unlikely(k.k->p.snapshot != snapshot ||
1521 !bch2_extent_is_writeable(op, k)))
1524 if (bch2_keylist_realloc(&op->insert_keys,
1526 ARRAY_SIZE(op->inline_keys),
1530 /* Get iorefs before dropping btree locks: */
1531 ptrs = bch2_bkey_ptrs_c(k);
1532 bkey_for_each_ptr(ptrs, ptr) {
1533 buckets[nr_buckets].b = PTR_BUCKET_POS(c, ptr);
1534 buckets[nr_buckets].gen = ptr->gen;
1535 buckets[nr_buckets].l =
1536 bucket_nocow_lock(&c->nocow_locks,
1537 bucket_to_u64(buckets[nr_buckets].b));
1539 prefetch(buckets[nr_buckets].l);
1541 if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1547 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1550 /* Unlock before taking nocow locks, doing IO: */
1551 bkey_reassemble(op->insert_keys.top, k);
1552 bch2_trans_unlock(&trans);
1554 bch2_cut_front(op->pos, op->insert_keys.top);
1555 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1556 bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1558 for (i = 0; i < nr_buckets; i++) {
1559 struct bch_dev *ca = bch_dev_bkey_exists(c, buckets[i].b.inode);
1560 struct nocow_lock_bucket *l = buckets[i].l;
1563 __bch2_bucket_nocow_lock(&c->nocow_locks, l,
1564 bucket_to_u64(buckets[i].b),
1565 BUCKET_NOCOW_LOCK_UPDATE);
1568 stale = gen_after(*bucket_gen(ca, buckets[i].b.offset), buckets[i].gen);
1571 if (unlikely(stale))
1572 goto err_bucket_stale;
1575 bio = &op->wbio.bio;
1576 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1577 bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1578 GFP_KERNEL, &c->bio_write);
1579 wbio_init(bio)->put_bio = true;
1580 bio->bi_opf = op->wbio.bio.bi_opf;
1582 op->flags |= BCH_WRITE_DONE;
1585 op->pos.offset += bio_sectors(bio);
1586 op->written += bio_sectors(bio);
1588 bio->bi_end_io = bch2_write_endio;
1589 bio->bi_private = &op->cl;
1590 bio->bi_opf |= REQ_OP_WRITE;
1591 closure_get(&op->cl);
1592 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1593 op->insert_keys.top, true);
1595 bch2_keylist_push(&op->insert_keys);
1596 if (op->flags & BCH_WRITE_DONE)
1598 bch2_btree_iter_advance(&iter);
1601 bch2_trans_iter_exit(&trans, &iter);
1603 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1607 bch_err_inum_offset_ratelimited(c,
1609 op->pos.offset << 9,
1610 "%s: btree lookup error %s",
1611 __func__, bch2_err_str(ret));
1613 op->flags |= BCH_WRITE_DONE;
1616 bch2_trans_exit(&trans);
1618 /* fallback to cow write path? */
1619 if (!(op->flags & BCH_WRITE_DONE)) {
1620 closure_sync(&op->cl);
1621 __bch2_nocow_write_done(op);
1622 op->insert_keys.top = op->insert_keys.keys;
1623 } else if (op->flags & BCH_WRITE_SYNC) {
1624 closure_sync(&op->cl);
1625 bch2_nocow_write_done(&op->cl);
1629 * needs to run out of process context because ei_quota_lock is
1632 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1636 for (i = 0; i < nr_buckets; i++)
1637 percpu_ref_put(&bch_dev_bkey_exists(c, buckets[i].b.inode)->io_ref);
1639 /* Fall back to COW path: */
1643 bch2_bucket_nocow_unlock(&c->nocow_locks,
1645 BUCKET_NOCOW_LOCK_UPDATE);
1646 for (i = 0; i < nr_buckets; i++)
1647 percpu_ref_put(&bch_dev_bkey_exists(c, buckets[i].b.inode)->io_ref);
1649 /* We can retry this: */
1650 ret = -BCH_ERR_transaction_restart;
1654 static void __bch2_write(struct bch_write_op *op)
1656 struct bch_fs *c = op->c;
1657 struct write_point *wp = NULL;
1658 struct bio *bio = NULL;
1659 unsigned nofs_flags;
1662 nofs_flags = memalloc_nofs_save();
1664 if (unlikely(op->opts.nocow && c->opts.nocow_enabled)) {
1665 bch2_nocow_write(op);
1666 if (op->flags & BCH_WRITE_DONE)
1667 goto out_nofs_restore;
1670 memset(&op->failed, 0, sizeof(op->failed));
1673 struct bkey_i *key_to_write;
1674 unsigned key_to_write_offset = op->insert_keys.top_p -
1675 op->insert_keys.keys_p;
1677 /* +1 for possible cache device: */
1678 if (op->open_buckets.nr + op->nr_replicas + 1 >
1679 ARRAY_SIZE(op->open_buckets.v))
1682 if (bch2_keylist_realloc(&op->insert_keys,
1684 ARRAY_SIZE(op->inline_keys),
1685 BKEY_EXTENT_U64s_MAX))
1689 * The copygc thread is now global, which means it's no longer
1690 * freeing up space on specific disks, which means that
1691 * allocations for specific disks may hang arbitrarily long:
1693 ret = bch2_trans_do(c, NULL, NULL, 0,
1694 bch2_alloc_sectors_start_trans(&trans,
1696 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1700 op->nr_replicas_required,
1703 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1704 BCH_WRITE_ONLY_SPECIFIED_DEVS))
1705 ? NULL : &op->cl, &wp));
1706 if (unlikely(ret)) {
1707 if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1715 bch2_open_bucket_get(c, wp, &op->open_buckets);
1716 ret = bch2_write_extent(op, wp, &bio);
1718 bch2_alloc_sectors_done_inlined(c, wp);
1721 op->flags |= BCH_WRITE_DONE;
1729 bio->bi_end_io = bch2_write_endio;
1730 bio->bi_private = &op->cl;
1731 bio->bi_opf |= REQ_OP_WRITE;
1733 closure_get(bio->bi_private);
1735 key_to_write = (void *) (op->insert_keys.keys_p +
1736 key_to_write_offset);
1738 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1739 key_to_write, false);
1745 * If we're running asynchronously, wne may still want to block
1746 * synchronously here if we weren't able to submit all of the IO at
1747 * once, as that signals backpressure to the caller.
1749 if ((op->flags & BCH_WRITE_SYNC) ||
1750 (!(op->flags & BCH_WRITE_DONE) &&
1751 !(op->flags & BCH_WRITE_IN_WORKER))) {
1752 closure_sync(&op->cl);
1753 __bch2_write_index(op);
1755 if (!(op->flags & BCH_WRITE_DONE))
1757 bch2_write_done(&op->cl);
1759 bch2_write_queue(op, wp);
1760 continue_at(&op->cl, bch2_write_index, NULL);
1763 memalloc_nofs_restore(nofs_flags);
1766 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1768 struct bio *bio = &op->wbio.bio;
1769 struct bvec_iter iter;
1770 struct bkey_i_inline_data *id;
1774 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1775 op->flags |= BCH_WRITE_DONE;
1777 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1779 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1780 ARRAY_SIZE(op->inline_keys),
1781 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1787 sectors = bio_sectors(bio);
1788 op->pos.offset += sectors;
1790 id = bkey_inline_data_init(op->insert_keys.top);
1792 id->k.version = op->version;
1793 id->k.size = sectors;
1795 iter = bio->bi_iter;
1796 iter.bi_size = data_len;
1797 memcpy_from_bio(id->v.data, bio, iter);
1799 while (data_len & 7)
1800 id->v.data[data_len++] = '\0';
1801 set_bkey_val_bytes(&id->k, data_len);
1802 bch2_keylist_push(&op->insert_keys);
1804 __bch2_write_index(op);
1806 bch2_write_done(&op->cl);
1810 * bch_write - handle a write to a cache device or flash only volume
1812 * This is the starting point for any data to end up in a cache device; it could
1813 * be from a normal write, or a writeback write, or a write to a flash only
1814 * volume - it's also used by the moving garbage collector to compact data in
1815 * mostly empty buckets.
1817 * It first writes the data to the cache, creating a list of keys to be inserted
1818 * (if the data won't fit in a single open bucket, there will be multiple keys);
1819 * after the data is written it calls bch_journal, and after the keys have been
1820 * added to the next journal write they're inserted into the btree.
1822 * If op->discard is true, instead of inserting the data it invalidates the
1823 * region of the cache represented by op->bio and op->inode.
1825 void bch2_write(struct closure *cl)
1827 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1828 struct bio *bio = &op->wbio.bio;
1829 struct bch_fs *c = op->c;
1832 EBUG_ON(op->cl.parent);
1833 BUG_ON(!op->nr_replicas);
1834 BUG_ON(!op->write_point.v);
1835 BUG_ON(bkey_eq(op->pos, POS_MAX));
1837 op->start_time = local_clock();
1838 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1839 wbio_init(bio)->put_bio = false;
1841 if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1842 bch_err_inum_offset_ratelimited(c,
1844 op->pos.offset << 9,
1845 "misaligned write");
1850 if (c->opts.nochanges) {
1851 op->error = -BCH_ERR_erofs_no_writes;
1855 if (!(op->flags & BCH_WRITE_MOVE) &&
1856 !bch2_write_ref_tryget(c, BCH_WRITE_REF_write)) {
1857 op->error = -BCH_ERR_erofs_no_writes;
1861 this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1862 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1864 data_len = min_t(u64, bio->bi_iter.bi_size,
1865 op->new_i_size - (op->pos.offset << 9));
1867 if (c->opts.inline_data &&
1868 data_len <= min(block_bytes(c) / 2, 1024U)) {
1869 bch2_write_data_inline(op, data_len);
1876 bch2_disk_reservation_put(c, &op->res);
1878 closure_debug_destroy(&op->cl);
1883 static const char * const bch2_write_flags[] = {
1890 void bch2_write_op_to_text(struct printbuf *out, struct bch_write_op *op)
1892 prt_str(out, "pos: ");
1893 bch2_bpos_to_text(out, op->pos);
1895 printbuf_indent_add(out, 2);
1897 prt_str(out, "started: ");
1898 bch2_pr_time_units(out, local_clock() - op->start_time);
1901 prt_str(out, "flags: ");
1902 prt_bitflags(out, bch2_write_flags, op->flags);
1905 prt_printf(out, "ref: %u", closure_nr_remaining(&op->cl));
1908 printbuf_indent_sub(out, 2);
1911 /* Cache promotion on read */
1914 struct rcu_head rcu;
1917 struct rhash_head hash;
1920 struct data_update write;
1921 struct bio_vec bi_inline_vecs[0]; /* must be last */
1924 static const struct rhashtable_params bch_promote_params = {
1925 .head_offset = offsetof(struct promote_op, hash),
1926 .key_offset = offsetof(struct promote_op, pos),
1927 .key_len = sizeof(struct bpos),
1930 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1932 struct bch_io_opts opts,
1935 if (!(flags & BCH_READ_MAY_PROMOTE))
1938 if (!opts.promote_target)
1941 if (bch2_bkey_has_target(c, k, opts.promote_target))
1944 if (bkey_extent_is_unwritten(k))
1947 if (bch2_target_congested(c, opts.promote_target)) {
1948 /* XXX trace this */
1952 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1953 bch_promote_params))
1959 static void promote_free(struct bch_fs *c, struct promote_op *op)
1963 bch2_data_update_exit(&op->write);
1965 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1966 bch_promote_params);
1968 bch2_write_ref_put(c, BCH_WRITE_REF_promote);
1972 static void promote_done(struct bch_write_op *wop)
1974 struct promote_op *op =
1975 container_of(wop, struct promote_op, write.op);
1976 struct bch_fs *c = op->write.op.c;
1978 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1980 promote_free(c, op);
1983 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1985 struct bio *bio = &op->write.op.wbio.bio;
1987 trace_and_count(op->write.op.c, read_promote, &rbio->bio);
1989 /* we now own pages: */
1990 BUG_ON(!rbio->bounce);
1991 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1993 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1994 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1995 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1997 bch2_data_update_read_done(&op->write, rbio->pick.crc);
2000 static struct promote_op *__promote_alloc(struct btree_trans *trans,
2001 enum btree_id btree_id,
2004 struct extent_ptr_decoded *pick,
2005 struct bch_io_opts opts,
2007 struct bch_read_bio **rbio)
2009 struct bch_fs *c = trans->c;
2010 struct promote_op *op = NULL;
2012 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
2015 if (!bch2_write_ref_tryget(c, BCH_WRITE_REF_promote))
2018 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOFS);
2022 op->start_time = local_clock();
2026 * We don't use the mempool here because extents that aren't
2027 * checksummed or compressed can be too big for the mempool:
2029 *rbio = kzalloc(sizeof(struct bch_read_bio) +
2030 sizeof(struct bio_vec) * pages,
2035 rbio_init(&(*rbio)->bio, opts);
2036 bio_init(&(*rbio)->bio, NULL, (*rbio)->bio.bi_inline_vecs, pages, 0);
2038 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
2042 (*rbio)->bounce = true;
2043 (*rbio)->split = true;
2044 (*rbio)->kmalloc = true;
2046 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
2047 bch_promote_params))
2050 bio = &op->write.op.wbio.bio;
2051 bio_init(bio, NULL, bio->bi_inline_vecs, pages, 0);
2053 ret = bch2_data_update_init(trans, NULL, &op->write,
2054 writepoint_hashed((unsigned long) current),
2056 (struct data_update_opts) {
2057 .target = opts.promote_target,
2058 .extra_replicas = 1,
2059 .write_flags = BCH_WRITE_ALLOC_NOWAIT|BCH_WRITE_CACHED,
2063 * possible errors: -BCH_ERR_nocow_lock_blocked,
2064 * -BCH_ERR_ENOSPC_disk_reservation:
2067 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
2068 bch_promote_params);
2073 op->write.op.end_io = promote_done;
2078 bio_free_pages(&(*rbio)->bio);
2082 bch2_write_ref_put(c, BCH_WRITE_REF_promote);
2087 static struct promote_op *promote_alloc(struct btree_trans *trans,
2088 struct bvec_iter iter,
2090 struct extent_ptr_decoded *pick,
2091 struct bch_io_opts opts,
2093 struct bch_read_bio **rbio,
2097 struct bch_fs *c = trans->c;
2098 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
2099 /* data might have to be decompressed in the write path: */
2100 unsigned sectors = promote_full
2101 ? max(pick->crc.compressed_size, pick->crc.live_size)
2102 : bvec_iter_sectors(iter);
2103 struct bpos pos = promote_full
2104 ? bkey_start_pos(k.k)
2105 : POS(k.k->p.inode, iter.bi_sector);
2106 struct promote_op *promote;
2108 if (!should_promote(c, k, pos, opts, flags))
2111 promote = __promote_alloc(trans,
2112 k.k->type == KEY_TYPE_reflink_v
2115 k, pos, pick, opts, sectors, rbio);
2120 *read_full = promote_full;
2126 #define READ_RETRY_AVOID 1
2127 #define READ_RETRY 2
2132 RBIO_CONTEXT_HIGHPRI,
2133 RBIO_CONTEXT_UNBOUND,
2136 static inline struct bch_read_bio *
2137 bch2_rbio_parent(struct bch_read_bio *rbio)
2139 return rbio->split ? rbio->parent : rbio;
2143 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
2144 enum rbio_context context,
2145 struct workqueue_struct *wq)
2147 if (context <= rbio->context) {
2150 rbio->work.func = fn;
2151 rbio->context = context;
2152 queue_work(wq, &rbio->work);
2156 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
2158 BUG_ON(rbio->bounce && !rbio->split);
2161 promote_free(rbio->c, rbio->promote);
2162 rbio->promote = NULL;
2165 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
2168 struct bch_read_bio *parent = rbio->parent;
2173 bio_put(&rbio->bio);
2182 * Only called on a top level bch_read_bio to complete an entire read request,
2185 static void bch2_rbio_done(struct bch_read_bio *rbio)
2187 if (rbio->start_time)
2188 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
2190 bio_endio(&rbio->bio);
2193 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
2194 struct bvec_iter bvec_iter,
2195 struct bch_io_failures *failed,
2198 struct btree_trans trans;
2199 struct btree_iter iter;
2204 flags &= ~BCH_READ_LAST_FRAGMENT;
2205 flags |= BCH_READ_MUST_CLONE;
2207 bch2_bkey_buf_init(&sk);
2208 bch2_trans_init(&trans, c, 0, 0);
2210 bch2_trans_iter_init(&trans, &iter, rbio->data_btree,
2211 rbio->read_pos, BTREE_ITER_SLOTS);
2213 rbio->bio.bi_status = 0;
2215 k = bch2_btree_iter_peek_slot(&iter);
2219 bch2_bkey_buf_reassemble(&sk, c, k);
2220 k = bkey_i_to_s_c(sk.k);
2221 bch2_trans_unlock(&trans);
2223 if (!bch2_bkey_matches_ptr(c, k,
2225 rbio->data_pos.offset -
2226 rbio->pick.crc.offset)) {
2227 /* extent we wanted to read no longer exists: */
2232 ret = __bch2_read_extent(&trans, rbio, bvec_iter,
2235 k, 0, failed, flags);
2236 if (ret == READ_RETRY)
2241 bch2_rbio_done(rbio);
2242 bch2_trans_iter_exit(&trans, &iter);
2243 bch2_trans_exit(&trans);
2244 bch2_bkey_buf_exit(&sk, c);
2247 rbio->bio.bi_status = BLK_STS_IOERR;
2251 static void bch2_rbio_retry(struct work_struct *work)
2253 struct bch_read_bio *rbio =
2254 container_of(work, struct bch_read_bio, work);
2255 struct bch_fs *c = rbio->c;
2256 struct bvec_iter iter = rbio->bvec_iter;
2257 unsigned flags = rbio->flags;
2258 subvol_inum inum = {
2259 .subvol = rbio->subvol,
2260 .inum = rbio->read_pos.inode,
2262 struct bch_io_failures failed = { .nr = 0 };
2264 trace_and_count(c, read_retry, &rbio->bio);
2266 if (rbio->retry == READ_RETRY_AVOID)
2267 bch2_mark_io_failure(&failed, &rbio->pick);
2269 rbio->bio.bi_status = 0;
2271 rbio = bch2_rbio_free(rbio);
2273 flags |= BCH_READ_IN_RETRY;
2274 flags &= ~BCH_READ_MAY_PROMOTE;
2276 if (flags & BCH_READ_NODECODE) {
2277 bch2_read_retry_nodecode(c, rbio, iter, &failed, flags);
2279 flags &= ~BCH_READ_LAST_FRAGMENT;
2280 flags |= BCH_READ_MUST_CLONE;
2282 __bch2_read(c, rbio, iter, inum, &failed, flags);
2286 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
2289 rbio->retry = retry;
2291 if (rbio->flags & BCH_READ_IN_RETRY)
2294 if (retry == READ_ERR) {
2295 rbio = bch2_rbio_free(rbio);
2297 rbio->bio.bi_status = error;
2298 bch2_rbio_done(rbio);
2300 bch2_rbio_punt(rbio, bch2_rbio_retry,
2301 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
2305 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
2306 struct bch_read_bio *rbio)
2308 struct bch_fs *c = rbio->c;
2309 u64 data_offset = rbio->data_pos.offset - rbio->pick.crc.offset;
2310 struct bch_extent_crc_unpacked new_crc;
2311 struct btree_iter iter;
2316 if (crc_is_compressed(rbio->pick.crc))
2319 k = bch2_bkey_get_iter(trans, &iter, rbio->data_btree, rbio->data_pos,
2320 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2321 if ((ret = bkey_err(k)))
2324 if (bversion_cmp(k.k->version, rbio->version) ||
2325 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
2328 /* Extent was merged? */
2329 if (bkey_start_offset(k.k) < data_offset ||
2330 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
2333 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
2334 rbio->pick.crc, NULL, &new_crc,
2335 bkey_start_offset(k.k) - data_offset, k.k->size,
2336 rbio->pick.crc.csum_type)) {
2337 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
2343 * going to be temporarily appending another checksum entry:
2345 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
2346 sizeof(struct bch_extent_crc128));
2347 if ((ret = PTR_ERR_OR_ZERO(new)))
2350 bkey_reassemble(new, k);
2352 if (!bch2_bkey_narrow_crcs(new, new_crc))
2355 ret = bch2_trans_update(trans, &iter, new,
2356 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
2358 bch2_trans_iter_exit(trans, &iter);
2362 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
2364 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
2365 __bch2_rbio_narrow_crcs(&trans, rbio));
2368 /* Inner part that may run in process context */
2369 static void __bch2_read_endio(struct work_struct *work)
2371 struct bch_read_bio *rbio =
2372 container_of(work, struct bch_read_bio, work);
2373 struct bch_fs *c = rbio->c;
2374 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2375 struct bio *src = &rbio->bio;
2376 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
2377 struct bvec_iter dst_iter = rbio->bvec_iter;
2378 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
2379 struct nonce nonce = extent_nonce(rbio->version, crc);
2380 unsigned nofs_flags;
2381 struct bch_csum csum;
2384 nofs_flags = memalloc_nofs_save();
2386 /* Reset iterator for checksumming and copying bounced data: */
2388 src->bi_iter.bi_size = crc.compressed_size << 9;
2389 src->bi_iter.bi_idx = 0;
2390 src->bi_iter.bi_bvec_done = 0;
2392 src->bi_iter = rbio->bvec_iter;
2395 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
2396 if (bch2_crc_cmp(csum, rbio->pick.crc.csum) && !c->opts.no_data_io)
2401 * We need to rework the narrow_crcs path to deliver the read completion
2402 * first, and then punt to a different workqueue, otherwise we're
2403 * holding up reads while doing btree updates which is bad for memory
2406 if (unlikely(rbio->narrow_crcs))
2407 bch2_rbio_narrow_crcs(rbio);
2409 if (rbio->flags & BCH_READ_NODECODE)
2412 /* Adjust crc to point to subset of data we want: */
2413 crc.offset += rbio->offset_into_extent;
2414 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
2416 if (crc_is_compressed(crc)) {
2417 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2421 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc) &&
2422 !c->opts.no_data_io)
2423 goto decompression_err;
2425 /* don't need to decrypt the entire bio: */
2426 nonce = nonce_add(nonce, crc.offset << 9);
2427 bio_advance(src, crc.offset << 9);
2429 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
2430 src->bi_iter.bi_size = dst_iter.bi_size;
2432 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2437 struct bvec_iter src_iter = src->bi_iter;
2438 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
2442 if (rbio->promote) {
2444 * Re encrypt data we decrypted, so it's consistent with
2447 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2451 promote_start(rbio->promote, rbio);
2452 rbio->promote = NULL;
2455 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
2456 rbio = bch2_rbio_free(rbio);
2457 bch2_rbio_done(rbio);
2460 memalloc_nofs_restore(nofs_flags);
2464 * Checksum error: if the bio wasn't bounced, we may have been
2465 * reading into buffers owned by userspace (that userspace can
2466 * scribble over) - retry the read, bouncing it this time:
2468 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
2469 rbio->flags |= BCH_READ_MUST_BOUNCE;
2470 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
2474 bch_err_inum_offset_ratelimited(ca,
2475 rbio->read_pos.inode,
2476 rbio->read_pos.offset << 9,
2477 "data checksum error: expected %0llx:%0llx got %0llx:%0llx (type %s)",
2478 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
2479 csum.hi, csum.lo, bch2_csum_types[crc.csum_type]);
2481 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2484 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2485 rbio->read_pos.offset << 9,
2486 "decompression error");
2487 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2490 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2491 rbio->read_pos.offset << 9,
2493 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2497 static void bch2_read_endio(struct bio *bio)
2499 struct bch_read_bio *rbio =
2500 container_of(bio, struct bch_read_bio, bio);
2501 struct bch_fs *c = rbio->c;
2502 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2503 struct workqueue_struct *wq = NULL;
2504 enum rbio_context context = RBIO_CONTEXT_NULL;
2506 if (rbio->have_ioref) {
2507 bch2_latency_acct(ca, rbio->submit_time, READ);
2508 percpu_ref_put(&ca->io_ref);
2512 rbio->bio.bi_end_io = rbio->end_io;
2514 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
2515 rbio->read_pos.inode,
2516 rbio->read_pos.offset,
2517 "data read error: %s",
2518 bch2_blk_status_to_str(bio->bi_status))) {
2519 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
2523 if (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
2524 ptr_stale(ca, &rbio->pick.ptr)) {
2525 trace_and_count(c, read_reuse_race, &rbio->bio);
2527 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
2528 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
2530 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
2534 if (rbio->narrow_crcs ||
2536 crc_is_compressed(rbio->pick.crc) ||
2537 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
2538 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
2539 else if (rbio->pick.crc.csum_type)
2540 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
2542 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
2545 int __bch2_read_indirect_extent(struct btree_trans *trans,
2546 unsigned *offset_into_extent,
2547 struct bkey_buf *orig_k)
2549 struct btree_iter iter;
2554 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
2555 *offset_into_extent;
2557 k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_reflink,
2558 POS(0, reflink_offset), 0);
2563 if (k.k->type != KEY_TYPE_reflink_v &&
2564 k.k->type != KEY_TYPE_indirect_inline_data) {
2565 bch_err_inum_offset_ratelimited(trans->c,
2566 orig_k->k->k.p.inode,
2567 orig_k->k->k.p.offset << 9,
2568 "%llu len %u points to nonexistent indirect extent %llu",
2569 orig_k->k->k.p.offset,
2572 bch2_inconsistent_error(trans->c);
2577 *offset_into_extent = iter.pos.offset - bkey_start_offset(k.k);
2578 bch2_bkey_buf_reassemble(orig_k, trans->c, k);
2580 bch2_trans_iter_exit(trans, &iter);
2584 static noinline void read_from_stale_dirty_pointer(struct btree_trans *trans,
2586 struct bch_extent_ptr ptr)
2588 struct bch_fs *c = trans->c;
2589 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr.dev);
2590 struct btree_iter iter;
2591 struct printbuf buf = PRINTBUF;
2594 bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
2595 PTR_BUCKET_POS(c, &ptr),
2598 prt_printf(&buf, "Attempting to read from stale dirty pointer:");
2599 printbuf_indent_add(&buf, 2);
2602 bch2_bkey_val_to_text(&buf, c, k);
2605 prt_printf(&buf, "memory gen: %u", *bucket_gen(ca, iter.pos.offset));
2607 ret = lockrestart_do(trans, bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
2610 bch2_bkey_val_to_text(&buf, c, k);
2613 bch2_fs_inconsistent(c, "%s", buf.buf);
2615 bch2_trans_iter_exit(trans, &iter);
2616 printbuf_exit(&buf);
2619 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2620 struct bvec_iter iter, struct bpos read_pos,
2621 enum btree_id data_btree, struct bkey_s_c k,
2622 unsigned offset_into_extent,
2623 struct bch_io_failures *failed, unsigned flags)
2625 struct bch_fs *c = trans->c;
2626 struct extent_ptr_decoded pick;
2627 struct bch_read_bio *rbio = NULL;
2628 struct bch_dev *ca = NULL;
2629 struct promote_op *promote = NULL;
2630 bool bounce = false, read_full = false, narrow_crcs = false;
2631 struct bpos data_pos = bkey_start_pos(k.k);
2634 if (bkey_extent_is_inline_data(k.k)) {
2635 unsigned bytes = min_t(unsigned, iter.bi_size,
2636 bkey_inline_data_bytes(k.k));
2638 swap(iter.bi_size, bytes);
2639 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2640 swap(iter.bi_size, bytes);
2641 bio_advance_iter(&orig->bio, &iter, bytes);
2642 zero_fill_bio_iter(&orig->bio, iter);
2646 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2648 /* hole or reservation - just zero fill: */
2653 bch_err_inum_offset_ratelimited(c,
2654 read_pos.inode, read_pos.offset << 9,
2655 "no device to read from");
2659 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2662 * Stale dirty pointers are treated as IO errors, but @failed isn't
2663 * allocated unless we're in the retry path - so if we're not in the
2664 * retry path, don't check here, it'll be caught in bch2_read_endio()
2665 * and we'll end up in the retry path:
2667 if ((flags & BCH_READ_IN_RETRY) &&
2669 unlikely(ptr_stale(ca, &pick.ptr))) {
2670 read_from_stale_dirty_pointer(trans, k, pick.ptr);
2671 bch2_mark_io_failure(failed, &pick);
2676 * Unlock the iterator while the btree node's lock is still in
2677 * cache, before doing the IO:
2679 bch2_trans_unlock(trans);
2681 if (flags & BCH_READ_NODECODE) {
2683 * can happen if we retry, and the extent we were going to read
2684 * has been merged in the meantime:
2686 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2689 iter.bi_size = pick.crc.compressed_size << 9;
2693 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2694 bio_flagged(&orig->bio, BIO_CHAIN))
2695 flags |= BCH_READ_MUST_CLONE;
2697 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2698 bch2_can_narrow_extent_crcs(k, pick.crc);
2700 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2701 flags |= BCH_READ_MUST_BOUNCE;
2703 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2705 if (crc_is_compressed(pick.crc) ||
2706 (pick.crc.csum_type != BCH_CSUM_none &&
2707 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2708 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2709 (flags & BCH_READ_USER_MAPPED)) ||
2710 (flags & BCH_READ_MUST_BOUNCE)))) {
2715 if (orig->opts.promote_target)
2716 promote = promote_alloc(trans, iter, k, &pick, orig->opts, flags,
2717 &rbio, &bounce, &read_full);
2720 EBUG_ON(crc_is_compressed(pick.crc));
2721 EBUG_ON(pick.crc.csum_type &&
2722 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2723 bvec_iter_sectors(iter) != pick.crc.live_size ||
2725 offset_into_extent));
2727 data_pos.offset += offset_into_extent;
2728 pick.ptr.offset += pick.crc.offset +
2730 offset_into_extent = 0;
2731 pick.crc.compressed_size = bvec_iter_sectors(iter);
2732 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2733 pick.crc.offset = 0;
2734 pick.crc.live_size = bvec_iter_sectors(iter);
2735 offset_into_extent = 0;
2740 * promote already allocated bounce rbio:
2741 * promote needs to allocate a bio big enough for uncompressing
2742 * data in the write path, but we're not going to use it all
2745 EBUG_ON(rbio->bio.bi_iter.bi_size <
2746 pick.crc.compressed_size << 9);
2747 rbio->bio.bi_iter.bi_size =
2748 pick.crc.compressed_size << 9;
2749 } else if (bounce) {
2750 unsigned sectors = pick.crc.compressed_size;
2752 rbio = rbio_init(bio_alloc_bioset(NULL,
2753 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2756 &c->bio_read_split),
2759 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2760 rbio->bounce = true;
2762 } else if (flags & BCH_READ_MUST_CLONE) {
2764 * Have to clone if there were any splits, due to error
2765 * reporting issues (if a split errored, and retrying didn't
2766 * work, when it reports the error to its parent (us) we don't
2767 * know if the error was from our bio, and we should retry, or
2768 * from the whole bio, in which case we don't want to retry and
2771 rbio = rbio_init(bio_alloc_clone(NULL, &orig->bio, GFP_NOFS,
2772 &c->bio_read_split),
2774 rbio->bio.bi_iter = iter;
2778 rbio->bio.bi_iter = iter;
2779 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2782 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2785 rbio->submit_time = local_clock();
2787 rbio->parent = orig;
2789 rbio->end_io = orig->bio.bi_end_io;
2790 rbio->bvec_iter = iter;
2791 rbio->offset_into_extent= offset_into_extent;
2792 rbio->flags = flags;
2793 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2794 rbio->narrow_crcs = narrow_crcs;
2798 /* XXX: only initialize this if needed */
2799 rbio->devs_have = bch2_bkey_devs(k);
2801 rbio->subvol = orig->subvol;
2802 rbio->read_pos = read_pos;
2803 rbio->data_btree = data_btree;
2804 rbio->data_pos = data_pos;
2805 rbio->version = k.k->version;
2806 rbio->promote = promote;
2807 INIT_WORK(&rbio->work, NULL);
2809 rbio->bio.bi_opf = orig->bio.bi_opf;
2810 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2811 rbio->bio.bi_end_io = bch2_read_endio;
2814 trace_and_count(c, read_bounce, &rbio->bio);
2816 this_cpu_add(c->counters[BCH_COUNTER_io_read], bio_sectors(&rbio->bio));
2817 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2820 * If it's being moved internally, we don't want to flag it as a cache
2823 if (pick.ptr.cached && !(flags & BCH_READ_NODECODE))
2824 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2825 PTR_BUCKET_NR(ca, &pick.ptr), READ);
2827 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2828 bio_inc_remaining(&orig->bio);
2829 trace_and_count(c, read_split, &orig->bio);
2832 if (!rbio->pick.idx) {
2833 if (!rbio->have_ioref) {
2834 bch_err_inum_offset_ratelimited(c,
2836 read_pos.offset << 9,
2837 "no device to read from");
2838 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2842 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2843 bio_sectors(&rbio->bio));
2844 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2846 if (unlikely(c->opts.no_data_io)) {
2847 if (likely(!(flags & BCH_READ_IN_RETRY)))
2848 bio_endio(&rbio->bio);
2850 if (likely(!(flags & BCH_READ_IN_RETRY)))
2851 submit_bio(&rbio->bio);
2853 submit_bio_wait(&rbio->bio);
2857 * We just submitted IO which may block, we expect relock fail
2858 * events and shouldn't count them:
2860 trans->notrace_relock_fail = true;
2862 /* Attempting reconstruct read: */
2863 if (bch2_ec_read_extent(c, rbio)) {
2864 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2868 if (likely(!(flags & BCH_READ_IN_RETRY)))
2869 bio_endio(&rbio->bio);
2872 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2877 rbio->context = RBIO_CONTEXT_UNBOUND;
2878 bch2_read_endio(&rbio->bio);
2881 rbio = bch2_rbio_free(rbio);
2883 if (ret == READ_RETRY_AVOID) {
2884 bch2_mark_io_failure(failed, &pick);
2895 if (flags & BCH_READ_IN_RETRY)
2898 orig->bio.bi_status = BLK_STS_IOERR;
2903 * won't normally happen in the BCH_READ_NODECODE
2904 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2905 * to read no longer exists we have to signal that:
2907 if (flags & BCH_READ_NODECODE)
2910 zero_fill_bio_iter(&orig->bio, iter);
2912 if (flags & BCH_READ_LAST_FRAGMENT)
2913 bch2_rbio_done(orig);
2917 void __bch2_read(struct bch_fs *c, struct bch_read_bio *rbio,
2918 struct bvec_iter bvec_iter, subvol_inum inum,
2919 struct bch_io_failures *failed, unsigned flags)
2921 struct btree_trans trans;
2922 struct btree_iter iter;
2928 BUG_ON(flags & BCH_READ_NODECODE);
2930 bch2_bkey_buf_init(&sk);
2931 bch2_trans_init(&trans, c, 0, 0);
2933 bch2_trans_begin(&trans);
2934 iter = (struct btree_iter) { NULL };
2936 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
2940 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2941 SPOS(inum.inum, bvec_iter.bi_sector, snapshot),
2944 unsigned bytes, sectors, offset_into_extent;
2945 enum btree_id data_btree = BTREE_ID_extents;
2948 * read_extent -> io_time_reset may cause a transaction restart
2949 * without returning an error, we need to check for that here:
2951 ret = bch2_trans_relock(&trans);
2955 bch2_btree_iter_set_pos(&iter,
2956 POS(inum.inum, bvec_iter.bi_sector));
2958 k = bch2_btree_iter_peek_slot(&iter);
2963 offset_into_extent = iter.pos.offset -
2964 bkey_start_offset(k.k);
2965 sectors = k.k->size - offset_into_extent;
2967 bch2_bkey_buf_reassemble(&sk, c, k);
2969 ret = bch2_read_indirect_extent(&trans, &data_btree,
2970 &offset_into_extent, &sk);
2974 k = bkey_i_to_s_c(sk.k);
2977 * With indirect extents, the amount of data to read is the min
2978 * of the original extent and the indirect extent:
2980 sectors = min(sectors, k.k->size - offset_into_extent);
2982 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
2983 swap(bvec_iter.bi_size, bytes);
2985 if (bvec_iter.bi_size == bytes)
2986 flags |= BCH_READ_LAST_FRAGMENT;
2988 ret = __bch2_read_extent(&trans, rbio, bvec_iter, iter.pos,
2990 offset_into_extent, failed, flags);
2994 if (flags & BCH_READ_LAST_FRAGMENT)
2997 swap(bvec_iter.bi_size, bytes);
2998 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
3000 ret = btree_trans_too_many_iters(&trans);
3005 bch2_trans_iter_exit(&trans, &iter);
3007 if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
3008 ret == READ_RETRY ||
3009 ret == READ_RETRY_AVOID)
3012 bch2_trans_exit(&trans);
3013 bch2_bkey_buf_exit(&sk, c);
3016 bch_err_inum_offset_ratelimited(c, inum.inum,
3017 bvec_iter.bi_sector << 9,
3018 "read error %i from btree lookup", ret);
3019 rbio->bio.bi_status = BLK_STS_IOERR;
3020 bch2_rbio_done(rbio);
3024 void bch2_fs_io_exit(struct bch_fs *c)
3026 if (c->promote_table.tbl)
3027 rhashtable_destroy(&c->promote_table);
3028 mempool_exit(&c->bio_bounce_pages);
3029 bioset_exit(&c->bio_write);
3030 bioset_exit(&c->bio_read_split);
3031 bioset_exit(&c->bio_read);
3034 int bch2_fs_io_init(struct bch_fs *c)
3036 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
3038 return -BCH_ERR_ENOMEM_bio_read_init;
3040 if (bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
3042 return -BCH_ERR_ENOMEM_bio_read_split_init;
3044 if (bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
3046 return -BCH_ERR_ENOMEM_bio_write_init;
3048 if (mempool_init_page_pool(&c->bio_bounce_pages,
3050 c->opts.btree_node_size,
3051 c->opts.encoded_extent_max) /
3053 return -BCH_ERR_ENOMEM_bio_bounce_pages_init;
3055 if (rhashtable_init(&c->promote_table, &bch_promote_params))
3056 return -BCH_ERR_ENOMEM_promote_table_init;