Merge tag 'sound-4.20-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/tiwai...
[sfrench/cifs-2.6.git] / fs / iomap.c
1 /*
2  * Copyright (C) 2010 Red Hat, Inc.
3  * Copyright (c) 2016-2018 Christoph Hellwig.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14 #include <linux/module.h>
15 #include <linux/compiler.h>
16 #include <linux/fs.h>
17 #include <linux/iomap.h>
18 #include <linux/uaccess.h>
19 #include <linux/gfp.h>
20 #include <linux/migrate.h>
21 #include <linux/mm.h>
22 #include <linux/mm_inline.h>
23 #include <linux/swap.h>
24 #include <linux/pagemap.h>
25 #include <linux/pagevec.h>
26 #include <linux/file.h>
27 #include <linux/uio.h>
28 #include <linux/backing-dev.h>
29 #include <linux/buffer_head.h>
30 #include <linux/task_io_accounting_ops.h>
31 #include <linux/dax.h>
32 #include <linux/sched/signal.h>
33
34 #include "internal.h"
35
36 /*
37  * Execute a iomap write on a segment of the mapping that spans a
38  * contiguous range of pages that have identical block mapping state.
39  *
40  * This avoids the need to map pages individually, do individual allocations
41  * for each page and most importantly avoid the need for filesystem specific
42  * locking per page. Instead, all the operations are amortised over the entire
43  * range of pages. It is assumed that the filesystems will lock whatever
44  * resources they require in the iomap_begin call, and release them in the
45  * iomap_end call.
46  */
47 loff_t
48 iomap_apply(struct inode *inode, loff_t pos, loff_t length, unsigned flags,
49                 const struct iomap_ops *ops, void *data, iomap_actor_t actor)
50 {
51         struct iomap iomap = { 0 };
52         loff_t written = 0, ret;
53
54         /*
55          * Need to map a range from start position for length bytes. This can
56          * span multiple pages - it is only guaranteed to return a range of a
57          * single type of pages (e.g. all into a hole, all mapped or all
58          * unwritten). Failure at this point has nothing to undo.
59          *
60          * If allocation is required for this range, reserve the space now so
61          * that the allocation is guaranteed to succeed later on. Once we copy
62          * the data into the page cache pages, then we cannot fail otherwise we
63          * expose transient stale data. If the reserve fails, we can safely
64          * back out at this point as there is nothing to undo.
65          */
66         ret = ops->iomap_begin(inode, pos, length, flags, &iomap);
67         if (ret)
68                 return ret;
69         if (WARN_ON(iomap.offset > pos))
70                 return -EIO;
71         if (WARN_ON(iomap.length == 0))
72                 return -EIO;
73
74         /*
75          * Cut down the length to the one actually provided by the filesystem,
76          * as it might not be able to give us the whole size that we requested.
77          */
78         if (iomap.offset + iomap.length < pos + length)
79                 length = iomap.offset + iomap.length - pos;
80
81         /*
82          * Now that we have guaranteed that the space allocation will succeed.
83          * we can do the copy-in page by page without having to worry about
84          * failures exposing transient data.
85          */
86         written = actor(inode, pos, length, data, &iomap);
87
88         /*
89          * Now the data has been copied, commit the range we've copied.  This
90          * should not fail unless the filesystem has had a fatal error.
91          */
92         if (ops->iomap_end) {
93                 ret = ops->iomap_end(inode, pos, length,
94                                      written > 0 ? written : 0,
95                                      flags, &iomap);
96         }
97
98         return written ? written : ret;
99 }
100
101 static sector_t
102 iomap_sector(struct iomap *iomap, loff_t pos)
103 {
104         return (iomap->addr + pos - iomap->offset) >> SECTOR_SHIFT;
105 }
106
107 static struct iomap_page *
108 iomap_page_create(struct inode *inode, struct page *page)
109 {
110         struct iomap_page *iop = to_iomap_page(page);
111
112         if (iop || i_blocksize(inode) == PAGE_SIZE)
113                 return iop;
114
115         iop = kmalloc(sizeof(*iop), GFP_NOFS | __GFP_NOFAIL);
116         atomic_set(&iop->read_count, 0);
117         atomic_set(&iop->write_count, 0);
118         bitmap_zero(iop->uptodate, PAGE_SIZE / SECTOR_SIZE);
119         set_page_private(page, (unsigned long)iop);
120         SetPagePrivate(page);
121         return iop;
122 }
123
124 static void
125 iomap_page_release(struct page *page)
126 {
127         struct iomap_page *iop = to_iomap_page(page);
128
129         if (!iop)
130                 return;
131         WARN_ON_ONCE(atomic_read(&iop->read_count));
132         WARN_ON_ONCE(atomic_read(&iop->write_count));
133         ClearPagePrivate(page);
134         set_page_private(page, 0);
135         kfree(iop);
136 }
137
138 /*
139  * Calculate the range inside the page that we actually need to read.
140  */
141 static void
142 iomap_adjust_read_range(struct inode *inode, struct iomap_page *iop,
143                 loff_t *pos, loff_t length, unsigned *offp, unsigned *lenp)
144 {
145         loff_t orig_pos = *pos;
146         loff_t isize = i_size_read(inode);
147         unsigned block_bits = inode->i_blkbits;
148         unsigned block_size = (1 << block_bits);
149         unsigned poff = offset_in_page(*pos);
150         unsigned plen = min_t(loff_t, PAGE_SIZE - poff, length);
151         unsigned first = poff >> block_bits;
152         unsigned last = (poff + plen - 1) >> block_bits;
153
154         /*
155          * If the block size is smaller than the page size we need to check the
156          * per-block uptodate status and adjust the offset and length if needed
157          * to avoid reading in already uptodate ranges.
158          */
159         if (iop) {
160                 unsigned int i;
161
162                 /* move forward for each leading block marked uptodate */
163                 for (i = first; i <= last; i++) {
164                         if (!test_bit(i, iop->uptodate))
165                                 break;
166                         *pos += block_size;
167                         poff += block_size;
168                         plen -= block_size;
169                         first++;
170                 }
171
172                 /* truncate len if we find any trailing uptodate block(s) */
173                 for ( ; i <= last; i++) {
174                         if (test_bit(i, iop->uptodate)) {
175                                 plen -= (last - i + 1) * block_size;
176                                 last = i - 1;
177                                 break;
178                         }
179                 }
180         }
181
182         /*
183          * If the extent spans the block that contains the i_size we need to
184          * handle both halves separately so that we properly zero data in the
185          * page cache for blocks that are entirely outside of i_size.
186          */
187         if (orig_pos <= isize && orig_pos + length > isize) {
188                 unsigned end = offset_in_page(isize - 1) >> block_bits;
189
190                 if (first <= end && last > end)
191                         plen -= (last - end) * block_size;
192         }
193
194         *offp = poff;
195         *lenp = plen;
196 }
197
198 static void
199 iomap_set_range_uptodate(struct page *page, unsigned off, unsigned len)
200 {
201         struct iomap_page *iop = to_iomap_page(page);
202         struct inode *inode = page->mapping->host;
203         unsigned first = off >> inode->i_blkbits;
204         unsigned last = (off + len - 1) >> inode->i_blkbits;
205         unsigned int i;
206         bool uptodate = true;
207
208         if (iop) {
209                 for (i = 0; i < PAGE_SIZE / i_blocksize(inode); i++) {
210                         if (i >= first && i <= last)
211                                 set_bit(i, iop->uptodate);
212                         else if (!test_bit(i, iop->uptodate))
213                                 uptodate = false;
214                 }
215         }
216
217         if (uptodate && !PageError(page))
218                 SetPageUptodate(page);
219 }
220
221 static void
222 iomap_read_finish(struct iomap_page *iop, struct page *page)
223 {
224         if (!iop || atomic_dec_and_test(&iop->read_count))
225                 unlock_page(page);
226 }
227
228 static void
229 iomap_read_page_end_io(struct bio_vec *bvec, int error)
230 {
231         struct page *page = bvec->bv_page;
232         struct iomap_page *iop = to_iomap_page(page);
233
234         if (unlikely(error)) {
235                 ClearPageUptodate(page);
236                 SetPageError(page);
237         } else {
238                 iomap_set_range_uptodate(page, bvec->bv_offset, bvec->bv_len);
239         }
240
241         iomap_read_finish(iop, page);
242 }
243
244 static void
245 iomap_read_inline_data(struct inode *inode, struct page *page,
246                 struct iomap *iomap)
247 {
248         size_t size = i_size_read(inode);
249         void *addr;
250
251         if (PageUptodate(page))
252                 return;
253
254         BUG_ON(page->index);
255         BUG_ON(size > PAGE_SIZE - offset_in_page(iomap->inline_data));
256
257         addr = kmap_atomic(page);
258         memcpy(addr, iomap->inline_data, size);
259         memset(addr + size, 0, PAGE_SIZE - size);
260         kunmap_atomic(addr);
261         SetPageUptodate(page);
262 }
263
264 static void
265 iomap_read_end_io(struct bio *bio)
266 {
267         int error = blk_status_to_errno(bio->bi_status);
268         struct bio_vec *bvec;
269         int i;
270
271         bio_for_each_segment_all(bvec, bio, i)
272                 iomap_read_page_end_io(bvec, error);
273         bio_put(bio);
274 }
275
276 struct iomap_readpage_ctx {
277         struct page             *cur_page;
278         bool                    cur_page_in_bio;
279         bool                    is_readahead;
280         struct bio              *bio;
281         struct list_head        *pages;
282 };
283
284 static loff_t
285 iomap_readpage_actor(struct inode *inode, loff_t pos, loff_t length, void *data,
286                 struct iomap *iomap)
287 {
288         struct iomap_readpage_ctx *ctx = data;
289         struct page *page = ctx->cur_page;
290         struct iomap_page *iop = iomap_page_create(inode, page);
291         bool is_contig = false;
292         loff_t orig_pos = pos;
293         unsigned poff, plen;
294         sector_t sector;
295
296         if (iomap->type == IOMAP_INLINE) {
297                 WARN_ON_ONCE(pos);
298                 iomap_read_inline_data(inode, page, iomap);
299                 return PAGE_SIZE;
300         }
301
302         /* zero post-eof blocks as the page may be mapped */
303         iomap_adjust_read_range(inode, iop, &pos, length, &poff, &plen);
304         if (plen == 0)
305                 goto done;
306
307         if (iomap->type != IOMAP_MAPPED || pos >= i_size_read(inode)) {
308                 zero_user(page, poff, plen);
309                 iomap_set_range_uptodate(page, poff, plen);
310                 goto done;
311         }
312
313         ctx->cur_page_in_bio = true;
314
315         /*
316          * Try to merge into a previous segment if we can.
317          */
318         sector = iomap_sector(iomap, pos);
319         if (ctx->bio && bio_end_sector(ctx->bio) == sector) {
320                 if (__bio_try_merge_page(ctx->bio, page, plen, poff))
321                         goto done;
322                 is_contig = true;
323         }
324
325         /*
326          * If we start a new segment we need to increase the read count, and we
327          * need to do so before submitting any previous full bio to make sure
328          * that we don't prematurely unlock the page.
329          */
330         if (iop)
331                 atomic_inc(&iop->read_count);
332
333         if (!ctx->bio || !is_contig || bio_full(ctx->bio)) {
334                 gfp_t gfp = mapping_gfp_constraint(page->mapping, GFP_KERNEL);
335                 int nr_vecs = (length + PAGE_SIZE - 1) >> PAGE_SHIFT;
336
337                 if (ctx->bio)
338                         submit_bio(ctx->bio);
339
340                 if (ctx->is_readahead) /* same as readahead_gfp_mask */
341                         gfp |= __GFP_NORETRY | __GFP_NOWARN;
342                 ctx->bio = bio_alloc(gfp, min(BIO_MAX_PAGES, nr_vecs));
343                 ctx->bio->bi_opf = REQ_OP_READ;
344                 if (ctx->is_readahead)
345                         ctx->bio->bi_opf |= REQ_RAHEAD;
346                 ctx->bio->bi_iter.bi_sector = sector;
347                 bio_set_dev(ctx->bio, iomap->bdev);
348                 ctx->bio->bi_end_io = iomap_read_end_io;
349         }
350
351         __bio_add_page(ctx->bio, page, plen, poff);
352 done:
353         /*
354          * Move the caller beyond our range so that it keeps making progress.
355          * For that we have to include any leading non-uptodate ranges, but
356          * we can skip trailing ones as they will be handled in the next
357          * iteration.
358          */
359         return pos - orig_pos + plen;
360 }
361
362 int
363 iomap_readpage(struct page *page, const struct iomap_ops *ops)
364 {
365         struct iomap_readpage_ctx ctx = { .cur_page = page };
366         struct inode *inode = page->mapping->host;
367         unsigned poff;
368         loff_t ret;
369
370         for (poff = 0; poff < PAGE_SIZE; poff += ret) {
371                 ret = iomap_apply(inode, page_offset(page) + poff,
372                                 PAGE_SIZE - poff, 0, ops, &ctx,
373                                 iomap_readpage_actor);
374                 if (ret <= 0) {
375                         WARN_ON_ONCE(ret == 0);
376                         SetPageError(page);
377                         break;
378                 }
379         }
380
381         if (ctx.bio) {
382                 submit_bio(ctx.bio);
383                 WARN_ON_ONCE(!ctx.cur_page_in_bio);
384         } else {
385                 WARN_ON_ONCE(ctx.cur_page_in_bio);
386                 unlock_page(page);
387         }
388
389         /*
390          * Just like mpage_readpages and block_read_full_page we always
391          * return 0 and just mark the page as PageError on errors.  This
392          * should be cleaned up all through the stack eventually.
393          */
394         return 0;
395 }
396 EXPORT_SYMBOL_GPL(iomap_readpage);
397
398 static struct page *
399 iomap_next_page(struct inode *inode, struct list_head *pages, loff_t pos,
400                 loff_t length, loff_t *done)
401 {
402         while (!list_empty(pages)) {
403                 struct page *page = lru_to_page(pages);
404
405                 if (page_offset(page) >= (u64)pos + length)
406                         break;
407
408                 list_del(&page->lru);
409                 if (!add_to_page_cache_lru(page, inode->i_mapping, page->index,
410                                 GFP_NOFS))
411                         return page;
412
413                 /*
414                  * If we already have a page in the page cache at index we are
415                  * done.  Upper layers don't care if it is uptodate after the
416                  * readpages call itself as every page gets checked again once
417                  * actually needed.
418                  */
419                 *done += PAGE_SIZE;
420                 put_page(page);
421         }
422
423         return NULL;
424 }
425
426 static loff_t
427 iomap_readpages_actor(struct inode *inode, loff_t pos, loff_t length,
428                 void *data, struct iomap *iomap)
429 {
430         struct iomap_readpage_ctx *ctx = data;
431         loff_t done, ret;
432
433         for (done = 0; done < length; done += ret) {
434                 if (ctx->cur_page && offset_in_page(pos + done) == 0) {
435                         if (!ctx->cur_page_in_bio)
436                                 unlock_page(ctx->cur_page);
437                         put_page(ctx->cur_page);
438                         ctx->cur_page = NULL;
439                 }
440                 if (!ctx->cur_page) {
441                         ctx->cur_page = iomap_next_page(inode, ctx->pages,
442                                         pos, length, &done);
443                         if (!ctx->cur_page)
444                                 break;
445                         ctx->cur_page_in_bio = false;
446                 }
447                 ret = iomap_readpage_actor(inode, pos + done, length - done,
448                                 ctx, iomap);
449         }
450
451         return done;
452 }
453
454 int
455 iomap_readpages(struct address_space *mapping, struct list_head *pages,
456                 unsigned nr_pages, const struct iomap_ops *ops)
457 {
458         struct iomap_readpage_ctx ctx = {
459                 .pages          = pages,
460                 .is_readahead   = true,
461         };
462         loff_t pos = page_offset(list_entry(pages->prev, struct page, lru));
463         loff_t last = page_offset(list_entry(pages->next, struct page, lru));
464         loff_t length = last - pos + PAGE_SIZE, ret = 0;
465
466         while (length > 0) {
467                 ret = iomap_apply(mapping->host, pos, length, 0, ops,
468                                 &ctx, iomap_readpages_actor);
469                 if (ret <= 0) {
470                         WARN_ON_ONCE(ret == 0);
471                         goto done;
472                 }
473                 pos += ret;
474                 length -= ret;
475         }
476         ret = 0;
477 done:
478         if (ctx.bio)
479                 submit_bio(ctx.bio);
480         if (ctx.cur_page) {
481                 if (!ctx.cur_page_in_bio)
482                         unlock_page(ctx.cur_page);
483                 put_page(ctx.cur_page);
484         }
485
486         /*
487          * Check that we didn't lose a page due to the arcance calling
488          * conventions..
489          */
490         WARN_ON_ONCE(!ret && !list_empty(ctx.pages));
491         return ret;
492 }
493 EXPORT_SYMBOL_GPL(iomap_readpages);
494
495 int
496 iomap_is_partially_uptodate(struct page *page, unsigned long from,
497                 unsigned long count)
498 {
499         struct iomap_page *iop = to_iomap_page(page);
500         struct inode *inode = page->mapping->host;
501         unsigned first = from >> inode->i_blkbits;
502         unsigned last = (from + count - 1) >> inode->i_blkbits;
503         unsigned i;
504
505         if (iop) {
506                 for (i = first; i <= last; i++)
507                         if (!test_bit(i, iop->uptodate))
508                                 return 0;
509                 return 1;
510         }
511
512         return 0;
513 }
514 EXPORT_SYMBOL_GPL(iomap_is_partially_uptodate);
515
516 int
517 iomap_releasepage(struct page *page, gfp_t gfp_mask)
518 {
519         /*
520          * mm accommodates an old ext3 case where clean pages might not have had
521          * the dirty bit cleared. Thus, it can send actual dirty pages to
522          * ->releasepage() via shrink_active_list(), skip those here.
523          */
524         if (PageDirty(page) || PageWriteback(page))
525                 return 0;
526         iomap_page_release(page);
527         return 1;
528 }
529 EXPORT_SYMBOL_GPL(iomap_releasepage);
530
531 void
532 iomap_invalidatepage(struct page *page, unsigned int offset, unsigned int 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, NULL, mode, 0);
554         if (ret != MIGRATEPAGE_SUCCESS)
555                 return ret;
556
557         if (page_has_private(page)) {
558                 ClearPagePrivate(page);
559                 set_page_private(newpage, page_private(page));
560                 set_page_private(page, 0);
561                 SetPagePrivate(newpage);
562         }
563
564         if (mode != MIGRATE_SYNC_NO_COPY)
565                 migrate_page_copy(newpage, page);
566         else
567                 migrate_page_states(newpage, page);
568         return MIGRATEPAGE_SUCCESS;
569 }
570 EXPORT_SYMBOL_GPL(iomap_migrate_page);
571 #endif /* CONFIG_MIGRATION */
572
573 static void
574 iomap_write_failed(struct inode *inode, loff_t pos, unsigned len)
575 {
576         loff_t i_size = i_size_read(inode);
577
578         /*
579          * Only truncate newly allocated pages beyoned EOF, even if the
580          * write started inside the existing inode size.
581          */
582         if (pos + len > i_size)
583                 truncate_pagecache_range(inode, max(pos, i_size), pos + len);
584 }
585
586 static int
587 iomap_read_page_sync(struct inode *inode, loff_t block_start, struct page *page,
588                 unsigned poff, unsigned plen, unsigned from, unsigned to,
589                 struct iomap *iomap)
590 {
591         struct bio_vec bvec;
592         struct bio bio;
593
594         if (iomap->type != IOMAP_MAPPED || block_start >= i_size_read(inode)) {
595                 zero_user_segments(page, poff, from, to, poff + plen);
596                 iomap_set_range_uptodate(page, poff, plen);
597                 return 0;
598         }
599
600         bio_init(&bio, &bvec, 1);
601         bio.bi_opf = REQ_OP_READ;
602         bio.bi_iter.bi_sector = iomap_sector(iomap, block_start);
603         bio_set_dev(&bio, iomap->bdev);
604         __bio_add_page(&bio, page, plen, poff);
605         return submit_bio_wait(&bio);
606 }
607
608 static int
609 __iomap_write_begin(struct inode *inode, loff_t pos, unsigned len,
610                 struct page *page, struct iomap *iomap)
611 {
612         struct iomap_page *iop = iomap_page_create(inode, page);
613         loff_t block_size = i_blocksize(inode);
614         loff_t block_start = pos & ~(block_size - 1);
615         loff_t block_end = (pos + len + block_size - 1) & ~(block_size - 1);
616         unsigned from = offset_in_page(pos), to = from + len, poff, plen;
617         int status = 0;
618
619         if (PageUptodate(page))
620                 return 0;
621
622         do {
623                 iomap_adjust_read_range(inode, iop, &block_start,
624                                 block_end - block_start, &poff, &plen);
625                 if (plen == 0)
626                         break;
627
628                 if ((from > poff && from < poff + plen) ||
629                     (to > poff && to < poff + plen)) {
630                         status = iomap_read_page_sync(inode, block_start, page,
631                                         poff, plen, from, to, iomap);
632                         if (status)
633                                 break;
634                 }
635
636         } while ((block_start += plen) < block_end);
637
638         return status;
639 }
640
641 static int
642 iomap_write_begin(struct inode *inode, loff_t pos, unsigned len, unsigned flags,
643                 struct page **pagep, struct iomap *iomap)
644 {
645         pgoff_t index = pos >> PAGE_SHIFT;
646         struct page *page;
647         int status = 0;
648
649         BUG_ON(pos + len > iomap->offset + iomap->length);
650
651         if (fatal_signal_pending(current))
652                 return -EINTR;
653
654         page = grab_cache_page_write_begin(inode->i_mapping, index, flags);
655         if (!page)
656                 return -ENOMEM;
657
658         if (iomap->type == IOMAP_INLINE)
659                 iomap_read_inline_data(inode, page, iomap);
660         else if (iomap->flags & IOMAP_F_BUFFER_HEAD)
661                 status = __block_write_begin_int(page, pos, len, NULL, iomap);
662         else
663                 status = __iomap_write_begin(inode, pos, len, page, iomap);
664         if (unlikely(status)) {
665                 unlock_page(page);
666                 put_page(page);
667                 page = NULL;
668
669                 iomap_write_failed(inode, pos, len);
670         }
671
672         *pagep = page;
673         return status;
674 }
675
676 int
677 iomap_set_page_dirty(struct page *page)
678 {
679         struct address_space *mapping = page_mapping(page);
680         int newly_dirty;
681
682         if (unlikely(!mapping))
683                 return !TestSetPageDirty(page);
684
685         /*
686          * Lock out page->mem_cgroup migration to keep PageDirty
687          * synchronized with per-memcg dirty page counters.
688          */
689         lock_page_memcg(page);
690         newly_dirty = !TestSetPageDirty(page);
691         if (newly_dirty)
692                 __set_page_dirty(page, mapping, 0);
693         unlock_page_memcg(page);
694
695         if (newly_dirty)
696                 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
697         return newly_dirty;
698 }
699 EXPORT_SYMBOL_GPL(iomap_set_page_dirty);
700
701 static int
702 __iomap_write_end(struct inode *inode, loff_t pos, unsigned len,
703                 unsigned copied, struct page *page, struct iomap *iomap)
704 {
705         flush_dcache_page(page);
706
707         /*
708          * The blocks that were entirely written will now be uptodate, so we
709          * don't have to worry about a readpage reading them and overwriting a
710          * partial write.  However if we have encountered a short write and only
711          * partially written into a block, it will not be marked uptodate, so a
712          * readpage might come in and destroy our partial write.
713          *
714          * Do the simplest thing, and just treat any short write to a non
715          * uptodate page as a zero-length write, and force the caller to redo
716          * the whole thing.
717          */
718         if (unlikely(copied < len && !PageUptodate(page))) {
719                 copied = 0;
720         } else {
721                 iomap_set_range_uptodate(page, offset_in_page(pos), len);
722                 iomap_set_page_dirty(page);
723         }
724         return __generic_write_end(inode, pos, copied, page);
725 }
726
727 static int
728 iomap_write_end_inline(struct inode *inode, struct page *page,
729                 struct iomap *iomap, loff_t pos, unsigned copied)
730 {
731         void *addr;
732
733         WARN_ON_ONCE(!PageUptodate(page));
734         BUG_ON(pos + copied > PAGE_SIZE - offset_in_page(iomap->inline_data));
735
736         addr = kmap_atomic(page);
737         memcpy(iomap->inline_data + pos, addr + pos, copied);
738         kunmap_atomic(addr);
739
740         mark_inode_dirty(inode);
741         __generic_write_end(inode, pos, copied, page);
742         return copied;
743 }
744
745 static int
746 iomap_write_end(struct inode *inode, loff_t pos, unsigned len,
747                 unsigned copied, struct page *page, struct iomap *iomap)
748 {
749         int ret;
750
751         if (iomap->type == IOMAP_INLINE) {
752                 ret = iomap_write_end_inline(inode, page, iomap, pos, copied);
753         } else if (iomap->flags & IOMAP_F_BUFFER_HEAD) {
754                 ret = generic_write_end(NULL, inode->i_mapping, pos, len,
755                                 copied, page, NULL);
756         } else {
757                 ret = __iomap_write_end(inode, pos, len, copied, page, iomap);
758         }
759
760         if (iomap->page_done)
761                 iomap->page_done(inode, pos, copied, page, iomap);
762
763         if (ret < len)
764                 iomap_write_failed(inode, pos, len);
765         return ret;
766 }
767
768 static loff_t
769 iomap_write_actor(struct inode *inode, loff_t pos, loff_t length, void *data,
770                 struct iomap *iomap)
771 {
772         struct iov_iter *i = data;
773         long status = 0;
774         ssize_t written = 0;
775         unsigned int flags = AOP_FLAG_NOFS;
776
777         do {
778                 struct page *page;
779                 unsigned long offset;   /* Offset into pagecache page */
780                 unsigned long bytes;    /* Bytes to write to page */
781                 size_t copied;          /* Bytes copied from user */
782
783                 offset = offset_in_page(pos);
784                 bytes = min_t(unsigned long, PAGE_SIZE - offset,
785                                                 iov_iter_count(i));
786 again:
787                 if (bytes > length)
788                         bytes = length;
789
790                 /*
791                  * Bring in the user page that we will copy from _first_.
792                  * Otherwise there's a nasty deadlock on copying from the
793                  * same page as we're writing to, without it being marked
794                  * up-to-date.
795                  *
796                  * Not only is this an optimisation, but it is also required
797                  * to check that the address is actually valid, when atomic
798                  * usercopies are used, below.
799                  */
800                 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
801                         status = -EFAULT;
802                         break;
803                 }
804
805                 status = iomap_write_begin(inode, pos, bytes, flags, &page,
806                                 iomap);
807                 if (unlikely(status))
808                         break;
809
810                 if (mapping_writably_mapped(inode->i_mapping))
811                         flush_dcache_page(page);
812
813                 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
814
815                 flush_dcache_page(page);
816
817                 status = iomap_write_end(inode, pos, bytes, copied, page,
818                                 iomap);
819                 if (unlikely(status < 0))
820                         break;
821                 copied = status;
822
823                 cond_resched();
824
825                 iov_iter_advance(i, copied);
826                 if (unlikely(copied == 0)) {
827                         /*
828                          * If we were unable to copy any data at all, we must
829                          * fall back to a single segment length write.
830                          *
831                          * If we didn't fallback here, we could livelock
832                          * because not all segments in the iov can be copied at
833                          * once without a pagefault.
834                          */
835                         bytes = min_t(unsigned long, PAGE_SIZE - offset,
836                                                 iov_iter_single_seg_count(i));
837                         goto again;
838                 }
839                 pos += copied;
840                 written += copied;
841                 length -= copied;
842
843                 balance_dirty_pages_ratelimited(inode->i_mapping);
844         } while (iov_iter_count(i) && length);
845
846         return written ? written : status;
847 }
848
849 ssize_t
850 iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *iter,
851                 const struct iomap_ops *ops)
852 {
853         struct inode *inode = iocb->ki_filp->f_mapping->host;
854         loff_t pos = iocb->ki_pos, ret = 0, written = 0;
855
856         while (iov_iter_count(iter)) {
857                 ret = iomap_apply(inode, pos, iov_iter_count(iter),
858                                 IOMAP_WRITE, ops, iter, iomap_write_actor);
859                 if (ret <= 0)
860                         break;
861                 pos += ret;
862                 written += ret;
863         }
864
865         return written ? written : ret;
866 }
867 EXPORT_SYMBOL_GPL(iomap_file_buffered_write);
868
869 static struct page *
870 __iomap_read_page(struct inode *inode, loff_t offset)
871 {
872         struct address_space *mapping = inode->i_mapping;
873         struct page *page;
874
875         page = read_mapping_page(mapping, offset >> PAGE_SHIFT, NULL);
876         if (IS_ERR(page))
877                 return page;
878         if (!PageUptodate(page)) {
879                 put_page(page);
880                 return ERR_PTR(-EIO);
881         }
882         return page;
883 }
884
885 static loff_t
886 iomap_dirty_actor(struct inode *inode, loff_t pos, loff_t length, void *data,
887                 struct iomap *iomap)
888 {
889         long status = 0;
890         ssize_t written = 0;
891
892         do {
893                 struct page *page, *rpage;
894                 unsigned long offset;   /* Offset into pagecache page */
895                 unsigned long bytes;    /* Bytes to write to page */
896
897                 offset = offset_in_page(pos);
898                 bytes = min_t(loff_t, PAGE_SIZE - offset, length);
899
900                 rpage = __iomap_read_page(inode, pos);
901                 if (IS_ERR(rpage))
902                         return PTR_ERR(rpage);
903
904                 status = iomap_write_begin(inode, pos, bytes,
905                                            AOP_FLAG_NOFS, &page, iomap);
906                 put_page(rpage);
907                 if (unlikely(status))
908                         return status;
909
910                 WARN_ON_ONCE(!PageUptodate(page));
911
912                 status = iomap_write_end(inode, pos, bytes, bytes, page, iomap);
913                 if (unlikely(status <= 0)) {
914                         if (WARN_ON_ONCE(status == 0))
915                                 return -EIO;
916                         return status;
917                 }
918
919                 cond_resched();
920
921                 pos += status;
922                 written += status;
923                 length -= status;
924
925                 balance_dirty_pages_ratelimited(inode->i_mapping);
926         } while (length);
927
928         return written;
929 }
930
931 int
932 iomap_file_dirty(struct inode *inode, loff_t pos, loff_t len,
933                 const struct iomap_ops *ops)
934 {
935         loff_t ret;
936
937         while (len) {
938                 ret = iomap_apply(inode, pos, len, IOMAP_WRITE, ops, NULL,
939                                 iomap_dirty_actor);
940                 if (ret <= 0)
941                         return ret;
942                 pos += ret;
943                 len -= ret;
944         }
945
946         return 0;
947 }
948 EXPORT_SYMBOL_GPL(iomap_file_dirty);
949
950 static int iomap_zero(struct inode *inode, loff_t pos, unsigned offset,
951                 unsigned bytes, struct iomap *iomap)
952 {
953         struct page *page;
954         int status;
955
956         status = iomap_write_begin(inode, pos, bytes, AOP_FLAG_NOFS, &page,
957                                    iomap);
958         if (status)
959                 return status;
960
961         zero_user(page, offset, bytes);
962         mark_page_accessed(page);
963
964         return iomap_write_end(inode, pos, bytes, bytes, page, iomap);
965 }
966
967 static int iomap_dax_zero(loff_t pos, unsigned offset, unsigned bytes,
968                 struct iomap *iomap)
969 {
970         return __dax_zero_page_range(iomap->bdev, iomap->dax_dev,
971                         iomap_sector(iomap, pos & PAGE_MASK), offset, bytes);
972 }
973
974 static loff_t
975 iomap_zero_range_actor(struct inode *inode, loff_t pos, loff_t count,
976                 void *data, struct iomap *iomap)
977 {
978         bool *did_zero = data;
979         loff_t written = 0;
980         int status;
981
982         /* already zeroed?  we're done. */
983         if (iomap->type == IOMAP_HOLE || iomap->type == IOMAP_UNWRITTEN)
984                 return count;
985
986         do {
987                 unsigned offset, bytes;
988
989                 offset = offset_in_page(pos);
990                 bytes = min_t(loff_t, PAGE_SIZE - offset, count);
991
992                 if (IS_DAX(inode))
993                         status = iomap_dax_zero(pos, offset, bytes, iomap);
994                 else
995                         status = iomap_zero(inode, pos, offset, bytes, iomap);
996                 if (status < 0)
997                         return status;
998
999                 pos += bytes;
1000                 count -= bytes;
1001                 written += bytes;
1002                 if (did_zero)
1003                         *did_zero = true;
1004         } while (count > 0);
1005
1006         return written;
1007 }
1008
1009 int
1010 iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero,
1011                 const struct iomap_ops *ops)
1012 {
1013         loff_t ret;
1014
1015         while (len > 0) {
1016                 ret = iomap_apply(inode, pos, len, IOMAP_ZERO,
1017                                 ops, did_zero, iomap_zero_range_actor);
1018                 if (ret <= 0)
1019                         return ret;
1020
1021                 pos += ret;
1022                 len -= ret;
1023         }
1024
1025         return 0;
1026 }
1027 EXPORT_SYMBOL_GPL(iomap_zero_range);
1028
1029 int
1030 iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero,
1031                 const struct iomap_ops *ops)
1032 {
1033         unsigned int blocksize = i_blocksize(inode);
1034         unsigned int off = pos & (blocksize - 1);
1035
1036         /* Block boundary? Nothing to do */
1037         if (!off)
1038                 return 0;
1039         return iomap_zero_range(inode, pos, blocksize - off, did_zero, ops);
1040 }
1041 EXPORT_SYMBOL_GPL(iomap_truncate_page);
1042
1043 static loff_t
1044 iomap_page_mkwrite_actor(struct inode *inode, loff_t pos, loff_t length,
1045                 void *data, struct iomap *iomap)
1046 {
1047         struct page *page = data;
1048         int ret;
1049
1050         if (iomap->flags & IOMAP_F_BUFFER_HEAD) {
1051                 ret = __block_write_begin_int(page, pos, length, NULL, iomap);
1052                 if (ret)
1053                         return ret;
1054                 block_commit_write(page, 0, length);
1055         } else {
1056                 WARN_ON_ONCE(!PageUptodate(page));
1057                 iomap_page_create(inode, page);
1058                 set_page_dirty(page);
1059         }
1060
1061         return length;
1062 }
1063
1064 vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops)
1065 {
1066         struct page *page = vmf->page;
1067         struct inode *inode = file_inode(vmf->vma->vm_file);
1068         unsigned long length;
1069         loff_t offset, size;
1070         ssize_t ret;
1071
1072         lock_page(page);
1073         size = i_size_read(inode);
1074         if ((page->mapping != inode->i_mapping) ||
1075             (page_offset(page) > size)) {
1076                 /* We overload EFAULT to mean page got truncated */
1077                 ret = -EFAULT;
1078                 goto out_unlock;
1079         }
1080
1081         /* page is wholly or partially inside EOF */
1082         if (((page->index + 1) << PAGE_SHIFT) > size)
1083                 length = offset_in_page(size);
1084         else
1085                 length = PAGE_SIZE;
1086
1087         offset = page_offset(page);
1088         while (length > 0) {
1089                 ret = iomap_apply(inode, offset, length,
1090                                 IOMAP_WRITE | IOMAP_FAULT, ops, page,
1091                                 iomap_page_mkwrite_actor);
1092                 if (unlikely(ret <= 0))
1093                         goto out_unlock;
1094                 offset += ret;
1095                 length -= ret;
1096         }
1097
1098         wait_for_stable_page(page);
1099         return VM_FAULT_LOCKED;
1100 out_unlock:
1101         unlock_page(page);
1102         return block_page_mkwrite_return(ret);
1103 }
1104 EXPORT_SYMBOL_GPL(iomap_page_mkwrite);
1105
1106 struct fiemap_ctx {
1107         struct fiemap_extent_info *fi;
1108         struct iomap prev;
1109 };
1110
1111 static int iomap_to_fiemap(struct fiemap_extent_info *fi,
1112                 struct iomap *iomap, u32 flags)
1113 {
1114         switch (iomap->type) {
1115         case IOMAP_HOLE:
1116                 /* skip holes */
1117                 return 0;
1118         case IOMAP_DELALLOC:
1119                 flags |= FIEMAP_EXTENT_DELALLOC | FIEMAP_EXTENT_UNKNOWN;
1120                 break;
1121         case IOMAP_MAPPED:
1122                 break;
1123         case IOMAP_UNWRITTEN:
1124                 flags |= FIEMAP_EXTENT_UNWRITTEN;
1125                 break;
1126         case IOMAP_INLINE:
1127                 flags |= FIEMAP_EXTENT_DATA_INLINE;
1128                 break;
1129         }
1130
1131         if (iomap->flags & IOMAP_F_MERGED)
1132                 flags |= FIEMAP_EXTENT_MERGED;
1133         if (iomap->flags & IOMAP_F_SHARED)
1134                 flags |= FIEMAP_EXTENT_SHARED;
1135
1136         return fiemap_fill_next_extent(fi, iomap->offset,
1137                         iomap->addr != IOMAP_NULL_ADDR ? iomap->addr : 0,
1138                         iomap->length, flags);
1139 }
1140
1141 static loff_t
1142 iomap_fiemap_actor(struct inode *inode, loff_t pos, loff_t length, void *data,
1143                 struct iomap *iomap)
1144 {
1145         struct fiemap_ctx *ctx = data;
1146         loff_t ret = length;
1147
1148         if (iomap->type == IOMAP_HOLE)
1149                 return length;
1150
1151         ret = iomap_to_fiemap(ctx->fi, &ctx->prev, 0);
1152         ctx->prev = *iomap;
1153         switch (ret) {
1154         case 0:         /* success */
1155                 return length;
1156         case 1:         /* extent array full */
1157                 return 0;
1158         default:
1159                 return ret;
1160         }
1161 }
1162
1163 int iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fi,
1164                 loff_t start, loff_t len, const struct iomap_ops *ops)
1165 {
1166         struct fiemap_ctx ctx;
1167         loff_t ret;
1168
1169         memset(&ctx, 0, sizeof(ctx));
1170         ctx.fi = fi;
1171         ctx.prev.type = IOMAP_HOLE;
1172
1173         ret = fiemap_check_flags(fi, FIEMAP_FLAG_SYNC);
1174         if (ret)
1175                 return ret;
1176
1177         if (fi->fi_flags & FIEMAP_FLAG_SYNC) {
1178                 ret = filemap_write_and_wait(inode->i_mapping);
1179                 if (ret)
1180                         return ret;
1181         }
1182
1183         while (len > 0) {
1184                 ret = iomap_apply(inode, start, len, IOMAP_REPORT, ops, &ctx,
1185                                 iomap_fiemap_actor);
1186                 /* inode with no (attribute) mapping will give ENOENT */
1187                 if (ret == -ENOENT)
1188                         break;
1189                 if (ret < 0)
1190                         return ret;
1191                 if (ret == 0)
1192                         break;
1193
1194                 start += ret;
1195                 len -= ret;
1196         }
1197
1198         if (ctx.prev.type != IOMAP_HOLE) {
1199                 ret = iomap_to_fiemap(fi, &ctx.prev, FIEMAP_EXTENT_LAST);
1200                 if (ret < 0)
1201                         return ret;
1202         }
1203
1204         return 0;
1205 }
1206 EXPORT_SYMBOL_GPL(iomap_fiemap);
1207
1208 /*
1209  * Seek for SEEK_DATA / SEEK_HOLE within @page, starting at @lastoff.
1210  * Returns true if found and updates @lastoff to the offset in file.
1211  */
1212 static bool
1213 page_seek_hole_data(struct inode *inode, struct page *page, loff_t *lastoff,
1214                 int whence)
1215 {
1216         const struct address_space_operations *ops = inode->i_mapping->a_ops;
1217         unsigned int bsize = i_blocksize(inode), off;
1218         bool seek_data = whence == SEEK_DATA;
1219         loff_t poff = page_offset(page);
1220
1221         if (WARN_ON_ONCE(*lastoff >= poff + PAGE_SIZE))
1222                 return false;
1223
1224         if (*lastoff < poff) {
1225                 /*
1226                  * Last offset smaller than the start of the page means we found
1227                  * a hole:
1228                  */
1229                 if (whence == SEEK_HOLE)
1230                         return true;
1231                 *lastoff = poff;
1232         }
1233
1234         /*
1235          * Just check the page unless we can and should check block ranges:
1236          */
1237         if (bsize == PAGE_SIZE || !ops->is_partially_uptodate)
1238                 return PageUptodate(page) == seek_data;
1239
1240         lock_page(page);
1241         if (unlikely(page->mapping != inode->i_mapping))
1242                 goto out_unlock_not_found;
1243
1244         for (off = 0; off < PAGE_SIZE; off += bsize) {
1245                 if (offset_in_page(*lastoff) >= off + bsize)
1246                         continue;
1247                 if (ops->is_partially_uptodate(page, off, bsize) == seek_data) {
1248                         unlock_page(page);
1249                         return true;
1250                 }
1251                 *lastoff = poff + off + bsize;
1252         }
1253
1254 out_unlock_not_found:
1255         unlock_page(page);
1256         return false;
1257 }
1258
1259 /*
1260  * Seek for SEEK_DATA / SEEK_HOLE in the page cache.
1261  *
1262  * Within unwritten extents, the page cache determines which parts are holes
1263  * and which are data: uptodate buffer heads count as data; everything else
1264  * counts as a hole.
1265  *
1266  * Returns the resulting offset on successs, and -ENOENT otherwise.
1267  */
1268 static loff_t
1269 page_cache_seek_hole_data(struct inode *inode, loff_t offset, loff_t length,
1270                 int whence)
1271 {
1272         pgoff_t index = offset >> PAGE_SHIFT;
1273         pgoff_t end = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1274         loff_t lastoff = offset;
1275         struct pagevec pvec;
1276
1277         if (length <= 0)
1278                 return -ENOENT;
1279
1280         pagevec_init(&pvec);
1281
1282         do {
1283                 unsigned nr_pages, i;
1284
1285                 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping, &index,
1286                                                 end - 1);
1287                 if (nr_pages == 0)
1288                         break;
1289
1290                 for (i = 0; i < nr_pages; i++) {
1291                         struct page *page = pvec.pages[i];
1292
1293                         if (page_seek_hole_data(inode, page, &lastoff, whence))
1294                                 goto check_range;
1295                         lastoff = page_offset(page) + PAGE_SIZE;
1296                 }
1297                 pagevec_release(&pvec);
1298         } while (index < end);
1299
1300         /* When no page at lastoff and we are not done, we found a hole. */
1301         if (whence != SEEK_HOLE)
1302                 goto not_found;
1303
1304 check_range:
1305         if (lastoff < offset + length)
1306                 goto out;
1307 not_found:
1308         lastoff = -ENOENT;
1309 out:
1310         pagevec_release(&pvec);
1311         return lastoff;
1312 }
1313
1314
1315 static loff_t
1316 iomap_seek_hole_actor(struct inode *inode, loff_t offset, loff_t length,
1317                       void *data, struct iomap *iomap)
1318 {
1319         switch (iomap->type) {
1320         case IOMAP_UNWRITTEN:
1321                 offset = page_cache_seek_hole_data(inode, offset, length,
1322                                                    SEEK_HOLE);
1323                 if (offset < 0)
1324                         return length;
1325                 /* fall through */
1326         case IOMAP_HOLE:
1327                 *(loff_t *)data = offset;
1328                 return 0;
1329         default:
1330                 return length;
1331         }
1332 }
1333
1334 loff_t
1335 iomap_seek_hole(struct inode *inode, loff_t offset, const struct iomap_ops *ops)
1336 {
1337         loff_t size = i_size_read(inode);
1338         loff_t length = size - offset;
1339         loff_t ret;
1340
1341         /* Nothing to be found before or beyond the end of the file. */
1342         if (offset < 0 || offset >= size)
1343                 return -ENXIO;
1344
1345         while (length > 0) {
1346                 ret = iomap_apply(inode, offset, length, IOMAP_REPORT, ops,
1347                                   &offset, iomap_seek_hole_actor);
1348                 if (ret < 0)
1349                         return ret;
1350                 if (ret == 0)
1351                         break;
1352
1353                 offset += ret;
1354                 length -= ret;
1355         }
1356
1357         return offset;
1358 }
1359 EXPORT_SYMBOL_GPL(iomap_seek_hole);
1360
1361 static loff_t
1362 iomap_seek_data_actor(struct inode *inode, loff_t offset, loff_t length,
1363                       void *data, struct iomap *iomap)
1364 {
1365         switch (iomap->type) {
1366         case IOMAP_HOLE:
1367                 return length;
1368         case IOMAP_UNWRITTEN:
1369                 offset = page_cache_seek_hole_data(inode, offset, length,
1370                                                    SEEK_DATA);
1371                 if (offset < 0)
1372                         return length;
1373                 /*FALLTHRU*/
1374         default:
1375                 *(loff_t *)data = offset;
1376                 return 0;
1377         }
1378 }
1379
1380 loff_t
1381 iomap_seek_data(struct inode *inode, loff_t offset, const struct iomap_ops *ops)
1382 {
1383         loff_t size = i_size_read(inode);
1384         loff_t length = size - offset;
1385         loff_t ret;
1386
1387         /* Nothing to be found before or beyond the end of the file. */
1388         if (offset < 0 || offset >= size)
1389                 return -ENXIO;
1390
1391         while (length > 0) {
1392                 ret = iomap_apply(inode, offset, length, IOMAP_REPORT, ops,
1393                                   &offset, iomap_seek_data_actor);
1394                 if (ret < 0)
1395                         return ret;
1396                 if (ret == 0)
1397                         break;
1398
1399                 offset += ret;
1400                 length -= ret;
1401         }
1402
1403         if (length <= 0)
1404                 return -ENXIO;
1405         return offset;
1406 }
1407 EXPORT_SYMBOL_GPL(iomap_seek_data);
1408
1409 /*
1410  * Private flags for iomap_dio, must not overlap with the public ones in
1411  * iomap.h:
1412  */
1413 #define IOMAP_DIO_WRITE_FUA     (1 << 28)
1414 #define IOMAP_DIO_NEED_SYNC     (1 << 29)
1415 #define IOMAP_DIO_WRITE         (1 << 30)
1416 #define IOMAP_DIO_DIRTY         (1 << 31)
1417
1418 struct iomap_dio {
1419         struct kiocb            *iocb;
1420         iomap_dio_end_io_t      *end_io;
1421         loff_t                  i_size;
1422         loff_t                  size;
1423         atomic_t                ref;
1424         unsigned                flags;
1425         int                     error;
1426         bool                    wait_for_completion;
1427
1428         union {
1429                 /* used during submission and for synchronous completion: */
1430                 struct {
1431                         struct iov_iter         *iter;
1432                         struct task_struct      *waiter;
1433                         struct request_queue    *last_queue;
1434                         blk_qc_t                cookie;
1435                 } submit;
1436
1437                 /* used for aio completion: */
1438                 struct {
1439                         struct work_struct      work;
1440                 } aio;
1441         };
1442 };
1443
1444 static ssize_t iomap_dio_complete(struct iomap_dio *dio)
1445 {
1446         struct kiocb *iocb = dio->iocb;
1447         struct inode *inode = file_inode(iocb->ki_filp);
1448         loff_t offset = iocb->ki_pos;
1449         ssize_t ret;
1450
1451         if (dio->end_io) {
1452                 ret = dio->end_io(iocb,
1453                                 dio->error ? dio->error : dio->size,
1454                                 dio->flags);
1455         } else {
1456                 ret = dio->error;
1457         }
1458
1459         if (likely(!ret)) {
1460                 ret = dio->size;
1461                 /* check for short read */
1462                 if (offset + ret > dio->i_size &&
1463                     !(dio->flags & IOMAP_DIO_WRITE))
1464                         ret = dio->i_size - offset;
1465                 iocb->ki_pos += ret;
1466         }
1467
1468         /*
1469          * Try again to invalidate clean pages which might have been cached by
1470          * non-direct readahead, or faulted in by get_user_pages() if the source
1471          * of the write was an mmap'ed region of the file we're writing.  Either
1472          * one is a pretty crazy thing to do, so we don't support it 100%.  If
1473          * this invalidation fails, tough, the write still worked...
1474          *
1475          * And this page cache invalidation has to be after dio->end_io(), as
1476          * some filesystems convert unwritten extents to real allocations in
1477          * end_io() when necessary, otherwise a racing buffer read would cache
1478          * zeros from unwritten extents.
1479          */
1480         if (!dio->error &&
1481             (dio->flags & IOMAP_DIO_WRITE) && inode->i_mapping->nrpages) {
1482                 int err;
1483                 err = invalidate_inode_pages2_range(inode->i_mapping,
1484                                 offset >> PAGE_SHIFT,
1485                                 (offset + dio->size - 1) >> PAGE_SHIFT);
1486                 if (err)
1487                         dio_warn_stale_pagecache(iocb->ki_filp);
1488         }
1489
1490         /*
1491          * If this is a DSYNC write, make sure we push it to stable storage now
1492          * that we've written data.
1493          */
1494         if (ret > 0 && (dio->flags & IOMAP_DIO_NEED_SYNC))
1495                 ret = generic_write_sync(iocb, ret);
1496
1497         inode_dio_end(file_inode(iocb->ki_filp));
1498         kfree(dio);
1499
1500         return ret;
1501 }
1502
1503 static void iomap_dio_complete_work(struct work_struct *work)
1504 {
1505         struct iomap_dio *dio = container_of(work, struct iomap_dio, aio.work);
1506         struct kiocb *iocb = dio->iocb;
1507
1508         iocb->ki_complete(iocb, iomap_dio_complete(dio), 0);
1509 }
1510
1511 /*
1512  * Set an error in the dio if none is set yet.  We have to use cmpxchg
1513  * as the submission context and the completion context(s) can race to
1514  * update the error.
1515  */
1516 static inline void iomap_dio_set_error(struct iomap_dio *dio, int ret)
1517 {
1518         cmpxchg(&dio->error, 0, ret);
1519 }
1520
1521 static void iomap_dio_bio_end_io(struct bio *bio)
1522 {
1523         struct iomap_dio *dio = bio->bi_private;
1524         bool should_dirty = (dio->flags & IOMAP_DIO_DIRTY);
1525
1526         if (bio->bi_status)
1527                 iomap_dio_set_error(dio, blk_status_to_errno(bio->bi_status));
1528
1529         if (atomic_dec_and_test(&dio->ref)) {
1530                 if (dio->wait_for_completion) {
1531                         struct task_struct *waiter = dio->submit.waiter;
1532                         WRITE_ONCE(dio->submit.waiter, NULL);
1533                         wake_up_process(waiter);
1534                 } else if (dio->flags & IOMAP_DIO_WRITE) {
1535                         struct inode *inode = file_inode(dio->iocb->ki_filp);
1536
1537                         INIT_WORK(&dio->aio.work, iomap_dio_complete_work);
1538                         queue_work(inode->i_sb->s_dio_done_wq, &dio->aio.work);
1539                 } else {
1540                         iomap_dio_complete_work(&dio->aio.work);
1541                 }
1542         }
1543
1544         if (should_dirty) {
1545                 bio_check_pages_dirty(bio);
1546         } else {
1547                 struct bio_vec *bvec;
1548                 int i;
1549
1550                 bio_for_each_segment_all(bvec, bio, i)
1551                         put_page(bvec->bv_page);
1552                 bio_put(bio);
1553         }
1554 }
1555
1556 static blk_qc_t
1557 iomap_dio_zero(struct iomap_dio *dio, struct iomap *iomap, loff_t pos,
1558                 unsigned len)
1559 {
1560         struct page *page = ZERO_PAGE(0);
1561         struct bio *bio;
1562
1563         bio = bio_alloc(GFP_KERNEL, 1);
1564         bio_set_dev(bio, iomap->bdev);
1565         bio->bi_iter.bi_sector = iomap_sector(iomap, pos);
1566         bio->bi_private = dio;
1567         bio->bi_end_io = iomap_dio_bio_end_io;
1568
1569         get_page(page);
1570         __bio_add_page(bio, page, len, 0);
1571         bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_SYNC | REQ_IDLE);
1572
1573         atomic_inc(&dio->ref);
1574         return submit_bio(bio);
1575 }
1576
1577 static loff_t
1578 iomap_dio_bio_actor(struct inode *inode, loff_t pos, loff_t length,
1579                 struct iomap_dio *dio, struct iomap *iomap)
1580 {
1581         unsigned int blkbits = blksize_bits(bdev_logical_block_size(iomap->bdev));
1582         unsigned int fs_block_size = i_blocksize(inode), pad;
1583         unsigned int align = iov_iter_alignment(dio->submit.iter);
1584         struct iov_iter iter;
1585         struct bio *bio;
1586         bool need_zeroout = false;
1587         bool use_fua = false;
1588         int nr_pages, ret = 0;
1589         size_t copied = 0;
1590
1591         if ((pos | length | align) & ((1 << blkbits) - 1))
1592                 return -EINVAL;
1593
1594         if (iomap->type == IOMAP_UNWRITTEN) {
1595                 dio->flags |= IOMAP_DIO_UNWRITTEN;
1596                 need_zeroout = true;
1597         }
1598
1599         if (iomap->flags & IOMAP_F_SHARED)
1600                 dio->flags |= IOMAP_DIO_COW;
1601
1602         if (iomap->flags & IOMAP_F_NEW) {
1603                 need_zeroout = true;
1604         } else if (iomap->type == IOMAP_MAPPED) {
1605                 /*
1606                  * Use a FUA write if we need datasync semantics, this is a pure
1607                  * data IO that doesn't require any metadata updates (including
1608                  * after IO completion such as unwritten extent conversion) and
1609                  * the underlying device supports FUA. This allows us to avoid
1610                  * cache flushes on IO completion.
1611                  */
1612                 if (!(iomap->flags & (IOMAP_F_SHARED|IOMAP_F_DIRTY)) &&
1613                     (dio->flags & IOMAP_DIO_WRITE_FUA) &&
1614                     blk_queue_fua(bdev_get_queue(iomap->bdev)))
1615                         use_fua = true;
1616         }
1617
1618         /*
1619          * Operate on a partial iter trimmed to the extent we were called for.
1620          * We'll update the iter in the dio once we're done with this extent.
1621          */
1622         iter = *dio->submit.iter;
1623         iov_iter_truncate(&iter, length);
1624
1625         nr_pages = iov_iter_npages(&iter, BIO_MAX_PAGES);
1626         if (nr_pages <= 0)
1627                 return nr_pages;
1628
1629         if (need_zeroout) {
1630                 /* zero out from the start of the block to the write offset */
1631                 pad = pos & (fs_block_size - 1);
1632                 if (pad)
1633                         iomap_dio_zero(dio, iomap, pos - pad, pad);
1634         }
1635
1636         do {
1637                 size_t n;
1638                 if (dio->error) {
1639                         iov_iter_revert(dio->submit.iter, copied);
1640                         return 0;
1641                 }
1642
1643                 bio = bio_alloc(GFP_KERNEL, nr_pages);
1644                 bio_set_dev(bio, iomap->bdev);
1645                 bio->bi_iter.bi_sector = iomap_sector(iomap, pos);
1646                 bio->bi_write_hint = dio->iocb->ki_hint;
1647                 bio->bi_ioprio = dio->iocb->ki_ioprio;
1648                 bio->bi_private = dio;
1649                 bio->bi_end_io = iomap_dio_bio_end_io;
1650
1651                 ret = bio_iov_iter_get_pages(bio, &iter);
1652                 if (unlikely(ret)) {
1653                         /*
1654                          * We have to stop part way through an IO. We must fall
1655                          * through to the sub-block tail zeroing here, otherwise
1656                          * this short IO may expose stale data in the tail of
1657                          * the block we haven't written data to.
1658                          */
1659                         bio_put(bio);
1660                         goto zero_tail;
1661                 }
1662
1663                 n = bio->bi_iter.bi_size;
1664                 if (dio->flags & IOMAP_DIO_WRITE) {
1665                         bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
1666                         if (use_fua)
1667                                 bio->bi_opf |= REQ_FUA;
1668                         else
1669                                 dio->flags &= ~IOMAP_DIO_WRITE_FUA;
1670                         task_io_account_write(n);
1671                 } else {
1672                         bio->bi_opf = REQ_OP_READ;
1673                         if (dio->flags & IOMAP_DIO_DIRTY)
1674                                 bio_set_pages_dirty(bio);
1675                 }
1676
1677                 iov_iter_advance(dio->submit.iter, n);
1678
1679                 dio->size += n;
1680                 pos += n;
1681                 copied += n;
1682
1683                 nr_pages = iov_iter_npages(&iter, BIO_MAX_PAGES);
1684
1685                 atomic_inc(&dio->ref);
1686
1687                 dio->submit.last_queue = bdev_get_queue(iomap->bdev);
1688                 dio->submit.cookie = submit_bio(bio);
1689         } while (nr_pages);
1690
1691         /*
1692          * We need to zeroout the tail of a sub-block write if the extent type
1693          * requires zeroing or the write extends beyond EOF. If we don't zero
1694          * the block tail in the latter case, we can expose stale data via mmap
1695          * reads of the EOF block.
1696          */
1697 zero_tail:
1698         if (need_zeroout ||
1699             ((dio->flags & IOMAP_DIO_WRITE) && pos >= i_size_read(inode))) {
1700                 /* zero out from the end of the write to the end of the block */
1701                 pad = pos & (fs_block_size - 1);
1702                 if (pad)
1703                         iomap_dio_zero(dio, iomap, pos, fs_block_size - pad);
1704         }
1705         return copied ? copied : ret;
1706 }
1707
1708 static loff_t
1709 iomap_dio_hole_actor(loff_t length, struct iomap_dio *dio)
1710 {
1711         length = iov_iter_zero(length, dio->submit.iter);
1712         dio->size += length;
1713         return length;
1714 }
1715
1716 static loff_t
1717 iomap_dio_inline_actor(struct inode *inode, loff_t pos, loff_t length,
1718                 struct iomap_dio *dio, struct iomap *iomap)
1719 {
1720         struct iov_iter *iter = dio->submit.iter;
1721         size_t copied;
1722
1723         BUG_ON(pos + length > PAGE_SIZE - offset_in_page(iomap->inline_data));
1724
1725         if (dio->flags & IOMAP_DIO_WRITE) {
1726                 loff_t size = inode->i_size;
1727
1728                 if (pos > size)
1729                         memset(iomap->inline_data + size, 0, pos - size);
1730                 copied = copy_from_iter(iomap->inline_data + pos, length, iter);
1731                 if (copied) {
1732                         if (pos + copied > size)
1733                                 i_size_write(inode, pos + copied);
1734                         mark_inode_dirty(inode);
1735                 }
1736         } else {
1737                 copied = copy_to_iter(iomap->inline_data + pos, length, iter);
1738         }
1739         dio->size += copied;
1740         return copied;
1741 }
1742
1743 static loff_t
1744 iomap_dio_actor(struct inode *inode, loff_t pos, loff_t length,
1745                 void *data, struct iomap *iomap)
1746 {
1747         struct iomap_dio *dio = data;
1748
1749         switch (iomap->type) {
1750         case IOMAP_HOLE:
1751                 if (WARN_ON_ONCE(dio->flags & IOMAP_DIO_WRITE))
1752                         return -EIO;
1753                 return iomap_dio_hole_actor(length, dio);
1754         case IOMAP_UNWRITTEN:
1755                 if (!(dio->flags & IOMAP_DIO_WRITE))
1756                         return iomap_dio_hole_actor(length, dio);
1757                 return iomap_dio_bio_actor(inode, pos, length, dio, iomap);
1758         case IOMAP_MAPPED:
1759                 return iomap_dio_bio_actor(inode, pos, length, dio, iomap);
1760         case IOMAP_INLINE:
1761                 return iomap_dio_inline_actor(inode, pos, length, dio, iomap);
1762         default:
1763                 WARN_ON_ONCE(1);
1764                 return -EIO;
1765         }
1766 }
1767
1768 /*
1769  * iomap_dio_rw() always completes O_[D]SYNC writes regardless of whether the IO
1770  * is being issued as AIO or not.  This allows us to optimise pure data writes
1771  * to use REQ_FUA rather than requiring generic_write_sync() to issue a
1772  * REQ_FLUSH post write. This is slightly tricky because a single request here
1773  * can be mapped into multiple disjoint IOs and only a subset of the IOs issued
1774  * may be pure data writes. In that case, we still need to do a full data sync
1775  * completion.
1776  */
1777 ssize_t
1778 iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
1779                 const struct iomap_ops *ops, iomap_dio_end_io_t end_io)
1780 {
1781         struct address_space *mapping = iocb->ki_filp->f_mapping;
1782         struct inode *inode = file_inode(iocb->ki_filp);
1783         size_t count = iov_iter_count(iter);
1784         loff_t pos = iocb->ki_pos, start = pos;
1785         loff_t end = iocb->ki_pos + count - 1, ret = 0;
1786         unsigned int flags = IOMAP_DIRECT;
1787         struct blk_plug plug;
1788         struct iomap_dio *dio;
1789
1790         lockdep_assert_held(&inode->i_rwsem);
1791
1792         if (!count)
1793                 return 0;
1794
1795         dio = kmalloc(sizeof(*dio), GFP_KERNEL);
1796         if (!dio)
1797                 return -ENOMEM;
1798
1799         dio->iocb = iocb;
1800         atomic_set(&dio->ref, 1);
1801         dio->size = 0;
1802         dio->i_size = i_size_read(inode);
1803         dio->end_io = end_io;
1804         dio->error = 0;
1805         dio->flags = 0;
1806         dio->wait_for_completion = is_sync_kiocb(iocb);
1807
1808         dio->submit.iter = iter;
1809         dio->submit.waiter = current;
1810         dio->submit.cookie = BLK_QC_T_NONE;
1811         dio->submit.last_queue = NULL;
1812
1813         if (iov_iter_rw(iter) == READ) {
1814                 if (pos >= dio->i_size)
1815                         goto out_free_dio;
1816
1817                 if (iter_is_iovec(iter) && iov_iter_rw(iter) == READ)
1818                         dio->flags |= IOMAP_DIO_DIRTY;
1819         } else {
1820                 flags |= IOMAP_WRITE;
1821                 dio->flags |= IOMAP_DIO_WRITE;
1822
1823                 /* for data sync or sync, we need sync completion processing */
1824                 if (iocb->ki_flags & IOCB_DSYNC)
1825                         dio->flags |= IOMAP_DIO_NEED_SYNC;
1826
1827                 /*
1828                  * For datasync only writes, we optimistically try using FUA for
1829                  * this IO.  Any non-FUA write that occurs will clear this flag,
1830                  * hence we know before completion whether a cache flush is
1831                  * necessary.
1832                  */
1833                 if ((iocb->ki_flags & (IOCB_DSYNC | IOCB_SYNC)) == IOCB_DSYNC)
1834                         dio->flags |= IOMAP_DIO_WRITE_FUA;
1835         }
1836
1837         if (iocb->ki_flags & IOCB_NOWAIT) {
1838                 if (filemap_range_has_page(mapping, start, end)) {
1839                         ret = -EAGAIN;
1840                         goto out_free_dio;
1841                 }
1842                 flags |= IOMAP_NOWAIT;
1843         }
1844
1845         ret = filemap_write_and_wait_range(mapping, start, end);
1846         if (ret)
1847                 goto out_free_dio;
1848
1849         /*
1850          * Try to invalidate cache pages for the range we're direct
1851          * writing.  If this invalidation fails, tough, the write will
1852          * still work, but racing two incompatible write paths is a
1853          * pretty crazy thing to do, so we don't support it 100%.
1854          */
1855         ret = invalidate_inode_pages2_range(mapping,
1856                         start >> PAGE_SHIFT, end >> PAGE_SHIFT);
1857         if (ret)
1858                 dio_warn_stale_pagecache(iocb->ki_filp);
1859         ret = 0;
1860
1861         if (iov_iter_rw(iter) == WRITE && !dio->wait_for_completion &&
1862             !inode->i_sb->s_dio_done_wq) {
1863                 ret = sb_init_dio_done_wq(inode->i_sb);
1864                 if (ret < 0)
1865                         goto out_free_dio;
1866         }
1867
1868         inode_dio_begin(inode);
1869
1870         blk_start_plug(&plug);
1871         do {
1872                 ret = iomap_apply(inode, pos, count, flags, ops, dio,
1873                                 iomap_dio_actor);
1874                 if (ret <= 0) {
1875                         /* magic error code to fall back to buffered I/O */
1876                         if (ret == -ENOTBLK) {
1877                                 dio->wait_for_completion = true;
1878                                 ret = 0;
1879                         }
1880
1881                         /*
1882                          * Splicing to pipes can fail on a full pipe. We have to
1883                          * swallow this to make it look like a short IO
1884                          * otherwise the higher splice layers will completely
1885                          * mishandle the error and stop moving data.
1886                          */
1887                         if (ret == -EFAULT)
1888                                 ret = 0;
1889                         break;
1890                 }
1891                 pos += ret;
1892
1893                 if (iov_iter_rw(iter) == READ && pos >= dio->i_size)
1894                         break;
1895         } while ((count = iov_iter_count(iter)) > 0);
1896         blk_finish_plug(&plug);
1897
1898         if (ret < 0)
1899                 iomap_dio_set_error(dio, ret);
1900
1901         /*
1902          * If all the writes we issued were FUA, we don't need to flush the
1903          * cache on IO completion. Clear the sync flag for this case.
1904          */
1905         if (dio->flags & IOMAP_DIO_WRITE_FUA)
1906                 dio->flags &= ~IOMAP_DIO_NEED_SYNC;
1907
1908         if (!atomic_dec_and_test(&dio->ref)) {
1909                 if (!dio->wait_for_completion)
1910                         return -EIOCBQUEUED;
1911
1912                 for (;;) {
1913                         set_current_state(TASK_UNINTERRUPTIBLE);
1914                         if (!READ_ONCE(dio->submit.waiter))
1915                                 break;
1916
1917                         if (!(iocb->ki_flags & IOCB_HIPRI) ||
1918                             !dio->submit.last_queue ||
1919                             !blk_poll(dio->submit.last_queue,
1920                                          dio->submit.cookie))
1921                                 io_schedule();
1922                 }
1923                 __set_current_state(TASK_RUNNING);
1924         }
1925
1926         ret = iomap_dio_complete(dio);
1927
1928         return ret;
1929
1930 out_free_dio:
1931         kfree(dio);
1932         return ret;
1933 }
1934 EXPORT_SYMBOL_GPL(iomap_dio_rw);
1935
1936 /* Swapfile activation */
1937
1938 #ifdef CONFIG_SWAP
1939 struct iomap_swapfile_info {
1940         struct iomap iomap;             /* accumulated iomap */
1941         struct swap_info_struct *sis;
1942         uint64_t lowest_ppage;          /* lowest physical addr seen (pages) */
1943         uint64_t highest_ppage;         /* highest physical addr seen (pages) */
1944         unsigned long nr_pages;         /* number of pages collected */
1945         int nr_extents;                 /* extent count */
1946 };
1947
1948 /*
1949  * Collect physical extents for this swap file.  Physical extents reported to
1950  * the swap code must be trimmed to align to a page boundary.  The logical
1951  * offset within the file is irrelevant since the swapfile code maps logical
1952  * page numbers of the swap device to the physical page-aligned extents.
1953  */
1954 static int iomap_swapfile_add_extent(struct iomap_swapfile_info *isi)
1955 {
1956         struct iomap *iomap = &isi->iomap;
1957         unsigned long nr_pages;
1958         uint64_t first_ppage;
1959         uint64_t first_ppage_reported;
1960         uint64_t next_ppage;
1961         int error;
1962
1963         /*
1964          * Round the start up and the end down so that the physical
1965          * extent aligns to a page boundary.
1966          */
1967         first_ppage = ALIGN(iomap->addr, PAGE_SIZE) >> PAGE_SHIFT;
1968         next_ppage = ALIGN_DOWN(iomap->addr + iomap->length, PAGE_SIZE) >>
1969                         PAGE_SHIFT;
1970
1971         /* Skip too-short physical extents. */
1972         if (first_ppage >= next_ppage)
1973                 return 0;
1974         nr_pages = next_ppage - first_ppage;
1975
1976         /*
1977          * Calculate how much swap space we're adding; the first page contains
1978          * the swap header and doesn't count.  The mm still wants that first
1979          * page fed to add_swap_extent, however.
1980          */
1981         first_ppage_reported = first_ppage;
1982         if (iomap->offset == 0)
1983                 first_ppage_reported++;
1984         if (isi->lowest_ppage > first_ppage_reported)
1985                 isi->lowest_ppage = first_ppage_reported;
1986         if (isi->highest_ppage < (next_ppage - 1))
1987                 isi->highest_ppage = next_ppage - 1;
1988
1989         /* Add extent, set up for the next call. */
1990         error = add_swap_extent(isi->sis, isi->nr_pages, nr_pages, first_ppage);
1991         if (error < 0)
1992                 return error;
1993         isi->nr_extents += error;
1994         isi->nr_pages += nr_pages;
1995         return 0;
1996 }
1997
1998 /*
1999  * Accumulate iomaps for this swap file.  We have to accumulate iomaps because
2000  * swap only cares about contiguous page-aligned physical extents and makes no
2001  * distinction between written and unwritten extents.
2002  */
2003 static loff_t iomap_swapfile_activate_actor(struct inode *inode, loff_t pos,
2004                 loff_t count, void *data, struct iomap *iomap)
2005 {
2006         struct iomap_swapfile_info *isi = data;
2007         int error;
2008
2009         switch (iomap->type) {
2010         case IOMAP_MAPPED:
2011         case IOMAP_UNWRITTEN:
2012                 /* Only real or unwritten extents. */
2013                 break;
2014         case IOMAP_INLINE:
2015                 /* No inline data. */
2016                 pr_err("swapon: file is inline\n");
2017                 return -EINVAL;
2018         default:
2019                 pr_err("swapon: file has unallocated extents\n");
2020                 return -EINVAL;
2021         }
2022
2023         /* No uncommitted metadata or shared blocks. */
2024         if (iomap->flags & IOMAP_F_DIRTY) {
2025                 pr_err("swapon: file is not committed\n");
2026                 return -EINVAL;
2027         }
2028         if (iomap->flags & IOMAP_F_SHARED) {
2029                 pr_err("swapon: file has shared extents\n");
2030                 return -EINVAL;
2031         }
2032
2033         /* Only one bdev per swap file. */
2034         if (iomap->bdev != isi->sis->bdev) {
2035                 pr_err("swapon: file is on multiple devices\n");
2036                 return -EINVAL;
2037         }
2038
2039         if (isi->iomap.length == 0) {
2040                 /* No accumulated extent, so just store it. */
2041                 memcpy(&isi->iomap, iomap, sizeof(isi->iomap));
2042         } else if (isi->iomap.addr + isi->iomap.length == iomap->addr) {
2043                 /* Append this to the accumulated extent. */
2044                 isi->iomap.length += iomap->length;
2045         } else {
2046                 /* Otherwise, add the retained iomap and store this one. */
2047                 error = iomap_swapfile_add_extent(isi);
2048                 if (error)
2049                         return error;
2050                 memcpy(&isi->iomap, iomap, sizeof(isi->iomap));
2051         }
2052         return count;
2053 }
2054
2055 /*
2056  * Iterate a swap file's iomaps to construct physical extents that can be
2057  * passed to the swapfile subsystem.
2058  */
2059 int iomap_swapfile_activate(struct swap_info_struct *sis,
2060                 struct file *swap_file, sector_t *pagespan,
2061                 const struct iomap_ops *ops)
2062 {
2063         struct iomap_swapfile_info isi = {
2064                 .sis = sis,
2065                 .lowest_ppage = (sector_t)-1ULL,
2066         };
2067         struct address_space *mapping = swap_file->f_mapping;
2068         struct inode *inode = mapping->host;
2069         loff_t pos = 0;
2070         loff_t len = ALIGN_DOWN(i_size_read(inode), PAGE_SIZE);
2071         loff_t ret;
2072
2073         /*
2074          * Persist all file mapping metadata so that we won't have any
2075          * IOMAP_F_DIRTY iomaps.
2076          */
2077         ret = vfs_fsync(swap_file, 1);
2078         if (ret)
2079                 return ret;
2080
2081         while (len > 0) {
2082                 ret = iomap_apply(inode, pos, len, IOMAP_REPORT,
2083                                 ops, &isi, iomap_swapfile_activate_actor);
2084                 if (ret <= 0)
2085                         return ret;
2086
2087                 pos += ret;
2088                 len -= ret;
2089         }
2090
2091         if (isi.iomap.length) {
2092                 ret = iomap_swapfile_add_extent(&isi);
2093                 if (ret)
2094                         return ret;
2095         }
2096
2097         *pagespan = 1 + isi.highest_ppage - isi.lowest_ppage;
2098         sis->max = isi.nr_pages;
2099         sis->pages = isi.nr_pages - 1;
2100         sis->highest_bit = isi.nr_pages - 1;
2101         return isi.nr_extents;
2102 }
2103 EXPORT_SYMBOL_GPL(iomap_swapfile_activate);
2104 #endif /* CONFIG_SWAP */
2105
2106 static loff_t
2107 iomap_bmap_actor(struct inode *inode, loff_t pos, loff_t length,
2108                 void *data, struct iomap *iomap)
2109 {
2110         sector_t *bno = data, addr;
2111
2112         if (iomap->type == IOMAP_MAPPED) {
2113                 addr = (pos - iomap->offset + iomap->addr) >> inode->i_blkbits;
2114                 if (addr > INT_MAX)
2115                         WARN(1, "would truncate bmap result\n");
2116                 else
2117                         *bno = addr;
2118         }
2119         return 0;
2120 }
2121
2122 /* legacy ->bmap interface.  0 is the error return (!) */
2123 sector_t
2124 iomap_bmap(struct address_space *mapping, sector_t bno,
2125                 const struct iomap_ops *ops)
2126 {
2127         struct inode *inode = mapping->host;
2128         loff_t pos = bno << inode->i_blkbits;
2129         unsigned blocksize = i_blocksize(inode);
2130
2131         if (filemap_write_and_wait(mapping))
2132                 return 0;
2133
2134         bno = 0;
2135         iomap_apply(inode, pos, blocksize, 0, ops, &bno, iomap_bmap_actor);
2136         return bno;
2137 }
2138 EXPORT_SYMBOL_GPL(iomap_bmap);