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