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