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