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