xref: /linux/fs/iomap/buffered-io.c (revision add07519ea6b6c2ba2b7842225eb87e0f08f2b0f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Red Hat, Inc.
4  * Copyright (C) 2016-2023 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/swap.h>
16 #include <linux/bio.h>
17 #include <linux/sched/signal.h>
18 #include <linux/migrate.h>
19 #include "internal.h"
20 #include "trace.h"
21 
22 #include "../internal.h"
23 
24 /*
25  * Structure allocated for each folio to track per-block uptodate, dirty state
26  * and I/O completions.
27  */
28 struct iomap_folio_state {
29 	spinlock_t		state_lock;
30 	unsigned int		read_bytes_pending;
31 	atomic_t		write_bytes_pending;
32 
33 	/*
34 	 * Each block has two bits in this bitmap:
35 	 * Bits [0..blocks_per_folio) has the uptodate status.
36 	 * Bits [b_p_f...(2*b_p_f))   has the dirty status.
37 	 */
38 	unsigned long		state[];
39 };
40 
41 static inline bool ifs_is_fully_uptodate(struct folio *folio,
42 		struct iomap_folio_state *ifs)
43 {
44 	struct inode *inode = folio->mapping->host;
45 
46 	return bitmap_full(ifs->state, i_blocks_per_folio(inode, folio));
47 }
48 
49 static inline bool ifs_block_is_uptodate(struct iomap_folio_state *ifs,
50 		unsigned int block)
51 {
52 	return test_bit(block, ifs->state);
53 }
54 
55 static bool ifs_set_range_uptodate(struct folio *folio,
56 		struct iomap_folio_state *ifs, size_t off, size_t len)
57 {
58 	struct inode *inode = folio->mapping->host;
59 	unsigned int first_blk = off >> inode->i_blkbits;
60 	unsigned int last_blk = (off + len - 1) >> inode->i_blkbits;
61 	unsigned int nr_blks = last_blk - first_blk + 1;
62 
63 	bitmap_set(ifs->state, first_blk, nr_blks);
64 	return ifs_is_fully_uptodate(folio, ifs);
65 }
66 
67 static void iomap_set_range_uptodate(struct folio *folio, size_t off,
68 		size_t len)
69 {
70 	struct iomap_folio_state *ifs = folio->private;
71 	unsigned long flags;
72 	bool uptodate = true;
73 
74 	if (folio_test_uptodate(folio))
75 		return;
76 
77 	if (ifs) {
78 		spin_lock_irqsave(&ifs->state_lock, flags);
79 		uptodate = ifs_set_range_uptodate(folio, ifs, off, len);
80 		spin_unlock_irqrestore(&ifs->state_lock, flags);
81 	}
82 
83 	if (uptodate)
84 		folio_mark_uptodate(folio);
85 }
86 
87 static inline bool ifs_block_is_dirty(struct folio *folio,
88 		struct iomap_folio_state *ifs, int block)
89 {
90 	struct inode *inode = folio->mapping->host;
91 	unsigned int blks_per_folio = i_blocks_per_folio(inode, folio);
92 
93 	return test_bit(block + blks_per_folio, ifs->state);
94 }
95 
96 static unsigned ifs_find_dirty_range(struct folio *folio,
97 		struct iomap_folio_state *ifs, u64 *range_start, u64 range_end)
98 {
99 	struct inode *inode = folio->mapping->host;
100 	unsigned start_blk =
101 		offset_in_folio(folio, *range_start) >> inode->i_blkbits;
102 	unsigned end_blk = min_not_zero(
103 		offset_in_folio(folio, range_end) >> inode->i_blkbits,
104 		i_blocks_per_folio(inode, folio));
105 	unsigned nblks = 1;
106 
107 	while (!ifs_block_is_dirty(folio, ifs, start_blk))
108 		if (++start_blk == end_blk)
109 			return 0;
110 
111 	while (start_blk + nblks < end_blk) {
112 		if (!ifs_block_is_dirty(folio, ifs, start_blk + nblks))
113 			break;
114 		nblks++;
115 	}
116 
117 	*range_start = folio_pos(folio) + (start_blk << inode->i_blkbits);
118 	return nblks << inode->i_blkbits;
119 }
120 
121 static unsigned iomap_find_dirty_range(struct folio *folio, u64 *range_start,
122 		u64 range_end)
123 {
124 	struct iomap_folio_state *ifs = folio->private;
125 
126 	if (*range_start >= range_end)
127 		return 0;
128 
129 	if (ifs)
130 		return ifs_find_dirty_range(folio, ifs, range_start, range_end);
131 	return range_end - *range_start;
132 }
133 
134 static void ifs_clear_range_dirty(struct folio *folio,
135 		struct iomap_folio_state *ifs, size_t off, size_t len)
136 {
137 	struct inode *inode = folio->mapping->host;
138 	unsigned int blks_per_folio = i_blocks_per_folio(inode, folio);
139 	unsigned int first_blk = (off >> inode->i_blkbits);
140 	unsigned int last_blk = (off + len - 1) >> inode->i_blkbits;
141 	unsigned int nr_blks = last_blk - first_blk + 1;
142 	unsigned long flags;
143 
144 	spin_lock_irqsave(&ifs->state_lock, flags);
145 	bitmap_clear(ifs->state, first_blk + blks_per_folio, nr_blks);
146 	spin_unlock_irqrestore(&ifs->state_lock, flags);
147 }
148 
149 static void iomap_clear_range_dirty(struct folio *folio, size_t off, size_t len)
150 {
151 	struct iomap_folio_state *ifs = folio->private;
152 
153 	if (ifs)
154 		ifs_clear_range_dirty(folio, ifs, off, len);
155 }
156 
157 static void ifs_set_range_dirty(struct folio *folio,
158 		struct iomap_folio_state *ifs, size_t off, size_t len)
159 {
160 	struct inode *inode = folio->mapping->host;
161 	unsigned int blks_per_folio = i_blocks_per_folio(inode, folio);
162 	unsigned int first_blk = (off >> inode->i_blkbits);
163 	unsigned int last_blk = (off + len - 1) >> inode->i_blkbits;
164 	unsigned int nr_blks = last_blk - first_blk + 1;
165 	unsigned long flags;
166 
167 	spin_lock_irqsave(&ifs->state_lock, flags);
168 	bitmap_set(ifs->state, first_blk + blks_per_folio, nr_blks);
169 	spin_unlock_irqrestore(&ifs->state_lock, flags);
170 }
171 
172 static void iomap_set_range_dirty(struct folio *folio, size_t off, size_t len)
173 {
174 	struct iomap_folio_state *ifs = folio->private;
175 
176 	if (ifs)
177 		ifs_set_range_dirty(folio, ifs, off, len);
178 }
179 
180 static struct iomap_folio_state *ifs_alloc(struct inode *inode,
181 		struct folio *folio, unsigned int flags)
182 {
183 	struct iomap_folio_state *ifs = folio->private;
184 	unsigned int nr_blocks = i_blocks_per_folio(inode, folio);
185 	gfp_t gfp;
186 
187 	if (ifs || nr_blocks <= 1)
188 		return ifs;
189 
190 	if (flags & IOMAP_NOWAIT)
191 		gfp = GFP_NOWAIT;
192 	else
193 		gfp = GFP_NOFS | __GFP_NOFAIL;
194 
195 	/*
196 	 * ifs->state tracks two sets of state flags when the
197 	 * filesystem block size is smaller than the folio size.
198 	 * The first state tracks per-block uptodate and the
199 	 * second tracks per-block dirty state.
200 	 */
201 	ifs = kzalloc(struct_size(ifs, state,
202 		      BITS_TO_LONGS(2 * nr_blocks)), gfp);
203 	if (!ifs)
204 		return ifs;
205 
206 	spin_lock_init(&ifs->state_lock);
207 	if (folio_test_uptodate(folio))
208 		bitmap_set(ifs->state, 0, nr_blocks);
209 	if (folio_test_dirty(folio))
210 		bitmap_set(ifs->state, nr_blocks, nr_blocks);
211 	folio_attach_private(folio, ifs);
212 
213 	return ifs;
214 }
215 
216 static void ifs_free(struct folio *folio)
217 {
218 	struct iomap_folio_state *ifs = folio_detach_private(folio);
219 
220 	if (!ifs)
221 		return;
222 	WARN_ON_ONCE(ifs->read_bytes_pending != 0);
223 	WARN_ON_ONCE(atomic_read(&ifs->write_bytes_pending));
224 	WARN_ON_ONCE(ifs_is_fully_uptodate(folio, ifs) !=
225 			folio_test_uptodate(folio));
226 	kfree(ifs);
227 }
228 
229 /*
230  * Calculate the range inside the folio that we actually need to read.
231  */
232 static void iomap_adjust_read_range(struct inode *inode, struct folio *folio,
233 		loff_t *pos, loff_t length, size_t *offp, size_t *lenp)
234 {
235 	struct iomap_folio_state *ifs = folio->private;
236 	loff_t orig_pos = *pos;
237 	loff_t isize = i_size_read(inode);
238 	unsigned block_bits = inode->i_blkbits;
239 	unsigned block_size = (1 << block_bits);
240 	size_t poff = offset_in_folio(folio, *pos);
241 	size_t plen = min_t(loff_t, folio_size(folio) - poff, length);
242 	size_t orig_plen = plen;
243 	unsigned first = poff >> block_bits;
244 	unsigned last = (poff + plen - 1) >> block_bits;
245 
246 	/*
247 	 * If the block size is smaller than the page size, we need to check the
248 	 * per-block uptodate status and adjust the offset and length if needed
249 	 * to avoid reading in already uptodate ranges.
250 	 */
251 	if (ifs) {
252 		unsigned int i;
253 
254 		/* move forward for each leading block marked uptodate */
255 		for (i = first; i <= last; i++) {
256 			if (!ifs_block_is_uptodate(ifs, i))
257 				break;
258 			*pos += block_size;
259 			poff += block_size;
260 			plen -= block_size;
261 			first++;
262 		}
263 
264 		/* truncate len if we find any trailing uptodate block(s) */
265 		while (++i <= last) {
266 			if (ifs_block_is_uptodate(ifs, i)) {
267 				plen -= (last - i + 1) * block_size;
268 				last = i - 1;
269 				break;
270 			}
271 		}
272 	}
273 
274 	/*
275 	 * If the extent spans the block that contains the i_size, we need to
276 	 * handle both halves separately so that we properly zero data in the
277 	 * page cache for blocks that are entirely outside of i_size.
278 	 */
279 	if (orig_pos <= isize && orig_pos + orig_plen > isize) {
280 		unsigned end = offset_in_folio(folio, isize - 1) >> block_bits;
281 
282 		if (first <= end && last > end)
283 			plen -= (last - end) * block_size;
284 	}
285 
286 	*offp = poff;
287 	*lenp = plen;
288 }
289 
290 static void iomap_finish_folio_read(struct folio *folio, size_t off,
291 		size_t len, int error)
292 {
293 	struct iomap_folio_state *ifs = folio->private;
294 	bool uptodate = !error;
295 	bool finished = true;
296 
297 	if (ifs) {
298 		unsigned long flags;
299 
300 		spin_lock_irqsave(&ifs->state_lock, flags);
301 		if (!error)
302 			uptodate = ifs_set_range_uptodate(folio, ifs, off, len);
303 		ifs->read_bytes_pending -= len;
304 		finished = !ifs->read_bytes_pending;
305 		spin_unlock_irqrestore(&ifs->state_lock, flags);
306 	}
307 
308 	if (finished)
309 		folio_end_read(folio, uptodate);
310 }
311 
312 static void iomap_read_end_io(struct bio *bio)
313 {
314 	int error = blk_status_to_errno(bio->bi_status);
315 	struct folio_iter fi;
316 
317 	bio_for_each_folio_all(fi, bio)
318 		iomap_finish_folio_read(fi.folio, fi.offset, fi.length, error);
319 	bio_put(bio);
320 }
321 
322 struct iomap_readpage_ctx {
323 	struct folio		*cur_folio;
324 	bool			cur_folio_in_bio;
325 	struct bio		*bio;
326 	struct readahead_control *rac;
327 };
328 
329 /**
330  * iomap_read_inline_data - copy inline data into the page cache
331  * @iter: iteration structure
332  * @folio: folio to copy to
333  *
334  * Copy the inline data in @iter into @folio and zero out the rest of the folio.
335  * Only a single IOMAP_INLINE extent is allowed at the end of each file.
336  * Returns zero for success to complete the read, or the usual negative errno.
337  */
338 static int iomap_read_inline_data(const struct iomap_iter *iter,
339 		struct folio *folio)
340 {
341 	const struct iomap *iomap = iomap_iter_srcmap(iter);
342 	size_t size = i_size_read(iter->inode) - iomap->offset;
343 	size_t offset = offset_in_folio(folio, iomap->offset);
344 
345 	if (folio_test_uptodate(folio))
346 		return 0;
347 
348 	if (WARN_ON_ONCE(size > iomap->length))
349 		return -EIO;
350 	if (offset > 0)
351 		ifs_alloc(iter->inode, folio, iter->flags);
352 
353 	folio_fill_tail(folio, offset, iomap->inline_data, size);
354 	iomap_set_range_uptodate(folio, offset, folio_size(folio) - offset);
355 	return 0;
356 }
357 
358 static inline bool iomap_block_needs_zeroing(const struct iomap_iter *iter,
359 		loff_t pos)
360 {
361 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
362 
363 	return srcmap->type != IOMAP_MAPPED ||
364 		(srcmap->flags & IOMAP_F_NEW) ||
365 		pos >= i_size_read(iter->inode);
366 }
367 
368 static int iomap_readpage_iter(struct iomap_iter *iter,
369 		struct iomap_readpage_ctx *ctx)
370 {
371 	const struct iomap *iomap = &iter->iomap;
372 	loff_t pos = iter->pos;
373 	loff_t length = iomap_length(iter);
374 	struct folio *folio = ctx->cur_folio;
375 	struct iomap_folio_state *ifs;
376 	size_t poff, plen;
377 	sector_t sector;
378 	int ret;
379 
380 	if (iomap->type == IOMAP_INLINE) {
381 		ret = iomap_read_inline_data(iter, folio);
382 		if (ret)
383 			return ret;
384 		return iomap_iter_advance(iter, &length);
385 	}
386 
387 	/* zero post-eof blocks as the page may be mapped */
388 	ifs = ifs_alloc(iter->inode, folio, iter->flags);
389 	iomap_adjust_read_range(iter->inode, folio, &pos, length, &poff, &plen);
390 	if (plen == 0)
391 		goto done;
392 
393 	if (iomap_block_needs_zeroing(iter, pos)) {
394 		folio_zero_range(folio, poff, plen);
395 		iomap_set_range_uptodate(folio, poff, plen);
396 		goto done;
397 	}
398 
399 	ctx->cur_folio_in_bio = true;
400 	if (ifs) {
401 		spin_lock_irq(&ifs->state_lock);
402 		ifs->read_bytes_pending += plen;
403 		spin_unlock_irq(&ifs->state_lock);
404 	}
405 
406 	sector = iomap_sector(iomap, pos);
407 	if (!ctx->bio ||
408 	    bio_end_sector(ctx->bio) != sector ||
409 	    !bio_add_folio(ctx->bio, folio, plen, poff)) {
410 		gfp_t gfp = mapping_gfp_constraint(folio->mapping, GFP_KERNEL);
411 		gfp_t orig_gfp = gfp;
412 		unsigned int nr_vecs = DIV_ROUND_UP(length, PAGE_SIZE);
413 
414 		if (ctx->bio)
415 			submit_bio(ctx->bio);
416 
417 		if (ctx->rac) /* same as readahead_gfp_mask */
418 			gfp |= __GFP_NORETRY | __GFP_NOWARN;
419 		ctx->bio = bio_alloc(iomap->bdev, bio_max_segs(nr_vecs),
420 				     REQ_OP_READ, gfp);
421 		/*
422 		 * If the bio_alloc fails, try it again for a single page to
423 		 * avoid having to deal with partial page reads.  This emulates
424 		 * what do_mpage_read_folio does.
425 		 */
426 		if (!ctx->bio) {
427 			ctx->bio = bio_alloc(iomap->bdev, 1, REQ_OP_READ,
428 					     orig_gfp);
429 		}
430 		if (ctx->rac)
431 			ctx->bio->bi_opf |= REQ_RAHEAD;
432 		ctx->bio->bi_iter.bi_sector = sector;
433 		ctx->bio->bi_end_io = iomap_read_end_io;
434 		bio_add_folio_nofail(ctx->bio, folio, plen, poff);
435 	}
436 
437 done:
438 	/*
439 	 * Move the caller beyond our range so that it keeps making progress.
440 	 * For that, we have to include any leading non-uptodate ranges, but
441 	 * we can skip trailing ones as they will be handled in the next
442 	 * iteration.
443 	 */
444 	length = pos - iter->pos + plen;
445 	return iomap_iter_advance(iter, &length);
446 }
447 
448 static int iomap_read_folio_iter(struct iomap_iter *iter,
449 		struct iomap_readpage_ctx *ctx)
450 {
451 	int ret;
452 
453 	while (iomap_length(iter)) {
454 		ret = iomap_readpage_iter(iter, ctx);
455 		if (ret)
456 			return ret;
457 	}
458 
459 	return 0;
460 }
461 
462 int iomap_read_folio(struct folio *folio, const struct iomap_ops *ops)
463 {
464 	struct iomap_iter iter = {
465 		.inode		= folio->mapping->host,
466 		.pos		= folio_pos(folio),
467 		.len		= folio_size(folio),
468 	};
469 	struct iomap_readpage_ctx ctx = {
470 		.cur_folio	= folio,
471 	};
472 	int ret;
473 
474 	trace_iomap_readpage(iter.inode, 1);
475 
476 	while ((ret = iomap_iter(&iter, ops)) > 0)
477 		iter.status = iomap_read_folio_iter(&iter, &ctx);
478 
479 	if (ctx.bio) {
480 		submit_bio(ctx.bio);
481 		WARN_ON_ONCE(!ctx.cur_folio_in_bio);
482 	} else {
483 		WARN_ON_ONCE(ctx.cur_folio_in_bio);
484 		folio_unlock(folio);
485 	}
486 
487 	/*
488 	 * Just like mpage_readahead and block_read_full_folio, we always
489 	 * return 0 and just set the folio error flag on errors.  This
490 	 * should be cleaned up throughout the stack eventually.
491 	 */
492 	return 0;
493 }
494 EXPORT_SYMBOL_GPL(iomap_read_folio);
495 
496 static int iomap_readahead_iter(struct iomap_iter *iter,
497 		struct iomap_readpage_ctx *ctx)
498 {
499 	int ret;
500 
501 	while (iomap_length(iter)) {
502 		if (ctx->cur_folio &&
503 		    offset_in_folio(ctx->cur_folio, iter->pos) == 0) {
504 			if (!ctx->cur_folio_in_bio)
505 				folio_unlock(ctx->cur_folio);
506 			ctx->cur_folio = NULL;
507 		}
508 		if (!ctx->cur_folio) {
509 			ctx->cur_folio = readahead_folio(ctx->rac);
510 			ctx->cur_folio_in_bio = false;
511 		}
512 		ret = iomap_readpage_iter(iter, ctx);
513 		if (ret)
514 			return ret;
515 	}
516 
517 	return 0;
518 }
519 
520 /**
521  * iomap_readahead - Attempt to read pages from a file.
522  * @rac: Describes the pages to be read.
523  * @ops: The operations vector for the filesystem.
524  *
525  * This function is for filesystems to call to implement their readahead
526  * address_space operation.
527  *
528  * Context: The @ops callbacks may submit I/O (eg to read the addresses of
529  * blocks from disc), and may wait for it.  The caller may be trying to
530  * access a different page, and so sleeping excessively should be avoided.
531  * It may allocate memory, but should avoid costly allocations.  This
532  * function is called with memalloc_nofs set, so allocations will not cause
533  * the filesystem to be reentered.
534  */
535 void iomap_readahead(struct readahead_control *rac, const struct iomap_ops *ops)
536 {
537 	struct iomap_iter iter = {
538 		.inode	= rac->mapping->host,
539 		.pos	= readahead_pos(rac),
540 		.len	= readahead_length(rac),
541 	};
542 	struct iomap_readpage_ctx ctx = {
543 		.rac	= rac,
544 	};
545 
546 	trace_iomap_readahead(rac->mapping->host, readahead_count(rac));
547 
548 	while (iomap_iter(&iter, ops) > 0)
549 		iter.status = iomap_readahead_iter(&iter, &ctx);
550 
551 	if (ctx.bio)
552 		submit_bio(ctx.bio);
553 	if (ctx.cur_folio) {
554 		if (!ctx.cur_folio_in_bio)
555 			folio_unlock(ctx.cur_folio);
556 	}
557 }
558 EXPORT_SYMBOL_GPL(iomap_readahead);
559 
560 /*
561  * iomap_is_partially_uptodate checks whether blocks within a folio are
562  * uptodate or not.
563  *
564  * Returns true if all blocks which correspond to the specified part
565  * of the folio are uptodate.
566  */
567 bool iomap_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
568 {
569 	struct iomap_folio_state *ifs = folio->private;
570 	struct inode *inode = folio->mapping->host;
571 	unsigned first, last, i;
572 
573 	if (!ifs)
574 		return false;
575 
576 	/* Caller's range may extend past the end of this folio */
577 	count = min(folio_size(folio) - from, count);
578 
579 	/* First and last blocks in range within folio */
580 	first = from >> inode->i_blkbits;
581 	last = (from + count - 1) >> inode->i_blkbits;
582 
583 	for (i = first; i <= last; i++)
584 		if (!ifs_block_is_uptodate(ifs, i))
585 			return false;
586 	return true;
587 }
588 EXPORT_SYMBOL_GPL(iomap_is_partially_uptodate);
589 
590 /**
591  * iomap_get_folio - get a folio reference for writing
592  * @iter: iteration structure
593  * @pos: start offset of write
594  * @len: Suggested size of folio to create.
595  *
596  * Returns a locked reference to the folio at @pos, or an error pointer if the
597  * folio could not be obtained.
598  */
599 struct folio *iomap_get_folio(struct iomap_iter *iter, loff_t pos, size_t len)
600 {
601 	fgf_t fgp = FGP_WRITEBEGIN | FGP_NOFS;
602 
603 	if (iter->flags & IOMAP_NOWAIT)
604 		fgp |= FGP_NOWAIT;
605 	if (iter->flags & IOMAP_DONTCACHE)
606 		fgp |= FGP_DONTCACHE;
607 	fgp |= fgf_set_order(len);
608 
609 	return __filemap_get_folio(iter->inode->i_mapping, pos >> PAGE_SHIFT,
610 			fgp, mapping_gfp_mask(iter->inode->i_mapping));
611 }
612 EXPORT_SYMBOL_GPL(iomap_get_folio);
613 
614 bool iomap_release_folio(struct folio *folio, gfp_t gfp_flags)
615 {
616 	trace_iomap_release_folio(folio->mapping->host, folio_pos(folio),
617 			folio_size(folio));
618 
619 	/*
620 	 * If the folio is dirty, we refuse to release our metadata because
621 	 * it may be partially dirty.  Once we track per-block dirty state,
622 	 * we can release the metadata if every block is dirty.
623 	 */
624 	if (folio_test_dirty(folio))
625 		return false;
626 	ifs_free(folio);
627 	return true;
628 }
629 EXPORT_SYMBOL_GPL(iomap_release_folio);
630 
631 void iomap_invalidate_folio(struct folio *folio, size_t offset, size_t len)
632 {
633 	trace_iomap_invalidate_folio(folio->mapping->host,
634 					folio_pos(folio) + offset, len);
635 
636 	/*
637 	 * If we're invalidating the entire folio, clear the dirty state
638 	 * from it and release it to avoid unnecessary buildup of the LRU.
639 	 */
640 	if (offset == 0 && len == folio_size(folio)) {
641 		WARN_ON_ONCE(folio_test_writeback(folio));
642 		folio_cancel_dirty(folio);
643 		ifs_free(folio);
644 	}
645 }
646 EXPORT_SYMBOL_GPL(iomap_invalidate_folio);
647 
648 bool iomap_dirty_folio(struct address_space *mapping, struct folio *folio)
649 {
650 	struct inode *inode = mapping->host;
651 	size_t len = folio_size(folio);
652 
653 	ifs_alloc(inode, folio, 0);
654 	iomap_set_range_dirty(folio, 0, len);
655 	return filemap_dirty_folio(mapping, folio);
656 }
657 EXPORT_SYMBOL_GPL(iomap_dirty_folio);
658 
659 static void
660 iomap_write_failed(struct inode *inode, loff_t pos, unsigned len)
661 {
662 	loff_t i_size = i_size_read(inode);
663 
664 	/*
665 	 * Only truncate newly allocated pages beyoned EOF, even if the
666 	 * write started inside the existing inode size.
667 	 */
668 	if (pos + len > i_size)
669 		truncate_pagecache_range(inode, max(pos, i_size),
670 					 pos + len - 1);
671 }
672 
673 static int iomap_read_folio_sync(loff_t block_start, struct folio *folio,
674 		size_t poff, size_t plen, const struct iomap *iomap)
675 {
676 	struct bio_vec bvec;
677 	struct bio bio;
678 
679 	bio_init(&bio, iomap->bdev, &bvec, 1, REQ_OP_READ);
680 	bio.bi_iter.bi_sector = iomap_sector(iomap, block_start);
681 	bio_add_folio_nofail(&bio, folio, plen, poff);
682 	return submit_bio_wait(&bio);
683 }
684 
685 static int __iomap_write_begin(const struct iomap_iter *iter, size_t len,
686 		struct folio *folio)
687 {
688 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
689 	struct iomap_folio_state *ifs;
690 	loff_t pos = iter->pos;
691 	loff_t block_size = i_blocksize(iter->inode);
692 	loff_t block_start = round_down(pos, block_size);
693 	loff_t block_end = round_up(pos + len, block_size);
694 	unsigned int nr_blocks = i_blocks_per_folio(iter->inode, folio);
695 	size_t from = offset_in_folio(folio, pos), to = from + len;
696 	size_t poff, plen;
697 
698 	/*
699 	 * If the write or zeroing completely overlaps the current folio, then
700 	 * entire folio will be dirtied so there is no need for
701 	 * per-block state tracking structures to be attached to this folio.
702 	 * For the unshare case, we must read in the ondisk contents because we
703 	 * are not changing pagecache contents.
704 	 */
705 	if (!(iter->flags & IOMAP_UNSHARE) && pos <= folio_pos(folio) &&
706 	    pos + len >= folio_pos(folio) + folio_size(folio))
707 		return 0;
708 
709 	ifs = ifs_alloc(iter->inode, folio, iter->flags);
710 	if ((iter->flags & IOMAP_NOWAIT) && !ifs && nr_blocks > 1)
711 		return -EAGAIN;
712 
713 	if (folio_test_uptodate(folio))
714 		return 0;
715 
716 	do {
717 		iomap_adjust_read_range(iter->inode, folio, &block_start,
718 				block_end - block_start, &poff, &plen);
719 		if (plen == 0)
720 			break;
721 
722 		if (!(iter->flags & IOMAP_UNSHARE) &&
723 		    (from <= poff || from >= poff + plen) &&
724 		    (to <= poff || to >= poff + plen))
725 			continue;
726 
727 		if (iomap_block_needs_zeroing(iter, block_start)) {
728 			if (WARN_ON_ONCE(iter->flags & IOMAP_UNSHARE))
729 				return -EIO;
730 			folio_zero_segments(folio, poff, from, to, poff + plen);
731 		} else {
732 			int status;
733 
734 			if (iter->flags & IOMAP_NOWAIT)
735 				return -EAGAIN;
736 
737 			status = iomap_read_folio_sync(block_start, folio,
738 					poff, plen, srcmap);
739 			if (status)
740 				return status;
741 		}
742 		iomap_set_range_uptodate(folio, poff, plen);
743 	} while ((block_start += plen) < block_end);
744 
745 	return 0;
746 }
747 
748 static struct folio *__iomap_get_folio(struct iomap_iter *iter, size_t len)
749 {
750 	const struct iomap_folio_ops *folio_ops = iter->iomap.folio_ops;
751 	loff_t pos = iter->pos;
752 
753 	if (!mapping_large_folio_support(iter->inode->i_mapping))
754 		len = min_t(size_t, len, PAGE_SIZE - offset_in_page(pos));
755 
756 	if (folio_ops && folio_ops->get_folio)
757 		return folio_ops->get_folio(iter, pos, len);
758 	else
759 		return iomap_get_folio(iter, pos, len);
760 }
761 
762 static void __iomap_put_folio(struct iomap_iter *iter, size_t ret,
763 		struct folio *folio)
764 {
765 	const struct iomap_folio_ops *folio_ops = iter->iomap.folio_ops;
766 	loff_t pos = iter->pos;
767 
768 	if (folio_ops && folio_ops->put_folio) {
769 		folio_ops->put_folio(iter->inode, pos, ret, folio);
770 	} else {
771 		folio_unlock(folio);
772 		folio_put(folio);
773 	}
774 }
775 
776 /* trim pos and bytes to within a given folio */
777 static loff_t iomap_trim_folio_range(struct iomap_iter *iter,
778 		struct folio *folio, size_t *offset, u64 *bytes)
779 {
780 	loff_t pos = iter->pos;
781 	size_t fsize = folio_size(folio);
782 
783 	WARN_ON_ONCE(pos < folio_pos(folio));
784 	WARN_ON_ONCE(pos >= folio_pos(folio) + fsize);
785 
786 	*offset = offset_in_folio(folio, pos);
787 	*bytes = min(*bytes, fsize - *offset);
788 
789 	return pos;
790 }
791 
792 static int iomap_write_begin_inline(const struct iomap_iter *iter,
793 		struct folio *folio)
794 {
795 	/* needs more work for the tailpacking case; disable for now */
796 	if (WARN_ON_ONCE(iomap_iter_srcmap(iter)->offset != 0))
797 		return -EIO;
798 	return iomap_read_inline_data(iter, folio);
799 }
800 
801 /*
802  * Grab and prepare a folio for write based on iter state. Returns the folio,
803  * offset, and length. Callers can optionally pass a max length *plen,
804  * otherwise init to zero.
805  */
806 static int iomap_write_begin(struct iomap_iter *iter, struct folio **foliop,
807 		size_t *poffset, u64 *plen)
808 {
809 	const struct iomap_folio_ops *folio_ops = iter->iomap.folio_ops;
810 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
811 	loff_t pos = iter->pos;
812 	u64 len = min_t(u64, SIZE_MAX, iomap_length(iter));
813 	struct folio *folio;
814 	int status = 0;
815 
816 	len = min_not_zero(len, *plen);
817 	BUG_ON(pos + len > iter->iomap.offset + iter->iomap.length);
818 	if (srcmap != &iter->iomap)
819 		BUG_ON(pos + len > srcmap->offset + srcmap->length);
820 
821 	if (fatal_signal_pending(current))
822 		return -EINTR;
823 
824 	folio = __iomap_get_folio(iter, len);
825 	if (IS_ERR(folio))
826 		return PTR_ERR(folio);
827 
828 	/*
829 	 * Now we have a locked folio, before we do anything with it we need to
830 	 * check that the iomap we have cached is not stale. The inode extent
831 	 * mapping can change due to concurrent IO in flight (e.g.
832 	 * IOMAP_UNWRITTEN state can change and memory reclaim could have
833 	 * reclaimed a previously partially written page at this index after IO
834 	 * completion before this write reaches this file offset) and hence we
835 	 * could do the wrong thing here (zero a page range incorrectly or fail
836 	 * to zero) and corrupt data.
837 	 */
838 	if (folio_ops && folio_ops->iomap_valid) {
839 		bool iomap_valid = folio_ops->iomap_valid(iter->inode,
840 							 &iter->iomap);
841 		if (!iomap_valid) {
842 			iter->iomap.flags |= IOMAP_F_STALE;
843 			status = 0;
844 			goto out_unlock;
845 		}
846 	}
847 
848 	pos = iomap_trim_folio_range(iter, folio, poffset, &len);
849 
850 	if (srcmap->type == IOMAP_INLINE)
851 		status = iomap_write_begin_inline(iter, folio);
852 	else if (srcmap->flags & IOMAP_F_BUFFER_HEAD)
853 		status = __block_write_begin_int(folio, pos, len, NULL, srcmap);
854 	else
855 		status = __iomap_write_begin(iter, len, folio);
856 
857 	if (unlikely(status))
858 		goto out_unlock;
859 
860 	*foliop = folio;
861 	*plen = len;
862 	return 0;
863 
864 out_unlock:
865 	__iomap_put_folio(iter, 0, folio);
866 
867 	return status;
868 }
869 
870 static bool __iomap_write_end(struct inode *inode, loff_t pos, size_t len,
871 		size_t copied, struct folio *folio)
872 {
873 	flush_dcache_folio(folio);
874 
875 	/*
876 	 * The blocks that were entirely written will now be uptodate, so we
877 	 * don't have to worry about a read_folio reading them and overwriting a
878 	 * partial write.  However, if we've encountered a short write and only
879 	 * partially written into a block, it will not be marked uptodate, so a
880 	 * read_folio might come in and destroy our partial write.
881 	 *
882 	 * Do the simplest thing and just treat any short write to a
883 	 * non-uptodate page as a zero-length write, and force the caller to
884 	 * redo the whole thing.
885 	 */
886 	if (unlikely(copied < len && !folio_test_uptodate(folio)))
887 		return false;
888 	iomap_set_range_uptodate(folio, offset_in_folio(folio, pos), len);
889 	iomap_set_range_dirty(folio, offset_in_folio(folio, pos), copied);
890 	filemap_dirty_folio(inode->i_mapping, folio);
891 	return true;
892 }
893 
894 static void iomap_write_end_inline(const struct iomap_iter *iter,
895 		struct folio *folio, loff_t pos, size_t copied)
896 {
897 	const struct iomap *iomap = &iter->iomap;
898 	void *addr;
899 
900 	WARN_ON_ONCE(!folio_test_uptodate(folio));
901 	BUG_ON(!iomap_inline_data_valid(iomap));
902 
903 	flush_dcache_folio(folio);
904 	addr = kmap_local_folio(folio, pos);
905 	memcpy(iomap_inline_data(iomap, pos), addr, copied);
906 	kunmap_local(addr);
907 
908 	mark_inode_dirty(iter->inode);
909 }
910 
911 /*
912  * Returns true if all copied bytes have been written to the pagecache,
913  * otherwise return false.
914  */
915 static bool iomap_write_end(struct iomap_iter *iter, size_t len, size_t copied,
916 		struct folio *folio)
917 {
918 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
919 	loff_t pos = iter->pos;
920 
921 	if (srcmap->type == IOMAP_INLINE) {
922 		iomap_write_end_inline(iter, folio, pos, copied);
923 		return true;
924 	}
925 
926 	if (srcmap->flags & IOMAP_F_BUFFER_HEAD) {
927 		size_t bh_written;
928 
929 		bh_written = block_write_end(pos, len, copied, folio);
930 		WARN_ON_ONCE(bh_written != copied && bh_written != 0);
931 		return bh_written == copied;
932 	}
933 
934 	return __iomap_write_end(iter->inode, pos, len, copied, folio);
935 }
936 
937 static int iomap_write_iter(struct iomap_iter *iter, struct iov_iter *i)
938 {
939 	ssize_t total_written = 0;
940 	int status = 0;
941 	struct address_space *mapping = iter->inode->i_mapping;
942 	size_t chunk = mapping_max_folio_size(mapping);
943 	unsigned int bdp_flags = (iter->flags & IOMAP_NOWAIT) ? BDP_ASYNC : 0;
944 
945 	do {
946 		struct folio *folio;
947 		loff_t old_size;
948 		size_t offset;		/* Offset into folio */
949 		u64 bytes;		/* Bytes to write to folio */
950 		size_t copied;		/* Bytes copied from user */
951 		u64 written;		/* Bytes have been written */
952 		loff_t pos;
953 
954 		bytes = iov_iter_count(i);
955 retry:
956 		offset = iter->pos & (chunk - 1);
957 		bytes = min(chunk - offset, bytes);
958 		status = balance_dirty_pages_ratelimited_flags(mapping,
959 							       bdp_flags);
960 		if (unlikely(status))
961 			break;
962 
963 		if (bytes > iomap_length(iter))
964 			bytes = iomap_length(iter);
965 
966 		/*
967 		 * Bring in the user page that we'll copy from _first_.
968 		 * Otherwise there's a nasty deadlock on copying from the
969 		 * same page as we're writing to, without it being marked
970 		 * up-to-date.
971 		 *
972 		 * For async buffered writes the assumption is that the user
973 		 * page has already been faulted in. This can be optimized by
974 		 * faulting the user page.
975 		 */
976 		if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
977 			status = -EFAULT;
978 			break;
979 		}
980 
981 		status = iomap_write_begin(iter, &folio, &offset, &bytes);
982 		if (unlikely(status)) {
983 			iomap_write_failed(iter->inode, iter->pos, bytes);
984 			break;
985 		}
986 		if (iter->iomap.flags & IOMAP_F_STALE)
987 			break;
988 
989 		pos = iter->pos;
990 
991 		if (mapping_writably_mapped(mapping))
992 			flush_dcache_folio(folio);
993 
994 		copied = copy_folio_from_iter_atomic(folio, offset, bytes, i);
995 		written = iomap_write_end(iter, bytes, copied, folio) ?
996 			  copied : 0;
997 
998 		/*
999 		 * Update the in-memory inode size after copying the data into
1000 		 * the page cache.  It's up to the file system to write the
1001 		 * updated size to disk, preferably after I/O completion so that
1002 		 * no stale data is exposed.  Only once that's done can we
1003 		 * unlock and release the folio.
1004 		 */
1005 		old_size = iter->inode->i_size;
1006 		if (pos + written > old_size) {
1007 			i_size_write(iter->inode, pos + written);
1008 			iter->iomap.flags |= IOMAP_F_SIZE_CHANGED;
1009 		}
1010 		__iomap_put_folio(iter, written, folio);
1011 
1012 		if (old_size < pos)
1013 			pagecache_isize_extended(iter->inode, old_size, pos);
1014 
1015 		cond_resched();
1016 		if (unlikely(written == 0)) {
1017 			/*
1018 			 * A short copy made iomap_write_end() reject the
1019 			 * thing entirely.  Might be memory poisoning
1020 			 * halfway through, might be a race with munmap,
1021 			 * might be severe memory pressure.
1022 			 */
1023 			iomap_write_failed(iter->inode, pos, bytes);
1024 			iov_iter_revert(i, copied);
1025 
1026 			if (chunk > PAGE_SIZE)
1027 				chunk /= 2;
1028 			if (copied) {
1029 				bytes = copied;
1030 				goto retry;
1031 			}
1032 		} else {
1033 			total_written += written;
1034 			iomap_iter_advance(iter, &written);
1035 		}
1036 	} while (iov_iter_count(i) && iomap_length(iter));
1037 
1038 	return total_written ? 0 : status;
1039 }
1040 
1041 ssize_t
1042 iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i,
1043 		const struct iomap_ops *ops, void *private)
1044 {
1045 	struct iomap_iter iter = {
1046 		.inode		= iocb->ki_filp->f_mapping->host,
1047 		.pos		= iocb->ki_pos,
1048 		.len		= iov_iter_count(i),
1049 		.flags		= IOMAP_WRITE,
1050 		.private	= private,
1051 	};
1052 	ssize_t ret;
1053 
1054 	if (iocb->ki_flags & IOCB_NOWAIT)
1055 		iter.flags |= IOMAP_NOWAIT;
1056 	if (iocb->ki_flags & IOCB_DONTCACHE)
1057 		iter.flags |= IOMAP_DONTCACHE;
1058 
1059 	while ((ret = iomap_iter(&iter, ops)) > 0)
1060 		iter.status = iomap_write_iter(&iter, i);
1061 
1062 	if (unlikely(iter.pos == iocb->ki_pos))
1063 		return ret;
1064 	ret = iter.pos - iocb->ki_pos;
1065 	iocb->ki_pos = iter.pos;
1066 	return ret;
1067 }
1068 EXPORT_SYMBOL_GPL(iomap_file_buffered_write);
1069 
1070 static void iomap_write_delalloc_ifs_punch(struct inode *inode,
1071 		struct folio *folio, loff_t start_byte, loff_t end_byte,
1072 		struct iomap *iomap, iomap_punch_t punch)
1073 {
1074 	unsigned int first_blk, last_blk, i;
1075 	loff_t last_byte;
1076 	u8 blkbits = inode->i_blkbits;
1077 	struct iomap_folio_state *ifs;
1078 
1079 	/*
1080 	 * When we have per-block dirty tracking, there can be
1081 	 * blocks within a folio which are marked uptodate
1082 	 * but not dirty. In that case it is necessary to punch
1083 	 * out such blocks to avoid leaking any delalloc blocks.
1084 	 */
1085 	ifs = folio->private;
1086 	if (!ifs)
1087 		return;
1088 
1089 	last_byte = min_t(loff_t, end_byte - 1,
1090 			folio_pos(folio) + folio_size(folio) - 1);
1091 	first_blk = offset_in_folio(folio, start_byte) >> blkbits;
1092 	last_blk = offset_in_folio(folio, last_byte) >> blkbits;
1093 	for (i = first_blk; i <= last_blk; i++) {
1094 		if (!ifs_block_is_dirty(folio, ifs, i))
1095 			punch(inode, folio_pos(folio) + (i << blkbits),
1096 				    1 << blkbits, iomap);
1097 	}
1098 }
1099 
1100 static void iomap_write_delalloc_punch(struct inode *inode, struct folio *folio,
1101 		loff_t *punch_start_byte, loff_t start_byte, loff_t end_byte,
1102 		struct iomap *iomap, iomap_punch_t punch)
1103 {
1104 	if (!folio_test_dirty(folio))
1105 		return;
1106 
1107 	/* if dirty, punch up to offset */
1108 	if (start_byte > *punch_start_byte) {
1109 		punch(inode, *punch_start_byte, start_byte - *punch_start_byte,
1110 				iomap);
1111 	}
1112 
1113 	/* Punch non-dirty blocks within folio */
1114 	iomap_write_delalloc_ifs_punch(inode, folio, start_byte, end_byte,
1115 			iomap, punch);
1116 
1117 	/*
1118 	 * Make sure the next punch start is correctly bound to
1119 	 * the end of this data range, not the end of the folio.
1120 	 */
1121 	*punch_start_byte = min_t(loff_t, end_byte,
1122 				folio_pos(folio) + folio_size(folio));
1123 }
1124 
1125 /*
1126  * Scan the data range passed to us for dirty page cache folios. If we find a
1127  * dirty folio, punch out the preceding range and update the offset from which
1128  * the next punch will start from.
1129  *
1130  * We can punch out storage reservations under clean pages because they either
1131  * contain data that has been written back - in which case the delalloc punch
1132  * over that range is a no-op - or they have been read faults in which case they
1133  * contain zeroes and we can remove the delalloc backing range and any new
1134  * writes to those pages will do the normal hole filling operation...
1135  *
1136  * This makes the logic simple: we only need to keep the delalloc extents only
1137  * over the dirty ranges of the page cache.
1138  *
1139  * This function uses [start_byte, end_byte) intervals (i.e. open ended) to
1140  * simplify range iterations.
1141  */
1142 static void iomap_write_delalloc_scan(struct inode *inode,
1143 		loff_t *punch_start_byte, loff_t start_byte, loff_t end_byte,
1144 		struct iomap *iomap, iomap_punch_t punch)
1145 {
1146 	while (start_byte < end_byte) {
1147 		struct folio	*folio;
1148 
1149 		/* grab locked page */
1150 		folio = filemap_lock_folio(inode->i_mapping,
1151 				start_byte >> PAGE_SHIFT);
1152 		if (IS_ERR(folio)) {
1153 			start_byte = ALIGN_DOWN(start_byte, PAGE_SIZE) +
1154 					PAGE_SIZE;
1155 			continue;
1156 		}
1157 
1158 		iomap_write_delalloc_punch(inode, folio, punch_start_byte,
1159 				start_byte, end_byte, iomap, punch);
1160 
1161 		/* move offset to start of next folio in range */
1162 		start_byte = folio_pos(folio) + folio_size(folio);
1163 		folio_unlock(folio);
1164 		folio_put(folio);
1165 	}
1166 }
1167 
1168 /*
1169  * When a short write occurs, the filesystem might need to use ->iomap_end
1170  * to remove space reservations created in ->iomap_begin.
1171  *
1172  * For filesystems that use delayed allocation, there can be dirty pages over
1173  * the delalloc extent outside the range of a short write but still within the
1174  * delalloc extent allocated for this iomap if the write raced with page
1175  * faults.
1176  *
1177  * Punch out all the delalloc blocks in the range given except for those that
1178  * have dirty data still pending in the page cache - those are going to be
1179  * written and so must still retain the delalloc backing for writeback.
1180  *
1181  * The punch() callback *must* only punch delalloc extents in the range passed
1182  * to it. It must skip over all other types of extents in the range and leave
1183  * them completely unchanged. It must do this punch atomically with respect to
1184  * other extent modifications.
1185  *
1186  * The punch() callback may be called with a folio locked to prevent writeback
1187  * extent allocation racing at the edge of the range we are currently punching.
1188  * The locked folio may or may not cover the range being punched, so it is not
1189  * safe for the punch() callback to lock folios itself.
1190  *
1191  * Lock order is:
1192  *
1193  * inode->i_rwsem (shared or exclusive)
1194  *   inode->i_mapping->invalidate_lock (exclusive)
1195  *     folio_lock()
1196  *       ->punch
1197  *         internal filesystem allocation lock
1198  *
1199  * As we are scanning the page cache for data, we don't need to reimplement the
1200  * wheel - mapping_seek_hole_data() does exactly what we need to identify the
1201  * start and end of data ranges correctly even for sub-folio block sizes. This
1202  * byte range based iteration is especially convenient because it means we
1203  * don't have to care about variable size folios, nor where the start or end of
1204  * the data range lies within a folio, if they lie within the same folio or even
1205  * if there are multiple discontiguous data ranges within the folio.
1206  *
1207  * It should be noted that mapping_seek_hole_data() is not aware of EOF, and so
1208  * can return data ranges that exist in the cache beyond EOF. e.g. a page fault
1209  * spanning EOF will initialise the post-EOF data to zeroes and mark it up to
1210  * date. A write page fault can then mark it dirty. If we then fail a write()
1211  * beyond EOF into that up to date cached range, we allocate a delalloc block
1212  * beyond EOF and then have to punch it out. Because the range is up to date,
1213  * mapping_seek_hole_data() will return it, and we will skip the punch because
1214  * the folio is dirty. THis is incorrect - we always need to punch out delalloc
1215  * beyond EOF in this case as writeback will never write back and covert that
1216  * delalloc block beyond EOF. Hence we limit the cached data scan range to EOF,
1217  * resulting in always punching out the range from the EOF to the end of the
1218  * range the iomap spans.
1219  *
1220  * Intervals are of the form [start_byte, end_byte) (i.e. open ended) because it
1221  * matches the intervals returned by mapping_seek_hole_data(). i.e. SEEK_DATA
1222  * returns the start of a data range (start_byte), and SEEK_HOLE(start_byte)
1223  * returns the end of the data range (data_end). Using closed intervals would
1224  * require sprinkling this code with magic "+ 1" and "- 1" arithmetic and expose
1225  * the code to subtle off-by-one bugs....
1226  */
1227 void iomap_write_delalloc_release(struct inode *inode, loff_t start_byte,
1228 		loff_t end_byte, unsigned flags, struct iomap *iomap,
1229 		iomap_punch_t punch)
1230 {
1231 	loff_t punch_start_byte = start_byte;
1232 	loff_t scan_end_byte = min(i_size_read(inode), end_byte);
1233 
1234 	/*
1235 	 * The caller must hold invalidate_lock to avoid races with page faults
1236 	 * re-instantiating folios and dirtying them via ->page_mkwrite whilst
1237 	 * we walk the cache and perform delalloc extent removal.  Failing to do
1238 	 * this can leave dirty pages with no space reservation in the cache.
1239 	 */
1240 	lockdep_assert_held_write(&inode->i_mapping->invalidate_lock);
1241 
1242 	while (start_byte < scan_end_byte) {
1243 		loff_t		data_end;
1244 
1245 		start_byte = mapping_seek_hole_data(inode->i_mapping,
1246 				start_byte, scan_end_byte, SEEK_DATA);
1247 		/*
1248 		 * If there is no more data to scan, all that is left is to
1249 		 * punch out the remaining range.
1250 		 *
1251 		 * Note that mapping_seek_hole_data is only supposed to return
1252 		 * either an offset or -ENXIO, so WARN on any other error as
1253 		 * that would be an API change without updating the callers.
1254 		 */
1255 		if (start_byte == -ENXIO || start_byte == scan_end_byte)
1256 			break;
1257 		if (WARN_ON_ONCE(start_byte < 0))
1258 			return;
1259 		WARN_ON_ONCE(start_byte < punch_start_byte);
1260 		WARN_ON_ONCE(start_byte > scan_end_byte);
1261 
1262 		/*
1263 		 * We find the end of this contiguous cached data range by
1264 		 * seeking from start_byte to the beginning of the next hole.
1265 		 */
1266 		data_end = mapping_seek_hole_data(inode->i_mapping, start_byte,
1267 				scan_end_byte, SEEK_HOLE);
1268 		if (WARN_ON_ONCE(data_end < 0))
1269 			return;
1270 
1271 		/*
1272 		 * If we race with post-direct I/O invalidation of the page cache,
1273 		 * there might be no data left at start_byte.
1274 		 */
1275 		if (data_end == start_byte)
1276 			continue;
1277 
1278 		WARN_ON_ONCE(data_end < start_byte);
1279 		WARN_ON_ONCE(data_end > scan_end_byte);
1280 
1281 		iomap_write_delalloc_scan(inode, &punch_start_byte, start_byte,
1282 				data_end, iomap, punch);
1283 
1284 		/* The next data search starts at the end of this one. */
1285 		start_byte = data_end;
1286 	}
1287 
1288 	if (punch_start_byte < end_byte)
1289 		punch(inode, punch_start_byte, end_byte - punch_start_byte,
1290 				iomap);
1291 }
1292 EXPORT_SYMBOL_GPL(iomap_write_delalloc_release);
1293 
1294 static int iomap_unshare_iter(struct iomap_iter *iter)
1295 {
1296 	struct iomap *iomap = &iter->iomap;
1297 	u64 bytes = iomap_length(iter);
1298 	int status;
1299 
1300 	if (!iomap_want_unshare_iter(iter))
1301 		return iomap_iter_advance(iter, &bytes);
1302 
1303 	do {
1304 		struct folio *folio;
1305 		size_t offset;
1306 		bool ret;
1307 
1308 		bytes = min_t(u64, SIZE_MAX, bytes);
1309 		status = iomap_write_begin(iter, &folio, &offset, &bytes);
1310 		if (unlikely(status))
1311 			return status;
1312 		if (iomap->flags & IOMAP_F_STALE)
1313 			break;
1314 
1315 		ret = iomap_write_end(iter, bytes, bytes, folio);
1316 		__iomap_put_folio(iter, bytes, folio);
1317 		if (WARN_ON_ONCE(!ret))
1318 			return -EIO;
1319 
1320 		cond_resched();
1321 
1322 		balance_dirty_pages_ratelimited(iter->inode->i_mapping);
1323 
1324 		status = iomap_iter_advance(iter, &bytes);
1325 		if (status)
1326 			break;
1327 	} while (bytes > 0);
1328 
1329 	return status;
1330 }
1331 
1332 int
1333 iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len,
1334 		const struct iomap_ops *ops)
1335 {
1336 	struct iomap_iter iter = {
1337 		.inode		= inode,
1338 		.pos		= pos,
1339 		.flags		= IOMAP_WRITE | IOMAP_UNSHARE,
1340 	};
1341 	loff_t size = i_size_read(inode);
1342 	int ret;
1343 
1344 	if (pos < 0 || pos >= size)
1345 		return 0;
1346 
1347 	iter.len = min(len, size - pos);
1348 	while ((ret = iomap_iter(&iter, ops)) > 0)
1349 		iter.status = iomap_unshare_iter(&iter);
1350 	return ret;
1351 }
1352 EXPORT_SYMBOL_GPL(iomap_file_unshare);
1353 
1354 /*
1355  * Flush the remaining range of the iter and mark the current mapping stale.
1356  * This is used when zero range sees an unwritten mapping that may have had
1357  * dirty pagecache over it.
1358  */
1359 static inline int iomap_zero_iter_flush_and_stale(struct iomap_iter *i)
1360 {
1361 	struct address_space *mapping = i->inode->i_mapping;
1362 	loff_t end = i->pos + i->len - 1;
1363 
1364 	i->iomap.flags |= IOMAP_F_STALE;
1365 	return filemap_write_and_wait_range(mapping, i->pos, end);
1366 }
1367 
1368 static int iomap_zero_iter(struct iomap_iter *iter, bool *did_zero)
1369 {
1370 	u64 bytes = iomap_length(iter);
1371 	int status;
1372 
1373 	do {
1374 		struct folio *folio;
1375 		size_t offset;
1376 		bool ret;
1377 
1378 		bytes = min_t(u64, SIZE_MAX, bytes);
1379 		status = iomap_write_begin(iter, &folio, &offset, &bytes);
1380 		if (status)
1381 			return status;
1382 		if (iter->iomap.flags & IOMAP_F_STALE)
1383 			break;
1384 
1385 		/* warn about zeroing folios beyond eof that won't write back */
1386 		WARN_ON_ONCE(folio_pos(folio) > iter->inode->i_size);
1387 
1388 		folio_zero_range(folio, offset, bytes);
1389 		folio_mark_accessed(folio);
1390 
1391 		ret = iomap_write_end(iter, bytes, bytes, folio);
1392 		__iomap_put_folio(iter, bytes, folio);
1393 		if (WARN_ON_ONCE(!ret))
1394 			return -EIO;
1395 
1396 		status = iomap_iter_advance(iter, &bytes);
1397 		if (status)
1398 			break;
1399 	} while (bytes > 0);
1400 
1401 	if (did_zero)
1402 		*did_zero = true;
1403 	return status;
1404 }
1405 
1406 int
1407 iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero,
1408 		const struct iomap_ops *ops, void *private)
1409 {
1410 	struct iomap_iter iter = {
1411 		.inode		= inode,
1412 		.pos		= pos,
1413 		.len		= len,
1414 		.flags		= IOMAP_ZERO,
1415 		.private	= private,
1416 	};
1417 	struct address_space *mapping = inode->i_mapping;
1418 	unsigned int blocksize = i_blocksize(inode);
1419 	unsigned int off = pos & (blocksize - 1);
1420 	loff_t plen = min_t(loff_t, len, blocksize - off);
1421 	int ret;
1422 	bool range_dirty;
1423 
1424 	/*
1425 	 * Zero range can skip mappings that are zero on disk so long as
1426 	 * pagecache is clean. If pagecache was dirty prior to zero range, the
1427 	 * mapping converts on writeback completion and so must be zeroed.
1428 	 *
1429 	 * The simplest way to deal with this across a range is to flush
1430 	 * pagecache and process the updated mappings. To avoid excessive
1431 	 * flushing on partial eof zeroing, special case it to zero the
1432 	 * unaligned start portion if already dirty in pagecache.
1433 	 */
1434 	if (off &&
1435 	    filemap_range_needs_writeback(mapping, pos, pos + plen - 1)) {
1436 		iter.len = plen;
1437 		while ((ret = iomap_iter(&iter, ops)) > 0)
1438 			iter.status = iomap_zero_iter(&iter, did_zero);
1439 
1440 		iter.len = len - (iter.pos - pos);
1441 		if (ret || !iter.len)
1442 			return ret;
1443 	}
1444 
1445 	/*
1446 	 * To avoid an unconditional flush, check pagecache state and only flush
1447 	 * if dirty and the fs returns a mapping that might convert on
1448 	 * writeback.
1449 	 */
1450 	range_dirty = filemap_range_needs_writeback(inode->i_mapping,
1451 					iter.pos, iter.pos + iter.len - 1);
1452 	while ((ret = iomap_iter(&iter, ops)) > 0) {
1453 		const struct iomap *srcmap = iomap_iter_srcmap(&iter);
1454 
1455 		if (srcmap->type == IOMAP_HOLE ||
1456 		    srcmap->type == IOMAP_UNWRITTEN) {
1457 			s64 status;
1458 
1459 			if (range_dirty) {
1460 				range_dirty = false;
1461 				status = iomap_zero_iter_flush_and_stale(&iter);
1462 			} else {
1463 				status = iomap_iter_advance_full(&iter);
1464 			}
1465 			iter.status = status;
1466 			continue;
1467 		}
1468 
1469 		iter.status = iomap_zero_iter(&iter, did_zero);
1470 	}
1471 	return ret;
1472 }
1473 EXPORT_SYMBOL_GPL(iomap_zero_range);
1474 
1475 int
1476 iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero,
1477 		const struct iomap_ops *ops, void *private)
1478 {
1479 	unsigned int blocksize = i_blocksize(inode);
1480 	unsigned int off = pos & (blocksize - 1);
1481 
1482 	/* Block boundary? Nothing to do */
1483 	if (!off)
1484 		return 0;
1485 	return iomap_zero_range(inode, pos, blocksize - off, did_zero, ops,
1486 			private);
1487 }
1488 EXPORT_SYMBOL_GPL(iomap_truncate_page);
1489 
1490 static int iomap_folio_mkwrite_iter(struct iomap_iter *iter,
1491 		struct folio *folio)
1492 {
1493 	loff_t length = iomap_length(iter);
1494 	int ret;
1495 
1496 	if (iter->iomap.flags & IOMAP_F_BUFFER_HEAD) {
1497 		ret = __block_write_begin_int(folio, iter->pos, length, NULL,
1498 					      &iter->iomap);
1499 		if (ret)
1500 			return ret;
1501 		block_commit_write(folio, 0, length);
1502 	} else {
1503 		WARN_ON_ONCE(!folio_test_uptodate(folio));
1504 		folio_mark_dirty(folio);
1505 	}
1506 
1507 	return iomap_iter_advance(iter, &length);
1508 }
1509 
1510 vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops,
1511 		void *private)
1512 {
1513 	struct iomap_iter iter = {
1514 		.inode		= file_inode(vmf->vma->vm_file),
1515 		.flags		= IOMAP_WRITE | IOMAP_FAULT,
1516 		.private	= private,
1517 	};
1518 	struct folio *folio = page_folio(vmf->page);
1519 	ssize_t ret;
1520 
1521 	folio_lock(folio);
1522 	ret = folio_mkwrite_check_truncate(folio, iter.inode);
1523 	if (ret < 0)
1524 		goto out_unlock;
1525 	iter.pos = folio_pos(folio);
1526 	iter.len = ret;
1527 	while ((ret = iomap_iter(&iter, ops)) > 0)
1528 		iter.status = iomap_folio_mkwrite_iter(&iter, folio);
1529 
1530 	if (ret < 0)
1531 		goto out_unlock;
1532 	folio_wait_stable(folio);
1533 	return VM_FAULT_LOCKED;
1534 out_unlock:
1535 	folio_unlock(folio);
1536 	return vmf_fs_error(ret);
1537 }
1538 EXPORT_SYMBOL_GPL(iomap_page_mkwrite);
1539 
1540 static void iomap_finish_folio_write(struct inode *inode, struct folio *folio,
1541 		size_t len)
1542 {
1543 	struct iomap_folio_state *ifs = folio->private;
1544 
1545 	WARN_ON_ONCE(i_blocks_per_folio(inode, folio) > 1 && !ifs);
1546 	WARN_ON_ONCE(ifs && atomic_read(&ifs->write_bytes_pending) <= 0);
1547 
1548 	if (!ifs || atomic_sub_and_test(len, &ifs->write_bytes_pending))
1549 		folio_end_writeback(folio);
1550 }
1551 
1552 /*
1553  * We're now finished for good with this ioend structure.  Update the page
1554  * state, release holds on bios, and finally free up memory.  Do not use the
1555  * ioend after this.
1556  */
1557 u32 iomap_finish_ioend_buffered(struct iomap_ioend *ioend)
1558 {
1559 	struct inode *inode = ioend->io_inode;
1560 	struct bio *bio = &ioend->io_bio;
1561 	struct folio_iter fi;
1562 	u32 folio_count = 0;
1563 
1564 	if (ioend->io_error) {
1565 		mapping_set_error(inode->i_mapping, ioend->io_error);
1566 		if (!bio_flagged(bio, BIO_QUIET)) {
1567 			pr_err_ratelimited(
1568 "%s: writeback error on inode %lu, offset %lld, sector %llu",
1569 				inode->i_sb->s_id, inode->i_ino,
1570 				ioend->io_offset, ioend->io_sector);
1571 		}
1572 	}
1573 
1574 	/* walk all folios in bio, ending page IO on them */
1575 	bio_for_each_folio_all(fi, bio) {
1576 		iomap_finish_folio_write(inode, fi.folio, fi.length);
1577 		folio_count++;
1578 	}
1579 
1580 	bio_put(bio);	/* frees the ioend */
1581 	return folio_count;
1582 }
1583 
1584 static void iomap_writepage_end_bio(struct bio *bio)
1585 {
1586 	struct iomap_ioend *ioend = iomap_ioend_from_bio(bio);
1587 
1588 	ioend->io_error = blk_status_to_errno(bio->bi_status);
1589 	iomap_finish_ioend_buffered(ioend);
1590 }
1591 
1592 /*
1593  * Submit an ioend.
1594  *
1595  * If @error is non-zero, it means that we have a situation where some part of
1596  * the submission process has failed after we've marked pages for writeback.
1597  * We cannot cancel ioend directly in that case, so call the bio end I/O handler
1598  * with the error status here to run the normal I/O completion handler to clear
1599  * the writeback bit and let the file system proess the errors.
1600  */
1601 static int iomap_submit_ioend(struct iomap_writepage_ctx *wpc, int error)
1602 {
1603 	if (!wpc->ioend)
1604 		return error;
1605 
1606 	/*
1607 	 * Let the file systems prepare the I/O submission and hook in an I/O
1608 	 * comletion handler.  This also needs to happen in case after a
1609 	 * failure happened so that the file system end I/O handler gets called
1610 	 * to clean up.
1611 	 */
1612 	if (wpc->ops->submit_ioend) {
1613 		error = wpc->ops->submit_ioend(wpc, error);
1614 	} else {
1615 		if (WARN_ON_ONCE(wpc->iomap.flags & IOMAP_F_ANON_WRITE))
1616 			error = -EIO;
1617 		if (!error)
1618 			submit_bio(&wpc->ioend->io_bio);
1619 	}
1620 
1621 	if (error) {
1622 		wpc->ioend->io_bio.bi_status = errno_to_blk_status(error);
1623 		bio_endio(&wpc->ioend->io_bio);
1624 	}
1625 
1626 	wpc->ioend = NULL;
1627 	return error;
1628 }
1629 
1630 static struct iomap_ioend *iomap_alloc_ioend(struct iomap_writepage_ctx *wpc,
1631 		struct writeback_control *wbc, struct inode *inode, loff_t pos,
1632 		u16 ioend_flags)
1633 {
1634 	struct bio *bio;
1635 
1636 	bio = bio_alloc_bioset(wpc->iomap.bdev, BIO_MAX_VECS,
1637 			       REQ_OP_WRITE | wbc_to_write_flags(wbc),
1638 			       GFP_NOFS, &iomap_ioend_bioset);
1639 	bio->bi_iter.bi_sector = iomap_sector(&wpc->iomap, pos);
1640 	bio->bi_end_io = iomap_writepage_end_bio;
1641 	bio->bi_write_hint = inode->i_write_hint;
1642 	wbc_init_bio(wbc, bio);
1643 	wpc->nr_folios = 0;
1644 	return iomap_init_ioend(inode, bio, pos, ioend_flags);
1645 }
1646 
1647 static bool iomap_can_add_to_ioend(struct iomap_writepage_ctx *wpc, loff_t pos,
1648 		u16 ioend_flags)
1649 {
1650 	if (ioend_flags & IOMAP_IOEND_BOUNDARY)
1651 		return false;
1652 	if ((ioend_flags & IOMAP_IOEND_NOMERGE_FLAGS) !=
1653 	    (wpc->ioend->io_flags & IOMAP_IOEND_NOMERGE_FLAGS))
1654 		return false;
1655 	if (pos != wpc->ioend->io_offset + wpc->ioend->io_size)
1656 		return false;
1657 	if (!(wpc->iomap.flags & IOMAP_F_ANON_WRITE) &&
1658 	    iomap_sector(&wpc->iomap, pos) !=
1659 	    bio_end_sector(&wpc->ioend->io_bio))
1660 		return false;
1661 	/*
1662 	 * Limit ioend bio chain lengths to minimise IO completion latency. This
1663 	 * also prevents long tight loops ending page writeback on all the
1664 	 * folios in the ioend.
1665 	 */
1666 	if (wpc->nr_folios >= IOEND_BATCH_SIZE)
1667 		return false;
1668 	return true;
1669 }
1670 
1671 /*
1672  * Test to see if we have an existing ioend structure that we could append to
1673  * first; otherwise finish off the current ioend and start another.
1674  *
1675  * If a new ioend is created and cached, the old ioend is submitted to the block
1676  * layer instantly.  Batching optimisations are provided by higher level block
1677  * plugging.
1678  *
1679  * At the end of a writeback pass, there will be a cached ioend remaining on the
1680  * writepage context that the caller will need to submit.
1681  */
1682 static int iomap_add_to_ioend(struct iomap_writepage_ctx *wpc,
1683 		struct writeback_control *wbc, struct folio *folio,
1684 		struct inode *inode, loff_t pos, loff_t end_pos,
1685 		unsigned len)
1686 {
1687 	struct iomap_folio_state *ifs = folio->private;
1688 	size_t poff = offset_in_folio(folio, pos);
1689 	unsigned int ioend_flags = 0;
1690 	int error;
1691 
1692 	if (wpc->iomap.type == IOMAP_UNWRITTEN)
1693 		ioend_flags |= IOMAP_IOEND_UNWRITTEN;
1694 	if (wpc->iomap.flags & IOMAP_F_SHARED)
1695 		ioend_flags |= IOMAP_IOEND_SHARED;
1696 	if (folio_test_dropbehind(folio))
1697 		ioend_flags |= IOMAP_IOEND_DONTCACHE;
1698 	if (pos == wpc->iomap.offset && (wpc->iomap.flags & IOMAP_F_BOUNDARY))
1699 		ioend_flags |= IOMAP_IOEND_BOUNDARY;
1700 
1701 	if (!wpc->ioend || !iomap_can_add_to_ioend(wpc, pos, ioend_flags)) {
1702 new_ioend:
1703 		error = iomap_submit_ioend(wpc, 0);
1704 		if (error)
1705 			return error;
1706 		wpc->ioend = iomap_alloc_ioend(wpc, wbc, inode, pos,
1707 				ioend_flags);
1708 	}
1709 
1710 	if (!bio_add_folio(&wpc->ioend->io_bio, folio, len, poff))
1711 		goto new_ioend;
1712 
1713 	if (ifs)
1714 		atomic_add(len, &ifs->write_bytes_pending);
1715 
1716 	/*
1717 	 * Clamp io_offset and io_size to the incore EOF so that ondisk
1718 	 * file size updates in the ioend completion are byte-accurate.
1719 	 * This avoids recovering files with zeroed tail regions when
1720 	 * writeback races with appending writes:
1721 	 *
1722 	 *    Thread 1:                  Thread 2:
1723 	 *    ------------               -----------
1724 	 *    write [A, A+B]
1725 	 *    update inode size to A+B
1726 	 *    submit I/O [A, A+BS]
1727 	 *                               write [A+B, A+B+C]
1728 	 *                               update inode size to A+B+C
1729 	 *    <I/O completes, updates disk size to min(A+B+C, A+BS)>
1730 	 *    <power failure>
1731 	 *
1732 	 *  After reboot:
1733 	 *    1) with A+B+C < A+BS, the file has zero padding in range
1734 	 *       [A+B, A+B+C]
1735 	 *
1736 	 *    |<     Block Size (BS)   >|
1737 	 *    |DDDDDDDDDDDD0000000000000|
1738 	 *    ^           ^        ^
1739 	 *    A          A+B     A+B+C
1740 	 *                       (EOF)
1741 	 *
1742 	 *    2) with A+B+C > A+BS, the file has zero padding in range
1743 	 *       [A+B, A+BS]
1744 	 *
1745 	 *    |<     Block Size (BS)   >|<     Block Size (BS)    >|
1746 	 *    |DDDDDDDDDDDD0000000000000|00000000000000000000000000|
1747 	 *    ^           ^             ^           ^
1748 	 *    A          A+B           A+BS       A+B+C
1749 	 *                             (EOF)
1750 	 *
1751 	 *    D = Valid Data
1752 	 *    0 = Zero Padding
1753 	 *
1754 	 * Note that this defeats the ability to chain the ioends of
1755 	 * appending writes.
1756 	 */
1757 	wpc->ioend->io_size += len;
1758 	if (wpc->ioend->io_offset + wpc->ioend->io_size > end_pos)
1759 		wpc->ioend->io_size = end_pos - wpc->ioend->io_offset;
1760 
1761 	wbc_account_cgroup_owner(wbc, folio, len);
1762 	return 0;
1763 }
1764 
1765 static int iomap_writepage_map_blocks(struct iomap_writepage_ctx *wpc,
1766 		struct writeback_control *wbc, struct folio *folio,
1767 		struct inode *inode, u64 pos, u64 end_pos,
1768 		unsigned dirty_len, unsigned *count)
1769 {
1770 	int error;
1771 
1772 	do {
1773 		unsigned map_len;
1774 
1775 		error = wpc->ops->map_blocks(wpc, inode, pos, dirty_len);
1776 		if (error)
1777 			break;
1778 		trace_iomap_writepage_map(inode, pos, dirty_len, &wpc->iomap);
1779 
1780 		map_len = min_t(u64, dirty_len,
1781 			wpc->iomap.offset + wpc->iomap.length - pos);
1782 		WARN_ON_ONCE(!folio->private && map_len < dirty_len);
1783 
1784 		switch (wpc->iomap.type) {
1785 		case IOMAP_INLINE:
1786 			WARN_ON_ONCE(1);
1787 			error = -EIO;
1788 			break;
1789 		case IOMAP_HOLE:
1790 			break;
1791 		default:
1792 			error = iomap_add_to_ioend(wpc, wbc, folio, inode, pos,
1793 					end_pos, map_len);
1794 			if (!error)
1795 				(*count)++;
1796 			break;
1797 		}
1798 		dirty_len -= map_len;
1799 		pos += map_len;
1800 	} while (dirty_len && !error);
1801 
1802 	/*
1803 	 * We cannot cancel the ioend directly here on error.  We may have
1804 	 * already set other pages under writeback and hence we have to run I/O
1805 	 * completion to mark the error state of the pages under writeback
1806 	 * appropriately.
1807 	 *
1808 	 * Just let the file system know what portion of the folio failed to
1809 	 * map.
1810 	 */
1811 	if (error && wpc->ops->discard_folio)
1812 		wpc->ops->discard_folio(folio, pos);
1813 	return error;
1814 }
1815 
1816 /*
1817  * Check interaction of the folio with the file end.
1818  *
1819  * If the folio is entirely beyond i_size, return false.  If it straddles
1820  * i_size, adjust end_pos and zero all data beyond i_size.
1821  */
1822 static bool iomap_writepage_handle_eof(struct folio *folio, struct inode *inode,
1823 		u64 *end_pos)
1824 {
1825 	u64 isize = i_size_read(inode);
1826 
1827 	if (*end_pos > isize) {
1828 		size_t poff = offset_in_folio(folio, isize);
1829 		pgoff_t end_index = isize >> PAGE_SHIFT;
1830 
1831 		/*
1832 		 * If the folio is entirely ouside of i_size, skip it.
1833 		 *
1834 		 * This can happen due to a truncate operation that is in
1835 		 * progress and in that case truncate will finish it off once
1836 		 * we've dropped the folio lock.
1837 		 *
1838 		 * Note that the pgoff_t used for end_index is an unsigned long.
1839 		 * If the given offset is greater than 16TB on a 32-bit system,
1840 		 * then if we checked if the folio is fully outside i_size with
1841 		 * "if (folio->index >= end_index + 1)", "end_index + 1" would
1842 		 * overflow and evaluate to 0.  Hence this folio would be
1843 		 * redirtied and written out repeatedly, which would result in
1844 		 * an infinite loop; the user program performing this operation
1845 		 * would hang.  Instead, we can detect this situation by
1846 		 * checking if the folio is totally beyond i_size or if its
1847 		 * offset is just equal to the EOF.
1848 		 */
1849 		if (folio->index > end_index ||
1850 		    (folio->index == end_index && poff == 0))
1851 			return false;
1852 
1853 		/*
1854 		 * The folio straddles i_size.
1855 		 *
1856 		 * It must be zeroed out on each and every writepage invocation
1857 		 * because it may be mmapped:
1858 		 *
1859 		 *    A file is mapped in multiples of the page size.  For a
1860 		 *    file that is not a multiple of the page size, the
1861 		 *    remaining memory is zeroed when mapped, and writes to that
1862 		 *    region are not written out to the file.
1863 		 *
1864 		 * Also adjust the end_pos to the end of file and skip writeback
1865 		 * for all blocks entirely beyond i_size.
1866 		 */
1867 		folio_zero_segment(folio, poff, folio_size(folio));
1868 		*end_pos = isize;
1869 	}
1870 
1871 	return true;
1872 }
1873 
1874 static int iomap_writepage_map(struct iomap_writepage_ctx *wpc,
1875 		struct writeback_control *wbc, struct folio *folio)
1876 {
1877 	struct iomap_folio_state *ifs = folio->private;
1878 	struct inode *inode = folio->mapping->host;
1879 	u64 pos = folio_pos(folio);
1880 	u64 end_pos = pos + folio_size(folio);
1881 	u64 end_aligned = 0;
1882 	unsigned count = 0;
1883 	int error = 0;
1884 	u32 rlen;
1885 
1886 	WARN_ON_ONCE(!folio_test_locked(folio));
1887 	WARN_ON_ONCE(folio_test_dirty(folio));
1888 	WARN_ON_ONCE(folio_test_writeback(folio));
1889 
1890 	trace_iomap_writepage(inode, pos, folio_size(folio));
1891 
1892 	if (!iomap_writepage_handle_eof(folio, inode, &end_pos)) {
1893 		folio_unlock(folio);
1894 		return 0;
1895 	}
1896 	WARN_ON_ONCE(end_pos <= pos);
1897 
1898 	if (i_blocks_per_folio(inode, folio) > 1) {
1899 		if (!ifs) {
1900 			ifs = ifs_alloc(inode, folio, 0);
1901 			iomap_set_range_dirty(folio, 0, end_pos - pos);
1902 		}
1903 
1904 		/*
1905 		 * Keep the I/O completion handler from clearing the writeback
1906 		 * bit until we have submitted all blocks by adding a bias to
1907 		 * ifs->write_bytes_pending, which is dropped after submitting
1908 		 * all blocks.
1909 		 */
1910 		WARN_ON_ONCE(atomic_read(&ifs->write_bytes_pending) != 0);
1911 		atomic_inc(&ifs->write_bytes_pending);
1912 	}
1913 
1914 	/*
1915 	 * Set the writeback bit ASAP, as the I/O completion for the single
1916 	 * block per folio case happen hit as soon as we're submitting the bio.
1917 	 */
1918 	folio_start_writeback(folio);
1919 
1920 	/*
1921 	 * Walk through the folio to find dirty areas to write back.
1922 	 */
1923 	end_aligned = round_up(end_pos, i_blocksize(inode));
1924 	while ((rlen = iomap_find_dirty_range(folio, &pos, end_aligned))) {
1925 		error = iomap_writepage_map_blocks(wpc, wbc, folio, inode,
1926 				pos, end_pos, rlen, &count);
1927 		if (error)
1928 			break;
1929 		pos += rlen;
1930 	}
1931 
1932 	if (count)
1933 		wpc->nr_folios++;
1934 
1935 	/*
1936 	 * We can have dirty bits set past end of file in page_mkwrite path
1937 	 * while mapping the last partial folio. Hence it's better to clear
1938 	 * all the dirty bits in the folio here.
1939 	 */
1940 	iomap_clear_range_dirty(folio, 0, folio_size(folio));
1941 
1942 	/*
1943 	 * Usually the writeback bit is cleared by the I/O completion handler.
1944 	 * But we may end up either not actually writing any blocks, or (when
1945 	 * there are multiple blocks in a folio) all I/O might have finished
1946 	 * already at this point.  In that case we need to clear the writeback
1947 	 * bit ourselves right after unlocking the page.
1948 	 */
1949 	folio_unlock(folio);
1950 	if (ifs) {
1951 		if (atomic_dec_and_test(&ifs->write_bytes_pending))
1952 			folio_end_writeback(folio);
1953 	} else {
1954 		if (!count)
1955 			folio_end_writeback(folio);
1956 	}
1957 	mapping_set_error(inode->i_mapping, error);
1958 	return error;
1959 }
1960 
1961 int
1962 iomap_writepages(struct address_space *mapping, struct writeback_control *wbc,
1963 		struct iomap_writepage_ctx *wpc,
1964 		const struct iomap_writeback_ops *ops)
1965 {
1966 	struct folio *folio = NULL;
1967 	int error;
1968 
1969 	/*
1970 	 * Writeback from reclaim context should never happen except in the case
1971 	 * of a VM regression so warn about it and refuse to write the data.
1972 	 */
1973 	if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC | PF_KSWAPD)) ==
1974 			PF_MEMALLOC))
1975 		return -EIO;
1976 
1977 	wpc->ops = ops;
1978 	while ((folio = writeback_iter(mapping, wbc, folio, &error)))
1979 		error = iomap_writepage_map(wpc, wbc, folio);
1980 	return iomap_submit_ioend(wpc, error);
1981 }
1982 EXPORT_SYMBOL_GPL(iomap_writepages);
1983