xref: /linux/fs/iomap/buffered-io.c (revision 8fb72b4a76933ae6f86725cc8e4a8190ba84d755)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Red Hat, Inc.
4  * Copyright (C) 2016-2019 Christoph Hellwig.
5  */
6 #include <linux/module.h>
7 #include <linux/compiler.h>
8 #include <linux/fs.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>
20 #include "trace.h"
21 
22 #include "../internal.h"
23 
24 #define IOEND_BATCH_SIZE	4096
25 
26 /*
27  * Structure allocated for each folio when block size < folio size
28  * to track sub-folio uptodate status and I/O completions.
29  */
30 struct iomap_page {
31 	atomic_t		read_bytes_pending;
32 	atomic_t		write_bytes_pending;
33 	spinlock_t		uptodate_lock;
34 	unsigned long		uptodate[];
35 };
36 
37 static inline struct iomap_page *to_iomap_page(struct folio *folio)
38 {
39 	if (folio_test_private(folio))
40 		return folio_get_private(folio);
41 	return NULL;
42 }
43 
44 static struct bio_set iomap_ioend_bioset;
45 
46 static struct iomap_page *
47 iomap_page_create(struct inode *inode, struct folio *folio)
48 {
49 	struct iomap_page *iop = to_iomap_page(folio);
50 	unsigned int nr_blocks = i_blocks_per_folio(inode, folio);
51 
52 	if (iop || nr_blocks <= 1)
53 		return iop;
54 
55 	iop = kzalloc(struct_size(iop, uptodate, BITS_TO_LONGS(nr_blocks)),
56 			GFP_NOFS | __GFP_NOFAIL);
57 	spin_lock_init(&iop->uptodate_lock);
58 	if (folio_test_uptodate(folio))
59 		bitmap_fill(iop->uptodate, nr_blocks);
60 	folio_attach_private(folio, iop);
61 	return iop;
62 }
63 
64 static void iomap_page_release(struct folio *folio)
65 {
66 	struct iomap_page *iop = folio_detach_private(folio);
67 	struct inode *inode = folio->mapping->host;
68 	unsigned int nr_blocks = i_blocks_per_folio(inode, folio);
69 
70 	if (!iop)
71 		return;
72 	WARN_ON_ONCE(atomic_read(&iop->read_bytes_pending));
73 	WARN_ON_ONCE(atomic_read(&iop->write_bytes_pending));
74 	WARN_ON_ONCE(bitmap_full(iop->uptodate, nr_blocks) !=
75 			folio_test_uptodate(folio));
76 	kfree(iop);
77 }
78 
79 /*
80  * Calculate the range inside the folio that we actually need to read.
81  */
82 static void iomap_adjust_read_range(struct inode *inode, struct folio *folio,
83 		loff_t *pos, loff_t length, size_t *offp, size_t *lenp)
84 {
85 	struct iomap_page *iop = to_iomap_page(folio);
86 	loff_t orig_pos = *pos;
87 	loff_t isize = i_size_read(inode);
88 	unsigned block_bits = inode->i_blkbits;
89 	unsigned block_size = (1 << block_bits);
90 	size_t poff = offset_in_folio(folio, *pos);
91 	size_t plen = min_t(loff_t, folio_size(folio) - poff, length);
92 	unsigned first = poff >> block_bits;
93 	unsigned last = (poff + plen - 1) >> block_bits;
94 
95 	/*
96 	 * If the block size is smaller than the page size, we need to check the
97 	 * per-block uptodate status and adjust the offset and length if needed
98 	 * to avoid reading in already uptodate ranges.
99 	 */
100 	if (iop) {
101 		unsigned int i;
102 
103 		/* move forward for each leading block marked uptodate */
104 		for (i = first; i <= last; i++) {
105 			if (!test_bit(i, iop->uptodate))
106 				break;
107 			*pos += block_size;
108 			poff += block_size;
109 			plen -= block_size;
110 			first++;
111 		}
112 
113 		/* truncate len if we find any trailing uptodate block(s) */
114 		for ( ; i <= last; i++) {
115 			if (test_bit(i, iop->uptodate)) {
116 				plen -= (last - i + 1) * block_size;
117 				last = i - 1;
118 				break;
119 			}
120 		}
121 	}
122 
123 	/*
124 	 * If the extent spans the block that contains the i_size, we need to
125 	 * handle both halves separately so that we properly zero data in the
126 	 * page cache for blocks that are entirely outside of i_size.
127 	 */
128 	if (orig_pos <= isize && orig_pos + length > isize) {
129 		unsigned end = offset_in_folio(folio, isize - 1) >> block_bits;
130 
131 		if (first <= end && last > end)
132 			plen -= (last - end) * block_size;
133 	}
134 
135 	*offp = poff;
136 	*lenp = plen;
137 }
138 
139 static void iomap_iop_set_range_uptodate(struct folio *folio,
140 		struct iomap_page *iop, size_t off, size_t len)
141 {
142 	struct inode *inode = folio->mapping->host;
143 	unsigned first = off >> inode->i_blkbits;
144 	unsigned last = (off + len - 1) >> inode->i_blkbits;
145 	unsigned long flags;
146 
147 	spin_lock_irqsave(&iop->uptodate_lock, flags);
148 	bitmap_set(iop->uptodate, first, last - first + 1);
149 	if (bitmap_full(iop->uptodate, i_blocks_per_folio(inode, folio)))
150 		folio_mark_uptodate(folio);
151 	spin_unlock_irqrestore(&iop->uptodate_lock, flags);
152 }
153 
154 static void iomap_set_range_uptodate(struct folio *folio,
155 		struct iomap_page *iop, size_t off, size_t len)
156 {
157 	if (folio_test_error(folio))
158 		return;
159 
160 	if (iop)
161 		iomap_iop_set_range_uptodate(folio, iop, off, len);
162 	else
163 		folio_mark_uptodate(folio);
164 }
165 
166 static void iomap_finish_folio_read(struct folio *folio, size_t offset,
167 		size_t len, int error)
168 {
169 	struct iomap_page *iop = to_iomap_page(folio);
170 
171 	if (unlikely(error)) {
172 		folio_clear_uptodate(folio);
173 		folio_set_error(folio);
174 	} else {
175 		iomap_set_range_uptodate(folio, iop, offset, len);
176 	}
177 
178 	if (!iop || atomic_sub_and_test(len, &iop->read_bytes_pending))
179 		folio_unlock(folio);
180 }
181 
182 static void iomap_read_end_io(struct bio *bio)
183 {
184 	int error = blk_status_to_errno(bio->bi_status);
185 	struct folio_iter fi;
186 
187 	bio_for_each_folio_all(fi, bio)
188 		iomap_finish_folio_read(fi.folio, fi.offset, fi.length, error);
189 	bio_put(bio);
190 }
191 
192 struct iomap_readpage_ctx {
193 	struct folio		*cur_folio;
194 	bool			cur_folio_in_bio;
195 	struct bio		*bio;
196 	struct readahead_control *rac;
197 };
198 
199 /**
200  * iomap_read_inline_data - copy inline data into the page cache
201  * @iter: iteration structure
202  * @folio: folio to copy to
203  *
204  * Copy the inline data in @iter into @folio and zero out the rest of the folio.
205  * Only a single IOMAP_INLINE extent is allowed at the end of each file.
206  * Returns zero for success to complete the read, or the usual negative errno.
207  */
208 static int iomap_read_inline_data(const struct iomap_iter *iter,
209 		struct folio *folio)
210 {
211 	struct iomap_page *iop;
212 	const struct iomap *iomap = iomap_iter_srcmap(iter);
213 	size_t size = i_size_read(iter->inode) - iomap->offset;
214 	size_t poff = offset_in_page(iomap->offset);
215 	size_t offset = offset_in_folio(folio, iomap->offset);
216 	void *addr;
217 
218 	if (folio_test_uptodate(folio))
219 		return 0;
220 
221 	if (WARN_ON_ONCE(size > PAGE_SIZE - poff))
222 		return -EIO;
223 	if (WARN_ON_ONCE(size > PAGE_SIZE -
224 			 offset_in_page(iomap->inline_data)))
225 		return -EIO;
226 	if (WARN_ON_ONCE(size > iomap->length))
227 		return -EIO;
228 	if (offset > 0)
229 		iop = iomap_page_create(iter->inode, folio);
230 	else
231 		iop = to_iomap_page(folio);
232 
233 	addr = kmap_local_folio(folio, offset);
234 	memcpy(addr, iomap->inline_data, size);
235 	memset(addr + size, 0, PAGE_SIZE - poff - size);
236 	kunmap_local(addr);
237 	iomap_set_range_uptodate(folio, iop, offset, PAGE_SIZE - poff);
238 	return 0;
239 }
240 
241 static inline bool iomap_block_needs_zeroing(const struct iomap_iter *iter,
242 		loff_t pos)
243 {
244 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
245 
246 	return srcmap->type != IOMAP_MAPPED ||
247 		(srcmap->flags & IOMAP_F_NEW) ||
248 		pos >= i_size_read(iter->inode);
249 }
250 
251 static loff_t iomap_readpage_iter(const struct iomap_iter *iter,
252 		struct iomap_readpage_ctx *ctx, loff_t offset)
253 {
254 	const struct iomap *iomap = &iter->iomap;
255 	loff_t pos = iter->pos + offset;
256 	loff_t length = iomap_length(iter) - offset;
257 	struct folio *folio = ctx->cur_folio;
258 	struct iomap_page *iop;
259 	loff_t orig_pos = pos;
260 	size_t poff, plen;
261 	sector_t sector;
262 
263 	if (iomap->type == IOMAP_INLINE)
264 		return iomap_read_inline_data(iter, folio);
265 
266 	/* zero post-eof blocks as the page may be mapped */
267 	iop = iomap_page_create(iter->inode, folio);
268 	iomap_adjust_read_range(iter->inode, folio, &pos, length, &poff, &plen);
269 	if (plen == 0)
270 		goto done;
271 
272 	if (iomap_block_needs_zeroing(iter, pos)) {
273 		folio_zero_range(folio, poff, plen);
274 		iomap_set_range_uptodate(folio, iop, poff, plen);
275 		goto done;
276 	}
277 
278 	ctx->cur_folio_in_bio = true;
279 	if (iop)
280 		atomic_add(plen, &iop->read_bytes_pending);
281 
282 	sector = iomap_sector(iomap, pos);
283 	if (!ctx->bio ||
284 	    bio_end_sector(ctx->bio) != sector ||
285 	    !bio_add_folio(ctx->bio, folio, plen, poff)) {
286 		gfp_t gfp = mapping_gfp_constraint(folio->mapping, GFP_KERNEL);
287 		gfp_t orig_gfp = gfp;
288 		unsigned int nr_vecs = DIV_ROUND_UP(length, PAGE_SIZE);
289 
290 		if (ctx->bio)
291 			submit_bio(ctx->bio);
292 
293 		if (ctx->rac) /* same as readahead_gfp_mask */
294 			gfp |= __GFP_NORETRY | __GFP_NOWARN;
295 		ctx->bio = bio_alloc(gfp, bio_max_segs(nr_vecs));
296 		/*
297 		 * If the bio_alloc fails, try it again for a single page to
298 		 * avoid having to deal with partial page reads.  This emulates
299 		 * what do_mpage_readpage does.
300 		 */
301 		if (!ctx->bio)
302 			ctx->bio = bio_alloc(orig_gfp, 1);
303 		ctx->bio->bi_opf = REQ_OP_READ;
304 		if (ctx->rac)
305 			ctx->bio->bi_opf |= REQ_RAHEAD;
306 		ctx->bio->bi_iter.bi_sector = sector;
307 		bio_set_dev(ctx->bio, iomap->bdev);
308 		ctx->bio->bi_end_io = iomap_read_end_io;
309 		bio_add_folio(ctx->bio, folio, plen, poff);
310 	}
311 
312 done:
313 	/*
314 	 * Move the caller beyond our range so that it keeps making progress.
315 	 * For that, we have to include any leading non-uptodate ranges, but
316 	 * we can skip trailing ones as they will be handled in the next
317 	 * iteration.
318 	 */
319 	return pos - orig_pos + plen;
320 }
321 
322 int
323 iomap_readpage(struct page *page, const struct iomap_ops *ops)
324 {
325 	struct folio *folio = page_folio(page);
326 	struct iomap_iter iter = {
327 		.inode		= folio->mapping->host,
328 		.pos		= folio_pos(folio),
329 		.len		= folio_size(folio),
330 	};
331 	struct iomap_readpage_ctx ctx = {
332 		.cur_folio	= folio,
333 	};
334 	int ret;
335 
336 	trace_iomap_readpage(iter.inode, 1);
337 
338 	while ((ret = iomap_iter(&iter, ops)) > 0)
339 		iter.processed = iomap_readpage_iter(&iter, &ctx, 0);
340 
341 	if (ret < 0)
342 		folio_set_error(folio);
343 
344 	if (ctx.bio) {
345 		submit_bio(ctx.bio);
346 		WARN_ON_ONCE(!ctx.cur_folio_in_bio);
347 	} else {
348 		WARN_ON_ONCE(ctx.cur_folio_in_bio);
349 		folio_unlock(folio);
350 	}
351 
352 	/*
353 	 * Just like mpage_readahead and block_read_full_page, we always
354 	 * return 0 and just mark the page as PageError on errors.  This
355 	 * should be cleaned up throughout the stack eventually.
356 	 */
357 	return 0;
358 }
359 EXPORT_SYMBOL_GPL(iomap_readpage);
360 
361 static loff_t iomap_readahead_iter(const struct iomap_iter *iter,
362 		struct iomap_readpage_ctx *ctx)
363 {
364 	loff_t length = iomap_length(iter);
365 	loff_t done, ret;
366 
367 	for (done = 0; done < length; done += ret) {
368 		if (ctx->cur_folio &&
369 		    offset_in_folio(ctx->cur_folio, iter->pos + done) == 0) {
370 			if (!ctx->cur_folio_in_bio)
371 				folio_unlock(ctx->cur_folio);
372 			ctx->cur_folio = NULL;
373 		}
374 		if (!ctx->cur_folio) {
375 			ctx->cur_folio = readahead_folio(ctx->rac);
376 			ctx->cur_folio_in_bio = false;
377 		}
378 		ret = iomap_readpage_iter(iter, ctx, done);
379 		if (ret <= 0)
380 			return ret;
381 	}
382 
383 	return done;
384 }
385 
386 /**
387  * iomap_readahead - Attempt to read pages from a file.
388  * @rac: Describes the pages to be read.
389  * @ops: The operations vector for the filesystem.
390  *
391  * This function is for filesystems to call to implement their readahead
392  * address_space operation.
393  *
394  * Context: The @ops callbacks may submit I/O (eg to read the addresses of
395  * blocks from disc), and may wait for it.  The caller may be trying to
396  * access a different page, and so sleeping excessively should be avoided.
397  * It may allocate memory, but should avoid costly allocations.  This
398  * function is called with memalloc_nofs set, so allocations will not cause
399  * the filesystem to be reentered.
400  */
401 void iomap_readahead(struct readahead_control *rac, const struct iomap_ops *ops)
402 {
403 	struct iomap_iter iter = {
404 		.inode	= rac->mapping->host,
405 		.pos	= readahead_pos(rac),
406 		.len	= readahead_length(rac),
407 	};
408 	struct iomap_readpage_ctx ctx = {
409 		.rac	= rac,
410 	};
411 
412 	trace_iomap_readahead(rac->mapping->host, readahead_count(rac));
413 
414 	while (iomap_iter(&iter, ops) > 0)
415 		iter.processed = iomap_readahead_iter(&iter, &ctx);
416 
417 	if (ctx.bio)
418 		submit_bio(ctx.bio);
419 	if (ctx.cur_folio) {
420 		if (!ctx.cur_folio_in_bio)
421 			folio_unlock(ctx.cur_folio);
422 	}
423 }
424 EXPORT_SYMBOL_GPL(iomap_readahead);
425 
426 /*
427  * iomap_is_partially_uptodate checks whether blocks within a folio are
428  * uptodate or not.
429  *
430  * Returns true if all blocks which correspond to the specified part
431  * of the folio are uptodate.
432  */
433 bool iomap_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
434 {
435 	struct iomap_page *iop = to_iomap_page(folio);
436 	struct inode *inode = folio->mapping->host;
437 	size_t len;
438 	unsigned first, last, i;
439 
440 	if (!iop)
441 		return false;
442 
443 	/* Limit range to this folio */
444 	len = min(folio_size(folio) - from, count);
445 
446 	/* First and last blocks in range within page */
447 	first = from >> inode->i_blkbits;
448 	last = (from + len - 1) >> inode->i_blkbits;
449 
450 	for (i = first; i <= last; i++)
451 		if (!test_bit(i, iop->uptodate))
452 			return false;
453 	return true;
454 }
455 EXPORT_SYMBOL_GPL(iomap_is_partially_uptodate);
456 
457 int
458 iomap_releasepage(struct page *page, gfp_t gfp_mask)
459 {
460 	struct folio *folio = page_folio(page);
461 
462 	trace_iomap_releasepage(folio->mapping->host, folio_pos(folio),
463 			folio_size(folio));
464 
465 	/*
466 	 * mm accommodates an old ext3 case where clean pages might not have had
467 	 * the dirty bit cleared. Thus, it can send actual dirty pages to
468 	 * ->releasepage() via shrink_active_list(); skip those here.
469 	 */
470 	if (folio_test_dirty(folio) || folio_test_writeback(folio))
471 		return 0;
472 	iomap_page_release(folio);
473 	return 1;
474 }
475 EXPORT_SYMBOL_GPL(iomap_releasepage);
476 
477 void iomap_invalidate_folio(struct folio *folio, size_t offset, size_t len)
478 {
479 	trace_iomap_invalidate_folio(folio->mapping->host,
480 					folio_pos(folio) + offset, len);
481 
482 	/*
483 	 * If we're invalidating the entire folio, clear the dirty state
484 	 * from it and release it to avoid unnecessary buildup of the LRU.
485 	 */
486 	if (offset == 0 && len == folio_size(folio)) {
487 		WARN_ON_ONCE(folio_test_writeback(folio));
488 		folio_cancel_dirty(folio);
489 		iomap_page_release(folio);
490 	} else if (folio_test_large(folio)) {
491 		/* Must release the iop so the page can be split */
492 		WARN_ON_ONCE(!folio_test_uptodate(folio) &&
493 			     folio_test_dirty(folio));
494 		iomap_page_release(folio);
495 	}
496 }
497 EXPORT_SYMBOL_GPL(iomap_invalidate_folio);
498 
499 #ifdef CONFIG_MIGRATION
500 int
501 iomap_migrate_page(struct address_space *mapping, struct page *newpage,
502 		struct page *page, enum migrate_mode mode)
503 {
504 	struct folio *folio = page_folio(page);
505 	struct folio *newfolio = page_folio(newpage);
506 	int ret;
507 
508 	ret = folio_migrate_mapping(mapping, newfolio, folio, 0);
509 	if (ret != MIGRATEPAGE_SUCCESS)
510 		return ret;
511 
512 	if (folio_test_private(folio))
513 		folio_attach_private(newfolio, folio_detach_private(folio));
514 
515 	if (mode != MIGRATE_SYNC_NO_COPY)
516 		folio_migrate_copy(newfolio, folio);
517 	else
518 		folio_migrate_flags(newfolio, folio);
519 	return MIGRATEPAGE_SUCCESS;
520 }
521 EXPORT_SYMBOL_GPL(iomap_migrate_page);
522 #endif /* CONFIG_MIGRATION */
523 
524 static void
525 iomap_write_failed(struct inode *inode, loff_t pos, unsigned len)
526 {
527 	loff_t i_size = i_size_read(inode);
528 
529 	/*
530 	 * Only truncate newly allocated pages beyoned EOF, even if the
531 	 * write started inside the existing inode size.
532 	 */
533 	if (pos + len > i_size)
534 		truncate_pagecache_range(inode, max(pos, i_size), pos + len);
535 }
536 
537 static int iomap_read_folio_sync(loff_t block_start, struct folio *folio,
538 		size_t poff, size_t plen, const struct iomap *iomap)
539 {
540 	struct bio_vec bvec;
541 	struct bio bio;
542 
543 	bio_init(&bio, &bvec, 1);
544 	bio.bi_opf = REQ_OP_READ;
545 	bio.bi_iter.bi_sector = iomap_sector(iomap, block_start);
546 	bio_set_dev(&bio, iomap->bdev);
547 	bio_add_folio(&bio, folio, plen, poff);
548 	return submit_bio_wait(&bio);
549 }
550 
551 static int __iomap_write_begin(const struct iomap_iter *iter, loff_t pos,
552 		size_t len, struct folio *folio)
553 {
554 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
555 	struct iomap_page *iop = iomap_page_create(iter->inode, folio);
556 	loff_t block_size = i_blocksize(iter->inode);
557 	loff_t block_start = round_down(pos, block_size);
558 	loff_t block_end = round_up(pos + len, block_size);
559 	size_t from = offset_in_folio(folio, pos), to = from + len;
560 	size_t poff, plen;
561 
562 	if (folio_test_uptodate(folio))
563 		return 0;
564 	folio_clear_error(folio);
565 
566 	do {
567 		iomap_adjust_read_range(iter->inode, folio, &block_start,
568 				block_end - block_start, &poff, &plen);
569 		if (plen == 0)
570 			break;
571 
572 		if (!(iter->flags & IOMAP_UNSHARE) &&
573 		    (from <= poff || from >= poff + plen) &&
574 		    (to <= poff || to >= poff + plen))
575 			continue;
576 
577 		if (iomap_block_needs_zeroing(iter, block_start)) {
578 			if (WARN_ON_ONCE(iter->flags & IOMAP_UNSHARE))
579 				return -EIO;
580 			folio_zero_segments(folio, poff, from, to, poff + plen);
581 		} else {
582 			int status = iomap_read_folio_sync(block_start, folio,
583 					poff, plen, srcmap);
584 			if (status)
585 				return status;
586 		}
587 		iomap_set_range_uptodate(folio, iop, poff, plen);
588 	} while ((block_start += plen) < block_end);
589 
590 	return 0;
591 }
592 
593 static int iomap_write_begin_inline(const struct iomap_iter *iter,
594 		struct folio *folio)
595 {
596 	/* needs more work for the tailpacking case; disable for now */
597 	if (WARN_ON_ONCE(iomap_iter_srcmap(iter)->offset != 0))
598 		return -EIO;
599 	return iomap_read_inline_data(iter, folio);
600 }
601 
602 static int iomap_write_begin(const struct iomap_iter *iter, loff_t pos,
603 		size_t len, struct folio **foliop)
604 {
605 	const struct iomap_page_ops *page_ops = iter->iomap.page_ops;
606 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
607 	struct folio *folio;
608 	unsigned fgp = FGP_LOCK | FGP_WRITE | FGP_CREAT | FGP_STABLE | FGP_NOFS;
609 	int status = 0;
610 
611 	BUG_ON(pos + len > iter->iomap.offset + iter->iomap.length);
612 	if (srcmap != &iter->iomap)
613 		BUG_ON(pos + len > srcmap->offset + srcmap->length);
614 
615 	if (fatal_signal_pending(current))
616 		return -EINTR;
617 
618 	if (!mapping_large_folio_support(iter->inode->i_mapping))
619 		len = min_t(size_t, len, PAGE_SIZE - offset_in_page(pos));
620 
621 	if (page_ops && page_ops->page_prepare) {
622 		status = page_ops->page_prepare(iter->inode, pos, len);
623 		if (status)
624 			return status;
625 	}
626 
627 	folio = __filemap_get_folio(iter->inode->i_mapping, pos >> PAGE_SHIFT,
628 			fgp, mapping_gfp_mask(iter->inode->i_mapping));
629 	if (!folio) {
630 		status = -ENOMEM;
631 		goto out_no_page;
632 	}
633 	if (pos + len > folio_pos(folio) + folio_size(folio))
634 		len = folio_pos(folio) + folio_size(folio) - pos;
635 
636 	if (srcmap->type == IOMAP_INLINE)
637 		status = iomap_write_begin_inline(iter, folio);
638 	else if (srcmap->flags & IOMAP_F_BUFFER_HEAD)
639 		status = __block_write_begin_int(folio, pos, len, NULL, srcmap);
640 	else
641 		status = __iomap_write_begin(iter, pos, len, folio);
642 
643 	if (unlikely(status))
644 		goto out_unlock;
645 
646 	*foliop = folio;
647 	return 0;
648 
649 out_unlock:
650 	folio_unlock(folio);
651 	folio_put(folio);
652 	iomap_write_failed(iter->inode, pos, len);
653 
654 out_no_page:
655 	if (page_ops && page_ops->page_done)
656 		page_ops->page_done(iter->inode, pos, 0, NULL);
657 	return status;
658 }
659 
660 static size_t __iomap_write_end(struct inode *inode, loff_t pos, size_t len,
661 		size_t copied, struct folio *folio)
662 {
663 	struct iomap_page *iop = to_iomap_page(folio);
664 	flush_dcache_folio(folio);
665 
666 	/*
667 	 * The blocks that were entirely written will now be uptodate, so we
668 	 * don't have to worry about a readpage reading them and overwriting a
669 	 * partial write.  However, if we've encountered a short write and only
670 	 * partially written into a block, it will not be marked uptodate, so a
671 	 * readpage might come in and destroy our partial write.
672 	 *
673 	 * Do the simplest thing and just treat any short write to a
674 	 * non-uptodate page as a zero-length write, and force the caller to
675 	 * redo the whole thing.
676 	 */
677 	if (unlikely(copied < len && !folio_test_uptodate(folio)))
678 		return 0;
679 	iomap_set_range_uptodate(folio, iop, offset_in_folio(folio, pos), len);
680 	filemap_dirty_folio(inode->i_mapping, folio);
681 	return copied;
682 }
683 
684 static size_t iomap_write_end_inline(const struct iomap_iter *iter,
685 		struct folio *folio, loff_t pos, size_t copied)
686 {
687 	const struct iomap *iomap = &iter->iomap;
688 	void *addr;
689 
690 	WARN_ON_ONCE(!folio_test_uptodate(folio));
691 	BUG_ON(!iomap_inline_data_valid(iomap));
692 
693 	flush_dcache_folio(folio);
694 	addr = kmap_local_folio(folio, pos);
695 	memcpy(iomap_inline_data(iomap, pos), addr, copied);
696 	kunmap_local(addr);
697 
698 	mark_inode_dirty(iter->inode);
699 	return copied;
700 }
701 
702 /* Returns the number of bytes copied.  May be 0.  Cannot be an errno. */
703 static size_t iomap_write_end(struct iomap_iter *iter, loff_t pos, size_t len,
704 		size_t copied, struct folio *folio)
705 {
706 	const struct iomap_page_ops *page_ops = iter->iomap.page_ops;
707 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
708 	loff_t old_size = iter->inode->i_size;
709 	size_t ret;
710 
711 	if (srcmap->type == IOMAP_INLINE) {
712 		ret = iomap_write_end_inline(iter, folio, pos, copied);
713 	} else if (srcmap->flags & IOMAP_F_BUFFER_HEAD) {
714 		ret = block_write_end(NULL, iter->inode->i_mapping, pos, len,
715 				copied, &folio->page, NULL);
716 	} else {
717 		ret = __iomap_write_end(iter->inode, pos, len, copied, folio);
718 	}
719 
720 	/*
721 	 * Update the in-memory inode size after copying the data into the page
722 	 * cache.  It's up to the file system to write the updated size to disk,
723 	 * preferably after I/O completion so that no stale data is exposed.
724 	 */
725 	if (pos + ret > old_size) {
726 		i_size_write(iter->inode, pos + ret);
727 		iter->iomap.flags |= IOMAP_F_SIZE_CHANGED;
728 	}
729 	folio_unlock(folio);
730 
731 	if (old_size < pos)
732 		pagecache_isize_extended(iter->inode, old_size, pos);
733 	if (page_ops && page_ops->page_done)
734 		page_ops->page_done(iter->inode, pos, ret, &folio->page);
735 	folio_put(folio);
736 
737 	if (ret < len)
738 		iomap_write_failed(iter->inode, pos, len);
739 	return ret;
740 }
741 
742 static loff_t iomap_write_iter(struct iomap_iter *iter, struct iov_iter *i)
743 {
744 	loff_t length = iomap_length(iter);
745 	loff_t pos = iter->pos;
746 	ssize_t written = 0;
747 	long status = 0;
748 
749 	do {
750 		struct folio *folio;
751 		struct page *page;
752 		unsigned long offset;	/* Offset into pagecache page */
753 		unsigned long bytes;	/* Bytes to write to page */
754 		size_t copied;		/* Bytes copied from user */
755 
756 		offset = offset_in_page(pos);
757 		bytes = min_t(unsigned long, PAGE_SIZE - offset,
758 						iov_iter_count(i));
759 again:
760 		if (bytes > length)
761 			bytes = length;
762 
763 		/*
764 		 * Bring in the user page that we'll copy from _first_.
765 		 * Otherwise there's a nasty deadlock on copying from the
766 		 * same page as we're writing to, without it being marked
767 		 * up-to-date.
768 		 */
769 		if (unlikely(fault_in_iov_iter_readable(i, bytes))) {
770 			status = -EFAULT;
771 			break;
772 		}
773 
774 		status = iomap_write_begin(iter, pos, bytes, &folio);
775 		if (unlikely(status))
776 			break;
777 
778 		page = folio_file_page(folio, pos >> PAGE_SHIFT);
779 		if (mapping_writably_mapped(iter->inode->i_mapping))
780 			flush_dcache_page(page);
781 
782 		copied = copy_page_from_iter_atomic(page, offset, bytes, i);
783 
784 		status = iomap_write_end(iter, pos, bytes, copied, folio);
785 
786 		if (unlikely(copied != status))
787 			iov_iter_revert(i, copied - status);
788 
789 		cond_resched();
790 		if (unlikely(status == 0)) {
791 			/*
792 			 * A short copy made iomap_write_end() reject the
793 			 * thing entirely.  Might be memory poisoning
794 			 * halfway through, might be a race with munmap,
795 			 * might be severe memory pressure.
796 			 */
797 			if (copied)
798 				bytes = copied;
799 			goto again;
800 		}
801 		pos += status;
802 		written += status;
803 		length -= status;
804 
805 		balance_dirty_pages_ratelimited(iter->inode->i_mapping);
806 	} while (iov_iter_count(i) && length);
807 
808 	return written ? written : status;
809 }
810 
811 ssize_t
812 iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i,
813 		const struct iomap_ops *ops)
814 {
815 	struct iomap_iter iter = {
816 		.inode		= iocb->ki_filp->f_mapping->host,
817 		.pos		= iocb->ki_pos,
818 		.len		= iov_iter_count(i),
819 		.flags		= IOMAP_WRITE,
820 	};
821 	int ret;
822 
823 	while ((ret = iomap_iter(&iter, ops)) > 0)
824 		iter.processed = iomap_write_iter(&iter, i);
825 	if (iter.pos == iocb->ki_pos)
826 		return ret;
827 	return iter.pos - iocb->ki_pos;
828 }
829 EXPORT_SYMBOL_GPL(iomap_file_buffered_write);
830 
831 static loff_t iomap_unshare_iter(struct iomap_iter *iter)
832 {
833 	struct iomap *iomap = &iter->iomap;
834 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
835 	loff_t pos = iter->pos;
836 	loff_t length = iomap_length(iter);
837 	long status = 0;
838 	loff_t written = 0;
839 
840 	/* don't bother with blocks that are not shared to start with */
841 	if (!(iomap->flags & IOMAP_F_SHARED))
842 		return length;
843 	/* don't bother with holes or unwritten extents */
844 	if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
845 		return length;
846 
847 	do {
848 		unsigned long offset = offset_in_page(pos);
849 		unsigned long bytes = min_t(loff_t, PAGE_SIZE - offset, length);
850 		struct folio *folio;
851 
852 		status = iomap_write_begin(iter, pos, bytes, &folio);
853 		if (unlikely(status))
854 			return status;
855 
856 		status = iomap_write_end(iter, pos, bytes, bytes, folio);
857 		if (WARN_ON_ONCE(status == 0))
858 			return -EIO;
859 
860 		cond_resched();
861 
862 		pos += status;
863 		written += status;
864 		length -= status;
865 
866 		balance_dirty_pages_ratelimited(iter->inode->i_mapping);
867 	} while (length);
868 
869 	return written;
870 }
871 
872 int
873 iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len,
874 		const struct iomap_ops *ops)
875 {
876 	struct iomap_iter iter = {
877 		.inode		= inode,
878 		.pos		= pos,
879 		.len		= len,
880 		.flags		= IOMAP_WRITE | IOMAP_UNSHARE,
881 	};
882 	int ret;
883 
884 	while ((ret = iomap_iter(&iter, ops)) > 0)
885 		iter.processed = iomap_unshare_iter(&iter);
886 	return ret;
887 }
888 EXPORT_SYMBOL_GPL(iomap_file_unshare);
889 
890 static loff_t iomap_zero_iter(struct iomap_iter *iter, bool *did_zero)
891 {
892 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
893 	loff_t pos = iter->pos;
894 	loff_t length = iomap_length(iter);
895 	loff_t written = 0;
896 
897 	/* already zeroed?  we're done. */
898 	if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
899 		return length;
900 
901 	do {
902 		struct folio *folio;
903 		int status;
904 		size_t offset;
905 		size_t bytes = min_t(u64, SIZE_MAX, length);
906 
907 		status = iomap_write_begin(iter, pos, bytes, &folio);
908 		if (status)
909 			return status;
910 
911 		offset = offset_in_folio(folio, pos);
912 		if (bytes > folio_size(folio) - offset)
913 			bytes = folio_size(folio) - offset;
914 
915 		folio_zero_range(folio, offset, bytes);
916 		folio_mark_accessed(folio);
917 
918 		bytes = iomap_write_end(iter, pos, bytes, bytes, folio);
919 		if (WARN_ON_ONCE(bytes == 0))
920 			return -EIO;
921 
922 		pos += bytes;
923 		length -= bytes;
924 		written += bytes;
925 		if (did_zero)
926 			*did_zero = true;
927 	} while (length > 0);
928 
929 	return written;
930 }
931 
932 int
933 iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero,
934 		const struct iomap_ops *ops)
935 {
936 	struct iomap_iter iter = {
937 		.inode		= inode,
938 		.pos		= pos,
939 		.len		= len,
940 		.flags		= IOMAP_ZERO,
941 	};
942 	int ret;
943 
944 	while ((ret = iomap_iter(&iter, ops)) > 0)
945 		iter.processed = iomap_zero_iter(&iter, did_zero);
946 	return ret;
947 }
948 EXPORT_SYMBOL_GPL(iomap_zero_range);
949 
950 int
951 iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero,
952 		const struct iomap_ops *ops)
953 {
954 	unsigned int blocksize = i_blocksize(inode);
955 	unsigned int off = pos & (blocksize - 1);
956 
957 	/* Block boundary? Nothing to do */
958 	if (!off)
959 		return 0;
960 	return iomap_zero_range(inode, pos, blocksize - off, did_zero, ops);
961 }
962 EXPORT_SYMBOL_GPL(iomap_truncate_page);
963 
964 static loff_t iomap_folio_mkwrite_iter(struct iomap_iter *iter,
965 		struct folio *folio)
966 {
967 	loff_t length = iomap_length(iter);
968 	int ret;
969 
970 	if (iter->iomap.flags & IOMAP_F_BUFFER_HEAD) {
971 		ret = __block_write_begin_int(folio, iter->pos, length, NULL,
972 					      &iter->iomap);
973 		if (ret)
974 			return ret;
975 		block_commit_write(&folio->page, 0, length);
976 	} else {
977 		WARN_ON_ONCE(!folio_test_uptodate(folio));
978 		folio_mark_dirty(folio);
979 	}
980 
981 	return length;
982 }
983 
984 vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops)
985 {
986 	struct iomap_iter iter = {
987 		.inode		= file_inode(vmf->vma->vm_file),
988 		.flags		= IOMAP_WRITE | IOMAP_FAULT,
989 	};
990 	struct folio *folio = page_folio(vmf->page);
991 	ssize_t ret;
992 
993 	folio_lock(folio);
994 	ret = folio_mkwrite_check_truncate(folio, iter.inode);
995 	if (ret < 0)
996 		goto out_unlock;
997 	iter.pos = folio_pos(folio);
998 	iter.len = ret;
999 	while ((ret = iomap_iter(&iter, ops)) > 0)
1000 		iter.processed = iomap_folio_mkwrite_iter(&iter, folio);
1001 
1002 	if (ret < 0)
1003 		goto out_unlock;
1004 	folio_wait_stable(folio);
1005 	return VM_FAULT_LOCKED;
1006 out_unlock:
1007 	folio_unlock(folio);
1008 	return block_page_mkwrite_return(ret);
1009 }
1010 EXPORT_SYMBOL_GPL(iomap_page_mkwrite);
1011 
1012 static void iomap_finish_folio_write(struct inode *inode, struct folio *folio,
1013 		size_t len, int error)
1014 {
1015 	struct iomap_page *iop = to_iomap_page(folio);
1016 
1017 	if (error) {
1018 		folio_set_error(folio);
1019 		mapping_set_error(inode->i_mapping, error);
1020 	}
1021 
1022 	WARN_ON_ONCE(i_blocks_per_folio(inode, folio) > 1 && !iop);
1023 	WARN_ON_ONCE(iop && atomic_read(&iop->write_bytes_pending) <= 0);
1024 
1025 	if (!iop || atomic_sub_and_test(len, &iop->write_bytes_pending))
1026 		folio_end_writeback(folio);
1027 }
1028 
1029 /*
1030  * We're now finished for good with this ioend structure.  Update the page
1031  * state, release holds on bios, and finally free up memory.  Do not use the
1032  * ioend after this.
1033  */
1034 static u32
1035 iomap_finish_ioend(struct iomap_ioend *ioend, int error)
1036 {
1037 	struct inode *inode = ioend->io_inode;
1038 	struct bio *bio = &ioend->io_inline_bio;
1039 	struct bio *last = ioend->io_bio, *next;
1040 	u64 start = bio->bi_iter.bi_sector;
1041 	loff_t offset = ioend->io_offset;
1042 	bool quiet = bio_flagged(bio, BIO_QUIET);
1043 	u32 folio_count = 0;
1044 
1045 	for (bio = &ioend->io_inline_bio; bio; bio = next) {
1046 		struct folio_iter fi;
1047 
1048 		/*
1049 		 * For the last bio, bi_private points to the ioend, so we
1050 		 * need to explicitly end the iteration here.
1051 		 */
1052 		if (bio == last)
1053 			next = NULL;
1054 		else
1055 			next = bio->bi_private;
1056 
1057 		/* walk all folios in bio, ending page IO on them */
1058 		bio_for_each_folio_all(fi, bio) {
1059 			iomap_finish_folio_write(inode, fi.folio, fi.length,
1060 					error);
1061 			folio_count++;
1062 		}
1063 		bio_put(bio);
1064 	}
1065 	/* The ioend has been freed by bio_put() */
1066 
1067 	if (unlikely(error && !quiet)) {
1068 		printk_ratelimited(KERN_ERR
1069 "%s: writeback error on inode %lu, offset %lld, sector %llu",
1070 			inode->i_sb->s_id, inode->i_ino, offset, start);
1071 	}
1072 	return folio_count;
1073 }
1074 
1075 /*
1076  * Ioend completion routine for merged bios. This can only be called from task
1077  * contexts as merged ioends can be of unbound length. Hence we have to break up
1078  * the writeback completions into manageable chunks to avoid long scheduler
1079  * holdoffs. We aim to keep scheduler holdoffs down below 10ms so that we get
1080  * good batch processing throughput without creating adverse scheduler latency
1081  * conditions.
1082  */
1083 void
1084 iomap_finish_ioends(struct iomap_ioend *ioend, int error)
1085 {
1086 	struct list_head tmp;
1087 	u32 completions;
1088 
1089 	might_sleep();
1090 
1091 	list_replace_init(&ioend->io_list, &tmp);
1092 	completions = iomap_finish_ioend(ioend, error);
1093 
1094 	while (!list_empty(&tmp)) {
1095 		if (completions > IOEND_BATCH_SIZE * 8) {
1096 			cond_resched();
1097 			completions = 0;
1098 		}
1099 		ioend = list_first_entry(&tmp, struct iomap_ioend, io_list);
1100 		list_del_init(&ioend->io_list);
1101 		completions += iomap_finish_ioend(ioend, error);
1102 	}
1103 }
1104 EXPORT_SYMBOL_GPL(iomap_finish_ioends);
1105 
1106 /*
1107  * We can merge two adjacent ioends if they have the same set of work to do.
1108  */
1109 static bool
1110 iomap_ioend_can_merge(struct iomap_ioend *ioend, struct iomap_ioend *next)
1111 {
1112 	if (ioend->io_bio->bi_status != next->io_bio->bi_status)
1113 		return false;
1114 	if ((ioend->io_flags & IOMAP_F_SHARED) ^
1115 	    (next->io_flags & IOMAP_F_SHARED))
1116 		return false;
1117 	if ((ioend->io_type == IOMAP_UNWRITTEN) ^
1118 	    (next->io_type == IOMAP_UNWRITTEN))
1119 		return false;
1120 	if (ioend->io_offset + ioend->io_size != next->io_offset)
1121 		return false;
1122 	/*
1123 	 * Do not merge physically discontiguous ioends. The filesystem
1124 	 * completion functions will have to iterate the physical
1125 	 * discontiguities even if we merge the ioends at a logical level, so
1126 	 * we don't gain anything by merging physical discontiguities here.
1127 	 *
1128 	 * We cannot use bio->bi_iter.bi_sector here as it is modified during
1129 	 * submission so does not point to the start sector of the bio at
1130 	 * completion.
1131 	 */
1132 	if (ioend->io_sector + (ioend->io_size >> 9) != next->io_sector)
1133 		return false;
1134 	return true;
1135 }
1136 
1137 void
1138 iomap_ioend_try_merge(struct iomap_ioend *ioend, struct list_head *more_ioends)
1139 {
1140 	struct iomap_ioend *next;
1141 
1142 	INIT_LIST_HEAD(&ioend->io_list);
1143 
1144 	while ((next = list_first_entry_or_null(more_ioends, struct iomap_ioend,
1145 			io_list))) {
1146 		if (!iomap_ioend_can_merge(ioend, next))
1147 			break;
1148 		list_move_tail(&next->io_list, &ioend->io_list);
1149 		ioend->io_size += next->io_size;
1150 	}
1151 }
1152 EXPORT_SYMBOL_GPL(iomap_ioend_try_merge);
1153 
1154 static int
1155 iomap_ioend_compare(void *priv, const struct list_head *a,
1156 		const struct list_head *b)
1157 {
1158 	struct iomap_ioend *ia = container_of(a, struct iomap_ioend, io_list);
1159 	struct iomap_ioend *ib = container_of(b, struct iomap_ioend, io_list);
1160 
1161 	if (ia->io_offset < ib->io_offset)
1162 		return -1;
1163 	if (ia->io_offset > ib->io_offset)
1164 		return 1;
1165 	return 0;
1166 }
1167 
1168 void
1169 iomap_sort_ioends(struct list_head *ioend_list)
1170 {
1171 	list_sort(NULL, ioend_list, iomap_ioend_compare);
1172 }
1173 EXPORT_SYMBOL_GPL(iomap_sort_ioends);
1174 
1175 static void iomap_writepage_end_bio(struct bio *bio)
1176 {
1177 	struct iomap_ioend *ioend = bio->bi_private;
1178 
1179 	iomap_finish_ioend(ioend, blk_status_to_errno(bio->bi_status));
1180 }
1181 
1182 /*
1183  * Submit the final bio for an ioend.
1184  *
1185  * If @error is non-zero, it means that we have a situation where some part of
1186  * the submission process has failed after we've marked pages for writeback
1187  * and unlocked them.  In this situation, we need to fail the bio instead of
1188  * submitting it.  This typically only happens on a filesystem shutdown.
1189  */
1190 static int
1191 iomap_submit_ioend(struct iomap_writepage_ctx *wpc, struct iomap_ioend *ioend,
1192 		int error)
1193 {
1194 	ioend->io_bio->bi_private = ioend;
1195 	ioend->io_bio->bi_end_io = iomap_writepage_end_bio;
1196 
1197 	if (wpc->ops->prepare_ioend)
1198 		error = wpc->ops->prepare_ioend(ioend, error);
1199 	if (error) {
1200 		/*
1201 		 * If we're failing the IO now, just mark the ioend with an
1202 		 * error and finish it.  This will run IO completion immediately
1203 		 * as there is only one reference to the ioend at this point in
1204 		 * time.
1205 		 */
1206 		ioend->io_bio->bi_status = errno_to_blk_status(error);
1207 		bio_endio(ioend->io_bio);
1208 		return error;
1209 	}
1210 
1211 	submit_bio(ioend->io_bio);
1212 	return 0;
1213 }
1214 
1215 static struct iomap_ioend *
1216 iomap_alloc_ioend(struct inode *inode, struct iomap_writepage_ctx *wpc,
1217 		loff_t offset, sector_t sector, struct writeback_control *wbc)
1218 {
1219 	struct iomap_ioend *ioend;
1220 	struct bio *bio;
1221 
1222 	bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_VECS, &iomap_ioend_bioset);
1223 	bio_set_dev(bio, wpc->iomap.bdev);
1224 	bio->bi_iter.bi_sector = sector;
1225 	bio->bi_opf = REQ_OP_WRITE | wbc_to_write_flags(wbc);
1226 	bio->bi_write_hint = inode->i_write_hint;
1227 	wbc_init_bio(wbc, bio);
1228 
1229 	ioend = container_of(bio, struct iomap_ioend, io_inline_bio);
1230 	INIT_LIST_HEAD(&ioend->io_list);
1231 	ioend->io_type = wpc->iomap.type;
1232 	ioend->io_flags = wpc->iomap.flags;
1233 	ioend->io_inode = inode;
1234 	ioend->io_size = 0;
1235 	ioend->io_folios = 0;
1236 	ioend->io_offset = offset;
1237 	ioend->io_bio = bio;
1238 	ioend->io_sector = sector;
1239 	return ioend;
1240 }
1241 
1242 /*
1243  * Allocate a new bio, and chain the old bio to the new one.
1244  *
1245  * Note that we have to perform the chaining in this unintuitive order
1246  * so that the bi_private linkage is set up in the right direction for the
1247  * traversal in iomap_finish_ioend().
1248  */
1249 static struct bio *
1250 iomap_chain_bio(struct bio *prev)
1251 {
1252 	struct bio *new;
1253 
1254 	new = bio_alloc(GFP_NOFS, BIO_MAX_VECS);
1255 	bio_copy_dev(new, prev);/* also copies over blkcg information */
1256 	new->bi_iter.bi_sector = bio_end_sector(prev);
1257 	new->bi_opf = prev->bi_opf;
1258 	new->bi_write_hint = prev->bi_write_hint;
1259 
1260 	bio_chain(prev, new);
1261 	bio_get(prev);		/* for iomap_finish_ioend */
1262 	submit_bio(prev);
1263 	return new;
1264 }
1265 
1266 static bool
1267 iomap_can_add_to_ioend(struct iomap_writepage_ctx *wpc, loff_t offset,
1268 		sector_t sector)
1269 {
1270 	if ((wpc->iomap.flags & IOMAP_F_SHARED) !=
1271 	    (wpc->ioend->io_flags & IOMAP_F_SHARED))
1272 		return false;
1273 	if (wpc->iomap.type != wpc->ioend->io_type)
1274 		return false;
1275 	if (offset != wpc->ioend->io_offset + wpc->ioend->io_size)
1276 		return false;
1277 	if (sector != bio_end_sector(wpc->ioend->io_bio))
1278 		return false;
1279 	/*
1280 	 * Limit ioend bio chain lengths to minimise IO completion latency. This
1281 	 * also prevents long tight loops ending page writeback on all the
1282 	 * folios in the ioend.
1283 	 */
1284 	if (wpc->ioend->io_folios >= IOEND_BATCH_SIZE)
1285 		return false;
1286 	return true;
1287 }
1288 
1289 /*
1290  * Test to see if we have an existing ioend structure that we could append to
1291  * first; otherwise finish off the current ioend and start another.
1292  */
1293 static void
1294 iomap_add_to_ioend(struct inode *inode, loff_t pos, struct folio *folio,
1295 		struct iomap_page *iop, struct iomap_writepage_ctx *wpc,
1296 		struct writeback_control *wbc, struct list_head *iolist)
1297 {
1298 	sector_t sector = iomap_sector(&wpc->iomap, pos);
1299 	unsigned len = i_blocksize(inode);
1300 	size_t poff = offset_in_folio(folio, pos);
1301 
1302 	if (!wpc->ioend || !iomap_can_add_to_ioend(wpc, pos, sector)) {
1303 		if (wpc->ioend)
1304 			list_add(&wpc->ioend->io_list, iolist);
1305 		wpc->ioend = iomap_alloc_ioend(inode, wpc, pos, sector, wbc);
1306 	}
1307 
1308 	if (!bio_add_folio(wpc->ioend->io_bio, folio, len, poff)) {
1309 		wpc->ioend->io_bio = iomap_chain_bio(wpc->ioend->io_bio);
1310 		bio_add_folio(wpc->ioend->io_bio, folio, len, poff);
1311 	}
1312 
1313 	if (iop)
1314 		atomic_add(len, &iop->write_bytes_pending);
1315 	wpc->ioend->io_size += len;
1316 	wbc_account_cgroup_owner(wbc, &folio->page, len);
1317 }
1318 
1319 /*
1320  * We implement an immediate ioend submission policy here to avoid needing to
1321  * chain multiple ioends and hence nest mempool allocations which can violate
1322  * the forward progress guarantees we need to provide. The current ioend we're
1323  * adding blocks to is cached in the writepage context, and if the new block
1324  * doesn't append to the cached ioend, it will create a new ioend and cache that
1325  * instead.
1326  *
1327  * If a new ioend is created and cached, the old ioend is returned and queued
1328  * locally for submission once the entire page is processed or an error has been
1329  * detected.  While ioends are submitted immediately after they are completed,
1330  * batching optimisations are provided by higher level block plugging.
1331  *
1332  * At the end of a writeback pass, there will be a cached ioend remaining on the
1333  * writepage context that the caller will need to submit.
1334  */
1335 static int
1336 iomap_writepage_map(struct iomap_writepage_ctx *wpc,
1337 		struct writeback_control *wbc, struct inode *inode,
1338 		struct folio *folio, u64 end_pos)
1339 {
1340 	struct iomap_page *iop = iomap_page_create(inode, folio);
1341 	struct iomap_ioend *ioend, *next;
1342 	unsigned len = i_blocksize(inode);
1343 	unsigned nblocks = i_blocks_per_folio(inode, folio);
1344 	u64 pos = folio_pos(folio);
1345 	int error = 0, count = 0, i;
1346 	LIST_HEAD(submit_list);
1347 
1348 	WARN_ON_ONCE(iop && atomic_read(&iop->write_bytes_pending) != 0);
1349 
1350 	/*
1351 	 * Walk through the folio to find areas to write back. If we
1352 	 * run off the end of the current map or find the current map
1353 	 * invalid, grab a new one.
1354 	 */
1355 	for (i = 0; i < nblocks && pos < end_pos; i++, pos += len) {
1356 		if (iop && !test_bit(i, iop->uptodate))
1357 			continue;
1358 
1359 		error = wpc->ops->map_blocks(wpc, inode, pos);
1360 		if (error)
1361 			break;
1362 		if (WARN_ON_ONCE(wpc->iomap.type == IOMAP_INLINE))
1363 			continue;
1364 		if (wpc->iomap.type == IOMAP_HOLE)
1365 			continue;
1366 		iomap_add_to_ioend(inode, pos, folio, iop, wpc, wbc,
1367 				 &submit_list);
1368 		count++;
1369 	}
1370 	if (count)
1371 		wpc->ioend->io_folios++;
1372 
1373 	WARN_ON_ONCE(!wpc->ioend && !list_empty(&submit_list));
1374 	WARN_ON_ONCE(!folio_test_locked(folio));
1375 	WARN_ON_ONCE(folio_test_writeback(folio));
1376 	WARN_ON_ONCE(folio_test_dirty(folio));
1377 
1378 	/*
1379 	 * We cannot cancel the ioend directly here on error.  We may have
1380 	 * already set other pages under writeback and hence we have to run I/O
1381 	 * completion to mark the error state of the pages under writeback
1382 	 * appropriately.
1383 	 */
1384 	if (unlikely(error)) {
1385 		/*
1386 		 * Let the filesystem know what portion of the current page
1387 		 * failed to map. If the page hasn't been added to ioend, it
1388 		 * won't be affected by I/O completion and we must unlock it
1389 		 * now.
1390 		 */
1391 		if (wpc->ops->discard_folio)
1392 			wpc->ops->discard_folio(folio, pos);
1393 		if (!count) {
1394 			folio_clear_uptodate(folio);
1395 			folio_unlock(folio);
1396 			goto done;
1397 		}
1398 	}
1399 
1400 	folio_start_writeback(folio);
1401 	folio_unlock(folio);
1402 
1403 	/*
1404 	 * Preserve the original error if there was one; catch
1405 	 * submission errors here and propagate into subsequent ioend
1406 	 * submissions.
1407 	 */
1408 	list_for_each_entry_safe(ioend, next, &submit_list, io_list) {
1409 		int error2;
1410 
1411 		list_del_init(&ioend->io_list);
1412 		error2 = iomap_submit_ioend(wpc, ioend, error);
1413 		if (error2 && !error)
1414 			error = error2;
1415 	}
1416 
1417 	/*
1418 	 * We can end up here with no error and nothing to write only if we race
1419 	 * with a partial page truncate on a sub-page block sized filesystem.
1420 	 */
1421 	if (!count)
1422 		folio_end_writeback(folio);
1423 done:
1424 	mapping_set_error(folio->mapping, error);
1425 	return error;
1426 }
1427 
1428 /*
1429  * Write out a dirty page.
1430  *
1431  * For delalloc space on the page, we need to allocate space and flush it.
1432  * For unwritten space on the page, we need to start the conversion to
1433  * regular allocated space.
1434  */
1435 static int
1436 iomap_do_writepage(struct page *page, struct writeback_control *wbc, void *data)
1437 {
1438 	struct folio *folio = page_folio(page);
1439 	struct iomap_writepage_ctx *wpc = data;
1440 	struct inode *inode = folio->mapping->host;
1441 	u64 end_pos, isize;
1442 
1443 	trace_iomap_writepage(inode, folio_pos(folio), folio_size(folio));
1444 
1445 	/*
1446 	 * Refuse to write the folio out if we're called from reclaim context.
1447 	 *
1448 	 * This avoids stack overflows when called from deeply used stacks in
1449 	 * random callers for direct reclaim or memcg reclaim.  We explicitly
1450 	 * allow reclaim from kswapd as the stack usage there is relatively low.
1451 	 *
1452 	 * This should never happen except in the case of a VM regression so
1453 	 * warn about it.
1454 	 */
1455 	if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1456 			PF_MEMALLOC))
1457 		goto redirty;
1458 
1459 	/*
1460 	 * Is this folio beyond the end of the file?
1461 	 *
1462 	 * The folio index is less than the end_index, adjust the end_pos
1463 	 * to the highest offset that this folio should represent.
1464 	 * -----------------------------------------------------
1465 	 * |			file mapping	       | <EOF> |
1466 	 * -----------------------------------------------------
1467 	 * | Page ... | Page N-2 | Page N-1 |  Page N  |       |
1468 	 * ^--------------------------------^----------|--------
1469 	 * |     desired writeback range    |      see else    |
1470 	 * ---------------------------------^------------------|
1471 	 */
1472 	isize = i_size_read(inode);
1473 	end_pos = folio_pos(folio) + folio_size(folio);
1474 	if (end_pos > isize) {
1475 		/*
1476 		 * Check whether the page to write out is beyond or straddles
1477 		 * i_size or not.
1478 		 * -------------------------------------------------------
1479 		 * |		file mapping		        | <EOF>  |
1480 		 * -------------------------------------------------------
1481 		 * | Page ... | Page N-2 | Page N-1 |  Page N   | Beyond |
1482 		 * ^--------------------------------^-----------|---------
1483 		 * |				    |      Straddles     |
1484 		 * ---------------------------------^-----------|--------|
1485 		 */
1486 		size_t poff = offset_in_folio(folio, isize);
1487 		pgoff_t end_index = isize >> PAGE_SHIFT;
1488 
1489 		/*
1490 		 * Skip the page if it's fully outside i_size, e.g. due to a
1491 		 * truncate operation that's in progress. We must redirty the
1492 		 * page so that reclaim stops reclaiming it. Otherwise
1493 		 * iomap_vm_releasepage() is called on it and gets confused.
1494 		 *
1495 		 * Note that the end_index is unsigned long.  If the given
1496 		 * offset is greater than 16TB on a 32-bit system then if we
1497 		 * checked if the page is fully outside i_size with
1498 		 * "if (page->index >= end_index + 1)", "end_index + 1" would
1499 		 * overflow and evaluate to 0.  Hence this page would be
1500 		 * redirtied and written out repeatedly, which would result in
1501 		 * an infinite loop; the user program performing this operation
1502 		 * would hang.  Instead, we can detect this situation by
1503 		 * checking if the page is totally beyond i_size or if its
1504 		 * offset is just equal to the EOF.
1505 		 */
1506 		if (folio->index > end_index ||
1507 		    (folio->index == end_index && poff == 0))
1508 			goto redirty;
1509 
1510 		/*
1511 		 * The page straddles i_size.  It must be zeroed out on each
1512 		 * and every writepage invocation because it may be mmapped.
1513 		 * "A file is mapped in multiples of the page size.  For a file
1514 		 * that is not a multiple of the page size, the remaining
1515 		 * memory is zeroed when mapped, and writes to that region are
1516 		 * not written out to the file."
1517 		 */
1518 		folio_zero_segment(folio, poff, folio_size(folio));
1519 		end_pos = isize;
1520 	}
1521 
1522 	return iomap_writepage_map(wpc, wbc, inode, folio, end_pos);
1523 
1524 redirty:
1525 	folio_redirty_for_writepage(wbc, folio);
1526 	folio_unlock(folio);
1527 	return 0;
1528 }
1529 
1530 int
1531 iomap_writepage(struct page *page, struct writeback_control *wbc,
1532 		struct iomap_writepage_ctx *wpc,
1533 		const struct iomap_writeback_ops *ops)
1534 {
1535 	int ret;
1536 
1537 	wpc->ops = ops;
1538 	ret = iomap_do_writepage(page, wbc, wpc);
1539 	if (!wpc->ioend)
1540 		return ret;
1541 	return iomap_submit_ioend(wpc, wpc->ioend, ret);
1542 }
1543 EXPORT_SYMBOL_GPL(iomap_writepage);
1544 
1545 int
1546 iomap_writepages(struct address_space *mapping, struct writeback_control *wbc,
1547 		struct iomap_writepage_ctx *wpc,
1548 		const struct iomap_writeback_ops *ops)
1549 {
1550 	int			ret;
1551 
1552 	wpc->ops = ops;
1553 	ret = write_cache_pages(mapping, wbc, iomap_do_writepage, wpc);
1554 	if (!wpc->ioend)
1555 		return ret;
1556 	return iomap_submit_ioend(wpc, wpc->ioend, ret);
1557 }
1558 EXPORT_SYMBOL_GPL(iomap_writepages);
1559 
1560 static int __init iomap_init(void)
1561 {
1562 	return bioset_init(&iomap_ioend_bioset, 4 * (PAGE_SIZE / SECTOR_SIZE),
1563 			   offsetof(struct iomap_ioend, io_inline_bio),
1564 			   BIOSET_NEED_BVECS);
1565 }
1566 fs_initcall(iomap_init);
1567