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