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