1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2010 Red Hat, Inc.
4 * Copyright (C) 2016-2019 Christoph Hellwig.
6 #include <linux/module.h>
7 #include <linux/compiler.h>
9 #include <linux/iomap.h>
10 #include <linux/pagemap.h>
11 #include <linux/uio.h>
12 #include <linux/buffer_head.h>
13 #include <linux/dax.h>
14 #include <linux/writeback.h>
15 #include <linux/list_sort.h>
16 #include <linux/swap.h>
17 #include <linux/bio.h>
18 #include <linux/sched/signal.h>
19 #include <linux/migrate.h>
22 #include "../internal.h"
24 #define IOEND_BATCH_SIZE 4096
27 * Structure allocated for each folio when block size < folio size
28 * to track sub-folio uptodate status and I/O completions.
31 atomic_t read_bytes_pending;
32 atomic_t write_bytes_pending;
33 spinlock_t uptodate_lock;
34 unsigned long uptodate[];
37 static inline struct iomap_page *to_iomap_page(struct folio *folio)
39 if (folio_test_private(folio))
40 return folio_get_private(folio);
44 static struct bio_set iomap_ioend_bioset;
46 static struct iomap_page *
47 iomap_page_create(struct inode *inode, struct folio *folio, unsigned int flags)
49 struct iomap_page *iop = to_iomap_page(folio);
50 unsigned int nr_blocks = i_blocks_per_folio(inode, folio);
53 if (iop || nr_blocks <= 1)
56 if (flags & IOMAP_NOWAIT)
59 gfp = GFP_NOFS | __GFP_NOFAIL;
61 iop = kzalloc(struct_size(iop, uptodate, BITS_TO_LONGS(nr_blocks)),
64 spin_lock_init(&iop->uptodate_lock);
65 if (folio_test_uptodate(folio))
66 bitmap_fill(iop->uptodate, nr_blocks);
67 folio_attach_private(folio, iop);
72 static void iomap_page_release(struct folio *folio)
74 struct iomap_page *iop = folio_detach_private(folio);
75 struct inode *inode = folio->mapping->host;
76 unsigned int nr_blocks = i_blocks_per_folio(inode, folio);
80 WARN_ON_ONCE(atomic_read(&iop->read_bytes_pending));
81 WARN_ON_ONCE(atomic_read(&iop->write_bytes_pending));
82 WARN_ON_ONCE(bitmap_full(iop->uptodate, nr_blocks) !=
83 folio_test_uptodate(folio));
88 * Calculate the range inside the folio that we actually need to read.
90 static void iomap_adjust_read_range(struct inode *inode, struct folio *folio,
91 loff_t *pos, loff_t length, size_t *offp, size_t *lenp)
93 struct iomap_page *iop = to_iomap_page(folio);
94 loff_t orig_pos = *pos;
95 loff_t isize = i_size_read(inode);
96 unsigned block_bits = inode->i_blkbits;
97 unsigned block_size = (1 << block_bits);
98 size_t poff = offset_in_folio(folio, *pos);
99 size_t plen = min_t(loff_t, folio_size(folio) - poff, length);
100 unsigned first = poff >> block_bits;
101 unsigned last = (poff + plen - 1) >> block_bits;
104 * If the block size is smaller than the page size, we need to check the
105 * per-block uptodate status and adjust the offset and length if needed
106 * to avoid reading in already uptodate ranges.
111 /* move forward for each leading block marked uptodate */
112 for (i = first; i <= last; i++) {
113 if (!test_bit(i, iop->uptodate))
121 /* truncate len if we find any trailing uptodate block(s) */
122 for ( ; i <= last; i++) {
123 if (test_bit(i, iop->uptodate)) {
124 plen -= (last - i + 1) * block_size;
132 * If the extent spans the block that contains the i_size, we need to
133 * handle both halves separately so that we properly zero data in the
134 * page cache for blocks that are entirely outside of i_size.
136 if (orig_pos <= isize && orig_pos + length > isize) {
137 unsigned end = offset_in_folio(folio, isize - 1) >> block_bits;
139 if (first <= end && last > end)
140 plen -= (last - end) * block_size;
147 static void iomap_iop_set_range_uptodate(struct folio *folio,
148 struct iomap_page *iop, size_t off, size_t len)
150 struct inode *inode = folio->mapping->host;
151 unsigned first = off >> inode->i_blkbits;
152 unsigned last = (off + len - 1) >> inode->i_blkbits;
155 spin_lock_irqsave(&iop->uptodate_lock, flags);
156 bitmap_set(iop->uptodate, first, last - first + 1);
157 if (bitmap_full(iop->uptodate, i_blocks_per_folio(inode, folio)))
158 folio_mark_uptodate(folio);
159 spin_unlock_irqrestore(&iop->uptodate_lock, flags);
162 static void iomap_set_range_uptodate(struct folio *folio,
163 struct iomap_page *iop, size_t off, size_t len)
166 iomap_iop_set_range_uptodate(folio, iop, off, len);
168 folio_mark_uptodate(folio);
171 static void iomap_finish_folio_read(struct folio *folio, size_t offset,
172 size_t len, int error)
174 struct iomap_page *iop = to_iomap_page(folio);
176 if (unlikely(error)) {
177 folio_clear_uptodate(folio);
178 folio_set_error(folio);
180 iomap_set_range_uptodate(folio, iop, offset, len);
183 if (!iop || atomic_sub_and_test(len, &iop->read_bytes_pending))
187 static void iomap_read_end_io(struct bio *bio)
189 int error = blk_status_to_errno(bio->bi_status);
190 struct folio_iter fi;
192 bio_for_each_folio_all(fi, bio)
193 iomap_finish_folio_read(fi.folio, fi.offset, fi.length, error);
197 struct iomap_readpage_ctx {
198 struct folio *cur_folio;
199 bool cur_folio_in_bio;
201 struct readahead_control *rac;
205 * iomap_read_inline_data - copy inline data into the page cache
206 * @iter: iteration structure
207 * @folio: folio to copy to
209 * Copy the inline data in @iter into @folio and zero out the rest of the folio.
210 * Only a single IOMAP_INLINE extent is allowed at the end of each file.
211 * Returns zero for success to complete the read, or the usual negative errno.
213 static int iomap_read_inline_data(const struct iomap_iter *iter,
216 struct iomap_page *iop;
217 const struct iomap *iomap = iomap_iter_srcmap(iter);
218 size_t size = i_size_read(iter->inode) - iomap->offset;
219 size_t poff = offset_in_page(iomap->offset);
220 size_t offset = offset_in_folio(folio, iomap->offset);
223 if (folio_test_uptodate(folio))
226 if (WARN_ON_ONCE(size > PAGE_SIZE - poff))
228 if (WARN_ON_ONCE(size > PAGE_SIZE -
229 offset_in_page(iomap->inline_data)))
231 if (WARN_ON_ONCE(size > iomap->length))
234 iop = iomap_page_create(iter->inode, folio, iter->flags);
236 iop = to_iomap_page(folio);
238 addr = kmap_local_folio(folio, offset);
239 memcpy(addr, iomap->inline_data, size);
240 memset(addr + size, 0, PAGE_SIZE - poff - size);
242 iomap_set_range_uptodate(folio, iop, offset, PAGE_SIZE - poff);
246 static inline bool iomap_block_needs_zeroing(const struct iomap_iter *iter,
249 const struct iomap *srcmap = iomap_iter_srcmap(iter);
251 return srcmap->type != IOMAP_MAPPED ||
252 (srcmap->flags & IOMAP_F_NEW) ||
253 pos >= i_size_read(iter->inode);
256 static loff_t iomap_readpage_iter(const struct iomap_iter *iter,
257 struct iomap_readpage_ctx *ctx, loff_t offset)
259 const struct iomap *iomap = &iter->iomap;
260 loff_t pos = iter->pos + offset;
261 loff_t length = iomap_length(iter) - offset;
262 struct folio *folio = ctx->cur_folio;
263 struct iomap_page *iop;
264 loff_t orig_pos = pos;
268 if (iomap->type == IOMAP_INLINE)
269 return iomap_read_inline_data(iter, folio);
271 /* zero post-eof blocks as the page may be mapped */
272 iop = iomap_page_create(iter->inode, folio, iter->flags);
273 iomap_adjust_read_range(iter->inode, folio, &pos, length, &poff, &plen);
277 if (iomap_block_needs_zeroing(iter, pos)) {
278 folio_zero_range(folio, poff, plen);
279 iomap_set_range_uptodate(folio, iop, poff, plen);
283 ctx->cur_folio_in_bio = true;
285 atomic_add(plen, &iop->read_bytes_pending);
287 sector = iomap_sector(iomap, pos);
289 bio_end_sector(ctx->bio) != sector ||
290 !bio_add_folio(ctx->bio, folio, plen, poff)) {
291 gfp_t gfp = mapping_gfp_constraint(folio->mapping, GFP_KERNEL);
292 gfp_t orig_gfp = gfp;
293 unsigned int nr_vecs = DIV_ROUND_UP(length, PAGE_SIZE);
296 submit_bio(ctx->bio);
298 if (ctx->rac) /* same as readahead_gfp_mask */
299 gfp |= __GFP_NORETRY | __GFP_NOWARN;
300 ctx->bio = bio_alloc(iomap->bdev, bio_max_segs(nr_vecs),
303 * If the bio_alloc fails, try it again for a single page to
304 * avoid having to deal with partial page reads. This emulates
305 * what do_mpage_read_folio does.
308 ctx->bio = bio_alloc(iomap->bdev, 1, REQ_OP_READ,
312 ctx->bio->bi_opf |= REQ_RAHEAD;
313 ctx->bio->bi_iter.bi_sector = sector;
314 ctx->bio->bi_end_io = iomap_read_end_io;
315 bio_add_folio(ctx->bio, folio, plen, poff);
320 * Move the caller beyond our range so that it keeps making progress.
321 * For that, we have to include any leading non-uptodate ranges, but
322 * we can skip trailing ones as they will be handled in the next
325 return pos - orig_pos + plen;
328 int iomap_read_folio(struct folio *folio, const struct iomap_ops *ops)
330 struct iomap_iter iter = {
331 .inode = folio->mapping->host,
332 .pos = folio_pos(folio),
333 .len = folio_size(folio),
335 struct iomap_readpage_ctx ctx = {
340 trace_iomap_readpage(iter.inode, 1);
342 while ((ret = iomap_iter(&iter, ops)) > 0)
343 iter.processed = iomap_readpage_iter(&iter, &ctx, 0);
346 folio_set_error(folio);
350 WARN_ON_ONCE(!ctx.cur_folio_in_bio);
352 WARN_ON_ONCE(ctx.cur_folio_in_bio);
357 * Just like mpage_readahead and block_read_full_folio, we always
358 * return 0 and just set the folio error flag on errors. This
359 * should be cleaned up throughout the stack eventually.
363 EXPORT_SYMBOL_GPL(iomap_read_folio);
365 static loff_t iomap_readahead_iter(const struct iomap_iter *iter,
366 struct iomap_readpage_ctx *ctx)
368 loff_t length = iomap_length(iter);
371 for (done = 0; done < length; done += ret) {
372 if (ctx->cur_folio &&
373 offset_in_folio(ctx->cur_folio, iter->pos + done) == 0) {
374 if (!ctx->cur_folio_in_bio)
375 folio_unlock(ctx->cur_folio);
376 ctx->cur_folio = NULL;
378 if (!ctx->cur_folio) {
379 ctx->cur_folio = readahead_folio(ctx->rac);
380 ctx->cur_folio_in_bio = false;
382 ret = iomap_readpage_iter(iter, ctx, done);
391 * iomap_readahead - Attempt to read pages from a file.
392 * @rac: Describes the pages to be read.
393 * @ops: The operations vector for the filesystem.
395 * This function is for filesystems to call to implement their readahead
396 * address_space operation.
398 * Context: The @ops callbacks may submit I/O (eg to read the addresses of
399 * blocks from disc), and may wait for it. The caller may be trying to
400 * access a different page, and so sleeping excessively should be avoided.
401 * It may allocate memory, but should avoid costly allocations. This
402 * function is called with memalloc_nofs set, so allocations will not cause
403 * the filesystem to be reentered.
405 void iomap_readahead(struct readahead_control *rac, const struct iomap_ops *ops)
407 struct iomap_iter iter = {
408 .inode = rac->mapping->host,
409 .pos = readahead_pos(rac),
410 .len = readahead_length(rac),
412 struct iomap_readpage_ctx ctx = {
416 trace_iomap_readahead(rac->mapping->host, readahead_count(rac));
418 while (iomap_iter(&iter, ops) > 0)
419 iter.processed = iomap_readahead_iter(&iter, &ctx);
424 if (!ctx.cur_folio_in_bio)
425 folio_unlock(ctx.cur_folio);
428 EXPORT_SYMBOL_GPL(iomap_readahead);
431 * iomap_is_partially_uptodate checks whether blocks within a folio are
434 * Returns true if all blocks which correspond to the specified part
435 * of the folio are uptodate.
437 bool iomap_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
439 struct iomap_page *iop = to_iomap_page(folio);
440 struct inode *inode = folio->mapping->host;
441 unsigned first, last, i;
446 /* Caller's range may extend past the end of this folio */
447 count = min(folio_size(folio) - from, count);
449 /* First and last blocks in range within folio */
450 first = from >> inode->i_blkbits;
451 last = (from + count - 1) >> inode->i_blkbits;
453 for (i = first; i <= last; i++)
454 if (!test_bit(i, iop->uptodate))
458 EXPORT_SYMBOL_GPL(iomap_is_partially_uptodate);
460 bool iomap_release_folio(struct folio *folio, gfp_t gfp_flags)
462 trace_iomap_release_folio(folio->mapping->host, folio_pos(folio),
466 * mm accommodates an old ext3 case where clean folios might
467 * not have had the dirty bit cleared. Thus, it can send actual
468 * dirty folios to ->release_folio() via shrink_active_list();
471 if (folio_test_dirty(folio) || folio_test_writeback(folio))
473 iomap_page_release(folio);
476 EXPORT_SYMBOL_GPL(iomap_release_folio);
478 void iomap_invalidate_folio(struct folio *folio, size_t offset, size_t len)
480 trace_iomap_invalidate_folio(folio->mapping->host,
481 folio_pos(folio) + offset, len);
484 * If we're invalidating the entire folio, clear the dirty state
485 * from it and release it to avoid unnecessary buildup of the LRU.
487 if (offset == 0 && len == folio_size(folio)) {
488 WARN_ON_ONCE(folio_test_writeback(folio));
489 folio_cancel_dirty(folio);
490 iomap_page_release(folio);
491 } else if (folio_test_large(folio)) {
492 /* Must release the iop so the page can be split */
493 WARN_ON_ONCE(!folio_test_uptodate(folio) &&
494 folio_test_dirty(folio));
495 iomap_page_release(folio);
498 EXPORT_SYMBOL_GPL(iomap_invalidate_folio);
501 iomap_write_failed(struct inode *inode, loff_t pos, unsigned len)
503 loff_t i_size = i_size_read(inode);
506 * Only truncate newly allocated pages beyoned EOF, even if the
507 * write started inside the existing inode size.
509 if (pos + len > i_size)
510 truncate_pagecache_range(inode, max(pos, i_size),
514 static int iomap_read_folio_sync(loff_t block_start, struct folio *folio,
515 size_t poff, size_t plen, const struct iomap *iomap)
520 bio_init(&bio, iomap->bdev, &bvec, 1, REQ_OP_READ);
521 bio.bi_iter.bi_sector = iomap_sector(iomap, block_start);
522 bio_add_folio(&bio, folio, plen, poff);
523 return submit_bio_wait(&bio);
526 static int __iomap_write_begin(const struct iomap_iter *iter, loff_t pos,
527 size_t len, struct folio *folio)
529 const struct iomap *srcmap = iomap_iter_srcmap(iter);
530 struct iomap_page *iop;
531 loff_t block_size = i_blocksize(iter->inode);
532 loff_t block_start = round_down(pos, block_size);
533 loff_t block_end = round_up(pos + len, block_size);
534 unsigned int nr_blocks = i_blocks_per_folio(iter->inode, folio);
535 size_t from = offset_in_folio(folio, pos), to = from + len;
538 if (folio_test_uptodate(folio))
540 folio_clear_error(folio);
542 iop = iomap_page_create(iter->inode, folio, iter->flags);
543 if ((iter->flags & IOMAP_NOWAIT) && !iop && nr_blocks > 1)
547 iomap_adjust_read_range(iter->inode, folio, &block_start,
548 block_end - block_start, &poff, &plen);
552 if (!(iter->flags & IOMAP_UNSHARE) &&
553 (from <= poff || from >= poff + plen) &&
554 (to <= poff || to >= poff + plen))
557 if (iomap_block_needs_zeroing(iter, block_start)) {
558 if (WARN_ON_ONCE(iter->flags & IOMAP_UNSHARE))
560 folio_zero_segments(folio, poff, from, to, poff + plen);
564 if (iter->flags & IOMAP_NOWAIT)
567 status = iomap_read_folio_sync(block_start, folio,
572 iomap_set_range_uptodate(folio, iop, poff, plen);
573 } while ((block_start += plen) < block_end);
578 static int iomap_write_begin_inline(const struct iomap_iter *iter,
581 /* needs more work for the tailpacking case; disable for now */
582 if (WARN_ON_ONCE(iomap_iter_srcmap(iter)->offset != 0))
584 return iomap_read_inline_data(iter, folio);
587 static int iomap_write_begin(struct iomap_iter *iter, loff_t pos,
588 size_t len, struct folio **foliop)
590 const struct iomap_page_ops *page_ops = iter->iomap.page_ops;
591 const struct iomap *srcmap = iomap_iter_srcmap(iter);
593 unsigned fgp = FGP_LOCK | FGP_WRITE | FGP_CREAT | FGP_STABLE | FGP_NOFS;
596 if (iter->flags & IOMAP_NOWAIT)
599 BUG_ON(pos + len > iter->iomap.offset + iter->iomap.length);
600 if (srcmap != &iter->iomap)
601 BUG_ON(pos + len > srcmap->offset + srcmap->length);
603 if (fatal_signal_pending(current))
606 if (!mapping_large_folio_support(iter->inode->i_mapping))
607 len = min_t(size_t, len, PAGE_SIZE - offset_in_page(pos));
609 if (page_ops && page_ops->page_prepare) {
610 status = page_ops->page_prepare(iter->inode, pos, len);
615 folio = __filemap_get_folio(iter->inode->i_mapping, pos >> PAGE_SHIFT,
616 fgp, mapping_gfp_mask(iter->inode->i_mapping));
618 status = (iter->flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOMEM;
623 * Now we have a locked folio, before we do anything with it we need to
624 * check that the iomap we have cached is not stale. The inode extent
625 * mapping can change due to concurrent IO in flight (e.g.
626 * IOMAP_UNWRITTEN state can change and memory reclaim could have
627 * reclaimed a previously partially written page at this index after IO
628 * completion before this write reaches this file offset) and hence we
629 * could do the wrong thing here (zero a page range incorrectly or fail
630 * to zero) and corrupt data.
632 if (page_ops && page_ops->iomap_valid) {
633 bool iomap_valid = page_ops->iomap_valid(iter->inode,
636 iter->iomap.flags |= IOMAP_F_STALE;
642 if (pos + len > folio_pos(folio) + folio_size(folio))
643 len = folio_pos(folio) + folio_size(folio) - pos;
645 if (srcmap->type == IOMAP_INLINE)
646 status = iomap_write_begin_inline(iter, folio);
647 else if (srcmap->flags & IOMAP_F_BUFFER_HEAD)
648 status = __block_write_begin_int(folio, pos, len, NULL, srcmap);
650 status = __iomap_write_begin(iter, pos, len, folio);
652 if (unlikely(status))
661 iomap_write_failed(iter->inode, pos, len);
664 if (page_ops && page_ops->page_done)
665 page_ops->page_done(iter->inode, pos, 0, NULL);
669 static size_t __iomap_write_end(struct inode *inode, loff_t pos, size_t len,
670 size_t copied, struct folio *folio)
672 struct iomap_page *iop = to_iomap_page(folio);
673 flush_dcache_folio(folio);
676 * The blocks that were entirely written will now be uptodate, so we
677 * don't have to worry about a read_folio reading them and overwriting a
678 * partial write. However, if we've encountered a short write and only
679 * partially written into a block, it will not be marked uptodate, so a
680 * read_folio might come in and destroy our partial write.
682 * Do the simplest thing and just treat any short write to a
683 * non-uptodate page as a zero-length write, and force the caller to
684 * redo the whole thing.
686 if (unlikely(copied < len && !folio_test_uptodate(folio)))
688 iomap_set_range_uptodate(folio, iop, offset_in_folio(folio, pos), len);
689 filemap_dirty_folio(inode->i_mapping, folio);
693 static size_t iomap_write_end_inline(const struct iomap_iter *iter,
694 struct folio *folio, loff_t pos, size_t copied)
696 const struct iomap *iomap = &iter->iomap;
699 WARN_ON_ONCE(!folio_test_uptodate(folio));
700 BUG_ON(!iomap_inline_data_valid(iomap));
702 flush_dcache_folio(folio);
703 addr = kmap_local_folio(folio, pos);
704 memcpy(iomap_inline_data(iomap, pos), addr, copied);
707 mark_inode_dirty(iter->inode);
711 /* Returns the number of bytes copied. May be 0. Cannot be an errno. */
712 static size_t iomap_write_end(struct iomap_iter *iter, loff_t pos, size_t len,
713 size_t copied, struct folio *folio)
715 const struct iomap_page_ops *page_ops = iter->iomap.page_ops;
716 const struct iomap *srcmap = iomap_iter_srcmap(iter);
717 loff_t old_size = iter->inode->i_size;
720 if (srcmap->type == IOMAP_INLINE) {
721 ret = iomap_write_end_inline(iter, folio, pos, copied);
722 } else if (srcmap->flags & IOMAP_F_BUFFER_HEAD) {
723 ret = block_write_end(NULL, iter->inode->i_mapping, pos, len,
724 copied, &folio->page, NULL);
726 ret = __iomap_write_end(iter->inode, pos, len, copied, folio);
730 * Update the in-memory inode size after copying the data into the page
731 * cache. It's up to the file system to write the updated size to disk,
732 * preferably after I/O completion so that no stale data is exposed.
734 if (pos + ret > old_size) {
735 i_size_write(iter->inode, pos + ret);
736 iter->iomap.flags |= IOMAP_F_SIZE_CHANGED;
741 pagecache_isize_extended(iter->inode, old_size, pos);
742 if (page_ops && page_ops->page_done)
743 page_ops->page_done(iter->inode, pos, ret, &folio->page);
747 iomap_write_failed(iter->inode, pos + ret, len - ret);
751 static loff_t iomap_write_iter(struct iomap_iter *iter, struct iov_iter *i)
753 loff_t length = iomap_length(iter);
754 loff_t pos = iter->pos;
757 struct address_space *mapping = iter->inode->i_mapping;
758 unsigned int bdp_flags = (iter->flags & IOMAP_NOWAIT) ? BDP_ASYNC : 0;
763 unsigned long offset; /* Offset into pagecache page */
764 unsigned long bytes; /* Bytes to write to page */
765 size_t copied; /* Bytes copied from user */
767 offset = offset_in_page(pos);
768 bytes = min_t(unsigned long, PAGE_SIZE - offset,
771 status = balance_dirty_pages_ratelimited_flags(mapping,
773 if (unlikely(status))
780 * Bring in the user page that we'll copy from _first_.
781 * Otherwise there's a nasty deadlock on copying from the
782 * same page as we're writing to, without it being marked
785 * For async buffered writes the assumption is that the user
786 * page has already been faulted in. This can be optimized by
787 * faulting the user page.
789 if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
794 status = iomap_write_begin(iter, pos, bytes, &folio);
795 if (unlikely(status))
797 if (iter->iomap.flags & IOMAP_F_STALE)
800 page = folio_file_page(folio, pos >> PAGE_SHIFT);
801 if (mapping_writably_mapped(mapping))
802 flush_dcache_page(page);
804 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
806 status = iomap_write_end(iter, pos, bytes, copied, folio);
808 if (unlikely(copied != status))
809 iov_iter_revert(i, copied - status);
812 if (unlikely(status == 0)) {
814 * A short copy made iomap_write_end() reject the
815 * thing entirely. Might be memory poisoning
816 * halfway through, might be a race with munmap,
817 * might be severe memory pressure.
826 } while (iov_iter_count(i) && length);
828 if (status == -EAGAIN) {
829 iov_iter_revert(i, written);
832 return written ? written : status;
836 iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i,
837 const struct iomap_ops *ops)
839 struct iomap_iter iter = {
840 .inode = iocb->ki_filp->f_mapping->host,
842 .len = iov_iter_count(i),
843 .flags = IOMAP_WRITE,
847 if (iocb->ki_flags & IOCB_NOWAIT)
848 iter.flags |= IOMAP_NOWAIT;
850 while ((ret = iomap_iter(&iter, ops)) > 0)
851 iter.processed = iomap_write_iter(&iter, i);
852 if (iter.pos == iocb->ki_pos)
854 return iter.pos - iocb->ki_pos;
856 EXPORT_SYMBOL_GPL(iomap_file_buffered_write);
859 * Scan the data range passed to us for dirty page cache folios. If we find a
860 * dirty folio, punch out the preceeding range and update the offset from which
861 * the next punch will start from.
863 * We can punch out storage reservations under clean pages because they either
864 * contain data that has been written back - in which case the delalloc punch
865 * over that range is a no-op - or they have been read faults in which case they
866 * contain zeroes and we can remove the delalloc backing range and any new
867 * writes to those pages will do the normal hole filling operation...
869 * This makes the logic simple: we only need to keep the delalloc extents only
870 * over the dirty ranges of the page cache.
872 * This function uses [start_byte, end_byte) intervals (i.e. open ended) to
873 * simplify range iterations.
875 static int iomap_write_delalloc_scan(struct inode *inode,
876 loff_t *punch_start_byte, loff_t start_byte, loff_t end_byte,
877 int (*punch)(struct inode *inode, loff_t offset, loff_t length))
879 while (start_byte < end_byte) {
882 /* grab locked page */
883 folio = filemap_lock_folio(inode->i_mapping,
884 start_byte >> PAGE_SHIFT);
886 start_byte = ALIGN_DOWN(start_byte, PAGE_SIZE) +
891 /* if dirty, punch up to offset */
892 if (folio_test_dirty(folio)) {
893 if (start_byte > *punch_start_byte) {
896 error = punch(inode, *punch_start_byte,
897 start_byte - *punch_start_byte);
906 * Make sure the next punch start is correctly bound to
907 * the end of this data range, not the end of the folio.
909 *punch_start_byte = min_t(loff_t, end_byte,
910 folio_next_index(folio) << PAGE_SHIFT);
913 /* move offset to start of next folio in range */
914 start_byte = folio_next_index(folio) << PAGE_SHIFT;
922 * Punch out all the delalloc blocks in the range given except for those that
923 * have dirty data still pending in the page cache - those are going to be
924 * written and so must still retain the delalloc backing for writeback.
926 * As we are scanning the page cache for data, we don't need to reimplement the
927 * wheel - mapping_seek_hole_data() does exactly what we need to identify the
928 * start and end of data ranges correctly even for sub-folio block sizes. This
929 * byte range based iteration is especially convenient because it means we
930 * don't have to care about variable size folios, nor where the start or end of
931 * the data range lies within a folio, if they lie within the same folio or even
932 * if there are multiple discontiguous data ranges within the folio.
934 * It should be noted that mapping_seek_hole_data() is not aware of EOF, and so
935 * can return data ranges that exist in the cache beyond EOF. e.g. a page fault
936 * spanning EOF will initialise the post-EOF data to zeroes and mark it up to
937 * date. A write page fault can then mark it dirty. If we then fail a write()
938 * beyond EOF into that up to date cached range, we allocate a delalloc block
939 * beyond EOF and then have to punch it out. Because the range is up to date,
940 * mapping_seek_hole_data() will return it, and we will skip the punch because
941 * the folio is dirty. THis is incorrect - we always need to punch out delalloc
942 * beyond EOF in this case as writeback will never write back and covert that
943 * delalloc block beyond EOF. Hence we limit the cached data scan range to EOF,
944 * resulting in always punching out the range from the EOF to the end of the
945 * range the iomap spans.
947 * Intervals are of the form [start_byte, end_byte) (i.e. open ended) because it
948 * matches the intervals returned by mapping_seek_hole_data(). i.e. SEEK_DATA
949 * returns the start of a data range (start_byte), and SEEK_HOLE(start_byte)
950 * returns the end of the data range (data_end). Using closed intervals would
951 * require sprinkling this code with magic "+ 1" and "- 1" arithmetic and expose
952 * the code to subtle off-by-one bugs....
954 static int iomap_write_delalloc_release(struct inode *inode,
955 loff_t start_byte, loff_t end_byte,
956 int (*punch)(struct inode *inode, loff_t pos, loff_t length))
958 loff_t punch_start_byte = start_byte;
959 loff_t scan_end_byte = min(i_size_read(inode), end_byte);
963 * Lock the mapping to avoid races with page faults re-instantiating
964 * folios and dirtying them via ->page_mkwrite whilst we walk the
965 * cache and perform delalloc extent removal. Failing to do this can
966 * leave dirty pages with no space reservation in the cache.
968 filemap_invalidate_lock(inode->i_mapping);
969 while (start_byte < scan_end_byte) {
972 start_byte = mapping_seek_hole_data(inode->i_mapping,
973 start_byte, scan_end_byte, SEEK_DATA);
975 * If there is no more data to scan, all that is left is to
976 * punch out the remaining range.
978 if (start_byte == -ENXIO || start_byte == scan_end_byte)
980 if (start_byte < 0) {
984 WARN_ON_ONCE(start_byte < punch_start_byte);
985 WARN_ON_ONCE(start_byte > scan_end_byte);
988 * We find the end of this contiguous cached data range by
989 * seeking from start_byte to the beginning of the next hole.
991 data_end = mapping_seek_hole_data(inode->i_mapping, start_byte,
992 scan_end_byte, SEEK_HOLE);
997 WARN_ON_ONCE(data_end <= start_byte);
998 WARN_ON_ONCE(data_end > scan_end_byte);
1000 error = iomap_write_delalloc_scan(inode, &punch_start_byte,
1001 start_byte, data_end, punch);
1005 /* The next data search starts at the end of this one. */
1006 start_byte = data_end;
1009 if (punch_start_byte < end_byte)
1010 error = punch(inode, punch_start_byte,
1011 end_byte - punch_start_byte);
1013 filemap_invalidate_unlock(inode->i_mapping);
1018 * When a short write occurs, the filesystem may need to remove reserved space
1019 * that was allocated in ->iomap_begin from it's ->iomap_end method. For
1020 * filesystems that use delayed allocation, we need to punch out delalloc
1021 * extents from the range that are not dirty in the page cache. As the write can
1022 * race with page faults, there can be dirty pages over the delalloc extent
1023 * outside the range of a short write but still within the delalloc extent
1024 * allocated for this iomap.
1026 * This function uses [start_byte, end_byte) intervals (i.e. open ended) to
1027 * simplify range iterations.
1029 * The punch() callback *must* only punch delalloc extents in the range passed
1030 * to it. It must skip over all other types of extents in the range and leave
1031 * them completely unchanged. It must do this punch atomically with respect to
1032 * other extent modifications.
1034 * The punch() callback may be called with a folio locked to prevent writeback
1035 * extent allocation racing at the edge of the range we are currently punching.
1036 * The locked folio may or may not cover the range being punched, so it is not
1037 * safe for the punch() callback to lock folios itself.
1041 * inode->i_rwsem (shared or exclusive)
1042 * inode->i_mapping->invalidate_lock (exclusive)
1045 * internal filesystem allocation lock
1047 int iomap_file_buffered_write_punch_delalloc(struct inode *inode,
1048 struct iomap *iomap, loff_t pos, loff_t length,
1050 int (*punch)(struct inode *inode, loff_t pos, loff_t length))
1054 int blocksize = i_blocksize(inode);
1056 if (iomap->type != IOMAP_DELALLOC)
1059 /* If we didn't reserve the blocks, we're not allowed to punch them. */
1060 if (!(iomap->flags & IOMAP_F_NEW))
1064 * start_byte refers to the first unused block after a short write. If
1065 * nothing was written, round offset down to point at the first block in
1068 if (unlikely(!written))
1069 start_byte = round_down(pos, blocksize);
1071 start_byte = round_up(pos + written, blocksize);
1072 end_byte = round_up(pos + length, blocksize);
1074 /* Nothing to do if we've written the entire delalloc extent */
1075 if (start_byte >= end_byte)
1078 return iomap_write_delalloc_release(inode, start_byte, end_byte,
1081 EXPORT_SYMBOL_GPL(iomap_file_buffered_write_punch_delalloc);
1083 static loff_t iomap_unshare_iter(struct iomap_iter *iter)
1085 struct iomap *iomap = &iter->iomap;
1086 const struct iomap *srcmap = iomap_iter_srcmap(iter);
1087 loff_t pos = iter->pos;
1088 loff_t length = iomap_length(iter);
1092 /* don't bother with blocks that are not shared to start with */
1093 if (!(iomap->flags & IOMAP_F_SHARED))
1095 /* don't bother with holes or unwritten extents */
1096 if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
1100 unsigned long offset = offset_in_page(pos);
1101 unsigned long bytes = min_t(loff_t, PAGE_SIZE - offset, length);
1102 struct folio *folio;
1104 status = iomap_write_begin(iter, pos, bytes, &folio);
1105 if (unlikely(status))
1107 if (iter->iomap.flags & IOMAP_F_STALE)
1110 status = iomap_write_end(iter, pos, bytes, bytes, folio);
1111 if (WARN_ON_ONCE(status == 0))
1120 balance_dirty_pages_ratelimited(iter->inode->i_mapping);
1127 iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len,
1128 const struct iomap_ops *ops)
1130 struct iomap_iter iter = {
1134 .flags = IOMAP_WRITE | IOMAP_UNSHARE,
1138 while ((ret = iomap_iter(&iter, ops)) > 0)
1139 iter.processed = iomap_unshare_iter(&iter);
1142 EXPORT_SYMBOL_GPL(iomap_file_unshare);
1144 static loff_t iomap_zero_iter(struct iomap_iter *iter, bool *did_zero)
1146 const struct iomap *srcmap = iomap_iter_srcmap(iter);
1147 loff_t pos = iter->pos;
1148 loff_t length = iomap_length(iter);
1151 /* already zeroed? we're done. */
1152 if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
1156 struct folio *folio;
1159 size_t bytes = min_t(u64, SIZE_MAX, length);
1161 status = iomap_write_begin(iter, pos, bytes, &folio);
1164 if (iter->iomap.flags & IOMAP_F_STALE)
1167 offset = offset_in_folio(folio, pos);
1168 if (bytes > folio_size(folio) - offset)
1169 bytes = folio_size(folio) - offset;
1171 folio_zero_range(folio, offset, bytes);
1172 folio_mark_accessed(folio);
1174 bytes = iomap_write_end(iter, pos, bytes, bytes, folio);
1175 if (WARN_ON_ONCE(bytes == 0))
1181 } while (length > 0);
1189 iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero,
1190 const struct iomap_ops *ops)
1192 struct iomap_iter iter = {
1196 .flags = IOMAP_ZERO,
1200 while ((ret = iomap_iter(&iter, ops)) > 0)
1201 iter.processed = iomap_zero_iter(&iter, did_zero);
1204 EXPORT_SYMBOL_GPL(iomap_zero_range);
1207 iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero,
1208 const struct iomap_ops *ops)
1210 unsigned int blocksize = i_blocksize(inode);
1211 unsigned int off = pos & (blocksize - 1);
1213 /* Block boundary? Nothing to do */
1216 return iomap_zero_range(inode, pos, blocksize - off, did_zero, ops);
1218 EXPORT_SYMBOL_GPL(iomap_truncate_page);
1220 static loff_t iomap_folio_mkwrite_iter(struct iomap_iter *iter,
1221 struct folio *folio)
1223 loff_t length = iomap_length(iter);
1226 if (iter->iomap.flags & IOMAP_F_BUFFER_HEAD) {
1227 ret = __block_write_begin_int(folio, iter->pos, length, NULL,
1231 block_commit_write(&folio->page, 0, length);
1233 WARN_ON_ONCE(!folio_test_uptodate(folio));
1234 folio_mark_dirty(folio);
1240 vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops)
1242 struct iomap_iter iter = {
1243 .inode = file_inode(vmf->vma->vm_file),
1244 .flags = IOMAP_WRITE | IOMAP_FAULT,
1246 struct folio *folio = page_folio(vmf->page);
1250 ret = folio_mkwrite_check_truncate(folio, iter.inode);
1253 iter.pos = folio_pos(folio);
1255 while ((ret = iomap_iter(&iter, ops)) > 0)
1256 iter.processed = iomap_folio_mkwrite_iter(&iter, folio);
1260 folio_wait_stable(folio);
1261 return VM_FAULT_LOCKED;
1263 folio_unlock(folio);
1264 return block_page_mkwrite_return(ret);
1266 EXPORT_SYMBOL_GPL(iomap_page_mkwrite);
1268 static void iomap_finish_folio_write(struct inode *inode, struct folio *folio,
1269 size_t len, int error)
1271 struct iomap_page *iop = to_iomap_page(folio);
1274 folio_set_error(folio);
1275 mapping_set_error(inode->i_mapping, error);
1278 WARN_ON_ONCE(i_blocks_per_folio(inode, folio) > 1 && !iop);
1279 WARN_ON_ONCE(iop && atomic_read(&iop->write_bytes_pending) <= 0);
1281 if (!iop || atomic_sub_and_test(len, &iop->write_bytes_pending))
1282 folio_end_writeback(folio);
1286 * We're now finished for good with this ioend structure. Update the page
1287 * state, release holds on bios, and finally free up memory. Do not use the
1291 iomap_finish_ioend(struct iomap_ioend *ioend, int error)
1293 struct inode *inode = ioend->io_inode;
1294 struct bio *bio = &ioend->io_inline_bio;
1295 struct bio *last = ioend->io_bio, *next;
1296 u64 start = bio->bi_iter.bi_sector;
1297 loff_t offset = ioend->io_offset;
1298 bool quiet = bio_flagged(bio, BIO_QUIET);
1299 u32 folio_count = 0;
1301 for (bio = &ioend->io_inline_bio; bio; bio = next) {
1302 struct folio_iter fi;
1305 * For the last bio, bi_private points to the ioend, so we
1306 * need to explicitly end the iteration here.
1311 next = bio->bi_private;
1313 /* walk all folios in bio, ending page IO on them */
1314 bio_for_each_folio_all(fi, bio) {
1315 iomap_finish_folio_write(inode, fi.folio, fi.length,
1321 /* The ioend has been freed by bio_put() */
1323 if (unlikely(error && !quiet)) {
1324 printk_ratelimited(KERN_ERR
1325 "%s: writeback error on inode %lu, offset %lld, sector %llu",
1326 inode->i_sb->s_id, inode->i_ino, offset, start);
1332 * Ioend completion routine for merged bios. This can only be called from task
1333 * contexts as merged ioends can be of unbound length. Hence we have to break up
1334 * the writeback completions into manageable chunks to avoid long scheduler
1335 * holdoffs. We aim to keep scheduler holdoffs down below 10ms so that we get
1336 * good batch processing throughput without creating adverse scheduler latency
1340 iomap_finish_ioends(struct iomap_ioend *ioend, int error)
1342 struct list_head tmp;
1347 list_replace_init(&ioend->io_list, &tmp);
1348 completions = iomap_finish_ioend(ioend, error);
1350 while (!list_empty(&tmp)) {
1351 if (completions > IOEND_BATCH_SIZE * 8) {
1355 ioend = list_first_entry(&tmp, struct iomap_ioend, io_list);
1356 list_del_init(&ioend->io_list);
1357 completions += iomap_finish_ioend(ioend, error);
1360 EXPORT_SYMBOL_GPL(iomap_finish_ioends);
1363 * We can merge two adjacent ioends if they have the same set of work to do.
1366 iomap_ioend_can_merge(struct iomap_ioend *ioend, struct iomap_ioend *next)
1368 if (ioend->io_bio->bi_status != next->io_bio->bi_status)
1370 if ((ioend->io_flags & IOMAP_F_SHARED) ^
1371 (next->io_flags & IOMAP_F_SHARED))
1373 if ((ioend->io_type == IOMAP_UNWRITTEN) ^
1374 (next->io_type == IOMAP_UNWRITTEN))
1376 if (ioend->io_offset + ioend->io_size != next->io_offset)
1379 * Do not merge physically discontiguous ioends. The filesystem
1380 * completion functions will have to iterate the physical
1381 * discontiguities even if we merge the ioends at a logical level, so
1382 * we don't gain anything by merging physical discontiguities here.
1384 * We cannot use bio->bi_iter.bi_sector here as it is modified during
1385 * submission so does not point to the start sector of the bio at
1388 if (ioend->io_sector + (ioend->io_size >> 9) != next->io_sector)
1394 iomap_ioend_try_merge(struct iomap_ioend *ioend, struct list_head *more_ioends)
1396 struct iomap_ioend *next;
1398 INIT_LIST_HEAD(&ioend->io_list);
1400 while ((next = list_first_entry_or_null(more_ioends, struct iomap_ioend,
1402 if (!iomap_ioend_can_merge(ioend, next))
1404 list_move_tail(&next->io_list, &ioend->io_list);
1405 ioend->io_size += next->io_size;
1408 EXPORT_SYMBOL_GPL(iomap_ioend_try_merge);
1411 iomap_ioend_compare(void *priv, const struct list_head *a,
1412 const struct list_head *b)
1414 struct iomap_ioend *ia = container_of(a, struct iomap_ioend, io_list);
1415 struct iomap_ioend *ib = container_of(b, struct iomap_ioend, io_list);
1417 if (ia->io_offset < ib->io_offset)
1419 if (ia->io_offset > ib->io_offset)
1425 iomap_sort_ioends(struct list_head *ioend_list)
1427 list_sort(NULL, ioend_list, iomap_ioend_compare);
1429 EXPORT_SYMBOL_GPL(iomap_sort_ioends);
1431 static void iomap_writepage_end_bio(struct bio *bio)
1433 struct iomap_ioend *ioend = bio->bi_private;
1435 iomap_finish_ioend(ioend, blk_status_to_errno(bio->bi_status));
1439 * Submit the final bio for an ioend.
1441 * If @error is non-zero, it means that we have a situation where some part of
1442 * the submission process has failed after we've marked pages for writeback
1443 * and unlocked them. In this situation, we need to fail the bio instead of
1444 * submitting it. This typically only happens on a filesystem shutdown.
1447 iomap_submit_ioend(struct iomap_writepage_ctx *wpc, struct iomap_ioend *ioend,
1450 ioend->io_bio->bi_private = ioend;
1451 ioend->io_bio->bi_end_io = iomap_writepage_end_bio;
1453 if (wpc->ops->prepare_ioend)
1454 error = wpc->ops->prepare_ioend(ioend, error);
1457 * If we're failing the IO now, just mark the ioend with an
1458 * error and finish it. This will run IO completion immediately
1459 * as there is only one reference to the ioend at this point in
1462 ioend->io_bio->bi_status = errno_to_blk_status(error);
1463 bio_endio(ioend->io_bio);
1467 submit_bio(ioend->io_bio);
1471 static struct iomap_ioend *
1472 iomap_alloc_ioend(struct inode *inode, struct iomap_writepage_ctx *wpc,
1473 loff_t offset, sector_t sector, struct writeback_control *wbc)
1475 struct iomap_ioend *ioend;
1478 bio = bio_alloc_bioset(wpc->iomap.bdev, BIO_MAX_VECS,
1479 REQ_OP_WRITE | wbc_to_write_flags(wbc),
1480 GFP_NOFS, &iomap_ioend_bioset);
1481 bio->bi_iter.bi_sector = sector;
1482 wbc_init_bio(wbc, bio);
1484 ioend = container_of(bio, struct iomap_ioend, io_inline_bio);
1485 INIT_LIST_HEAD(&ioend->io_list);
1486 ioend->io_type = wpc->iomap.type;
1487 ioend->io_flags = wpc->iomap.flags;
1488 ioend->io_inode = inode;
1490 ioend->io_folios = 0;
1491 ioend->io_offset = offset;
1492 ioend->io_bio = bio;
1493 ioend->io_sector = sector;
1498 * Allocate a new bio, and chain the old bio to the new one.
1500 * Note that we have to perform the chaining in this unintuitive order
1501 * so that the bi_private linkage is set up in the right direction for the
1502 * traversal in iomap_finish_ioend().
1505 iomap_chain_bio(struct bio *prev)
1509 new = bio_alloc(prev->bi_bdev, BIO_MAX_VECS, prev->bi_opf, GFP_NOFS);
1510 bio_clone_blkg_association(new, prev);
1511 new->bi_iter.bi_sector = bio_end_sector(prev);
1513 bio_chain(prev, new);
1514 bio_get(prev); /* for iomap_finish_ioend */
1520 iomap_can_add_to_ioend(struct iomap_writepage_ctx *wpc, loff_t offset,
1523 if ((wpc->iomap.flags & IOMAP_F_SHARED) !=
1524 (wpc->ioend->io_flags & IOMAP_F_SHARED))
1526 if (wpc->iomap.type != wpc->ioend->io_type)
1528 if (offset != wpc->ioend->io_offset + wpc->ioend->io_size)
1530 if (sector != bio_end_sector(wpc->ioend->io_bio))
1533 * Limit ioend bio chain lengths to minimise IO completion latency. This
1534 * also prevents long tight loops ending page writeback on all the
1535 * folios in the ioend.
1537 if (wpc->ioend->io_folios >= IOEND_BATCH_SIZE)
1543 * Test to see if we have an existing ioend structure that we could append to
1544 * first; otherwise finish off the current ioend and start another.
1547 iomap_add_to_ioend(struct inode *inode, loff_t pos, struct folio *folio,
1548 struct iomap_page *iop, struct iomap_writepage_ctx *wpc,
1549 struct writeback_control *wbc, struct list_head *iolist)
1551 sector_t sector = iomap_sector(&wpc->iomap, pos);
1552 unsigned len = i_blocksize(inode);
1553 size_t poff = offset_in_folio(folio, pos);
1555 if (!wpc->ioend || !iomap_can_add_to_ioend(wpc, pos, sector)) {
1557 list_add(&wpc->ioend->io_list, iolist);
1558 wpc->ioend = iomap_alloc_ioend(inode, wpc, pos, sector, wbc);
1561 if (!bio_add_folio(wpc->ioend->io_bio, folio, len, poff)) {
1562 wpc->ioend->io_bio = iomap_chain_bio(wpc->ioend->io_bio);
1563 bio_add_folio(wpc->ioend->io_bio, folio, len, poff);
1567 atomic_add(len, &iop->write_bytes_pending);
1568 wpc->ioend->io_size += len;
1569 wbc_account_cgroup_owner(wbc, &folio->page, len);
1573 * We implement an immediate ioend submission policy here to avoid needing to
1574 * chain multiple ioends and hence nest mempool allocations which can violate
1575 * the forward progress guarantees we need to provide. The current ioend we're
1576 * adding blocks to is cached in the writepage context, and if the new block
1577 * doesn't append to the cached ioend, it will create a new ioend and cache that
1580 * If a new ioend is created and cached, the old ioend is returned and queued
1581 * locally for submission once the entire page is processed or an error has been
1582 * detected. While ioends are submitted immediately after they are completed,
1583 * batching optimisations are provided by higher level block plugging.
1585 * At the end of a writeback pass, there will be a cached ioend remaining on the
1586 * writepage context that the caller will need to submit.
1589 iomap_writepage_map(struct iomap_writepage_ctx *wpc,
1590 struct writeback_control *wbc, struct inode *inode,
1591 struct folio *folio, u64 end_pos)
1593 struct iomap_page *iop = iomap_page_create(inode, folio, 0);
1594 struct iomap_ioend *ioend, *next;
1595 unsigned len = i_blocksize(inode);
1596 unsigned nblocks = i_blocks_per_folio(inode, folio);
1597 u64 pos = folio_pos(folio);
1598 int error = 0, count = 0, i;
1599 LIST_HEAD(submit_list);
1601 WARN_ON_ONCE(iop && atomic_read(&iop->write_bytes_pending) != 0);
1604 * Walk through the folio to find areas to write back. If we
1605 * run off the end of the current map or find the current map
1606 * invalid, grab a new one.
1608 for (i = 0; i < nblocks && pos < end_pos; i++, pos += len) {
1609 if (iop && !test_bit(i, iop->uptodate))
1612 error = wpc->ops->map_blocks(wpc, inode, pos);
1615 trace_iomap_writepage_map(inode, &wpc->iomap);
1616 if (WARN_ON_ONCE(wpc->iomap.type == IOMAP_INLINE))
1618 if (wpc->iomap.type == IOMAP_HOLE)
1620 iomap_add_to_ioend(inode, pos, folio, iop, wpc, wbc,
1625 wpc->ioend->io_folios++;
1627 WARN_ON_ONCE(!wpc->ioend && !list_empty(&submit_list));
1628 WARN_ON_ONCE(!folio_test_locked(folio));
1629 WARN_ON_ONCE(folio_test_writeback(folio));
1630 WARN_ON_ONCE(folio_test_dirty(folio));
1633 * We cannot cancel the ioend directly here on error. We may have
1634 * already set other pages under writeback and hence we have to run I/O
1635 * completion to mark the error state of the pages under writeback
1638 if (unlikely(error)) {
1640 * Let the filesystem know what portion of the current page
1641 * failed to map. If the page hasn't been added to ioend, it
1642 * won't be affected by I/O completion and we must unlock it
1645 if (wpc->ops->discard_folio)
1646 wpc->ops->discard_folio(folio, pos);
1648 folio_unlock(folio);
1653 folio_start_writeback(folio);
1654 folio_unlock(folio);
1657 * Preserve the original error if there was one; catch
1658 * submission errors here and propagate into subsequent ioend
1661 list_for_each_entry_safe(ioend, next, &submit_list, io_list) {
1664 list_del_init(&ioend->io_list);
1665 error2 = iomap_submit_ioend(wpc, ioend, error);
1666 if (error2 && !error)
1671 * We can end up here with no error and nothing to write only if we race
1672 * with a partial page truncate on a sub-page block sized filesystem.
1675 folio_end_writeback(folio);
1677 mapping_set_error(inode->i_mapping, error);
1682 * Write out a dirty page.
1684 * For delalloc space on the page, we need to allocate space and flush it.
1685 * For unwritten space on the page, we need to start the conversion to
1686 * regular allocated space.
1689 iomap_do_writepage(struct page *page, struct writeback_control *wbc, void *data)
1691 struct folio *folio = page_folio(page);
1692 struct iomap_writepage_ctx *wpc = data;
1693 struct inode *inode = folio->mapping->host;
1696 trace_iomap_writepage(inode, folio_pos(folio), folio_size(folio));
1699 * Refuse to write the folio out if we're called from reclaim context.
1701 * This avoids stack overflows when called from deeply used stacks in
1702 * random callers for direct reclaim or memcg reclaim. We explicitly
1703 * allow reclaim from kswapd as the stack usage there is relatively low.
1705 * This should never happen except in the case of a VM regression so
1708 if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1713 * Is this folio beyond the end of the file?
1715 * The folio index is less than the end_index, adjust the end_pos
1716 * to the highest offset that this folio should represent.
1717 * -----------------------------------------------------
1718 * | file mapping | <EOF> |
1719 * -----------------------------------------------------
1720 * | Page ... | Page N-2 | Page N-1 | Page N | |
1721 * ^--------------------------------^----------|--------
1722 * | desired writeback range | see else |
1723 * ---------------------------------^------------------|
1725 isize = i_size_read(inode);
1726 end_pos = folio_pos(folio) + folio_size(folio);
1727 if (end_pos > isize) {
1729 * Check whether the page to write out is beyond or straddles
1731 * -------------------------------------------------------
1732 * | file mapping | <EOF> |
1733 * -------------------------------------------------------
1734 * | Page ... | Page N-2 | Page N-1 | Page N | Beyond |
1735 * ^--------------------------------^-----------|---------
1737 * ---------------------------------^-----------|--------|
1739 size_t poff = offset_in_folio(folio, isize);
1740 pgoff_t end_index = isize >> PAGE_SHIFT;
1743 * Skip the page if it's fully outside i_size, e.g.
1744 * due to a truncate operation that's in progress. We've
1745 * cleaned this page and truncate will finish things off for
1748 * Note that the end_index is unsigned long. If the given
1749 * offset is greater than 16TB on a 32-bit system then if we
1750 * checked if the page is fully outside i_size with
1751 * "if (page->index >= end_index + 1)", "end_index + 1" would
1752 * overflow and evaluate to 0. Hence this page would be
1753 * redirtied and written out repeatedly, which would result in
1754 * an infinite loop; the user program performing this operation
1755 * would hang. Instead, we can detect this situation by
1756 * checking if the page is totally beyond i_size or if its
1757 * offset is just equal to the EOF.
1759 if (folio->index > end_index ||
1760 (folio->index == end_index && poff == 0))
1764 * The page straddles i_size. It must be zeroed out on each
1765 * and every writepage invocation because it may be mmapped.
1766 * "A file is mapped in multiples of the page size. For a file
1767 * that is not a multiple of the page size, the remaining
1768 * memory is zeroed when mapped, and writes to that region are
1769 * not written out to the file."
1771 folio_zero_segment(folio, poff, folio_size(folio));
1775 return iomap_writepage_map(wpc, wbc, inode, folio, end_pos);
1778 folio_redirty_for_writepage(wbc, folio);
1780 folio_unlock(folio);
1785 iomap_writepages(struct address_space *mapping, struct writeback_control *wbc,
1786 struct iomap_writepage_ctx *wpc,
1787 const struct iomap_writeback_ops *ops)
1792 ret = write_cache_pages(mapping, wbc, iomap_do_writepage, wpc);
1795 return iomap_submit_ioend(wpc, wpc->ioend, ret);
1797 EXPORT_SYMBOL_GPL(iomap_writepages);
1799 static int __init iomap_init(void)
1801 return bioset_init(&iomap_ioend_bioset, 4 * (PAGE_SIZE / SECTOR_SIZE),
1802 offsetof(struct iomap_ioend, io_inline_bio),
1805 fs_initcall(iomap_init);