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