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 "rebalance.h"
31 #include "subvolume.h"
35 #include <linux/blkdev.h>
36 #include <linux/random.h>
37 #include <linux/sched/mm.h>
39 #include <trace/events/bcachefs.h>
41 const char *bch2_blk_status_to_str(blk_status_t status)
43 if (status == BLK_STS_REMOVED)
44 return "device removed";
45 return blk_status_to_str(status);
48 static bool bch2_target_congested(struct bch_fs *c, u16 target)
50 const struct bch_devs_mask *devs;
51 unsigned d, nr = 0, total = 0;
52 u64 now = local_clock(), last;
60 devs = bch2_target_to_mask(c, target) ?:
61 &c->rw_devs[BCH_DATA_user];
63 for_each_set_bit(d, devs->d, BCH_SB_MEMBERS_MAX) {
64 ca = rcu_dereference(c->devs[d]);
68 congested = atomic_read(&ca->congested);
69 last = READ_ONCE(ca->congested_last);
70 if (time_after64(now, last))
71 congested -= (now - last) >> 12;
73 total += max(congested, 0LL);
78 return bch2_rand_range(nr * CONGESTED_MAX) < total;
81 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
85 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
86 /* ideally we'd be taking into account the device's variance here: */
87 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
88 s64 latency_over = io_latency - latency_threshold;
90 if (latency_threshold && latency_over > 0) {
92 * bump up congested by approximately latency_over * 4 /
93 * latency_threshold - we don't need much accuracy here so don't
94 * bother with the divide:
96 if (atomic_read(&ca->congested) < CONGESTED_MAX)
97 atomic_add(latency_over >>
98 max_t(int, ilog2(latency_threshold) - 2, 0),
101 ca->congested_last = now;
102 } else if (atomic_read(&ca->congested) > 0) {
103 atomic_dec(&ca->congested);
107 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
109 atomic64_t *latency = &ca->cur_latency[rw];
110 u64 now = local_clock();
111 u64 io_latency = time_after64(now, submit_time)
114 u64 old, new, v = atomic64_read(latency);
120 * If the io latency was reasonably close to the current
121 * latency, skip doing the update and atomic operation - most of
124 if (abs((int) (old - io_latency)) < (old >> 1) &&
128 new = ewma_add(old, io_latency, 5);
129 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
131 bch2_congested_acct(ca, io_latency, now, rw);
133 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
136 /* Allocate, free from mempool: */
138 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
140 struct bvec_iter_all iter;
143 bio_for_each_segment_all(bv, bio, iter)
144 if (bv->bv_page != ZERO_PAGE(0))
145 mempool_free(bv->bv_page, &c->bio_bounce_pages);
149 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
153 if (likely(!*using_mempool)) {
154 page = alloc_page(GFP_NOIO);
155 if (unlikely(!page)) {
156 mutex_lock(&c->bio_bounce_pages_lock);
157 *using_mempool = true;
163 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOIO);
169 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
172 bool using_mempool = false;
175 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
176 unsigned len = min_t(size_t, PAGE_SIZE, size);
178 BUG_ON(!bio_add_page(bio, page, len, 0));
183 mutex_unlock(&c->bio_bounce_pages_lock);
186 /* Extent update path: */
188 int bch2_sum_sector_overwrites(struct btree_trans *trans,
189 struct btree_iter *extent_iter,
191 bool *usage_increasing,
192 s64 *i_sectors_delta,
193 s64 *disk_sectors_delta)
195 struct bch_fs *c = trans->c;
196 struct btree_iter iter;
198 unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
199 bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
202 *usage_increasing = false;
203 *i_sectors_delta = 0;
204 *disk_sectors_delta = 0;
206 bch2_trans_copy_iter(&iter, extent_iter);
208 for_each_btree_key_continue_norestart(iter, BTREE_ITER_SLOTS, old, ret) {
209 s64 sectors = min(new->k.p.offset, old.k->p.offset) -
210 max(bkey_start_offset(&new->k),
211 bkey_start_offset(old.k));
213 *i_sectors_delta += sectors *
214 (bkey_extent_is_allocation(&new->k) -
215 bkey_extent_is_allocation(old.k));
217 *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
218 *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
219 ? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
222 if (!*usage_increasing &&
223 (new->k.p.snapshot != old.k->p.snapshot ||
224 new_replicas > bch2_bkey_replicas(c, old) ||
225 (!new_compressed && bch2_bkey_sectors_compressed(old))))
226 *usage_increasing = true;
228 if (bkey_ge(old.k->p, new->k.p))
232 bch2_trans_iter_exit(trans, &iter);
236 static inline int bch2_extent_update_i_size_sectors(struct btree_trans *trans,
237 struct btree_iter *extent_iter,
241 struct btree_iter iter;
242 struct bkey_s_c inode_k;
243 struct bkey_s_c_inode_v3 inode;
244 struct bkey_i_inode_v3 *new_inode;
247 bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes,
249 extent_iter->pos.inode,
250 extent_iter->snapshot),
251 BTREE_ITER_INTENT|BTREE_ITER_CACHED);
252 inode_k = bch2_btree_iter_peek_slot(&iter);
253 ret = bkey_err(inode_k);
257 ret = bkey_is_inode(inode_k.k) ? 0 : -ENOENT;
261 if (unlikely(inode_k.k->type != KEY_TYPE_inode_v3)) {
262 inode_k = bch2_inode_to_v3(trans, inode_k);
263 ret = bkey_err(inode_k);
268 inode = bkey_s_c_to_inode_v3(inode_k);
270 new_inode = bch2_trans_kmalloc(trans, bkey_bytes(inode_k.k));
271 ret = PTR_ERR_OR_ZERO(new_inode);
275 bkey_reassemble(&new_inode->k_i, inode.s_c);
277 if (!(le64_to_cpu(inode.v->bi_flags) & BCH_INODE_I_SIZE_DIRTY) &&
278 new_i_size > le64_to_cpu(inode.v->bi_size))
279 new_inode->v.bi_size = cpu_to_le64(new_i_size);
281 le64_add_cpu(&new_inode->v.bi_sectors, i_sectors_delta);
283 new_inode->k.p.snapshot = iter.snapshot;
285 ret = bch2_trans_update(trans, &iter, &new_inode->k_i,
286 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
288 bch2_trans_iter_exit(trans, &iter);
292 int bch2_extent_update(struct btree_trans *trans,
294 struct btree_iter *iter,
296 struct disk_reservation *disk_res,
298 s64 *i_sectors_delta_total,
301 struct bpos next_pos;
302 bool usage_increasing;
303 s64 i_sectors_delta = 0, disk_sectors_delta = 0;
307 * This traverses us the iterator without changing iter->path->pos to
308 * search_key() (which is pos + 1 for extents): we want there to be a
309 * path already traversed at iter->pos because
310 * bch2_trans_extent_update() will use it to attempt extent merging
312 ret = __bch2_btree_iter_traverse(iter);
316 ret = bch2_extent_trim_atomic(trans, iter, k);
322 ret = bch2_sum_sector_overwrites(trans, iter, k,
325 &disk_sectors_delta);
330 disk_sectors_delta > (s64) disk_res->sectors) {
331 ret = bch2_disk_reservation_add(trans->c, disk_res,
332 disk_sectors_delta - disk_res->sectors,
333 !check_enospc || !usage_increasing
334 ? BCH_DISK_RESERVATION_NOFAIL : 0);
341 * We always have to do an inode update - even when i_size/i_sectors
342 * aren't changing - for fsync to work properly; fsync relies on
343 * inode->bi_journal_seq which is updated by the trigger code:
345 ret = bch2_extent_update_i_size_sectors(trans, iter,
346 min(k->k.p.offset << 9, new_i_size),
348 bch2_trans_update(trans, iter, k, 0) ?:
349 bch2_trans_commit(trans, disk_res, NULL,
350 BTREE_INSERT_NOCHECK_RW|
351 BTREE_INSERT_NOFAIL);
355 if (i_sectors_delta_total)
356 *i_sectors_delta_total += i_sectors_delta;
357 bch2_btree_iter_set_pos(iter, next_pos);
361 /* Overwrites whatever was present with zeroes: */
362 int bch2_extent_fallocate(struct btree_trans *trans,
364 struct btree_iter *iter,
366 struct bch_io_opts opts,
367 s64 *i_sectors_delta,
368 struct write_point_specifier write_point)
370 struct bch_fs *c = trans->c;
371 struct disk_reservation disk_res = { 0 };
373 struct open_buckets open_buckets;
375 struct bkey_buf old, new;
376 bool have_reservation = false;
377 bool unwritten = opts.nocow &&
378 c->sb.version >= bcachefs_metadata_version_unwritten_extents;
381 bch2_bkey_buf_init(&old);
382 bch2_bkey_buf_init(&new);
383 closure_init_stack(&cl);
386 k = bch2_btree_iter_peek_slot(iter);
391 sectors = min_t(u64, sectors, k.k->p.offset - iter->pos.offset);
393 if (!have_reservation) {
394 unsigned new_replicas =
395 max(0, (int) opts.data_replicas -
396 (int) bch2_bkey_nr_ptrs_fully_allocated(k));
398 * Get a disk reservation before (in the nocow case) calling
399 * into the allocator:
401 ret = bch2_disk_reservation_get(c, &disk_res, sectors, new_replicas, 0);
405 bch2_bkey_buf_reassemble(&old, c, k);
408 if (have_reservation) {
409 if (!bch2_extents_match(k, bkey_i_to_s_c(old.k)))
412 bch2_key_resize(&new.k->k, sectors);
413 } else if (!unwritten) {
414 struct bkey_i_reservation *reservation;
416 bch2_bkey_buf_realloc(&new, c, sizeof(*reservation) / sizeof(u64));
417 reservation = bkey_reservation_init(new.k);
418 reservation->k.p = iter->pos;
419 bch2_key_resize(&reservation->k, sectors);
420 reservation->v.nr_replicas = opts.data_replicas;
422 struct bkey_i_extent *e;
423 struct bch_devs_list devs_have;
424 struct write_point *wp;
425 struct bch_extent_ptr *ptr;
429 bch2_bkey_buf_realloc(&new, c, BKEY_EXTENT_U64s_MAX);
431 e = bkey_extent_init(new.k);
434 ret = bch2_alloc_sectors_start_trans(trans,
435 opts.foreground_target,
441 RESERVE_none, 0, &cl, &wp);
442 if (ret == -EAGAIN) {
443 bch2_trans_unlock(trans);
450 sectors = min(sectors, wp->sectors_free);
452 bch2_key_resize(&e->k, sectors);
454 bch2_open_bucket_get(c, wp, &open_buckets);
455 bch2_alloc_sectors_append_ptrs(c, wp, &e->k_i, sectors, false);
456 bch2_alloc_sectors_done(c, wp);
458 extent_for_each_ptr(extent_i_to_s(e), ptr)
459 ptr->unwritten = true;
462 have_reservation = true;
464 ret = bch2_extent_update(trans, inum, iter, new.k, &disk_res,
465 0, i_sectors_delta, true);
467 if ((atomic_read(&cl.remaining) & CLOSURE_REMAINING_MASK) != 1) {
468 bch2_trans_unlock(trans);
472 if (bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
473 bch2_trans_begin(trans);
477 bch2_open_buckets_put(c, &open_buckets);
478 bch2_disk_reservation_put(c, &disk_res);
479 bch2_bkey_buf_exit(&new, c);
480 bch2_bkey_buf_exit(&old, c);
486 * Returns -BCH_ERR_transacton_restart if we had to drop locks:
488 int bch2_fpunch_at(struct btree_trans *trans, struct btree_iter *iter,
489 subvol_inum inum, u64 end,
490 s64 *i_sectors_delta)
492 struct bch_fs *c = trans->c;
493 unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
494 struct bpos end_pos = POS(inum.inum, end);
496 int ret = 0, ret2 = 0;
500 bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
501 struct disk_reservation disk_res =
502 bch2_disk_reservation_init(c, 0);
503 struct bkey_i delete;
508 bch2_trans_begin(trans);
510 ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
514 bch2_btree_iter_set_snapshot(iter, snapshot);
516 k = bch2_btree_iter_peek(iter);
517 if (bkey_ge(iter->pos, end_pos)) {
518 bch2_btree_iter_set_pos(iter, end_pos);
526 bkey_init(&delete.k);
527 delete.k.p = iter->pos;
529 /* create the biggest key we can */
530 bch2_key_resize(&delete.k, max_sectors);
531 bch2_cut_back(end_pos, &delete);
533 ret = bch2_extent_update(trans, inum, iter, &delete,
534 &disk_res, 0, i_sectors_delta, false);
535 bch2_disk_reservation_put(c, &disk_res);
541 int bch2_fpunch(struct bch_fs *c, subvol_inum inum, u64 start, u64 end,
542 s64 *i_sectors_delta)
544 struct btree_trans trans;
545 struct btree_iter iter;
548 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
549 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
550 POS(inum.inum, start),
553 ret = bch2_fpunch_at(&trans, &iter, inum, end, i_sectors_delta);
555 bch2_trans_iter_exit(&trans, &iter);
556 bch2_trans_exit(&trans);
558 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
564 static int bch2_write_index_default(struct bch_write_op *op)
566 struct bch_fs *c = op->c;
568 struct keylist *keys = &op->insert_keys;
569 struct bkey_i *k = bch2_keylist_front(keys);
570 struct btree_trans trans;
571 struct btree_iter iter;
573 .subvol = op->subvol,
574 .inum = k->k.p.inode,
578 BUG_ON(!inum.subvol);
580 bch2_bkey_buf_init(&sk);
581 bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
584 bch2_trans_begin(&trans);
586 k = bch2_keylist_front(keys);
587 bch2_bkey_buf_copy(&sk, c, k);
589 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol,
590 &sk.k->k.p.snapshot);
591 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
596 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
597 bkey_start_pos(&sk.k->k),
598 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
600 ret = bch2_extent_update(&trans, inum, &iter, sk.k,
602 op->new_i_size, &op->i_sectors_delta,
603 op->flags & BCH_WRITE_CHECK_ENOSPC);
604 bch2_trans_iter_exit(&trans, &iter);
606 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
611 if (bkey_ge(iter.pos, k->k.p))
612 bch2_keylist_pop_front(&op->insert_keys);
614 bch2_cut_front(iter.pos, k);
615 } while (!bch2_keylist_empty(keys));
617 bch2_trans_exit(&trans);
618 bch2_bkey_buf_exit(&sk, c);
625 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
626 enum bch_data_type type,
627 const struct bkey_i *k,
630 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
631 const struct bch_extent_ptr *ptr;
632 struct bch_write_bio *n;
635 BUG_ON(c->opts.nochanges);
637 bkey_for_each_ptr(ptrs, ptr) {
638 BUG_ON(ptr->dev >= BCH_SB_MEMBERS_MAX ||
641 ca = bch_dev_bkey_exists(c, ptr->dev);
643 if (to_entry(ptr + 1) < ptrs.end) {
644 n = to_wbio(bio_alloc_clone(NULL, &wbio->bio,
645 GFP_NOIO, &ca->replica_set));
647 n->bio.bi_end_io = wbio->bio.bi_end_io;
648 n->bio.bi_private = wbio->bio.bi_private;
653 n->bio.bi_opf = wbio->bio.bi_opf;
654 bio_inc_remaining(&wbio->bio);
662 n->have_ioref = nocow || bch2_dev_get_ioref(ca,
663 type == BCH_DATA_btree ? READ : WRITE);
665 n->submit_time = local_clock();
666 n->inode_offset = bkey_start_offset(&k->k);
667 n->bio.bi_iter.bi_sector = ptr->offset;
669 if (likely(n->have_ioref)) {
670 this_cpu_add(ca->io_done->sectors[WRITE][type],
671 bio_sectors(&n->bio));
673 bio_set_dev(&n->bio, ca->disk_sb.bdev);
676 n->bio.bi_status = BLK_STS_REMOVED;
682 static void __bch2_write(struct bch_write_op *);
684 static void bch2_write_done(struct closure *cl)
686 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
687 struct bch_fs *c = op->c;
689 bch2_disk_reservation_put(c, &op->res);
690 percpu_ref_put(&c->writes);
691 bch2_keylist_free(&op->insert_keys, op->inline_keys);
693 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
695 closure_debug_destroy(cl);
700 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
702 struct keylist *keys = &op->insert_keys;
703 struct bch_extent_ptr *ptr;
704 struct bkey_i *src, *dst = keys->keys, *n;
706 for (src = keys->keys; src != keys->top; src = n) {
709 if (bkey_extent_is_direct_data(&src->k)) {
710 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
711 test_bit(ptr->dev, op->failed.d));
713 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
718 memmove_u64s_down(dst, src, src->u64s);
719 dst = bkey_next(dst);
727 * bch_write_index - after a write, update index to point to new data
729 static void __bch2_write_index(struct bch_write_op *op)
731 struct bch_fs *c = op->c;
732 struct keylist *keys = &op->insert_keys;
737 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
738 ret = bch2_write_drop_io_error_ptrs(op);
744 * probably not the ideal place to hook this in, but I don't
745 * particularly want to plumb io_opts all the way through the btree
746 * update stack right now
748 for_each_keylist_key(keys, k)
749 bch2_rebalance_add_key(c, bkey_i_to_s_c(k), &op->opts);
751 if (!bch2_keylist_empty(keys)) {
752 u64 sectors_start = keylist_sectors(keys);
754 ret = !(op->flags & BCH_WRITE_MOVE)
755 ? bch2_write_index_default(op)
756 : bch2_data_update_index_update(op);
758 BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
759 BUG_ON(keylist_sectors(keys) && !ret);
761 op->written += sectors_start - keylist_sectors(keys);
764 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
766 bch_err_inum_offset_ratelimited(c,
767 k->k.p.inode, k->k.p.offset << 9,
768 "write error while doing btree update: %s",
774 /* If some a bucket wasn't written, we can't erasure code it: */
775 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
776 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
778 bch2_open_buckets_put(c, &op->open_buckets);
781 keys->top = keys->keys;
783 op->flags |= BCH_WRITE_DONE;
787 static void bch2_write_index(struct closure *cl)
789 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
790 struct write_point *wp = op->wp;
791 struct workqueue_struct *wq = index_update_wq(op);
794 op->btree_update_ready = true;
795 queue_work(wq, &wp->index_update_work);
798 void bch2_write_point_do_index_updates(struct work_struct *work)
800 struct write_point *wp =
801 container_of(work, struct write_point, index_update_work);
802 struct bch_write_op *op;
805 spin_lock(&wp->writes_lock);
806 op = list_first_entry_or_null(&wp->writes, struct bch_write_op, wp_list);
807 if (op && !op->btree_update_ready)
810 list_del(&op->wp_list);
811 spin_unlock(&wp->writes_lock);
816 __bch2_write_index(op);
818 if (!(op->flags & BCH_WRITE_DONE))
821 bch2_write_done(&op->cl);
825 static void bch2_write_endio(struct bio *bio)
827 struct closure *cl = bio->bi_private;
828 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
829 struct bch_write_bio *wbio = to_wbio(bio);
830 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
831 struct bch_fs *c = wbio->c;
832 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
834 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
836 wbio->inode_offset << 9,
837 "data write error: %s",
838 bch2_blk_status_to_str(bio->bi_status))) {
839 set_bit(wbio->dev, op->failed.d);
840 op->flags |= BCH_WRITE_IO_ERROR;
844 set_bit(wbio->dev, op->devs_need_flush->d);
846 if (wbio->have_ioref) {
847 bch2_latency_acct(ca, wbio->submit_time, WRITE);
848 percpu_ref_put(&ca->io_ref);
852 bch2_bio_free_pages_pool(c, bio);
858 bio_endio(&parent->bio);
865 static void init_append_extent(struct bch_write_op *op,
866 struct write_point *wp,
867 struct bversion version,
868 struct bch_extent_crc_unpacked crc)
870 struct bch_fs *c = op->c;
871 struct bkey_i_extent *e;
873 op->pos.offset += crc.uncompressed_size;
875 e = bkey_extent_init(op->insert_keys.top);
877 e->k.size = crc.uncompressed_size;
878 e->k.version = version;
881 crc.compression_type ||
883 bch2_extent_crc_append(&e->k_i, crc);
885 bch2_alloc_sectors_append_ptrs_inlined(c, wp, &e->k_i, crc.compressed_size,
886 op->flags & BCH_WRITE_CACHED);
888 bch2_keylist_push(&op->insert_keys);
891 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
892 struct write_point *wp,
894 bool *page_alloc_failed,
897 struct bch_write_bio *wbio;
899 unsigned output_available =
900 min(wp->sectors_free << 9, src->bi_iter.bi_size);
901 unsigned pages = DIV_ROUND_UP(output_available +
903 ? ((unsigned long) buf & (PAGE_SIZE - 1))
906 pages = min(pages, BIO_MAX_VECS);
908 bio = bio_alloc_bioset(NULL, pages, 0,
909 GFP_NOIO, &c->bio_write);
910 wbio = wbio_init(bio);
911 wbio->put_bio = true;
912 /* copy WRITE_SYNC flag */
913 wbio->bio.bi_opf = src->bi_opf;
916 bch2_bio_map(bio, buf, output_available);
923 * We can't use mempool for more than c->sb.encoded_extent_max
924 * worth of pages, but we'd like to allocate more if we can:
926 bch2_bio_alloc_pages_pool(c, bio,
927 min_t(unsigned, output_available,
928 c->opts.encoded_extent_max));
930 if (bio->bi_iter.bi_size < output_available)
932 bch2_bio_alloc_pages(bio,
934 bio->bi_iter.bi_size,
940 static int bch2_write_rechecksum(struct bch_fs *c,
941 struct bch_write_op *op,
942 unsigned new_csum_type)
944 struct bio *bio = &op->wbio.bio;
945 struct bch_extent_crc_unpacked new_crc;
948 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
950 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
951 bch2_csum_type_is_encryption(new_csum_type))
952 new_csum_type = op->crc.csum_type;
954 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
956 op->crc.offset, op->crc.live_size,
961 bio_advance(bio, op->crc.offset << 9);
962 bio->bi_iter.bi_size = op->crc.live_size << 9;
967 static int bch2_write_decrypt(struct bch_write_op *op)
969 struct bch_fs *c = op->c;
970 struct nonce nonce = extent_nonce(op->version, op->crc);
971 struct bch_csum csum;
974 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
978 * If we need to decrypt data in the write path, we'll no longer be able
979 * to verify the existing checksum (poly1305 mac, in this case) after
980 * it's decrypted - this is the last point we'll be able to reverify the
983 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
984 if (bch2_crc_cmp(op->crc.csum, csum))
987 ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
988 op->crc.csum_type = 0;
989 op->crc.csum = (struct bch_csum) { 0, 0 };
993 static enum prep_encoded_ret {
996 PREP_ENCODED_CHECKSUM_ERR,
997 PREP_ENCODED_DO_WRITE,
998 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
1000 struct bch_fs *c = op->c;
1001 struct bio *bio = &op->wbio.bio;
1003 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
1004 return PREP_ENCODED_OK;
1006 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
1008 /* Can we just write the entire extent as is? */
1009 if (op->crc.uncompressed_size == op->crc.live_size &&
1010 op->crc.compressed_size <= wp->sectors_free &&
1011 (op->crc.compression_type == op->compression_type ||
1012 op->incompressible)) {
1013 if (!crc_is_compressed(op->crc) &&
1014 op->csum_type != op->crc.csum_type &&
1015 bch2_write_rechecksum(c, op, op->csum_type))
1016 return PREP_ENCODED_CHECKSUM_ERR;
1018 return PREP_ENCODED_DO_WRITE;
1022 * If the data is compressed and we couldn't write the entire extent as
1023 * is, we have to decompress it:
1025 if (crc_is_compressed(op->crc)) {
1026 struct bch_csum csum;
1028 if (bch2_write_decrypt(op))
1029 return PREP_ENCODED_CHECKSUM_ERR;
1031 /* Last point we can still verify checksum: */
1032 csum = bch2_checksum_bio(c, op->crc.csum_type,
1033 extent_nonce(op->version, op->crc),
1035 if (bch2_crc_cmp(op->crc.csum, csum))
1036 return PREP_ENCODED_CHECKSUM_ERR;
1038 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
1039 return PREP_ENCODED_ERR;
1043 * No longer have compressed data after this point - data might be
1048 * If the data is checksummed and we're only writing a subset,
1049 * rechecksum and adjust bio to point to currently live data:
1051 if ((op->crc.live_size != op->crc.uncompressed_size ||
1052 op->crc.csum_type != op->csum_type) &&
1053 bch2_write_rechecksum(c, op, op->csum_type))
1054 return PREP_ENCODED_CHECKSUM_ERR;
1057 * If we want to compress the data, it has to be decrypted:
1059 if ((op->compression_type ||
1060 bch2_csum_type_is_encryption(op->crc.csum_type) !=
1061 bch2_csum_type_is_encryption(op->csum_type)) &&
1062 bch2_write_decrypt(op))
1063 return PREP_ENCODED_CHECKSUM_ERR;
1065 return PREP_ENCODED_OK;
1068 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
1071 struct bch_fs *c = op->c;
1072 struct bio *src = &op->wbio.bio, *dst = src;
1073 struct bvec_iter saved_iter;
1075 unsigned total_output = 0, total_input = 0;
1076 bool bounce = false;
1077 bool page_alloc_failed = false;
1080 BUG_ON(!bio_sectors(src));
1082 ec_buf = bch2_writepoint_ec_buf(c, wp);
1084 switch (bch2_write_prep_encoded_data(op, wp)) {
1085 case PREP_ENCODED_OK:
1087 case PREP_ENCODED_ERR:
1090 case PREP_ENCODED_CHECKSUM_ERR:
1092 case PREP_ENCODED_DO_WRITE:
1093 /* XXX look for bug here */
1095 dst = bch2_write_bio_alloc(c, wp, src,
1098 bio_copy_data(dst, src);
1101 init_append_extent(op, wp, op->version, op->crc);
1106 op->compression_type ||
1108 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
1109 (bch2_csum_type_is_encryption(op->csum_type) &&
1110 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
1111 dst = bch2_write_bio_alloc(c, wp, src,
1117 saved_iter = dst->bi_iter;
1120 struct bch_extent_crc_unpacked crc = { 0 };
1121 struct bversion version = op->version;
1122 size_t dst_len, src_len;
1124 if (page_alloc_failed &&
1125 dst->bi_iter.bi_size < (wp->sectors_free << 9) &&
1126 dst->bi_iter.bi_size < c->opts.encoded_extent_max)
1129 BUG_ON(op->compression_type &&
1130 (op->flags & BCH_WRITE_DATA_ENCODED) &&
1131 bch2_csum_type_is_encryption(op->crc.csum_type));
1132 BUG_ON(op->compression_type && !bounce);
1134 crc.compression_type = op->incompressible
1135 ? BCH_COMPRESSION_TYPE_incompressible
1136 : op->compression_type
1137 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
1138 op->compression_type)
1140 if (!crc_is_compressed(crc)) {
1141 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
1142 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
1145 dst_len = min_t(unsigned, dst_len,
1146 c->opts.encoded_extent_max);
1149 swap(dst->bi_iter.bi_size, dst_len);
1150 bio_copy_data(dst, src);
1151 swap(dst->bi_iter.bi_size, dst_len);
1157 BUG_ON(!src_len || !dst_len);
1159 if (bch2_csum_type_is_encryption(op->csum_type)) {
1160 if (bversion_zero(version)) {
1161 version.lo = atomic64_inc_return(&c->key_version);
1163 crc.nonce = op->nonce;
1164 op->nonce += src_len >> 9;
1168 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1169 !crc_is_compressed(crc) &&
1170 bch2_csum_type_is_encryption(op->crc.csum_type) ==
1171 bch2_csum_type_is_encryption(op->csum_type)) {
1172 u8 compression_type = crc.compression_type;
1173 u16 nonce = crc.nonce;
1175 * Note: when we're using rechecksum(), we need to be
1176 * checksumming @src because it has all the data our
1177 * existing checksum covers - if we bounced (because we
1178 * were trying to compress), @dst will only have the
1179 * part of the data the new checksum will cover.
1181 * But normally we want to be checksumming post bounce,
1182 * because part of the reason for bouncing is so the
1183 * data can't be modified (by userspace) while it's in
1186 if (bch2_rechecksum_bio(c, src, version, op->crc,
1189 bio_sectors(src) - (src_len >> 9),
1193 * rchecksum_bio sets compression_type on crc from op->crc,
1194 * this isn't always correct as sometimes we're changing
1195 * an extent from uncompressed to incompressible.
1197 crc.compression_type = compression_type;
1200 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1201 bch2_rechecksum_bio(c, src, version, op->crc,
1204 bio_sectors(src) - (src_len >> 9),
1208 crc.compressed_size = dst_len >> 9;
1209 crc.uncompressed_size = src_len >> 9;
1210 crc.live_size = src_len >> 9;
1212 swap(dst->bi_iter.bi_size, dst_len);
1213 ret = bch2_encrypt_bio(c, op->csum_type,
1214 extent_nonce(version, crc), dst);
1218 crc.csum = bch2_checksum_bio(c, op->csum_type,
1219 extent_nonce(version, crc), dst);
1220 crc.csum_type = op->csum_type;
1221 swap(dst->bi_iter.bi_size, dst_len);
1224 init_append_extent(op, wp, version, crc);
1227 bio_advance(dst, dst_len);
1228 bio_advance(src, src_len);
1229 total_output += dst_len;
1230 total_input += src_len;
1231 } while (dst->bi_iter.bi_size &&
1232 src->bi_iter.bi_size &&
1234 !bch2_keylist_realloc(&op->insert_keys,
1236 ARRAY_SIZE(op->inline_keys),
1237 BKEY_EXTENT_U64s_MAX));
1239 more = src->bi_iter.bi_size != 0;
1241 dst->bi_iter = saved_iter;
1243 if (dst == src && more) {
1244 BUG_ON(total_output != total_input);
1246 dst = bio_split(src, total_input >> 9,
1247 GFP_NOIO, &c->bio_write);
1248 wbio_init(dst)->put_bio = true;
1249 /* copy WRITE_SYNC flag */
1250 dst->bi_opf = src->bi_opf;
1253 dst->bi_iter.bi_size = total_output;
1258 bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1261 if (to_wbio(dst)->bounce)
1262 bch2_bio_free_pages_pool(c, dst);
1263 if (to_wbio(dst)->put_bio)
1269 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1272 struct bch_fs *c = op->c;
1273 struct bkey_s_c_extent e;
1274 struct extent_ptr_decoded p;
1275 const union bch_extent_entry *entry;
1276 unsigned replicas = 0;
1278 if (k.k->type != KEY_TYPE_extent)
1281 e = bkey_s_c_to_extent(k);
1282 extent_for_each_ptr_decode(e, p, entry) {
1283 if (p.crc.csum_type ||
1284 crc_is_compressed(p.crc) ||
1288 replicas += bch2_extent_ptr_durability(c, &p);
1291 return replicas >= op->opts.data_replicas;
1294 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1296 struct bch_fs *c = op->c;
1297 const struct bch_extent_ptr *ptr;
1300 for_each_keylist_key(&op->insert_keys, k) {
1301 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1303 bkey_for_each_ptr(ptrs, ptr)
1304 bch2_bucket_nocow_unlock(&c->nocow_locks,
1305 PTR_BUCKET_POS(c, ptr),
1306 BUCKET_NOCOW_LOCK_UPDATE);
1310 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1311 struct btree_iter *iter,
1312 struct bkey_i *orig,
1317 struct bkey_ptrs ptrs;
1318 struct bch_extent_ptr *ptr;
1321 if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1326 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1327 ret = PTR_ERR_OR_ZERO(new);
1331 bkey_reassemble(new, k);
1333 bch2_cut_front(bkey_start_pos(&orig->k), new);
1334 bch2_cut_back(orig->k.p, new);
1336 ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1337 bkey_for_each_ptr(ptrs, ptr)
1341 * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1342 * that was done when we kicked off the write, and here it's important
1343 * that we update the extent that we wrote to - even if a snapshot has
1344 * since been created. The write is still outstanding, so we're ok
1345 * w.r.t. snapshot atomicity:
1347 return bch2_extent_update_i_size_sectors(trans, iter,
1348 min(new->k.p.offset << 9, new_i_size), 0) ?:
1349 bch2_trans_update(trans, iter, new,
1350 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1353 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1355 struct bch_fs *c = op->c;
1356 struct btree_trans trans;
1357 struct btree_iter iter;
1358 struct bkey_i *orig;
1362 bch2_trans_init(&trans, c, 0, 0);
1364 for_each_keylist_key(&op->insert_keys, orig) {
1365 ret = for_each_btree_key_commit(&trans, iter, BTREE_ID_extents,
1366 bkey_start_pos(&orig->k),
1367 BTREE_ITER_INTENT, k,
1368 NULL, NULL, BTREE_INSERT_NOFAIL, ({
1369 if (bkey_ge(bkey_start_pos(k.k), orig->k.p))
1372 bch2_nocow_write_convert_one_unwritten(&trans, &iter, orig, k, op->new_i_size);
1376 struct bkey_i *k = bch2_keylist_front(&op->insert_keys);
1378 bch_err_inum_offset_ratelimited(c,
1379 k->k.p.inode, k->k.p.offset << 9,
1380 "write error while doing btree update: %s",
1387 bch2_trans_exit(&trans);
1390 static void __bch2_nocow_write_done(struct bch_write_op *op)
1392 bch2_nocow_write_unlock(op);
1394 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1396 } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1397 bch2_nocow_write_convert_unwritten(op);
1400 static void bch2_nocow_write_done(struct closure *cl)
1402 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1404 __bch2_nocow_write_done(op);
1405 bch2_write_done(cl);
1408 static void bch2_nocow_write(struct bch_write_op *op)
1410 struct bch_fs *c = op->c;
1411 struct btree_trans trans;
1412 struct btree_iter iter;
1414 struct bkey_ptrs_c ptrs;
1415 const struct bch_extent_ptr *ptr, *ptr2;
1419 two_state_lock_t *l;
1420 } buckets[BCH_REPLICAS_MAX];
1421 unsigned nr_buckets = 0;
1425 if (op->flags & BCH_WRITE_MOVE)
1428 bch2_trans_init(&trans, c, 0, 0);
1430 bch2_trans_begin(&trans);
1432 ret = bch2_subvolume_get_snapshot(&trans, op->subvol, &snapshot);
1436 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
1437 SPOS(op->pos.inode, op->pos.offset, snapshot),
1440 struct bio *bio = &op->wbio.bio;
1444 k = bch2_btree_iter_peek_slot(&iter);
1449 /* fall back to normal cow write path? */
1450 if (unlikely(k.k->p.snapshot != snapshot ||
1451 !bch2_extent_is_writeable(op, k)))
1454 if (bch2_keylist_realloc(&op->insert_keys,
1456 ARRAY_SIZE(op->inline_keys),
1460 /* Get iorefs before dropping btree locks: */
1461 ptrs = bch2_bkey_ptrs_c(k);
1462 bkey_for_each_ptr(ptrs, ptr) {
1463 buckets[nr_buckets].b = PTR_BUCKET_POS(c, ptr);
1464 buckets[nr_buckets].gen = ptr->gen;
1465 buckets[nr_buckets].l =
1466 bucket_nocow_lock(&c->nocow_locks, buckets[nr_buckets].b);
1468 prefetch(buckets[nr_buckets].l);
1471 if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1475 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1478 /* Unlock before taking nocow locks, doing IO: */
1479 bkey_reassemble(op->insert_keys.top, k);
1480 bch2_trans_unlock(&trans);
1482 bch2_cut_front(op->pos, op->insert_keys.top);
1483 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1484 bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1486 for (i = 0; i < nr_buckets; i++) {
1487 struct bch_dev *ca = bch_dev_bkey_exists(c, buckets[i].b.inode);
1488 two_state_lock_t *l = buckets[i].l;
1491 if (!bch2_two_state_trylock(l, BUCKET_NOCOW_LOCK_UPDATE))
1492 __bch2_bucket_nocow_lock(&c->nocow_locks, l, BUCKET_NOCOW_LOCK_UPDATE);
1495 stale = gen_after(*bucket_gen(ca, buckets[i].b.offset), buckets[i].gen);
1498 if (unlikely(stale))
1499 goto err_bucket_stale;
1502 bio = &op->wbio.bio;
1503 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1504 bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1505 GFP_KERNEL, &c->bio_write);
1506 wbio_init(bio)->put_bio = true;
1507 bio->bi_opf = op->wbio.bio.bi_opf;
1509 op->flags |= BCH_WRITE_DONE;
1512 op->pos.offset += bio_sectors(bio);
1513 op->written += bio_sectors(bio);
1515 bio->bi_end_io = bch2_write_endio;
1516 bio->bi_private = &op->cl;
1517 bio->bi_opf |= REQ_OP_WRITE;
1518 closure_get(&op->cl);
1519 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1520 op->insert_keys.top, true);
1522 bch2_keylist_push(&op->insert_keys);
1523 if (op->flags & BCH_WRITE_DONE)
1525 bch2_btree_iter_advance(&iter);
1528 bch2_trans_iter_exit(&trans, &iter);
1530 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1534 bch_err_inum_offset_ratelimited(c,
1536 op->pos.offset << 9,
1537 "%s: btree lookup error %s",
1538 __func__, bch2_err_str(ret));
1540 op->flags |= BCH_WRITE_DONE;
1543 bch2_trans_exit(&trans);
1545 /* fallback to cow write path? */
1546 if (!(op->flags & BCH_WRITE_DONE)) {
1547 closure_sync(&op->cl);
1548 __bch2_nocow_write_done(op);
1549 op->insert_keys.top = op->insert_keys.keys;
1550 } else if (op->flags & BCH_WRITE_SYNC) {
1551 closure_sync(&op->cl);
1552 bch2_nocow_write_done(&op->cl);
1556 * needs to run out of process context because ei_quota_lock is
1559 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1563 bkey_for_each_ptr(ptrs, ptr2) {
1567 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1570 /* Fall back to COW path: */
1574 bch2_bucket_nocow_unlock(&c->nocow_locks,
1576 BUCKET_NOCOW_LOCK_UPDATE);
1578 bkey_for_each_ptr(ptrs, ptr2)
1579 percpu_ref_put(&bch_dev_bkey_exists(c, ptr2->dev)->io_ref);
1581 /* We can retry this: */
1582 ret = BCH_ERR_transaction_restart;
1586 static void __bch2_write(struct bch_write_op *op)
1588 struct bch_fs *c = op->c;
1589 struct write_point *wp = NULL;
1590 struct bio *bio = NULL;
1591 unsigned nofs_flags;
1594 nofs_flags = memalloc_nofs_save();
1596 if (unlikely(op->opts.nocow)) {
1597 bch2_nocow_write(op);
1598 if (op->flags & BCH_WRITE_DONE)
1599 goto out_nofs_restore;
1602 memset(&op->failed, 0, sizeof(op->failed));
1603 op->btree_update_ready = false;
1606 struct bkey_i *key_to_write;
1607 unsigned key_to_write_offset = op->insert_keys.top_p -
1608 op->insert_keys.keys_p;
1610 /* +1 for possible cache device: */
1611 if (op->open_buckets.nr + op->nr_replicas + 1 >
1612 ARRAY_SIZE(op->open_buckets.v))
1615 if (bch2_keylist_realloc(&op->insert_keys,
1617 ARRAY_SIZE(op->inline_keys),
1618 BKEY_EXTENT_U64s_MAX))
1622 * The copygc thread is now global, which means it's no longer
1623 * freeing up space on specific disks, which means that
1624 * allocations for specific disks may hang arbitrarily long:
1626 ret = bch2_trans_do(c, NULL, NULL, 0,
1627 bch2_alloc_sectors_start_trans(&trans,
1629 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1633 op->nr_replicas_required,
1636 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1637 BCH_WRITE_ONLY_SPECIFIED_DEVS))
1638 ? NULL : &op->cl, &wp));
1639 if (unlikely(ret)) {
1646 ret = bch2_write_extent(op, wp, &bio);
1649 bch2_open_bucket_get(c, wp, &op->open_buckets);
1650 bch2_alloc_sectors_done_inlined(c, wp);
1653 if (!(op->flags & BCH_WRITE_SYNC)) {
1654 spin_lock(&wp->writes_lock);
1656 list_add_tail(&op->wp_list, &wp->writes);
1657 spin_unlock(&wp->writes_lock);
1660 op->flags |= BCH_WRITE_DONE;
1668 bio->bi_end_io = bch2_write_endio;
1669 bio->bi_private = &op->cl;
1670 bio->bi_opf |= REQ_OP_WRITE;
1672 closure_get(bio->bi_private);
1674 key_to_write = (void *) (op->insert_keys.keys_p +
1675 key_to_write_offset);
1677 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1678 key_to_write, false);
1684 * If we're running asynchronously, wne may still want to block
1685 * synchronously here if we weren't able to submit all of the IO at
1686 * once, as that signals backpressure to the caller.
1688 if ((op->flags & BCH_WRITE_SYNC) || !(op->flags & BCH_WRITE_DONE)) {
1689 closure_sync(&op->cl);
1690 __bch2_write_index(op);
1692 if (!(op->flags & BCH_WRITE_DONE))
1694 bch2_write_done(&op->cl);
1696 continue_at(&op->cl, bch2_write_index, NULL);
1699 memalloc_nofs_restore(nofs_flags);
1702 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1704 struct bio *bio = &op->wbio.bio;
1705 struct bvec_iter iter;
1706 struct bkey_i_inline_data *id;
1710 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1712 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1713 ARRAY_SIZE(op->inline_keys),
1714 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1720 sectors = bio_sectors(bio);
1721 op->pos.offset += sectors;
1723 id = bkey_inline_data_init(op->insert_keys.top);
1725 id->k.version = op->version;
1726 id->k.size = sectors;
1728 iter = bio->bi_iter;
1729 iter.bi_size = data_len;
1730 memcpy_from_bio(id->v.data, bio, iter);
1732 while (data_len & 7)
1733 id->v.data[data_len++] = '\0';
1734 set_bkey_val_bytes(&id->k, data_len);
1735 bch2_keylist_push(&op->insert_keys);
1737 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1738 op->flags |= BCH_WRITE_DONE;
1740 __bch2_write_index(op);
1742 bch2_write_done(&op->cl);
1746 * bch_write - handle a write to a cache device or flash only volume
1748 * This is the starting point for any data to end up in a cache device; it could
1749 * be from a normal write, or a writeback write, or a write to a flash only
1750 * volume - it's also used by the moving garbage collector to compact data in
1751 * mostly empty buckets.
1753 * It first writes the data to the cache, creating a list of keys to be inserted
1754 * (if the data won't fit in a single open bucket, there will be multiple keys);
1755 * after the data is written it calls bch_journal, and after the keys have been
1756 * added to the next journal write they're inserted into the btree.
1758 * If op->discard is true, instead of inserting the data it invalidates the
1759 * region of the cache represented by op->bio and op->inode.
1761 void bch2_write(struct closure *cl)
1763 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
1764 struct bio *bio = &op->wbio.bio;
1765 struct bch_fs *c = op->c;
1768 EBUG_ON(op->cl.parent);
1769 BUG_ON(!op->nr_replicas);
1770 BUG_ON(!op->write_point.v);
1771 BUG_ON(bkey_eq(op->pos, POS_MAX));
1773 op->start_time = local_clock();
1774 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1775 wbio_init(bio)->put_bio = false;
1777 if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1778 bch_err_inum_offset_ratelimited(c,
1780 op->pos.offset << 9,
1781 "misaligned write");
1786 if (c->opts.nochanges ||
1787 !percpu_ref_tryget_live(&c->writes)) {
1792 this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1793 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1795 data_len = min_t(u64, bio->bi_iter.bi_size,
1796 op->new_i_size - (op->pos.offset << 9));
1798 if (c->opts.inline_data &&
1799 data_len <= min(block_bytes(c) / 2, 1024U)) {
1800 bch2_write_data_inline(op, data_len);
1807 bch2_disk_reservation_put(c, &op->res);
1809 closure_debug_destroy(&op->cl);
1814 /* Cache promotion on read */
1817 struct rcu_head rcu;
1820 struct rhash_head hash;
1823 struct data_update write;
1824 struct bio_vec bi_inline_vecs[0]; /* must be last */
1827 static const struct rhashtable_params bch_promote_params = {
1828 .head_offset = offsetof(struct promote_op, hash),
1829 .key_offset = offsetof(struct promote_op, pos),
1830 .key_len = sizeof(struct bpos),
1833 static inline bool should_promote(struct bch_fs *c, struct bkey_s_c k,
1835 struct bch_io_opts opts,
1838 if (!(flags & BCH_READ_MAY_PROMOTE))
1841 if (!opts.promote_target)
1844 if (bch2_bkey_has_target(c, k, opts.promote_target))
1847 if (bkey_extent_is_unwritten(k))
1850 if (bch2_target_congested(c, opts.promote_target)) {
1851 /* XXX trace this */
1855 if (rhashtable_lookup_fast(&c->promote_table, &pos,
1856 bch_promote_params))
1862 static void promote_free(struct bch_fs *c, struct promote_op *op)
1866 ret = rhashtable_remove_fast(&c->promote_table, &op->hash,
1867 bch_promote_params);
1869 percpu_ref_put(&c->writes);
1873 static void promote_done(struct bch_write_op *wop)
1875 struct promote_op *op =
1876 container_of(wop, struct promote_op, write.op);
1877 struct bch_fs *c = op->write.op.c;
1879 bch2_time_stats_update(&c->times[BCH_TIME_data_promote],
1882 bch2_data_update_exit(&op->write);
1883 promote_free(c, op);
1886 static void promote_start(struct promote_op *op, struct bch_read_bio *rbio)
1888 struct bio *bio = &op->write.op.wbio.bio;
1890 trace_and_count(op->write.op.c, read_promote, &rbio->bio);
1892 /* we now own pages: */
1893 BUG_ON(!rbio->bounce);
1894 BUG_ON(rbio->bio.bi_vcnt > bio->bi_max_vecs);
1896 memcpy(bio->bi_io_vec, rbio->bio.bi_io_vec,
1897 sizeof(struct bio_vec) * rbio->bio.bi_vcnt);
1898 swap(bio->bi_vcnt, rbio->bio.bi_vcnt);
1900 bch2_data_update_read_done(&op->write, rbio->pick.crc);
1903 static struct promote_op *__promote_alloc(struct bch_fs *c,
1904 enum btree_id btree_id,
1907 struct extent_ptr_decoded *pick,
1908 struct bch_io_opts opts,
1910 struct bch_read_bio **rbio)
1912 struct promote_op *op = NULL;
1914 unsigned pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
1917 if (!percpu_ref_tryget_live(&c->writes))
1920 op = kzalloc(sizeof(*op) + sizeof(struct bio_vec) * pages, GFP_NOIO);
1924 op->start_time = local_clock();
1928 * We don't use the mempool here because extents that aren't
1929 * checksummed or compressed can be too big for the mempool:
1931 *rbio = kzalloc(sizeof(struct bch_read_bio) +
1932 sizeof(struct bio_vec) * pages,
1937 rbio_init(&(*rbio)->bio, opts);
1938 bio_init(&(*rbio)->bio, NULL, (*rbio)->bio.bi_inline_vecs, pages, 0);
1940 if (bch2_bio_alloc_pages(&(*rbio)->bio, sectors << 9,
1944 (*rbio)->bounce = true;
1945 (*rbio)->split = true;
1946 (*rbio)->kmalloc = true;
1948 if (rhashtable_lookup_insert_fast(&c->promote_table, &op->hash,
1949 bch_promote_params))
1952 bio = &op->write.op.wbio.bio;
1953 bio_init(bio, NULL, bio->bi_inline_vecs, pages, 0);
1955 ret = bch2_data_update_init(c, &op->write,
1956 writepoint_hashed((unsigned long) current),
1958 (struct data_update_opts) {
1959 .target = opts.promote_target,
1960 .extra_replicas = 1,
1961 .write_flags = BCH_WRITE_ALLOC_NOWAIT|BCH_WRITE_CACHED,
1965 op->write.op.end_io = promote_done;
1970 bio_free_pages(&(*rbio)->bio);
1974 percpu_ref_put(&c->writes);
1979 static struct promote_op *promote_alloc(struct bch_fs *c,
1980 struct bvec_iter iter,
1982 struct extent_ptr_decoded *pick,
1983 struct bch_io_opts opts,
1985 struct bch_read_bio **rbio,
1989 bool promote_full = *read_full || READ_ONCE(c->promote_whole_extents);
1990 /* data might have to be decompressed in the write path: */
1991 unsigned sectors = promote_full
1992 ? max(pick->crc.compressed_size, pick->crc.live_size)
1993 : bvec_iter_sectors(iter);
1994 struct bpos pos = promote_full
1995 ? bkey_start_pos(k.k)
1996 : POS(k.k->p.inode, iter.bi_sector);
1997 struct promote_op *promote;
1999 if (!should_promote(c, k, pos, opts, flags))
2002 promote = __promote_alloc(c,
2003 k.k->type == KEY_TYPE_reflink_v
2006 k, pos, pick, opts, sectors, rbio);
2011 *read_full = promote_full;
2017 #define READ_RETRY_AVOID 1
2018 #define READ_RETRY 2
2023 RBIO_CONTEXT_HIGHPRI,
2024 RBIO_CONTEXT_UNBOUND,
2027 static inline struct bch_read_bio *
2028 bch2_rbio_parent(struct bch_read_bio *rbio)
2030 return rbio->split ? rbio->parent : rbio;
2034 static void bch2_rbio_punt(struct bch_read_bio *rbio, work_func_t fn,
2035 enum rbio_context context,
2036 struct workqueue_struct *wq)
2038 if (context <= rbio->context) {
2041 rbio->work.func = fn;
2042 rbio->context = context;
2043 queue_work(wq, &rbio->work);
2047 static inline struct bch_read_bio *bch2_rbio_free(struct bch_read_bio *rbio)
2049 BUG_ON(rbio->bounce && !rbio->split);
2052 promote_free(rbio->c, rbio->promote);
2053 rbio->promote = NULL;
2056 bch2_bio_free_pages_pool(rbio->c, &rbio->bio);
2059 struct bch_read_bio *parent = rbio->parent;
2064 bio_put(&rbio->bio);
2073 * Only called on a top level bch_read_bio to complete an entire read request,
2076 static void bch2_rbio_done(struct bch_read_bio *rbio)
2078 if (rbio->start_time)
2079 bch2_time_stats_update(&rbio->c->times[BCH_TIME_data_read],
2081 bio_endio(&rbio->bio);
2084 static void bch2_read_retry_nodecode(struct bch_fs *c, struct bch_read_bio *rbio,
2085 struct bvec_iter bvec_iter,
2086 struct bch_io_failures *failed,
2089 struct btree_trans trans;
2090 struct btree_iter iter;
2095 flags &= ~BCH_READ_LAST_FRAGMENT;
2096 flags |= BCH_READ_MUST_CLONE;
2098 bch2_bkey_buf_init(&sk);
2099 bch2_trans_init(&trans, c, 0, 0);
2101 bch2_trans_iter_init(&trans, &iter, rbio->data_btree,
2102 rbio->read_pos, BTREE_ITER_SLOTS);
2104 rbio->bio.bi_status = 0;
2106 k = bch2_btree_iter_peek_slot(&iter);
2110 bch2_bkey_buf_reassemble(&sk, c, k);
2111 k = bkey_i_to_s_c(sk.k);
2112 bch2_trans_unlock(&trans);
2114 if (!bch2_bkey_matches_ptr(c, k,
2116 rbio->data_pos.offset -
2117 rbio->pick.crc.offset)) {
2118 /* extent we wanted to read no longer exists: */
2123 ret = __bch2_read_extent(&trans, rbio, bvec_iter,
2126 k, 0, failed, flags);
2127 if (ret == READ_RETRY)
2132 bch2_rbio_done(rbio);
2133 bch2_trans_iter_exit(&trans, &iter);
2134 bch2_trans_exit(&trans);
2135 bch2_bkey_buf_exit(&sk, c);
2138 rbio->bio.bi_status = BLK_STS_IOERR;
2142 static void bch2_rbio_retry(struct work_struct *work)
2144 struct bch_read_bio *rbio =
2145 container_of(work, struct bch_read_bio, work);
2146 struct bch_fs *c = rbio->c;
2147 struct bvec_iter iter = rbio->bvec_iter;
2148 unsigned flags = rbio->flags;
2149 subvol_inum inum = {
2150 .subvol = rbio->subvol,
2151 .inum = rbio->read_pos.inode,
2153 struct bch_io_failures failed = { .nr = 0 };
2155 trace_and_count(c, read_retry, &rbio->bio);
2157 if (rbio->retry == READ_RETRY_AVOID)
2158 bch2_mark_io_failure(&failed, &rbio->pick);
2160 rbio->bio.bi_status = 0;
2162 rbio = bch2_rbio_free(rbio);
2164 flags |= BCH_READ_IN_RETRY;
2165 flags &= ~BCH_READ_MAY_PROMOTE;
2167 if (flags & BCH_READ_NODECODE) {
2168 bch2_read_retry_nodecode(c, rbio, iter, &failed, flags);
2170 flags &= ~BCH_READ_LAST_FRAGMENT;
2171 flags |= BCH_READ_MUST_CLONE;
2173 __bch2_read(c, rbio, iter, inum, &failed, flags);
2177 static void bch2_rbio_error(struct bch_read_bio *rbio, int retry,
2180 rbio->retry = retry;
2182 if (rbio->flags & BCH_READ_IN_RETRY)
2185 if (retry == READ_ERR) {
2186 rbio = bch2_rbio_free(rbio);
2188 rbio->bio.bi_status = error;
2189 bch2_rbio_done(rbio);
2191 bch2_rbio_punt(rbio, bch2_rbio_retry,
2192 RBIO_CONTEXT_UNBOUND, system_unbound_wq);
2196 static int __bch2_rbio_narrow_crcs(struct btree_trans *trans,
2197 struct bch_read_bio *rbio)
2199 struct bch_fs *c = rbio->c;
2200 u64 data_offset = rbio->data_pos.offset - rbio->pick.crc.offset;
2201 struct bch_extent_crc_unpacked new_crc;
2202 struct btree_iter iter;
2207 if (crc_is_compressed(rbio->pick.crc))
2210 bch2_trans_iter_init(trans, &iter, rbio->data_btree, rbio->data_pos,
2211 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2212 k = bch2_btree_iter_peek_slot(&iter);
2213 if ((ret = bkey_err(k)))
2216 if (bversion_cmp(k.k->version, rbio->version) ||
2217 !bch2_bkey_matches_ptr(c, k, rbio->pick.ptr, data_offset))
2220 /* Extent was merged? */
2221 if (bkey_start_offset(k.k) < data_offset ||
2222 k.k->p.offset > data_offset + rbio->pick.crc.uncompressed_size)
2225 if (bch2_rechecksum_bio(c, &rbio->bio, rbio->version,
2226 rbio->pick.crc, NULL, &new_crc,
2227 bkey_start_offset(k.k) - data_offset, k.k->size,
2228 rbio->pick.crc.csum_type)) {
2229 bch_err(c, "error verifying existing checksum while narrowing checksum (memory corruption?)");
2235 * going to be temporarily appending another checksum entry:
2237 new = bch2_trans_kmalloc(trans, bkey_bytes(k.k) +
2238 sizeof(struct bch_extent_crc128));
2239 if ((ret = PTR_ERR_OR_ZERO(new)))
2242 bkey_reassemble(new, k);
2244 if (!bch2_bkey_narrow_crcs(new, new_crc))
2247 ret = bch2_trans_update(trans, &iter, new,
2248 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
2250 bch2_trans_iter_exit(trans, &iter);
2254 static noinline void bch2_rbio_narrow_crcs(struct bch_read_bio *rbio)
2256 bch2_trans_do(rbio->c, NULL, NULL, BTREE_INSERT_NOFAIL,
2257 __bch2_rbio_narrow_crcs(&trans, rbio));
2260 /* Inner part that may run in process context */
2261 static void __bch2_read_endio(struct work_struct *work)
2263 struct bch_read_bio *rbio =
2264 container_of(work, struct bch_read_bio, work);
2265 struct bch_fs *c = rbio->c;
2266 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2267 struct bio *src = &rbio->bio;
2268 struct bio *dst = &bch2_rbio_parent(rbio)->bio;
2269 struct bvec_iter dst_iter = rbio->bvec_iter;
2270 struct bch_extent_crc_unpacked crc = rbio->pick.crc;
2271 struct nonce nonce = extent_nonce(rbio->version, crc);
2272 unsigned nofs_flags;
2273 struct bch_csum csum;
2276 nofs_flags = memalloc_nofs_save();
2278 /* Reset iterator for checksumming and copying bounced data: */
2280 src->bi_iter.bi_size = crc.compressed_size << 9;
2281 src->bi_iter.bi_idx = 0;
2282 src->bi_iter.bi_bvec_done = 0;
2284 src->bi_iter = rbio->bvec_iter;
2287 csum = bch2_checksum_bio(c, crc.csum_type, nonce, src);
2288 if (bch2_crc_cmp(csum, rbio->pick.crc.csum))
2293 * We need to rework the narrow_crcs path to deliver the read completion
2294 * first, and then punt to a different workqueue, otherwise we're
2295 * holding up reads while doing btree updates which is bad for memory
2298 if (unlikely(rbio->narrow_crcs))
2299 bch2_rbio_narrow_crcs(rbio);
2301 if (rbio->flags & BCH_READ_NODECODE)
2304 /* Adjust crc to point to subset of data we want: */
2305 crc.offset += rbio->offset_into_extent;
2306 crc.live_size = bvec_iter_sectors(rbio->bvec_iter);
2308 if (crc_is_compressed(crc)) {
2309 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2313 if (bch2_bio_uncompress(c, src, dst, dst_iter, crc))
2314 goto decompression_err;
2316 /* don't need to decrypt the entire bio: */
2317 nonce = nonce_add(nonce, crc.offset << 9);
2318 bio_advance(src, crc.offset << 9);
2320 BUG_ON(src->bi_iter.bi_size < dst_iter.bi_size);
2321 src->bi_iter.bi_size = dst_iter.bi_size;
2323 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2328 struct bvec_iter src_iter = src->bi_iter;
2329 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
2333 if (rbio->promote) {
2335 * Re encrypt data we decrypted, so it's consistent with
2338 ret = bch2_encrypt_bio(c, crc.csum_type, nonce, src);
2342 promote_start(rbio->promote, rbio);
2343 rbio->promote = NULL;
2346 if (likely(!(rbio->flags & BCH_READ_IN_RETRY))) {
2347 rbio = bch2_rbio_free(rbio);
2348 bch2_rbio_done(rbio);
2351 memalloc_nofs_restore(nofs_flags);
2355 * Checksum error: if the bio wasn't bounced, we may have been
2356 * reading into buffers owned by userspace (that userspace can
2357 * scribble over) - retry the read, bouncing it this time:
2359 if (!rbio->bounce && (rbio->flags & BCH_READ_USER_MAPPED)) {
2360 rbio->flags |= BCH_READ_MUST_BOUNCE;
2361 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_IOERR);
2365 bch_err_inum_offset_ratelimited(ca,
2366 rbio->read_pos.inode,
2367 rbio->read_pos.offset << 9,
2368 "data checksum error: expected %0llx:%0llx got %0llx:%0llx (type %s)",
2369 rbio->pick.crc.csum.hi, rbio->pick.crc.csum.lo,
2370 csum.hi, csum.lo, bch2_csum_types[crc.csum_type]);
2372 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2375 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2376 rbio->read_pos.offset << 9,
2377 "decompression error");
2378 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2381 bch_err_inum_offset_ratelimited(c, rbio->read_pos.inode,
2382 rbio->read_pos.offset << 9,
2384 bch2_rbio_error(rbio, READ_ERR, BLK_STS_IOERR);
2388 static void bch2_read_endio(struct bio *bio)
2390 struct bch_read_bio *rbio =
2391 container_of(bio, struct bch_read_bio, bio);
2392 struct bch_fs *c = rbio->c;
2393 struct bch_dev *ca = bch_dev_bkey_exists(c, rbio->pick.ptr.dev);
2394 struct workqueue_struct *wq = NULL;
2395 enum rbio_context context = RBIO_CONTEXT_NULL;
2397 if (rbio->have_ioref) {
2398 bch2_latency_acct(ca, rbio->submit_time, READ);
2399 percpu_ref_put(&ca->io_ref);
2403 rbio->bio.bi_end_io = rbio->end_io;
2405 if (bch2_dev_inum_io_err_on(bio->bi_status, ca,
2406 rbio->read_pos.inode,
2407 rbio->read_pos.offset,
2408 "data read error: %s",
2409 bch2_blk_status_to_str(bio->bi_status))) {
2410 bch2_rbio_error(rbio, READ_RETRY_AVOID, bio->bi_status);
2414 if (((rbio->flags & BCH_READ_RETRY_IF_STALE) && race_fault()) ||
2415 ptr_stale(ca, &rbio->pick.ptr)) {
2416 trace_and_count(c, read_reuse_race, &rbio->bio);
2418 if (rbio->flags & BCH_READ_RETRY_IF_STALE)
2419 bch2_rbio_error(rbio, READ_RETRY, BLK_STS_AGAIN);
2421 bch2_rbio_error(rbio, READ_ERR, BLK_STS_AGAIN);
2425 if (rbio->narrow_crcs ||
2427 crc_is_compressed(rbio->pick.crc) ||
2428 bch2_csum_type_is_encryption(rbio->pick.crc.csum_type))
2429 context = RBIO_CONTEXT_UNBOUND, wq = system_unbound_wq;
2430 else if (rbio->pick.crc.csum_type)
2431 context = RBIO_CONTEXT_HIGHPRI, wq = system_highpri_wq;
2433 bch2_rbio_punt(rbio, __bch2_read_endio, context, wq);
2436 int __bch2_read_indirect_extent(struct btree_trans *trans,
2437 unsigned *offset_into_extent,
2438 struct bkey_buf *orig_k)
2440 struct btree_iter iter;
2445 reflink_offset = le64_to_cpu(bkey_i_to_reflink_p(orig_k->k)->v.idx) +
2446 *offset_into_extent;
2448 bch2_trans_iter_init(trans, &iter, BTREE_ID_reflink,
2449 POS(0, reflink_offset),
2451 k = bch2_btree_iter_peek_slot(&iter);
2456 if (k.k->type != KEY_TYPE_reflink_v &&
2457 k.k->type != KEY_TYPE_indirect_inline_data) {
2458 bch_err_inum_offset_ratelimited(trans->c,
2459 orig_k->k->k.p.inode,
2460 orig_k->k->k.p.offset << 9,
2461 "%llu len %u points to nonexistent indirect extent %llu",
2462 orig_k->k->k.p.offset,
2465 bch2_inconsistent_error(trans->c);
2470 *offset_into_extent = iter.pos.offset - bkey_start_offset(k.k);
2471 bch2_bkey_buf_reassemble(orig_k, trans->c, k);
2473 bch2_trans_iter_exit(trans, &iter);
2477 static noinline void read_from_stale_dirty_pointer(struct btree_trans *trans,
2479 struct bch_extent_ptr ptr)
2481 struct bch_fs *c = trans->c;
2482 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr.dev);
2483 struct btree_iter iter;
2484 struct printbuf buf = PRINTBUF;
2487 bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
2488 PTR_BUCKET_POS(c, &ptr),
2491 prt_printf(&buf, "Attempting to read from stale dirty pointer:");
2492 printbuf_indent_add(&buf, 2);
2495 bch2_bkey_val_to_text(&buf, c, k);
2498 prt_printf(&buf, "memory gen: %u", *bucket_gen(ca, iter.pos.offset));
2500 ret = lockrestart_do(trans, bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
2503 bch2_bkey_val_to_text(&buf, c, k);
2506 bch2_fs_inconsistent(c, "%s", buf.buf);
2508 bch2_trans_iter_exit(trans, &iter);
2509 printbuf_exit(&buf);
2512 int __bch2_read_extent(struct btree_trans *trans, struct bch_read_bio *orig,
2513 struct bvec_iter iter, struct bpos read_pos,
2514 enum btree_id data_btree, struct bkey_s_c k,
2515 unsigned offset_into_extent,
2516 struct bch_io_failures *failed, unsigned flags)
2518 struct bch_fs *c = trans->c;
2519 struct extent_ptr_decoded pick;
2520 struct bch_read_bio *rbio = NULL;
2521 struct bch_dev *ca = NULL;
2522 struct promote_op *promote = NULL;
2523 bool bounce = false, read_full = false, narrow_crcs = false;
2524 struct bpos data_pos = bkey_start_pos(k.k);
2527 if (bkey_extent_is_inline_data(k.k)) {
2528 unsigned bytes = min_t(unsigned, iter.bi_size,
2529 bkey_inline_data_bytes(k.k));
2531 swap(iter.bi_size, bytes);
2532 memcpy_to_bio(&orig->bio, iter, bkey_inline_data_p(k));
2533 swap(iter.bi_size, bytes);
2534 bio_advance_iter(&orig->bio, &iter, bytes);
2535 zero_fill_bio_iter(&orig->bio, iter);
2539 pick_ret = bch2_bkey_pick_read_device(c, k, failed, &pick);
2541 /* hole or reservation - just zero fill: */
2546 bch_err_inum_offset_ratelimited(c,
2547 read_pos.inode, read_pos.offset << 9,
2548 "no device to read from");
2552 ca = bch_dev_bkey_exists(c, pick.ptr.dev);
2555 * Stale dirty pointers are treated as IO errors, but @failed isn't
2556 * allocated unless we're in the retry path - so if we're not in the
2557 * retry path, don't check here, it'll be caught in bch2_read_endio()
2558 * and we'll end up in the retry path:
2560 if ((flags & BCH_READ_IN_RETRY) &&
2562 unlikely(ptr_stale(ca, &pick.ptr))) {
2563 read_from_stale_dirty_pointer(trans, k, pick.ptr);
2564 bch2_mark_io_failure(failed, &pick);
2569 * Unlock the iterator while the btree node's lock is still in
2570 * cache, before doing the IO:
2572 bch2_trans_unlock(trans);
2574 if (flags & BCH_READ_NODECODE) {
2576 * can happen if we retry, and the extent we were going to read
2577 * has been merged in the meantime:
2579 if (pick.crc.compressed_size > orig->bio.bi_vcnt * PAGE_SECTORS)
2582 iter.bi_size = pick.crc.compressed_size << 9;
2586 if (!(flags & BCH_READ_LAST_FRAGMENT) ||
2587 bio_flagged(&orig->bio, BIO_CHAIN))
2588 flags |= BCH_READ_MUST_CLONE;
2590 narrow_crcs = !(flags & BCH_READ_IN_RETRY) &&
2591 bch2_can_narrow_extent_crcs(k, pick.crc);
2593 if (narrow_crcs && (flags & BCH_READ_USER_MAPPED))
2594 flags |= BCH_READ_MUST_BOUNCE;
2596 EBUG_ON(offset_into_extent + bvec_iter_sectors(iter) > k.k->size);
2598 if (crc_is_compressed(pick.crc) ||
2599 (pick.crc.csum_type != BCH_CSUM_none &&
2600 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2601 (bch2_csum_type_is_encryption(pick.crc.csum_type) &&
2602 (flags & BCH_READ_USER_MAPPED)) ||
2603 (flags & BCH_READ_MUST_BOUNCE)))) {
2608 if (orig->opts.promote_target)
2609 promote = promote_alloc(c, iter, k, &pick, orig->opts, flags,
2610 &rbio, &bounce, &read_full);
2613 EBUG_ON(crc_is_compressed(pick.crc));
2614 EBUG_ON(pick.crc.csum_type &&
2615 (bvec_iter_sectors(iter) != pick.crc.uncompressed_size ||
2616 bvec_iter_sectors(iter) != pick.crc.live_size ||
2618 offset_into_extent));
2620 data_pos.offset += offset_into_extent;
2621 pick.ptr.offset += pick.crc.offset +
2623 offset_into_extent = 0;
2624 pick.crc.compressed_size = bvec_iter_sectors(iter);
2625 pick.crc.uncompressed_size = bvec_iter_sectors(iter);
2626 pick.crc.offset = 0;
2627 pick.crc.live_size = bvec_iter_sectors(iter);
2628 offset_into_extent = 0;
2633 * promote already allocated bounce rbio:
2634 * promote needs to allocate a bio big enough for uncompressing
2635 * data in the write path, but we're not going to use it all
2638 EBUG_ON(rbio->bio.bi_iter.bi_size <
2639 pick.crc.compressed_size << 9);
2640 rbio->bio.bi_iter.bi_size =
2641 pick.crc.compressed_size << 9;
2642 } else if (bounce) {
2643 unsigned sectors = pick.crc.compressed_size;
2645 rbio = rbio_init(bio_alloc_bioset(NULL,
2646 DIV_ROUND_UP(sectors, PAGE_SECTORS),
2649 &c->bio_read_split),
2652 bch2_bio_alloc_pages_pool(c, &rbio->bio, sectors << 9);
2653 rbio->bounce = true;
2655 } else if (flags & BCH_READ_MUST_CLONE) {
2657 * Have to clone if there were any splits, due to error
2658 * reporting issues (if a split errored, and retrying didn't
2659 * work, when it reports the error to its parent (us) we don't
2660 * know if the error was from our bio, and we should retry, or
2661 * from the whole bio, in which case we don't want to retry and
2664 rbio = rbio_init(bio_alloc_clone(NULL, &orig->bio, GFP_NOIO,
2665 &c->bio_read_split),
2667 rbio->bio.bi_iter = iter;
2671 rbio->bio.bi_iter = iter;
2672 EBUG_ON(bio_flagged(&rbio->bio, BIO_CHAIN));
2675 EBUG_ON(bio_sectors(&rbio->bio) != pick.crc.compressed_size);
2678 rbio->submit_time = local_clock();
2680 rbio->parent = orig;
2682 rbio->end_io = orig->bio.bi_end_io;
2683 rbio->bvec_iter = iter;
2684 rbio->offset_into_extent= offset_into_extent;
2685 rbio->flags = flags;
2686 rbio->have_ioref = pick_ret > 0 && bch2_dev_get_ioref(ca, READ);
2687 rbio->narrow_crcs = narrow_crcs;
2691 /* XXX: only initialize this if needed */
2692 rbio->devs_have = bch2_bkey_devs(k);
2694 rbio->subvol = orig->subvol;
2695 rbio->read_pos = read_pos;
2696 rbio->data_btree = data_btree;
2697 rbio->data_pos = data_pos;
2698 rbio->version = k.k->version;
2699 rbio->promote = promote;
2700 INIT_WORK(&rbio->work, NULL);
2702 rbio->bio.bi_opf = orig->bio.bi_opf;
2703 rbio->bio.bi_iter.bi_sector = pick.ptr.offset;
2704 rbio->bio.bi_end_io = bch2_read_endio;
2707 trace_and_count(c, read_bounce, &rbio->bio);
2709 this_cpu_add(c->counters[BCH_COUNTER_io_read], bio_sectors(&rbio->bio));
2710 bch2_increment_clock(c, bio_sectors(&rbio->bio), READ);
2713 * If it's being moved internally, we don't want to flag it as a cache
2716 if (pick.ptr.cached && !(flags & BCH_READ_NODECODE))
2717 bch2_bucket_io_time_reset(trans, pick.ptr.dev,
2718 PTR_BUCKET_NR(ca, &pick.ptr), READ);
2720 if (!(flags & (BCH_READ_IN_RETRY|BCH_READ_LAST_FRAGMENT))) {
2721 bio_inc_remaining(&orig->bio);
2722 trace_and_count(c, read_split, &orig->bio);
2725 if (!rbio->pick.idx) {
2726 if (!rbio->have_ioref) {
2727 bch_err_inum_offset_ratelimited(c,
2729 read_pos.offset << 9,
2730 "no device to read from");
2731 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2735 this_cpu_add(ca->io_done->sectors[READ][BCH_DATA_user],
2736 bio_sectors(&rbio->bio));
2737 bio_set_dev(&rbio->bio, ca->disk_sb.bdev);
2739 if (likely(!(flags & BCH_READ_IN_RETRY)))
2740 submit_bio(&rbio->bio);
2742 submit_bio_wait(&rbio->bio);
2744 /* Attempting reconstruct read: */
2745 if (bch2_ec_read_extent(c, rbio)) {
2746 bch2_rbio_error(rbio, READ_RETRY_AVOID, BLK_STS_IOERR);
2750 if (likely(!(flags & BCH_READ_IN_RETRY)))
2751 bio_endio(&rbio->bio);
2754 if (likely(!(flags & BCH_READ_IN_RETRY))) {
2759 rbio->context = RBIO_CONTEXT_UNBOUND;
2760 bch2_read_endio(&rbio->bio);
2763 rbio = bch2_rbio_free(rbio);
2765 if (ret == READ_RETRY_AVOID) {
2766 bch2_mark_io_failure(failed, &pick);
2777 if (flags & BCH_READ_IN_RETRY)
2780 orig->bio.bi_status = BLK_STS_IOERR;
2785 * won't normally happen in the BCH_READ_NODECODE
2786 * (bch2_move_extent()) path, but if we retry and the extent we wanted
2787 * to read no longer exists we have to signal that:
2789 if (flags & BCH_READ_NODECODE)
2792 zero_fill_bio_iter(&orig->bio, iter);
2794 if (flags & BCH_READ_LAST_FRAGMENT)
2795 bch2_rbio_done(orig);
2799 void __bch2_read(struct bch_fs *c, struct bch_read_bio *rbio,
2800 struct bvec_iter bvec_iter, subvol_inum inum,
2801 struct bch_io_failures *failed, unsigned flags)
2803 struct btree_trans trans;
2804 struct btree_iter iter;
2810 BUG_ON(flags & BCH_READ_NODECODE);
2812 bch2_bkey_buf_init(&sk);
2813 bch2_trans_init(&trans, c, 0, 0);
2815 bch2_trans_begin(&trans);
2816 iter = (struct btree_iter) { NULL };
2818 ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
2822 bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2823 SPOS(inum.inum, bvec_iter.bi_sector, snapshot),
2826 unsigned bytes, sectors, offset_into_extent;
2827 enum btree_id data_btree = BTREE_ID_extents;
2830 * read_extent -> io_time_reset may cause a transaction restart
2831 * without returning an error, we need to check for that here:
2833 ret = bch2_trans_relock(&trans);
2837 bch2_btree_iter_set_pos(&iter,
2838 POS(inum.inum, bvec_iter.bi_sector));
2840 k = bch2_btree_iter_peek_slot(&iter);
2845 offset_into_extent = iter.pos.offset -
2846 bkey_start_offset(k.k);
2847 sectors = k.k->size - offset_into_extent;
2849 bch2_bkey_buf_reassemble(&sk, c, k);
2851 ret = bch2_read_indirect_extent(&trans, &data_btree,
2852 &offset_into_extent, &sk);
2856 k = bkey_i_to_s_c(sk.k);
2859 * With indirect extents, the amount of data to read is the min
2860 * of the original extent and the indirect extent:
2862 sectors = min(sectors, k.k->size - offset_into_extent);
2864 bytes = min(sectors, bvec_iter_sectors(bvec_iter)) << 9;
2865 swap(bvec_iter.bi_size, bytes);
2867 if (bvec_iter.bi_size == bytes)
2868 flags |= BCH_READ_LAST_FRAGMENT;
2870 ret = __bch2_read_extent(&trans, rbio, bvec_iter, iter.pos,
2872 offset_into_extent, failed, flags);
2876 if (flags & BCH_READ_LAST_FRAGMENT)
2879 swap(bvec_iter.bi_size, bytes);
2880 bio_advance_iter(&rbio->bio, &bvec_iter, bytes);
2882 ret = btree_trans_too_many_iters(&trans);
2887 bch2_trans_iter_exit(&trans, &iter);
2889 if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
2890 ret == READ_RETRY ||
2891 ret == READ_RETRY_AVOID)
2894 bch2_trans_exit(&trans);
2895 bch2_bkey_buf_exit(&sk, c);
2898 bch_err_inum_offset_ratelimited(c, inum.inum,
2899 bvec_iter.bi_sector << 9,
2900 "read error %i from btree lookup", ret);
2901 rbio->bio.bi_status = BLK_STS_IOERR;
2902 bch2_rbio_done(rbio);
2906 void bch2_fs_io_exit(struct bch_fs *c)
2908 if (c->promote_table.tbl)
2909 rhashtable_destroy(&c->promote_table);
2910 mempool_exit(&c->bio_bounce_pages);
2911 bioset_exit(&c->bio_write);
2912 bioset_exit(&c->bio_read_split);
2913 bioset_exit(&c->bio_read);
2916 int bch2_fs_io_init(struct bch_fs *c)
2920 for (i = 0; i < ARRAY_SIZE(c->nocow_locks.l); i++)
2921 two_state_lock_init(&c->nocow_locks.l[i]);
2923 if (bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
2924 BIOSET_NEED_BVECS) ||
2925 bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
2926 BIOSET_NEED_BVECS) ||
2927 bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
2928 BIOSET_NEED_BVECS) ||
2929 mempool_init_page_pool(&c->bio_bounce_pages,
2931 c->opts.btree_node_size,
2932 c->opts.encoded_extent_max) /
2934 rhashtable_init(&c->promote_table, &bch_promote_params))