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