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