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