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