1 // SPDX-License-Identifier: GPL-2.0
5 #include "alloc_foreground.h"
8 #include "fs-io-buffered.h"
9 #include "fs-io-direct.h"
10 #include "fs-io-pagecache.h"
14 #include <linux/backing-dev.h>
15 #include <linux/pagemap.h>
16 #include <linux/writeback.h>
18 static inline bool bio_full(struct bio *bio, unsigned len)
20 if (bio->bi_vcnt >= bio->bi_max_vecs)
22 if (bio->bi_iter.bi_size > UINT_MAX - len)
29 static void bch2_readpages_end_io(struct bio *bio)
33 bio_for_each_folio_all(fi, bio) {
34 if (!bio->bi_status) {
35 folio_mark_uptodate(fi.folio);
37 folio_clear_uptodate(fi.folio);
38 folio_set_error(fi.folio);
40 folio_unlock(fi.folio);
46 struct readpages_iter {
47 struct address_space *mapping;
52 static int readpages_iter_init(struct readpages_iter *iter,
53 struct readahead_control *ractl)
57 *iter = (struct readpages_iter) { ractl->mapping };
59 while ((folio = __readahead_folio(ractl))) {
60 if (!bch2_folio_create(folio, GFP_KERNEL) ||
61 darray_push(&iter->folios, folio)) {
62 bch2_folio_release(folio);
63 ractl->_nr_pages += folio_nr_pages(folio);
64 ractl->_index -= folio_nr_pages(folio);
65 return iter->folios.nr ? 0 : -ENOMEM;
74 static inline struct folio *readpage_iter_peek(struct readpages_iter *iter)
76 if (iter->idx >= iter->folios.nr)
78 return iter->folios.data[iter->idx];
81 static inline void readpage_iter_advance(struct readpages_iter *iter)
86 static bool extent_partial_reads_expensive(struct bkey_s_c k)
88 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
89 struct bch_extent_crc_unpacked crc;
90 const union bch_extent_entry *i;
92 bkey_for_each_crc(k.k, ptrs, crc, i)
93 if (crc.csum_type || crc.compression_type)
98 static int readpage_bio_extend(struct btree_trans *trans,
99 struct readpages_iter *iter,
101 unsigned sectors_this_extent,
104 /* Don't hold btree locks while allocating memory: */
105 bch2_trans_unlock(trans);
107 while (bio_sectors(bio) < sectors_this_extent &&
108 bio->bi_vcnt < bio->bi_max_vecs) {
109 struct folio *folio = readpage_iter_peek(iter);
113 readpage_iter_advance(iter);
115 pgoff_t folio_offset = bio_end_sector(bio) >> PAGE_SECTORS_SHIFT;
120 folio = xa_load(&iter->mapping->i_pages, folio_offset);
121 if (folio && !xa_is_value(folio))
124 folio = filemap_alloc_folio(readahead_gfp_mask(iter->mapping), 0);
128 if (!__bch2_folio_create(folio, GFP_KERNEL)) {
133 ret = filemap_add_folio(iter->mapping, folio, folio_offset, GFP_KERNEL);
135 __bch2_folio_release(folio);
143 BUG_ON(folio_sector(folio) != bio_end_sector(bio));
145 BUG_ON(!bio_add_folio(bio, folio, folio_size(folio), 0));
148 return bch2_trans_relock(trans);
151 static void bchfs_read(struct btree_trans *trans,
152 struct bch_read_bio *rbio,
154 struct readpages_iter *readpages_iter)
156 struct bch_fs *c = trans->c;
157 struct btree_iter iter;
159 int flags = BCH_READ_RETRY_IF_STALE|
160 BCH_READ_MAY_PROMOTE;
165 rbio->start_time = local_clock();
166 rbio->subvol = inum.subvol;
168 bch2_bkey_buf_init(&sk);
170 bch2_trans_begin(trans);
171 iter = (struct btree_iter) { NULL };
173 ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
177 bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
178 SPOS(inum.inum, rbio->bio.bi_iter.bi_sector, snapshot),
182 unsigned bytes, sectors, offset_into_extent;
183 enum btree_id data_btree = BTREE_ID_extents;
186 * read_extent -> io_time_reset may cause a transaction restart
187 * without returning an error, we need to check for that here:
189 ret = bch2_trans_relock(trans);
193 bch2_btree_iter_set_pos(&iter,
194 POS(inum.inum, rbio->bio.bi_iter.bi_sector));
196 k = bch2_btree_iter_peek_slot(&iter);
201 offset_into_extent = iter.pos.offset -
202 bkey_start_offset(k.k);
203 sectors = k.k->size - offset_into_extent;
205 bch2_bkey_buf_reassemble(&sk, c, k);
207 ret = bch2_read_indirect_extent(trans, &data_btree,
208 &offset_into_extent, &sk);
212 k = bkey_i_to_s_c(sk.k);
214 sectors = min(sectors, k.k->size - offset_into_extent);
216 if (readpages_iter) {
217 ret = readpage_bio_extend(trans, readpages_iter, &rbio->bio, sectors,
218 extent_partial_reads_expensive(k));
223 bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
224 swap(rbio->bio.bi_iter.bi_size, bytes);
226 if (rbio->bio.bi_iter.bi_size == bytes)
227 flags |= BCH_READ_LAST_FRAGMENT;
229 bch2_bio_page_state_set(&rbio->bio, k);
231 bch2_read_extent(trans, rbio, iter.pos,
232 data_btree, k, offset_into_extent, flags);
234 if (flags & BCH_READ_LAST_FRAGMENT)
237 swap(rbio->bio.bi_iter.bi_size, bytes);
238 bio_advance(&rbio->bio, bytes);
240 ret = btree_trans_too_many_iters(trans);
245 bch2_trans_iter_exit(trans, &iter);
247 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
251 bch_err_inum_offset_ratelimited(c,
253 iter.pos.offset << 9,
254 "read error %i from btree lookup", ret);
255 rbio->bio.bi_status = BLK_STS_IOERR;
256 bio_endio(&rbio->bio);
259 bch2_bkey_buf_exit(&sk, c);
262 void bch2_readahead(struct readahead_control *ractl)
264 struct bch_inode_info *inode = to_bch_ei(ractl->mapping->host);
265 struct bch_fs *c = inode->v.i_sb->s_fs_info;
266 struct bch_io_opts opts;
267 struct btree_trans *trans = bch2_trans_get(c);
269 struct readpages_iter readpages_iter;
271 bch2_inode_opts_get(&opts, c, &inode->ei_inode);
273 int ret = readpages_iter_init(&readpages_iter, ractl);
277 bch2_pagecache_add_get(inode);
279 while ((folio = readpage_iter_peek(&readpages_iter))) {
280 unsigned n = min_t(unsigned,
281 readpages_iter.folios.nr -
284 struct bch_read_bio *rbio =
285 rbio_init(bio_alloc_bioset(NULL, n, REQ_OP_READ,
286 GFP_KERNEL, &c->bio_read),
289 readpage_iter_advance(&readpages_iter);
291 rbio->bio.bi_iter.bi_sector = folio_sector(folio);
292 rbio->bio.bi_end_io = bch2_readpages_end_io;
293 BUG_ON(!bio_add_folio(&rbio->bio, folio, folio_size(folio), 0));
295 bchfs_read(trans, rbio, inode_inum(inode),
297 bch2_trans_unlock(trans);
300 bch2_pagecache_add_put(inode);
302 bch2_trans_put(trans);
303 darray_exit(&readpages_iter.folios);
306 static void bch2_read_single_folio_end_io(struct bio *bio)
308 complete(bio->bi_private);
311 int bch2_read_single_folio(struct folio *folio, struct address_space *mapping)
313 struct bch_inode_info *inode = to_bch_ei(mapping->host);
314 struct bch_fs *c = inode->v.i_sb->s_fs_info;
315 struct bch_read_bio *rbio;
316 struct bch_io_opts opts;
318 DECLARE_COMPLETION_ONSTACK(done);
320 if (!bch2_folio_create(folio, GFP_KERNEL))
323 bch2_inode_opts_get(&opts, c, &inode->ei_inode);
325 rbio = rbio_init(bio_alloc_bioset(NULL, 1, REQ_OP_READ, GFP_KERNEL, &c->bio_read),
327 rbio->bio.bi_private = &done;
328 rbio->bio.bi_end_io = bch2_read_single_folio_end_io;
330 rbio->bio.bi_opf = REQ_OP_READ|REQ_SYNC;
331 rbio->bio.bi_iter.bi_sector = folio_sector(folio);
332 BUG_ON(!bio_add_folio(&rbio->bio, folio, folio_size(folio), 0));
334 bch2_trans_run(c, (bchfs_read(trans, rbio, inode_inum(inode), NULL), 0));
335 wait_for_completion(&done);
337 ret = blk_status_to_errno(rbio->bio.bi_status);
343 folio_mark_uptodate(folio);
347 int bch2_read_folio(struct file *file, struct folio *folio)
351 ret = bch2_read_single_folio(folio, folio->mapping);
353 return bch2_err_class(ret);
358 struct bch_writepage_io {
359 struct bch_inode_info *inode;
362 struct bch_write_op op;
365 struct bch_writepage_state {
366 struct bch_writepage_io *io;
367 struct bch_io_opts opts;
368 struct bch_folio_sector *tmp;
369 unsigned tmp_sectors;
372 static inline struct bch_writepage_state bch_writepage_state_init(struct bch_fs *c,
373 struct bch_inode_info *inode)
375 struct bch_writepage_state ret = { 0 };
377 bch2_inode_opts_get(&ret.opts, c, &inode->ei_inode);
382 * Determine when a writepage io is full. We have to limit writepage bios to a
383 * single page per bvec (i.e. 1MB with 4k pages) because that is the limit to
384 * what the bounce path in bch2_write_extent() can handle. In theory we could
385 * loosen this restriction for non-bounce I/O, but we don't have that context
386 * here. Ideally, we can up this limit and make it configurable in the future
387 * when the bounce path can be enhanced to accommodate larger source bios.
389 static inline bool bch_io_full(struct bch_writepage_io *io, unsigned len)
391 struct bio *bio = &io->op.wbio.bio;
392 return bio_full(bio, len) ||
393 (bio->bi_iter.bi_size + len > BIO_MAX_VECS * PAGE_SIZE);
396 static void bch2_writepage_io_done(struct bch_write_op *op)
398 struct bch_writepage_io *io =
399 container_of(op, struct bch_writepage_io, op);
400 struct bch_fs *c = io->op.c;
401 struct bio *bio = &io->op.wbio.bio;
402 struct folio_iter fi;
406 set_bit(EI_INODE_ERROR, &io->inode->ei_flags);
408 bio_for_each_folio_all(fi, bio) {
411 folio_set_error(fi.folio);
412 mapping_set_error(fi.folio->mapping, -EIO);
414 s = __bch2_folio(fi.folio);
416 for (i = 0; i < folio_sectors(fi.folio); i++)
417 s->s[i].nr_replicas = 0;
418 spin_unlock(&s->lock);
422 if (io->op.flags & BCH_WRITE_WROTE_DATA_INLINE) {
423 bio_for_each_folio_all(fi, bio) {
426 s = __bch2_folio(fi.folio);
428 for (i = 0; i < folio_sectors(fi.folio); i++)
429 s->s[i].nr_replicas = 0;
430 spin_unlock(&s->lock);
435 * racing with fallocate can cause us to add fewer sectors than
436 * expected - but we shouldn't add more sectors than expected:
438 WARN_ON_ONCE(io->op.i_sectors_delta > 0);
441 * (error (due to going RO) halfway through a page can screw that up
444 BUG_ON(io->op.op.i_sectors_delta >= PAGE_SECTORS);
448 * PageWriteback is effectively our ref on the inode - fixup i_blocks
449 * before calling end_page_writeback:
451 bch2_i_sectors_acct(c, io->inode, NULL, io->op.i_sectors_delta);
453 bio_for_each_folio_all(fi, bio) {
454 struct bch_folio *s = __bch2_folio(fi.folio);
456 if (atomic_dec_and_test(&s->write_count))
457 folio_end_writeback(fi.folio);
460 bio_put(&io->op.wbio.bio);
463 static void bch2_writepage_do_io(struct bch_writepage_state *w)
465 struct bch_writepage_io *io = w->io;
468 closure_call(&io->op.cl, bch2_write, NULL, NULL);
472 * Get a bch_writepage_io and add @page to it - appending to an existing one if
473 * possible, else allocating a new one:
475 static void bch2_writepage_io_alloc(struct bch_fs *c,
476 struct writeback_control *wbc,
477 struct bch_writepage_state *w,
478 struct bch_inode_info *inode,
480 unsigned nr_replicas)
482 struct bch_write_op *op;
484 w->io = container_of(bio_alloc_bioset(NULL, BIO_MAX_VECS,
487 &c->writepage_bioset),
488 struct bch_writepage_io, op.wbio.bio);
490 w->io->inode = inode;
492 bch2_write_op_init(op, c, w->opts);
493 op->target = w->opts.foreground_target;
494 op->nr_replicas = nr_replicas;
495 op->res.nr_replicas = nr_replicas;
496 op->write_point = writepoint_hashed(inode->ei_last_dirtied);
497 op->subvol = inode->ei_subvol;
498 op->pos = POS(inode->v.i_ino, sector);
499 op->end_io = bch2_writepage_io_done;
500 op->devs_need_flush = &inode->ei_devs_need_flush;
501 op->wbio.bio.bi_iter.bi_sector = sector;
502 op->wbio.bio.bi_opf = wbc_to_write_flags(wbc);
505 static int __bch2_writepage(struct folio *folio,
506 struct writeback_control *wbc,
509 struct bch_inode_info *inode = to_bch_ei(folio->mapping->host);
510 struct bch_fs *c = inode->v.i_sb->s_fs_info;
511 struct bch_writepage_state *w = data;
513 unsigned i, offset, f_sectors, nr_replicas_this_write = U32_MAX;
514 loff_t i_size = i_size_read(&inode->v);
517 EBUG_ON(!folio_test_uptodate(folio));
519 /* Is the folio fully inside i_size? */
520 if (folio_end_pos(folio) <= i_size)
523 /* Is the folio fully outside i_size? (truncate in progress) */
524 if (folio_pos(folio) >= i_size) {
530 * The folio straddles i_size. It must be zeroed out on each and every
531 * writepage invocation because it may be mmapped. "A file is mapped
532 * in multiples of the folio size. For a file that is not a multiple of
533 * the folio size, the remaining memory is zeroed when mapped, and
534 * writes to that region are not written out to the file."
536 folio_zero_segment(folio,
537 i_size - folio_pos(folio),
540 f_sectors = folio_sectors(folio);
541 s = bch2_folio(folio);
543 if (f_sectors > w->tmp_sectors) {
545 w->tmp = kcalloc(f_sectors, sizeof(struct bch_folio_sector), __GFP_NOFAIL);
546 w->tmp_sectors = f_sectors;
550 * Things get really hairy with errors during writeback:
552 ret = bch2_get_folio_disk_reservation(c, inode, folio, false);
555 /* Before unlocking the page, get copy of reservations: */
557 memcpy(w->tmp, s->s, sizeof(struct bch_folio_sector) * f_sectors);
559 for (i = 0; i < f_sectors; i++) {
560 if (s->s[i].state < SECTOR_dirty)
563 nr_replicas_this_write =
564 min_t(unsigned, nr_replicas_this_write,
565 s->s[i].nr_replicas +
566 s->s[i].replicas_reserved);
569 for (i = 0; i < f_sectors; i++) {
570 if (s->s[i].state < SECTOR_dirty)
573 s->s[i].nr_replicas = w->opts.compression
574 ? 0 : nr_replicas_this_write;
576 s->s[i].replicas_reserved = 0;
577 bch2_folio_sector_set(folio, s, i, SECTOR_allocated);
579 spin_unlock(&s->lock);
581 BUG_ON(atomic_read(&s->write_count));
582 atomic_set(&s->write_count, 1);
584 BUG_ON(folio_test_writeback(folio));
585 folio_start_writeback(folio);
591 unsigned sectors = 0, dirty_sectors = 0, reserved_sectors = 0;
594 while (offset < f_sectors &&
595 w->tmp[offset].state < SECTOR_dirty)
598 if (offset == f_sectors)
601 while (offset + sectors < f_sectors &&
602 w->tmp[offset + sectors].state >= SECTOR_dirty) {
603 reserved_sectors += w->tmp[offset + sectors].replicas_reserved;
604 dirty_sectors += w->tmp[offset + sectors].state == SECTOR_dirty;
609 sector = folio_sector(folio) + offset;
612 (w->io->op.res.nr_replicas != nr_replicas_this_write ||
613 bch_io_full(w->io, sectors << 9) ||
614 bio_end_sector(&w->io->op.wbio.bio) != sector))
615 bch2_writepage_do_io(w);
618 bch2_writepage_io_alloc(c, wbc, w, inode, sector,
619 nr_replicas_this_write);
621 atomic_inc(&s->write_count);
623 BUG_ON(inode != w->io->inode);
624 BUG_ON(!bio_add_folio(&w->io->op.wbio.bio, folio,
625 sectors << 9, offset << 9));
627 /* Check for writing past i_size: */
628 WARN_ONCE((bio_end_sector(&w->io->op.wbio.bio) << 9) >
629 round_up(i_size, block_bytes(c)) &&
630 !test_bit(BCH_FS_emergency_ro, &c->flags),
631 "writing past i_size: %llu > %llu (unrounded %llu)\n",
632 bio_end_sector(&w->io->op.wbio.bio) << 9,
633 round_up(i_size, block_bytes(c)),
636 w->io->op.res.sectors += reserved_sectors;
637 w->io->op.i_sectors_delta -= dirty_sectors;
638 w->io->op.new_i_size = i_size;
643 if (atomic_dec_and_test(&s->write_count))
644 folio_end_writeback(folio);
649 int bch2_writepages(struct address_space *mapping, struct writeback_control *wbc)
651 struct bch_fs *c = mapping->host->i_sb->s_fs_info;
652 struct bch_writepage_state w =
653 bch_writepage_state_init(c, to_bch_ei(mapping->host));
654 struct blk_plug plug;
657 blk_start_plug(&plug);
658 ret = write_cache_pages(mapping, wbc, __bch2_writepage, &w);
660 bch2_writepage_do_io(&w);
661 blk_finish_plug(&plug);
663 return bch2_err_class(ret);
666 /* buffered writes: */
668 int bch2_write_begin(struct file *file, struct address_space *mapping,
669 loff_t pos, unsigned len,
670 struct page **pagep, void **fsdata)
672 struct bch_inode_info *inode = to_bch_ei(mapping->host);
673 struct bch_fs *c = inode->v.i_sb->s_fs_info;
674 struct bch2_folio_reservation *res;
679 res = kmalloc(sizeof(*res), GFP_KERNEL);
683 bch2_folio_reservation_init(c, inode, res);
686 bch2_pagecache_add_get(inode);
688 folio = __filemap_get_folio(mapping, pos >> PAGE_SHIFT,
689 FGP_LOCK|FGP_WRITE|FGP_CREAT|FGP_STABLE,
690 mapping_gfp_mask(mapping));
691 if (IS_ERR_OR_NULL(folio))
694 offset = pos - folio_pos(folio);
695 len = min_t(size_t, len, folio_end_pos(folio) - pos);
697 if (folio_test_uptodate(folio))
700 /* If we're writing entire folio, don't need to read it in first: */
701 if (!offset && len == folio_size(folio))
704 if (!offset && pos + len >= inode->v.i_size) {
705 folio_zero_segment(folio, len, folio_size(folio));
706 flush_dcache_folio(folio);
710 if (folio_pos(folio) >= inode->v.i_size) {
711 folio_zero_segments(folio, 0, offset, offset + len, folio_size(folio));
712 flush_dcache_folio(folio);
716 ret = bch2_read_single_folio(folio, mapping);
720 ret = bch2_folio_set(c, inode_inum(inode), &folio, 1);
724 ret = bch2_folio_reservation_get(c, inode, folio, res, offset, len);
726 if (!folio_test_uptodate(folio)) {
728 * If the folio hasn't been read in, we won't know if we
729 * actually need a reservation - we don't actually need
730 * to read here, we just need to check if the folio is
731 * fully backed by uncompressed data:
739 *pagep = &folio->page;
746 bch2_pagecache_add_put(inode);
749 return bch2_err_class(ret);
752 int bch2_write_end(struct file *file, struct address_space *mapping,
753 loff_t pos, unsigned len, unsigned copied,
754 struct page *page, void *fsdata)
756 struct bch_inode_info *inode = to_bch_ei(mapping->host);
757 struct bch_fs *c = inode->v.i_sb->s_fs_info;
758 struct bch2_folio_reservation *res = fsdata;
759 struct folio *folio = page_folio(page);
760 unsigned offset = pos - folio_pos(folio);
762 lockdep_assert_held(&inode->v.i_rwsem);
763 BUG_ON(offset + copied > folio_size(folio));
765 if (unlikely(copied < len && !folio_test_uptodate(folio))) {
767 * The folio needs to be read in, but that would destroy
768 * our partial write - simplest thing is to just force
769 * userspace to redo the write:
771 folio_zero_range(folio, 0, folio_size(folio));
772 flush_dcache_folio(folio);
776 spin_lock(&inode->v.i_lock);
777 if (pos + copied > inode->v.i_size)
778 i_size_write(&inode->v, pos + copied);
779 spin_unlock(&inode->v.i_lock);
782 if (!folio_test_uptodate(folio))
783 folio_mark_uptodate(folio);
785 bch2_set_folio_dirty(c, inode, folio, res, offset, copied);
787 inode->ei_last_dirtied = (unsigned long) current;
792 bch2_pagecache_add_put(inode);
794 bch2_folio_reservation_put(c, inode, res);
800 static noinline void folios_trunc(folios *fs, struct folio **fi)
802 while (fs->data + fs->nr > fi) {
803 struct folio *f = darray_pop(fs);
810 static int __bch2_buffered_write(struct bch_inode_info *inode,
811 struct address_space *mapping,
812 struct iov_iter *iter,
813 loff_t pos, unsigned len,
816 struct bch_fs *c = inode->v.i_sb->s_fs_info;
817 struct bch2_folio_reservation res;
820 unsigned copied = 0, f_offset, f_copied;
821 u64 end = pos + len, f_pos, f_len;
822 loff_t last_folio_pos = inode->v.i_size;
827 bch2_folio_reservation_init(c, inode, &res);
830 ret = bch2_filemap_get_contig_folios_d(mapping, pos, end,
831 FGP_LOCK|FGP_WRITE|FGP_STABLE|FGP_CREAT,
832 mapping_gfp_mask(mapping),
840 * If we're not using the inode lock, we need to lock all the folios for
841 * atomiticity of writes vs. other writes:
843 if (!inode_locked && folio_end_pos(darray_last(fs)) < end) {
844 ret = -BCH_ERR_need_inode_lock;
848 f = darray_first(fs);
849 if (pos != folio_pos(f) && !folio_test_uptodate(f)) {
850 ret = bch2_read_single_folio(f, mapping);
856 end = min(end, folio_end_pos(f));
857 last_folio_pos = folio_pos(f);
858 if (end != folio_end_pos(f) && !folio_test_uptodate(f)) {
859 if (end >= inode->v.i_size) {
860 folio_zero_range(f, 0, folio_size(f));
862 ret = bch2_read_single_folio(f, mapping);
868 ret = bch2_folio_set(c, inode_inum(inode), fs.data, fs.nr);
873 f_offset = pos - folio_pos(darray_first(fs));
874 darray_for_each(fs, fi) {
876 f_len = min(end, folio_end_pos(f)) - f_pos;
879 * XXX: per POSIX and fstests generic/275, on -ENOSPC we're
880 * supposed to write as much as we have disk space for.
882 * On failure here we should still write out a partial page if
883 * we aren't completely out of disk space - we don't do that
886 ret = bch2_folio_reservation_get(c, inode, f, &res, f_offset, f_len);
888 folios_trunc(&fs, fi);
892 end = min(end, folio_end_pos(darray_last(fs)));
896 f_pos = folio_end_pos(f);
900 if (mapping_writably_mapped(mapping))
901 darray_for_each(fs, fi)
902 flush_dcache_folio(*fi);
905 f_offset = pos - folio_pos(darray_first(fs));
906 darray_for_each(fs, fi) {
908 f_len = min(end, folio_end_pos(f)) - f_pos;
909 f_copied = copy_page_from_iter_atomic(&f->page, f_offset, f_len, iter);
911 folios_trunc(&fs, fi);
915 if (!folio_test_uptodate(f) &&
916 f_copied != folio_size(f) &&
917 pos + copied + f_copied < inode->v.i_size) {
918 iov_iter_revert(iter, f_copied);
919 folio_zero_range(f, 0, folio_size(f));
920 folios_trunc(&fs, fi);
924 flush_dcache_folio(f);
927 if (f_copied != f_len) {
928 folios_trunc(&fs, fi + 1);
932 f_pos = folio_end_pos(f);
941 spin_lock(&inode->v.i_lock);
942 if (end > inode->v.i_size) {
943 BUG_ON(!inode_locked);
944 i_size_write(&inode->v, end);
946 spin_unlock(&inode->v.i_lock);
949 f_offset = pos - folio_pos(darray_first(fs));
950 darray_for_each(fs, fi) {
952 f_len = min(end, folio_end_pos(f)) - f_pos;
954 if (!folio_test_uptodate(f))
955 folio_mark_uptodate(f);
957 bch2_set_folio_dirty(c, inode, f, &res, f_offset, f_len);
959 f_pos = folio_end_pos(f);
963 inode->ei_last_dirtied = (unsigned long) current;
965 darray_for_each(fs, fi) {
971 * If the last folio added to the mapping starts beyond current EOF, we
972 * performed a short write but left around at least one post-EOF folio.
973 * Clean up the mapping before we return.
975 if (last_folio_pos >= inode->v.i_size)
976 truncate_pagecache(&inode->v, inode->v.i_size);
979 bch2_folio_reservation_put(c, inode, &res);
981 return copied ?: ret;
984 static ssize_t bch2_buffered_write(struct kiocb *iocb, struct iov_iter *iter)
986 struct file *file = iocb->ki_filp;
987 struct address_space *mapping = file->f_mapping;
988 struct bch_inode_info *inode = file_bch_inode(file);
990 bool inode_locked = false;
991 ssize_t written = 0, written2 = 0, ret = 0;
994 * We don't take the inode lock unless i_size will be changing. Folio
995 * locks provide exclusion with other writes, and the pagecache add lock
996 * provides exclusion with truncate and hole punching.
998 * There is one nasty corner case where atomicity would be broken
999 * without great care: when copying data from userspace to the page
1000 * cache, we do that with faults disable - a page fault would recurse
1001 * back into the filesystem, taking filesystem locks again, and
1002 * deadlock; so it's done with faults disabled, and we fault in the user
1003 * buffer when we aren't holding locks.
1005 * If we do part of the write, but we then race and in the userspace
1006 * buffer have been evicted and are no longer resident, then we have to
1007 * drop our folio locks to re-fault them in, breaking write atomicity.
1009 * To fix this, we restart the write from the start, if we weren't
1010 * holding the inode lock.
1012 * There is another wrinkle after that; if we restart the write from the
1013 * start, and then get an unrecoverable error, we _cannot_ claim to
1014 * userspace that we did not write data we actually did - so we must
1015 * track (written2) the most we ever wrote.
1018 if ((iocb->ki_flags & IOCB_APPEND) ||
1019 (iocb->ki_pos + iov_iter_count(iter) > i_size_read(&inode->v))) {
1020 inode_lock(&inode->v);
1021 inode_locked = true;
1024 ret = generic_write_checks(iocb, iter);
1028 ret = file_remove_privs_flags(file, !inode_locked ? IOCB_NOWAIT : 0);
1030 if (!inode_locked) {
1031 inode_lock(&inode->v);
1032 inode_locked = true;
1033 ret = file_remove_privs_flags(file, 0);
1039 ret = file_update_time(file);
1045 bch2_pagecache_add_get(inode);
1047 if (!inode_locked &&
1048 (iocb->ki_pos + iov_iter_count(iter) > i_size_read(&inode->v)))
1049 goto get_inode_lock;
1052 unsigned offset = pos & (PAGE_SIZE - 1);
1053 unsigned bytes = iov_iter_count(iter);
1056 * Bring in the user page that we will copy from _first_.
1057 * Otherwise there's a nasty deadlock on copying from the
1058 * same page as we're writing to, without it being marked
1061 * Not only is this an optimisation, but it is also required
1062 * to check that the address is actually valid, when atomic
1063 * usercopies are used, below.
1065 if (unlikely(fault_in_iov_iter_readable(iter, bytes))) {
1066 bytes = min_t(unsigned long, iov_iter_count(iter),
1067 PAGE_SIZE - offset);
1069 if (unlikely(fault_in_iov_iter_readable(iter, bytes))) {
1075 if (unlikely(bytes != iov_iter_count(iter) && !inode_locked))
1076 goto get_inode_lock;
1078 if (unlikely(fatal_signal_pending(current))) {
1083 ret = __bch2_buffered_write(inode, mapping, iter, pos, bytes, inode_locked);
1084 if (ret == -BCH_ERR_need_inode_lock)
1085 goto get_inode_lock;
1086 if (unlikely(ret < 0))
1091 if (unlikely(ret == 0)) {
1093 * If we were unable to copy any data at all, we must
1094 * fall back to a single segment length write.
1096 * If we didn't fallback here, we could livelock
1097 * because not all segments in the iov can be copied at
1098 * once without a pagefault.
1100 bytes = min_t(unsigned long, PAGE_SIZE - offset,
1101 iov_iter_single_seg_count(iter));
1106 written2 = max(written, written2);
1108 if (ret != bytes && !inode_locked)
1109 goto get_inode_lock;
1112 balance_dirty_pages_ratelimited(mapping);
1116 bch2_pagecache_add_put(inode);
1117 inode_lock(&inode->v);
1118 inode_locked = true;
1119 bch2_pagecache_add_get(inode);
1121 iov_iter_revert(iter, written);
1126 } while (iov_iter_count(iter));
1127 bch2_pagecache_add_put(inode);
1130 inode_unlock(&inode->v);
1132 iocb->ki_pos += written;
1134 ret = max(written, written2) ?: ret;
1136 ret = generic_write_sync(iocb, ret);
1140 ssize_t bch2_write_iter(struct kiocb *iocb, struct iov_iter *iter)
1142 ssize_t ret = iocb->ki_flags & IOCB_DIRECT
1143 ? bch2_direct_write(iocb, iter)
1144 : bch2_buffered_write(iocb, iter);
1146 return bch2_err_class(ret);
1149 void bch2_fs_fs_io_buffered_exit(struct bch_fs *c)
1151 bioset_exit(&c->writepage_bioset);
1154 int bch2_fs_fs_io_buffered_init(struct bch_fs *c)
1156 if (bioset_init(&c->writepage_bioset,
1157 4, offsetof(struct bch_writepage_io, op.wbio.bio),
1159 return -BCH_ERR_ENOMEM_writepage_bioset_init;
1164 #endif /* NO_BCACHEFS_FS */