1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
4 * Copyright 2012 Google, Inc.
8 #include "alloc_foreground.h"
11 #include "btree_update.h"
19 #include "extent_update.h"
25 #include "nocow_locking.h"
26 #include "rebalance.h"
27 #include "subvolume.h"
32 #include <linux/blkdev.h>
33 #include <linux/prefetch.h>
34 #include <linux/random.h>
35 #include <linux/sched/mm.h>
37 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
39 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
43 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
44 /* ideally we'd be taking into account the device's variance here: */
45 u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
46 s64 latency_over = io_latency - latency_threshold;
48 if (latency_threshold && latency_over > 0) {
50 * bump up congested by approximately latency_over * 4 /
51 * latency_threshold - we don't need much accuracy here so don't
52 * bother with the divide:
54 if (atomic_read(&ca->congested) < CONGESTED_MAX)
55 atomic_add(latency_over >>
56 max_t(int, ilog2(latency_threshold) - 2, 0),
59 ca->congested_last = now;
60 } else if (atomic_read(&ca->congested) > 0) {
61 atomic_dec(&ca->congested);
65 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
67 atomic64_t *latency = &ca->cur_latency[rw];
68 u64 now = local_clock();
69 u64 io_latency = time_after64(now, submit_time)
72 u64 old, new, v = atomic64_read(latency);
78 * If the io latency was reasonably close to the current
79 * latency, skip doing the update and atomic operation - most of
82 if (abs((int) (old - io_latency)) < (old >> 1) &&
86 new = ewma_add(old, io_latency, 5);
87 } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
89 bch2_congested_acct(ca, io_latency, now, rw);
91 __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
96 /* Allocate, free from mempool: */
98 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
100 struct bvec_iter_all iter;
103 bio_for_each_segment_all(bv, bio, iter)
104 if (bv->bv_page != ZERO_PAGE(0))
105 mempool_free(bv->bv_page, &c->bio_bounce_pages);
109 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
113 if (likely(!*using_mempool)) {
114 page = alloc_page(GFP_NOFS);
115 if (unlikely(!page)) {
116 mutex_lock(&c->bio_bounce_pages_lock);
117 *using_mempool = true;
123 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOFS);
129 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
132 bool using_mempool = false;
135 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
136 unsigned len = min_t(size_t, PAGE_SIZE, size);
138 BUG_ON(!bio_add_page(bio, page, len, 0));
143 mutex_unlock(&c->bio_bounce_pages_lock);
146 /* Extent update path: */
148 int bch2_sum_sector_overwrites(struct btree_trans *trans,
149 struct btree_iter *extent_iter,
151 bool *usage_increasing,
152 s64 *i_sectors_delta,
153 s64 *disk_sectors_delta)
155 struct bch_fs *c = trans->c;
156 struct btree_iter iter;
158 unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
159 bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
162 *usage_increasing = false;
163 *i_sectors_delta = 0;
164 *disk_sectors_delta = 0;
166 bch2_trans_copy_iter(&iter, extent_iter);
168 for_each_btree_key_upto_continue_norestart(iter,
169 new->k.p, BTREE_ITER_SLOTS, old, ret) {
170 s64 sectors = min(new->k.p.offset, old.k->p.offset) -
171 max(bkey_start_offset(&new->k),
172 bkey_start_offset(old.k));
174 *i_sectors_delta += sectors *
175 (bkey_extent_is_allocation(&new->k) -
176 bkey_extent_is_allocation(old.k));
178 *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
179 *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
180 ? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
183 if (!*usage_increasing &&
184 (new->k.p.snapshot != old.k->p.snapshot ||
185 new_replicas > bch2_bkey_replicas(c, old) ||
186 (!new_compressed && bch2_bkey_sectors_compressed(old))))
187 *usage_increasing = true;
189 if (bkey_ge(old.k->p, new->k.p))
193 bch2_trans_iter_exit(trans, &iter);
197 static inline int bch2_extent_update_i_size_sectors(struct btree_trans *trans,
198 struct btree_iter *extent_iter,
202 struct btree_iter iter;
204 struct bkey_i_inode_v3 *inode;
206 * Crazy performance optimization:
207 * Every extent update needs to also update the inode: the inode trigger
208 * will set bi->journal_seq to the journal sequence number of this
209 * transaction - for fsync.
211 * But if that's the only reason we're updating the inode (we're not
212 * updating bi_size or bi_sectors), then we don't need the inode update
213 * to be journalled - if we crash, the bi_journal_seq update will be
214 * lost, but that's fine.
216 unsigned inode_update_flags = BTREE_UPDATE_NOJOURNAL;
219 k = bch2_bkey_get_mut_noupdate(trans, &iter, BTREE_ID_inodes,
221 extent_iter->pos.inode,
222 extent_iter->snapshot),
224 ret = PTR_ERR_OR_ZERO(k);
228 if (unlikely(k->k.type != KEY_TYPE_inode_v3)) {
229 k = bch2_inode_to_v3(trans, k);
230 ret = PTR_ERR_OR_ZERO(k);
235 inode = bkey_i_to_inode_v3(k);
237 if (!(le64_to_cpu(inode->v.bi_flags) & BCH_INODE_i_size_dirty) &&
238 new_i_size > le64_to_cpu(inode->v.bi_size)) {
239 inode->v.bi_size = cpu_to_le64(new_i_size);
240 inode_update_flags = 0;
243 if (i_sectors_delta) {
244 le64_add_cpu(&inode->v.bi_sectors, i_sectors_delta);
245 inode_update_flags = 0;
248 if (inode->k.p.snapshot != iter.snapshot) {
249 inode->k.p.snapshot = iter.snapshot;
250 inode_update_flags = 0;
253 ret = bch2_trans_update(trans, &iter, &inode->k_i,
254 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
257 bch2_trans_iter_exit(trans, &iter);
261 int bch2_extent_update(struct btree_trans *trans,
263 struct btree_iter *iter,
265 struct disk_reservation *disk_res,
267 s64 *i_sectors_delta_total,
270 struct bpos next_pos;
271 bool usage_increasing;
272 s64 i_sectors_delta = 0, disk_sectors_delta = 0;
276 * This traverses us the iterator without changing iter->path->pos to
277 * search_key() (which is pos + 1 for extents): we want there to be a
278 * path already traversed at iter->pos because
279 * bch2_trans_extent_update() will use it to attempt extent merging
281 ret = __bch2_btree_iter_traverse(iter);
285 ret = bch2_extent_trim_atomic(trans, iter, k);
291 ret = bch2_sum_sector_overwrites(trans, iter, k,
294 &disk_sectors_delta);
299 disk_sectors_delta > (s64) disk_res->sectors) {
300 ret = bch2_disk_reservation_add(trans->c, disk_res,
301 disk_sectors_delta - disk_res->sectors,
302 !check_enospc || !usage_increasing
303 ? BCH_DISK_RESERVATION_NOFAIL : 0);
310 * We always have to do an inode update - even when i_size/i_sectors
311 * aren't changing - for fsync to work properly; fsync relies on
312 * inode->bi_journal_seq which is updated by the trigger code:
314 ret = bch2_extent_update_i_size_sectors(trans, iter,
315 min(k->k.p.offset << 9, new_i_size),
317 bch2_trans_update(trans, iter, k, 0) ?:
318 bch2_trans_commit(trans, disk_res, NULL,
319 BCH_TRANS_COMMIT_no_check_rw|
320 BCH_TRANS_COMMIT_no_enospc);
324 if (i_sectors_delta_total)
325 *i_sectors_delta_total += i_sectors_delta;
326 bch2_btree_iter_set_pos(iter, next_pos);
330 static int bch2_write_index_default(struct bch_write_op *op)
332 struct bch_fs *c = op->c;
334 struct keylist *keys = &op->insert_keys;
335 struct bkey_i *k = bch2_keylist_front(keys);
336 struct btree_trans *trans = bch2_trans_get(c);
337 struct btree_iter iter;
339 .subvol = op->subvol,
340 .inum = k->k.p.inode,
344 BUG_ON(!inum.subvol);
346 bch2_bkey_buf_init(&sk);
349 bch2_trans_begin(trans);
351 k = bch2_keylist_front(keys);
352 bch2_bkey_buf_copy(&sk, c, k);
354 ret = bch2_subvolume_get_snapshot(trans, inum.subvol,
355 &sk.k->k.p.snapshot);
356 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
361 bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
362 bkey_start_pos(&sk.k->k),
363 BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
365 ret = bch2_bkey_set_needs_rebalance(c, sk.k,
366 op->opts.background_target,
367 op->opts.background_compression) ?:
368 bch2_extent_update(trans, inum, &iter, sk.k,
370 op->new_i_size, &op->i_sectors_delta,
371 op->flags & BCH_WRITE_CHECK_ENOSPC);
372 bch2_trans_iter_exit(trans, &iter);
374 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
379 if (bkey_ge(iter.pos, k->k.p))
380 bch2_keylist_pop_front(&op->insert_keys);
382 bch2_cut_front(iter.pos, k);
383 } while (!bch2_keylist_empty(keys));
385 bch2_trans_put(trans);
386 bch2_bkey_buf_exit(&sk, c);
393 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
394 enum bch_data_type type,
395 const struct bkey_i *k,
398 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
399 struct bch_write_bio *n;
401 BUG_ON(c->opts.nochanges);
403 bkey_for_each_ptr(ptrs, ptr) {
404 BUG_ON(!bch2_dev_exists2(c, ptr->dev));
406 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
408 if (to_entry(ptr + 1) < ptrs.end) {
409 n = to_wbio(bio_alloc_clone(NULL, &wbio->bio,
410 GFP_NOFS, &ca->replica_set));
412 n->bio.bi_end_io = wbio->bio.bi_end_io;
413 n->bio.bi_private = wbio->bio.bi_private;
418 n->bio.bi_opf = wbio->bio.bi_opf;
419 bio_inc_remaining(&wbio->bio);
427 n->have_ioref = nocow || bch2_dev_get_ioref(ca,
428 type == BCH_DATA_btree ? READ : WRITE);
430 n->submit_time = local_clock();
431 n->inode_offset = bkey_start_offset(&k->k);
432 n->bio.bi_iter.bi_sector = ptr->offset;
434 if (likely(n->have_ioref)) {
435 this_cpu_add(ca->io_done->sectors[WRITE][type],
436 bio_sectors(&n->bio));
438 bio_set_dev(&n->bio, ca->disk_sb.bdev);
440 if (type != BCH_DATA_btree && unlikely(c->opts.no_data_io)) {
447 n->bio.bi_status = BLK_STS_REMOVED;
453 static void __bch2_write(struct bch_write_op *);
455 static void bch2_write_done(struct closure *cl)
457 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
458 struct bch_fs *c = op->c;
460 EBUG_ON(op->open_buckets.nr);
462 bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
463 bch2_disk_reservation_put(c, &op->res);
465 if (!(op->flags & BCH_WRITE_MOVE))
466 bch2_write_ref_put(c, BCH_WRITE_REF_write);
467 bch2_keylist_free(&op->insert_keys, op->inline_keys);
470 closure_debug_destroy(cl);
475 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
477 struct keylist *keys = &op->insert_keys;
478 struct bch_extent_ptr *ptr;
479 struct bkey_i *src, *dst = keys->keys, *n;
481 for (src = keys->keys; src != keys->top; src = n) {
484 if (bkey_extent_is_direct_data(&src->k)) {
485 bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
486 test_bit(ptr->dev, op->failed.d));
488 if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
493 memmove_u64s_down(dst, src, src->k.u64s);
494 dst = bkey_next(dst);
502 * __bch2_write_index - after a write, update index to point to new data
503 * @op: bch_write_op to process
505 static void __bch2_write_index(struct bch_write_op *op)
507 struct bch_fs *c = op->c;
508 struct keylist *keys = &op->insert_keys;
512 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
513 ret = bch2_write_drop_io_error_ptrs(op);
518 if (!bch2_keylist_empty(keys)) {
519 u64 sectors_start = keylist_sectors(keys);
521 ret = !(op->flags & BCH_WRITE_MOVE)
522 ? bch2_write_index_default(op)
523 : bch2_data_update_index_update(op);
525 BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
526 BUG_ON(keylist_sectors(keys) && !ret);
528 op->written += sectors_start - keylist_sectors(keys);
530 if (ret && !bch2_err_matches(ret, EROFS)) {
531 struct bkey_i *insert = bch2_keylist_front(&op->insert_keys);
533 bch_err_inum_offset_ratelimited(c,
534 insert->k.p.inode, insert->k.p.offset << 9,
535 "write error while doing btree update: %s",
543 /* If some a bucket wasn't written, we can't erasure code it: */
544 for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
545 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
547 bch2_open_buckets_put(c, &op->open_buckets);
550 keys->top = keys->keys;
552 op->flags |= BCH_WRITE_DONE;
556 static inline void __wp_update_state(struct write_point *wp, enum write_point_state state)
558 if (state != wp->state) {
559 u64 now = ktime_get_ns();
561 if (wp->last_state_change &&
562 time_after64(now, wp->last_state_change))
563 wp->time[wp->state] += now - wp->last_state_change;
565 wp->last_state_change = now;
569 static inline void wp_update_state(struct write_point *wp, bool running)
571 enum write_point_state state;
573 state = running ? WRITE_POINT_running :
574 !list_empty(&wp->writes) ? WRITE_POINT_waiting_io
575 : WRITE_POINT_stopped;
577 __wp_update_state(wp, state);
580 static CLOSURE_CALLBACK(bch2_write_index)
582 closure_type(op, struct bch_write_op, cl);
583 struct write_point *wp = op->wp;
584 struct workqueue_struct *wq = index_update_wq(op);
587 if ((op->flags & BCH_WRITE_DONE) &&
588 (op->flags & BCH_WRITE_MOVE))
589 bch2_bio_free_pages_pool(op->c, &op->wbio.bio);
591 spin_lock_irqsave(&wp->writes_lock, flags);
592 if (wp->state == WRITE_POINT_waiting_io)
593 __wp_update_state(wp, WRITE_POINT_waiting_work);
594 list_add_tail(&op->wp_list, &wp->writes);
595 spin_unlock_irqrestore (&wp->writes_lock, flags);
597 queue_work(wq, &wp->index_update_work);
600 static inline void bch2_write_queue(struct bch_write_op *op, struct write_point *wp)
604 if (wp->state == WRITE_POINT_stopped) {
605 spin_lock_irq(&wp->writes_lock);
606 __wp_update_state(wp, WRITE_POINT_waiting_io);
607 spin_unlock_irq(&wp->writes_lock);
611 void bch2_write_point_do_index_updates(struct work_struct *work)
613 struct write_point *wp =
614 container_of(work, struct write_point, index_update_work);
615 struct bch_write_op *op;
618 spin_lock_irq(&wp->writes_lock);
619 op = list_first_entry_or_null(&wp->writes, struct bch_write_op, wp_list);
621 list_del(&op->wp_list);
622 wp_update_state(wp, op != NULL);
623 spin_unlock_irq(&wp->writes_lock);
628 op->flags |= BCH_WRITE_IN_WORKER;
630 __bch2_write_index(op);
632 if (!(op->flags & BCH_WRITE_DONE))
635 bch2_write_done(&op->cl);
639 static void bch2_write_endio(struct bio *bio)
641 struct closure *cl = bio->bi_private;
642 struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
643 struct bch_write_bio *wbio = to_wbio(bio);
644 struct bch_write_bio *parent = wbio->split ? wbio->parent : NULL;
645 struct bch_fs *c = wbio->c;
646 struct bch_dev *ca = bch_dev_bkey_exists(c, wbio->dev);
648 if (bch2_dev_inum_io_err_on(bio->bi_status, ca, BCH_MEMBER_ERROR_write,
650 wbio->inode_offset << 9,
651 "data write error: %s",
652 bch2_blk_status_to_str(bio->bi_status))) {
653 set_bit(wbio->dev, op->failed.d);
654 op->flags |= BCH_WRITE_IO_ERROR;
658 set_bit(wbio->dev, op->devs_need_flush->d);
660 if (wbio->have_ioref) {
661 bch2_latency_acct(ca, wbio->submit_time, WRITE);
662 percpu_ref_put(&ca->io_ref);
666 bch2_bio_free_pages_pool(c, bio);
672 bio_endio(&parent->bio);
677 static void init_append_extent(struct bch_write_op *op,
678 struct write_point *wp,
679 struct bversion version,
680 struct bch_extent_crc_unpacked crc)
682 struct bkey_i_extent *e;
684 op->pos.offset += crc.uncompressed_size;
686 e = bkey_extent_init(op->insert_keys.top);
688 e->k.size = crc.uncompressed_size;
689 e->k.version = version;
692 crc.compression_type ||
694 bch2_extent_crc_append(&e->k_i, crc);
696 bch2_alloc_sectors_append_ptrs_inlined(op->c, wp, &e->k_i, crc.compressed_size,
697 op->flags & BCH_WRITE_CACHED);
699 bch2_keylist_push(&op->insert_keys);
702 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
703 struct write_point *wp,
705 bool *page_alloc_failed,
708 struct bch_write_bio *wbio;
710 unsigned output_available =
711 min(wp->sectors_free << 9, src->bi_iter.bi_size);
712 unsigned pages = DIV_ROUND_UP(output_available +
714 ? ((unsigned long) buf & (PAGE_SIZE - 1))
717 pages = min(pages, BIO_MAX_VECS);
719 bio = bio_alloc_bioset(NULL, pages, 0,
720 GFP_NOFS, &c->bio_write);
721 wbio = wbio_init(bio);
722 wbio->put_bio = true;
723 /* copy WRITE_SYNC flag */
724 wbio->bio.bi_opf = src->bi_opf;
727 bch2_bio_map(bio, buf, output_available);
734 * We can't use mempool for more than c->sb.encoded_extent_max
735 * worth of pages, but we'd like to allocate more if we can:
737 bch2_bio_alloc_pages_pool(c, bio,
738 min_t(unsigned, output_available,
739 c->opts.encoded_extent_max));
741 if (bio->bi_iter.bi_size < output_available)
743 bch2_bio_alloc_pages(bio,
745 bio->bi_iter.bi_size,
751 static int bch2_write_rechecksum(struct bch_fs *c,
752 struct bch_write_op *op,
753 unsigned new_csum_type)
755 struct bio *bio = &op->wbio.bio;
756 struct bch_extent_crc_unpacked new_crc;
759 /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
761 if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
762 bch2_csum_type_is_encryption(new_csum_type))
763 new_csum_type = op->crc.csum_type;
765 ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
767 op->crc.offset, op->crc.live_size,
772 bio_advance(bio, op->crc.offset << 9);
773 bio->bi_iter.bi_size = op->crc.live_size << 9;
778 static int bch2_write_decrypt(struct bch_write_op *op)
780 struct bch_fs *c = op->c;
781 struct nonce nonce = extent_nonce(op->version, op->crc);
782 struct bch_csum csum;
785 if (!bch2_csum_type_is_encryption(op->crc.csum_type))
789 * If we need to decrypt data in the write path, we'll no longer be able
790 * to verify the existing checksum (poly1305 mac, in this case) after
791 * it's decrypted - this is the last point we'll be able to reverify the
794 csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
795 if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
798 ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
799 op->crc.csum_type = 0;
800 op->crc.csum = (struct bch_csum) { 0, 0 };
804 static enum prep_encoded_ret {
807 PREP_ENCODED_CHECKSUM_ERR,
808 PREP_ENCODED_DO_WRITE,
809 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
811 struct bch_fs *c = op->c;
812 struct bio *bio = &op->wbio.bio;
814 if (!(op->flags & BCH_WRITE_DATA_ENCODED))
815 return PREP_ENCODED_OK;
817 BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
819 /* Can we just write the entire extent as is? */
820 if (op->crc.uncompressed_size == op->crc.live_size &&
821 op->crc.uncompressed_size <= c->opts.encoded_extent_max >> 9 &&
822 op->crc.compressed_size <= wp->sectors_free &&
823 (op->crc.compression_type == bch2_compression_opt_to_type(op->compression_opt) ||
824 op->incompressible)) {
825 if (!crc_is_compressed(op->crc) &&
826 op->csum_type != op->crc.csum_type &&
827 bch2_write_rechecksum(c, op, op->csum_type) &&
829 return PREP_ENCODED_CHECKSUM_ERR;
831 return PREP_ENCODED_DO_WRITE;
835 * If the data is compressed and we couldn't write the entire extent as
836 * is, we have to decompress it:
838 if (crc_is_compressed(op->crc)) {
839 struct bch_csum csum;
841 if (bch2_write_decrypt(op))
842 return PREP_ENCODED_CHECKSUM_ERR;
844 /* Last point we can still verify checksum: */
845 csum = bch2_checksum_bio(c, op->crc.csum_type,
846 extent_nonce(op->version, op->crc),
848 if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
849 return PREP_ENCODED_CHECKSUM_ERR;
851 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
852 return PREP_ENCODED_ERR;
856 * No longer have compressed data after this point - data might be
861 * If the data is checksummed and we're only writing a subset,
862 * rechecksum and adjust bio to point to currently live data:
864 if ((op->crc.live_size != op->crc.uncompressed_size ||
865 op->crc.csum_type != op->csum_type) &&
866 bch2_write_rechecksum(c, op, op->csum_type) &&
868 return PREP_ENCODED_CHECKSUM_ERR;
871 * If we want to compress the data, it has to be decrypted:
873 if ((op->compression_opt ||
874 bch2_csum_type_is_encryption(op->crc.csum_type) !=
875 bch2_csum_type_is_encryption(op->csum_type)) &&
876 bch2_write_decrypt(op))
877 return PREP_ENCODED_CHECKSUM_ERR;
879 return PREP_ENCODED_OK;
882 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
885 struct bch_fs *c = op->c;
886 struct bio *src = &op->wbio.bio, *dst = src;
887 struct bvec_iter saved_iter;
889 unsigned total_output = 0, total_input = 0;
891 bool page_alloc_failed = false;
894 BUG_ON(!bio_sectors(src));
896 ec_buf = bch2_writepoint_ec_buf(c, wp);
898 switch (bch2_write_prep_encoded_data(op, wp)) {
899 case PREP_ENCODED_OK:
901 case PREP_ENCODED_ERR:
904 case PREP_ENCODED_CHECKSUM_ERR:
906 case PREP_ENCODED_DO_WRITE:
907 /* XXX look for bug here */
909 dst = bch2_write_bio_alloc(c, wp, src,
912 bio_copy_data(dst, src);
915 init_append_extent(op, wp, op->version, op->crc);
920 op->compression_opt ||
922 !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
923 (bch2_csum_type_is_encryption(op->csum_type) &&
924 !(op->flags & BCH_WRITE_PAGES_OWNED))) {
925 dst = bch2_write_bio_alloc(c, wp, src,
931 saved_iter = dst->bi_iter;
934 struct bch_extent_crc_unpacked crc = { 0 };
935 struct bversion version = op->version;
936 size_t dst_len = 0, src_len = 0;
938 if (page_alloc_failed &&
939 dst->bi_iter.bi_size < (wp->sectors_free << 9) &&
940 dst->bi_iter.bi_size < c->opts.encoded_extent_max)
943 BUG_ON(op->compression_opt &&
944 (op->flags & BCH_WRITE_DATA_ENCODED) &&
945 bch2_csum_type_is_encryption(op->crc.csum_type));
946 BUG_ON(op->compression_opt && !bounce);
948 crc.compression_type = op->incompressible
949 ? BCH_COMPRESSION_TYPE_incompressible
950 : op->compression_opt
951 ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
954 if (!crc_is_compressed(crc)) {
955 dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
956 dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
959 dst_len = min_t(unsigned, dst_len,
960 c->opts.encoded_extent_max);
963 swap(dst->bi_iter.bi_size, dst_len);
964 bio_copy_data(dst, src);
965 swap(dst->bi_iter.bi_size, dst_len);
971 BUG_ON(!src_len || !dst_len);
973 if (bch2_csum_type_is_encryption(op->csum_type)) {
974 if (bversion_zero(version)) {
975 version.lo = atomic64_inc_return(&c->key_version);
977 crc.nonce = op->nonce;
978 op->nonce += src_len >> 9;
982 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
983 !crc_is_compressed(crc) &&
984 bch2_csum_type_is_encryption(op->crc.csum_type) ==
985 bch2_csum_type_is_encryption(op->csum_type)) {
986 u8 compression_type = crc.compression_type;
987 u16 nonce = crc.nonce;
989 * Note: when we're using rechecksum(), we need to be
990 * checksumming @src because it has all the data our
991 * existing checksum covers - if we bounced (because we
992 * were trying to compress), @dst will only have the
993 * part of the data the new checksum will cover.
995 * But normally we want to be checksumming post bounce,
996 * because part of the reason for bouncing is so the
997 * data can't be modified (by userspace) while it's in
1000 if (bch2_rechecksum_bio(c, src, version, op->crc,
1003 bio_sectors(src) - (src_len >> 9),
1007 * rchecksum_bio sets compression_type on crc from op->crc,
1008 * this isn't always correct as sometimes we're changing
1009 * an extent from uncompressed to incompressible.
1011 crc.compression_type = compression_type;
1014 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1015 bch2_rechecksum_bio(c, src, version, op->crc,
1018 bio_sectors(src) - (src_len >> 9),
1022 crc.compressed_size = dst_len >> 9;
1023 crc.uncompressed_size = src_len >> 9;
1024 crc.live_size = src_len >> 9;
1026 swap(dst->bi_iter.bi_size, dst_len);
1027 ret = bch2_encrypt_bio(c, op->csum_type,
1028 extent_nonce(version, crc), dst);
1032 crc.csum = bch2_checksum_bio(c, op->csum_type,
1033 extent_nonce(version, crc), dst);
1034 crc.csum_type = op->csum_type;
1035 swap(dst->bi_iter.bi_size, dst_len);
1038 init_append_extent(op, wp, version, crc);
1041 bio_advance(dst, dst_len);
1042 bio_advance(src, src_len);
1043 total_output += dst_len;
1044 total_input += src_len;
1045 } while (dst->bi_iter.bi_size &&
1046 src->bi_iter.bi_size &&
1048 !bch2_keylist_realloc(&op->insert_keys,
1050 ARRAY_SIZE(op->inline_keys),
1051 BKEY_EXTENT_U64s_MAX));
1053 more = src->bi_iter.bi_size != 0;
1055 dst->bi_iter = saved_iter;
1057 if (dst == src && more) {
1058 BUG_ON(total_output != total_input);
1060 dst = bio_split(src, total_input >> 9,
1061 GFP_NOFS, &c->bio_write);
1062 wbio_init(dst)->put_bio = true;
1063 /* copy WRITE_SYNC flag */
1064 dst->bi_opf = src->bi_opf;
1067 dst->bi_iter.bi_size = total_output;
1072 bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1075 if (to_wbio(dst)->bounce)
1076 bch2_bio_free_pages_pool(c, dst);
1077 if (to_wbio(dst)->put_bio)
1083 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1086 struct bch_fs *c = op->c;
1087 struct bkey_s_c_extent e;
1088 struct extent_ptr_decoded p;
1089 const union bch_extent_entry *entry;
1090 unsigned replicas = 0;
1092 if (k.k->type != KEY_TYPE_extent)
1095 e = bkey_s_c_to_extent(k);
1096 extent_for_each_ptr_decode(e, p, entry) {
1097 if (crc_is_encoded(p.crc) || p.has_ec)
1100 replicas += bch2_extent_ptr_durability(c, &p);
1103 return replicas >= op->opts.data_replicas;
1106 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1108 struct bch_fs *c = op->c;
1110 for_each_keylist_key(&op->insert_keys, k) {
1111 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1113 bkey_for_each_ptr(ptrs, ptr)
1114 bch2_bucket_nocow_unlock(&c->nocow_locks,
1115 PTR_BUCKET_POS(c, ptr),
1116 BUCKET_NOCOW_LOCK_UPDATE);
1120 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1121 struct btree_iter *iter,
1122 struct bkey_i *orig,
1126 if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1131 struct bkey_i *new = bch2_bkey_make_mut_noupdate(trans, k);
1132 int ret = PTR_ERR_OR_ZERO(new);
1136 bch2_cut_front(bkey_start_pos(&orig->k), new);
1137 bch2_cut_back(orig->k.p, new);
1139 struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1140 bkey_for_each_ptr(ptrs, ptr)
1144 * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1145 * that was done when we kicked off the write, and here it's important
1146 * that we update the extent that we wrote to - even if a snapshot has
1147 * since been created. The write is still outstanding, so we're ok
1148 * w.r.t. snapshot atomicity:
1150 return bch2_extent_update_i_size_sectors(trans, iter,
1151 min(new->k.p.offset << 9, new_i_size), 0) ?:
1152 bch2_trans_update(trans, iter, new,
1153 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1156 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1158 struct bch_fs *c = op->c;
1159 struct btree_trans *trans = bch2_trans_get(c);
1161 for_each_keylist_key(&op->insert_keys, orig) {
1162 int ret = for_each_btree_key_upto_commit(trans, iter, BTREE_ID_extents,
1163 bkey_start_pos(&orig->k), orig->k.p,
1164 BTREE_ITER_INTENT, k,
1165 NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({
1166 bch2_nocow_write_convert_one_unwritten(trans, &iter, orig, k, op->new_i_size);
1169 if (ret && !bch2_err_matches(ret, EROFS)) {
1170 struct bkey_i *insert = bch2_keylist_front(&op->insert_keys);
1172 bch_err_inum_offset_ratelimited(c,
1173 insert->k.p.inode, insert->k.p.offset << 9,
1174 "write error while doing btree update: %s",
1184 bch2_trans_put(trans);
1187 static void __bch2_nocow_write_done(struct bch_write_op *op)
1189 bch2_nocow_write_unlock(op);
1191 if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1193 } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1194 bch2_nocow_write_convert_unwritten(op);
1197 static CLOSURE_CALLBACK(bch2_nocow_write_done)
1199 closure_type(op, struct bch_write_op, cl);
1201 __bch2_nocow_write_done(op);
1202 bch2_write_done(cl);
1205 struct bucket_to_lock {
1208 struct nocow_lock_bucket *l;
1211 static void bch2_nocow_write(struct bch_write_op *op)
1213 struct bch_fs *c = op->c;
1214 struct btree_trans *trans;
1215 struct btree_iter iter;
1217 DARRAY_PREALLOCATED(struct bucket_to_lock, 3) buckets;
1219 struct bucket_to_lock *stale_at;
1222 if (op->flags & BCH_WRITE_MOVE)
1225 darray_init(&buckets);
1226 trans = bch2_trans_get(c);
1228 bch2_trans_begin(trans);
1230 ret = bch2_subvolume_get_snapshot(trans, op->subvol, &snapshot);
1234 bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
1235 SPOS(op->pos.inode, op->pos.offset, snapshot),
1238 struct bio *bio = &op->wbio.bio;
1242 k = bch2_btree_iter_peek_slot(&iter);
1247 /* fall back to normal cow write path? */
1248 if (unlikely(k.k->p.snapshot != snapshot ||
1249 !bch2_extent_is_writeable(op, k)))
1252 if (bch2_keylist_realloc(&op->insert_keys,
1254 ARRAY_SIZE(op->inline_keys),
1258 /* Get iorefs before dropping btree locks: */
1259 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1260 bkey_for_each_ptr(ptrs, ptr) {
1261 struct bpos b = PTR_BUCKET_POS(c, ptr);
1262 struct nocow_lock_bucket *l =
1263 bucket_nocow_lock(&c->nocow_locks, bucket_to_u64(b));
1266 if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1269 /* XXX allocating memory with btree locks held - rare */
1270 darray_push_gfp(&buckets, ((struct bucket_to_lock) {
1271 .b = b, .gen = ptr->gen, .l = l,
1272 }), GFP_KERNEL|__GFP_NOFAIL);
1275 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1278 /* Unlock before taking nocow locks, doing IO: */
1279 bkey_reassemble(op->insert_keys.top, k);
1280 bch2_trans_unlock(trans);
1282 bch2_cut_front(op->pos, op->insert_keys.top);
1283 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1284 bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1286 darray_for_each(buckets, i) {
1287 struct bch_dev *ca = bch_dev_bkey_exists(c, i->b.inode);
1289 __bch2_bucket_nocow_lock(&c->nocow_locks, i->l,
1290 bucket_to_u64(i->b),
1291 BUCKET_NOCOW_LOCK_UPDATE);
1294 bool stale = gen_after(*bucket_gen(ca, i->b.offset), i->gen);
1297 if (unlikely(stale)) {
1299 goto err_bucket_stale;
1303 bio = &op->wbio.bio;
1304 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1305 bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1306 GFP_KERNEL, &c->bio_write);
1307 wbio_init(bio)->put_bio = true;
1308 bio->bi_opf = op->wbio.bio.bi_opf;
1310 op->flags |= BCH_WRITE_DONE;
1313 op->pos.offset += bio_sectors(bio);
1314 op->written += bio_sectors(bio);
1316 bio->bi_end_io = bch2_write_endio;
1317 bio->bi_private = &op->cl;
1318 bio->bi_opf |= REQ_OP_WRITE;
1319 closure_get(&op->cl);
1320 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1321 op->insert_keys.top, true);
1323 bch2_keylist_push(&op->insert_keys);
1324 if (op->flags & BCH_WRITE_DONE)
1326 bch2_btree_iter_advance(&iter);
1329 bch2_trans_iter_exit(trans, &iter);
1331 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1335 bch_err_inum_offset_ratelimited(c,
1336 op->pos.inode, op->pos.offset << 9,
1337 "%s: btree lookup error %s", __func__, bch2_err_str(ret));
1339 op->flags |= BCH_WRITE_DONE;
1342 bch2_trans_put(trans);
1343 darray_exit(&buckets);
1345 /* fallback to cow write path? */
1346 if (!(op->flags & BCH_WRITE_DONE)) {
1347 closure_sync(&op->cl);
1348 __bch2_nocow_write_done(op);
1349 op->insert_keys.top = op->insert_keys.keys;
1350 } else if (op->flags & BCH_WRITE_SYNC) {
1351 closure_sync(&op->cl);
1352 bch2_nocow_write_done(&op->cl.work);
1356 * needs to run out of process context because ei_quota_lock is
1359 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1363 darray_for_each(buckets, i)
1364 percpu_ref_put(&bch_dev_bkey_exists(c, i->b.inode)->io_ref);
1366 /* Fall back to COW path: */
1369 darray_for_each(buckets, i) {
1370 bch2_bucket_nocow_unlock(&c->nocow_locks, i->b, BUCKET_NOCOW_LOCK_UPDATE);
1375 /* We can retry this: */
1376 ret = -BCH_ERR_transaction_restart;
1380 static void __bch2_write(struct bch_write_op *op)
1382 struct bch_fs *c = op->c;
1383 struct write_point *wp = NULL;
1384 struct bio *bio = NULL;
1385 unsigned nofs_flags;
1388 nofs_flags = memalloc_nofs_save();
1390 if (unlikely(op->opts.nocow && c->opts.nocow_enabled)) {
1391 bch2_nocow_write(op);
1392 if (op->flags & BCH_WRITE_DONE)
1393 goto out_nofs_restore;
1396 memset(&op->failed, 0, sizeof(op->failed));
1399 struct bkey_i *key_to_write;
1400 unsigned key_to_write_offset = op->insert_keys.top_p -
1401 op->insert_keys.keys_p;
1403 /* +1 for possible cache device: */
1404 if (op->open_buckets.nr + op->nr_replicas + 1 >
1405 ARRAY_SIZE(op->open_buckets.v))
1408 if (bch2_keylist_realloc(&op->insert_keys,
1410 ARRAY_SIZE(op->inline_keys),
1411 BKEY_EXTENT_U64s_MAX))
1415 * The copygc thread is now global, which means it's no longer
1416 * freeing up space on specific disks, which means that
1417 * allocations for specific disks may hang arbitrarily long:
1419 ret = bch2_trans_do(c, NULL, NULL, 0,
1420 bch2_alloc_sectors_start_trans(trans,
1422 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1426 op->nr_replicas_required,
1429 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1430 BCH_WRITE_ONLY_SPECIFIED_DEVS))
1431 ? NULL : &op->cl, &wp));
1432 if (unlikely(ret)) {
1433 if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1441 bch2_open_bucket_get(c, wp, &op->open_buckets);
1442 ret = bch2_write_extent(op, wp, &bio);
1444 bch2_alloc_sectors_done_inlined(c, wp);
1447 op->flags |= BCH_WRITE_DONE;
1450 bch_err_inum_offset_ratelimited(c,
1452 op->pos.offset << 9,
1453 "%s(): error: %s", __func__, bch2_err_str(ret));
1459 bio->bi_end_io = bch2_write_endio;
1460 bio->bi_private = &op->cl;
1461 bio->bi_opf |= REQ_OP_WRITE;
1463 closure_get(bio->bi_private);
1465 key_to_write = (void *) (op->insert_keys.keys_p +
1466 key_to_write_offset);
1468 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1469 key_to_write, false);
1475 * If we're running asynchronously, wne may still want to block
1476 * synchronously here if we weren't able to submit all of the IO at
1477 * once, as that signals backpressure to the caller.
1479 if ((op->flags & BCH_WRITE_SYNC) ||
1480 (!(op->flags & BCH_WRITE_DONE) &&
1481 !(op->flags & BCH_WRITE_IN_WORKER))) {
1482 closure_sync(&op->cl);
1483 __bch2_write_index(op);
1485 if (!(op->flags & BCH_WRITE_DONE))
1487 bch2_write_done(&op->cl);
1489 bch2_write_queue(op, wp);
1490 continue_at(&op->cl, bch2_write_index, NULL);
1493 memalloc_nofs_restore(nofs_flags);
1496 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1498 struct bio *bio = &op->wbio.bio;
1499 struct bvec_iter iter;
1500 struct bkey_i_inline_data *id;
1504 op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1505 op->flags |= BCH_WRITE_DONE;
1507 bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1509 ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1510 ARRAY_SIZE(op->inline_keys),
1511 BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1517 sectors = bio_sectors(bio);
1518 op->pos.offset += sectors;
1520 id = bkey_inline_data_init(op->insert_keys.top);
1522 id->k.version = op->version;
1523 id->k.size = sectors;
1525 iter = bio->bi_iter;
1526 iter.bi_size = data_len;
1527 memcpy_from_bio(id->v.data, bio, iter);
1529 while (data_len & 7)
1530 id->v.data[data_len++] = '\0';
1531 set_bkey_val_bytes(&id->k, data_len);
1532 bch2_keylist_push(&op->insert_keys);
1534 __bch2_write_index(op);
1536 bch2_write_done(&op->cl);
1540 * bch2_write() - handle a write to a cache device or flash only volume
1541 * @cl: &bch_write_op->cl
1543 * This is the starting point for any data to end up in a cache device; it could
1544 * be from a normal write, or a writeback write, or a write to a flash only
1545 * volume - it's also used by the moving garbage collector to compact data in
1546 * mostly empty buckets.
1548 * It first writes the data to the cache, creating a list of keys to be inserted
1549 * (if the data won't fit in a single open bucket, there will be multiple keys);
1550 * after the data is written it calls bch_journal, and after the keys have been
1551 * added to the next journal write they're inserted into the btree.
1553 * If op->discard is true, instead of inserting the data it invalidates the
1554 * region of the cache represented by op->bio and op->inode.
1556 CLOSURE_CALLBACK(bch2_write)
1558 closure_type(op, struct bch_write_op, cl);
1559 struct bio *bio = &op->wbio.bio;
1560 struct bch_fs *c = op->c;
1563 EBUG_ON(op->cl.parent);
1564 BUG_ON(!op->nr_replicas);
1565 BUG_ON(!op->write_point.v);
1566 BUG_ON(bkey_eq(op->pos, POS_MAX));
1568 op->start_time = local_clock();
1569 bch2_keylist_init(&op->insert_keys, op->inline_keys);
1570 wbio_init(bio)->put_bio = false;
1572 if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1573 bch_err_inum_offset_ratelimited(c,
1575 op->pos.offset << 9,
1576 "misaligned write");
1581 if (c->opts.nochanges) {
1582 op->error = -BCH_ERR_erofs_no_writes;
1586 if (!(op->flags & BCH_WRITE_MOVE) &&
1587 !bch2_write_ref_tryget(c, BCH_WRITE_REF_write)) {
1588 op->error = -BCH_ERR_erofs_no_writes;
1592 this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1593 bch2_increment_clock(c, bio_sectors(bio), WRITE);
1595 data_len = min_t(u64, bio->bi_iter.bi_size,
1596 op->new_i_size - (op->pos.offset << 9));
1598 if (c->opts.inline_data &&
1599 data_len <= min(block_bytes(c) / 2, 1024U)) {
1600 bch2_write_data_inline(op, data_len);
1607 bch2_disk_reservation_put(c, &op->res);
1609 closure_debug_destroy(&op->cl);
1614 static const char * const bch2_write_flags[] = {
1621 void bch2_write_op_to_text(struct printbuf *out, struct bch_write_op *op)
1623 prt_str(out, "pos: ");
1624 bch2_bpos_to_text(out, op->pos);
1626 printbuf_indent_add(out, 2);
1628 prt_str(out, "started: ");
1629 bch2_pr_time_units(out, local_clock() - op->start_time);
1632 prt_str(out, "flags: ");
1633 prt_bitflags(out, bch2_write_flags, op->flags);
1636 prt_printf(out, "ref: %u", closure_nr_remaining(&op->cl));
1639 printbuf_indent_sub(out, 2);
1642 void bch2_fs_io_write_exit(struct bch_fs *c)
1644 mempool_exit(&c->bio_bounce_pages);
1645 bioset_exit(&c->bio_write);
1648 int bch2_fs_io_write_init(struct bch_fs *c)
1650 if (bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
1652 return -BCH_ERR_ENOMEM_bio_write_init;
1654 if (mempool_init_page_pool(&c->bio_bounce_pages,
1656 c->opts.btree_node_size,
1657 c->opts.encoded_extent_max) /
1659 return -BCH_ERR_ENOMEM_bio_bounce_pages_init;