OSDN Git Service

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