Merge tag 'erofs-for-5.12-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/xiang...
[linux-2.6-microblaze.git] / fs / iomap / direct-io.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Red Hat, Inc.
4  * Copyright (c) 2016-2018 Christoph Hellwig.
5  */
6 #include <linux/module.h>
7 #include <linux/compiler.h>
8 #include <linux/fs.h>
9 #include <linux/iomap.h>
10 #include <linux/backing-dev.h>
11 #include <linux/uio.h>
12 #include <linux/task_io_accounting_ops.h>
13 #include "trace.h"
14
15 #include "../internal.h"
16
17 /*
18  * Private flags for iomap_dio, must not overlap with the public ones in
19  * iomap.h:
20  */
21 #define IOMAP_DIO_WRITE_FUA     (1 << 28)
22 #define IOMAP_DIO_NEED_SYNC     (1 << 29)
23 #define IOMAP_DIO_WRITE         (1 << 30)
24 #define IOMAP_DIO_DIRTY         (1 << 31)
25
26 struct iomap_dio {
27         struct kiocb            *iocb;
28         const struct iomap_dio_ops *dops;
29         loff_t                  i_size;
30         loff_t                  size;
31         atomic_t                ref;
32         unsigned                flags;
33         int                     error;
34         bool                    wait_for_completion;
35
36         union {
37                 /* used during submission and for synchronous completion: */
38                 struct {
39                         struct iov_iter         *iter;
40                         struct task_struct      *waiter;
41                         struct request_queue    *last_queue;
42                         blk_qc_t                cookie;
43                 } submit;
44
45                 /* used for aio completion: */
46                 struct {
47                         struct work_struct      work;
48                 } aio;
49         };
50 };
51
52 int iomap_dio_iopoll(struct kiocb *kiocb, bool spin)
53 {
54         struct request_queue *q = READ_ONCE(kiocb->private);
55
56         if (!q)
57                 return 0;
58         return blk_poll(q, READ_ONCE(kiocb->ki_cookie), spin);
59 }
60 EXPORT_SYMBOL_GPL(iomap_dio_iopoll);
61
62 static void iomap_dio_submit_bio(struct iomap_dio *dio, struct iomap *iomap,
63                 struct bio *bio, loff_t pos)
64 {
65         atomic_inc(&dio->ref);
66
67         if (dio->iocb->ki_flags & IOCB_HIPRI)
68                 bio_set_polled(bio, dio->iocb);
69
70         dio->submit.last_queue = bdev_get_queue(iomap->bdev);
71         if (dio->dops && dio->dops->submit_io)
72                 dio->submit.cookie = dio->dops->submit_io(
73                                 file_inode(dio->iocb->ki_filp),
74                                 iomap, bio, pos);
75         else
76                 dio->submit.cookie = submit_bio(bio);
77 }
78
79 ssize_t iomap_dio_complete(struct iomap_dio *dio)
80 {
81         const struct iomap_dio_ops *dops = dio->dops;
82         struct kiocb *iocb = dio->iocb;
83         struct inode *inode = file_inode(iocb->ki_filp);
84         loff_t offset = iocb->ki_pos;
85         ssize_t ret = dio->error;
86
87         if (dops && dops->end_io)
88                 ret = dops->end_io(iocb, dio->size, ret, dio->flags);
89
90         if (likely(!ret)) {
91                 ret = dio->size;
92                 /* check for short read */
93                 if (offset + ret > dio->i_size &&
94                     !(dio->flags & IOMAP_DIO_WRITE))
95                         ret = dio->i_size - offset;
96                 iocb->ki_pos += ret;
97         }
98
99         /*
100          * Try again to invalidate clean pages which might have been cached by
101          * non-direct readahead, or faulted in by get_user_pages() if the source
102          * of the write was an mmap'ed region of the file we're writing.  Either
103          * one is a pretty crazy thing to do, so we don't support it 100%.  If
104          * this invalidation fails, tough, the write still worked...
105          *
106          * And this page cache invalidation has to be after ->end_io(), as some
107          * filesystems convert unwritten extents to real allocations in
108          * ->end_io() when necessary, otherwise a racing buffer read would cache
109          * zeros from unwritten extents.
110          */
111         if (!dio->error && dio->size &&
112             (dio->flags & IOMAP_DIO_WRITE) && inode->i_mapping->nrpages) {
113                 int err;
114                 err = invalidate_inode_pages2_range(inode->i_mapping,
115                                 offset >> PAGE_SHIFT,
116                                 (offset + dio->size - 1) >> PAGE_SHIFT);
117                 if (err)
118                         dio_warn_stale_pagecache(iocb->ki_filp);
119         }
120
121         inode_dio_end(file_inode(iocb->ki_filp));
122         /*
123          * If this is a DSYNC write, make sure we push it to stable storage now
124          * that we've written data.
125          */
126         if (ret > 0 && (dio->flags & IOMAP_DIO_NEED_SYNC))
127                 ret = generic_write_sync(iocb, ret);
128
129         kfree(dio);
130
131         return ret;
132 }
133 EXPORT_SYMBOL_GPL(iomap_dio_complete);
134
135 static void iomap_dio_complete_work(struct work_struct *work)
136 {
137         struct iomap_dio *dio = container_of(work, struct iomap_dio, aio.work);
138         struct kiocb *iocb = dio->iocb;
139
140         iocb->ki_complete(iocb, iomap_dio_complete(dio), 0);
141 }
142
143 /*
144  * Set an error in the dio if none is set yet.  We have to use cmpxchg
145  * as the submission context and the completion context(s) can race to
146  * update the error.
147  */
148 static inline void iomap_dio_set_error(struct iomap_dio *dio, int ret)
149 {
150         cmpxchg(&dio->error, 0, ret);
151 }
152
153 static void iomap_dio_bio_end_io(struct bio *bio)
154 {
155         struct iomap_dio *dio = bio->bi_private;
156         bool should_dirty = (dio->flags & IOMAP_DIO_DIRTY);
157
158         if (bio->bi_status)
159                 iomap_dio_set_error(dio, blk_status_to_errno(bio->bi_status));
160
161         if (atomic_dec_and_test(&dio->ref)) {
162                 if (dio->wait_for_completion) {
163                         struct task_struct *waiter = dio->submit.waiter;
164                         WRITE_ONCE(dio->submit.waiter, NULL);
165                         blk_wake_io_task(waiter);
166                 } else if (dio->flags & IOMAP_DIO_WRITE) {
167                         struct inode *inode = file_inode(dio->iocb->ki_filp);
168
169                         INIT_WORK(&dio->aio.work, iomap_dio_complete_work);
170                         queue_work(inode->i_sb->s_dio_done_wq, &dio->aio.work);
171                 } else {
172                         iomap_dio_complete_work(&dio->aio.work);
173                 }
174         }
175
176         if (should_dirty) {
177                 bio_check_pages_dirty(bio);
178         } else {
179                 bio_release_pages(bio, false);
180                 bio_put(bio);
181         }
182 }
183
184 static void
185 iomap_dio_zero(struct iomap_dio *dio, struct iomap *iomap, loff_t pos,
186                 unsigned len)
187 {
188         struct page *page = ZERO_PAGE(0);
189         int flags = REQ_SYNC | REQ_IDLE;
190         struct bio *bio;
191
192         bio = bio_alloc(GFP_KERNEL, 1);
193         bio_set_dev(bio, iomap->bdev);
194         bio->bi_iter.bi_sector = iomap_sector(iomap, pos);
195         bio->bi_private = dio;
196         bio->bi_end_io = iomap_dio_bio_end_io;
197
198         get_page(page);
199         __bio_add_page(bio, page, len, 0);
200         bio_set_op_attrs(bio, REQ_OP_WRITE, flags);
201         iomap_dio_submit_bio(dio, iomap, bio, pos);
202 }
203
204 /*
205  * Figure out the bio's operation flags from the dio request, the
206  * mapping, and whether or not we want FUA.  Note that we can end up
207  * clearing the WRITE_FUA flag in the dio request.
208  */
209 static inline unsigned int
210 iomap_dio_bio_opflags(struct iomap_dio *dio, struct iomap *iomap, bool use_fua)
211 {
212         unsigned int opflags = REQ_SYNC | REQ_IDLE;
213
214         if (!(dio->flags & IOMAP_DIO_WRITE)) {
215                 WARN_ON_ONCE(iomap->flags & IOMAP_F_ZONE_APPEND);
216                 return REQ_OP_READ;
217         }
218
219         if (iomap->flags & IOMAP_F_ZONE_APPEND)
220                 opflags |= REQ_OP_ZONE_APPEND;
221         else
222                 opflags |= REQ_OP_WRITE;
223
224         if (use_fua)
225                 opflags |= REQ_FUA;
226         else
227                 dio->flags &= ~IOMAP_DIO_WRITE_FUA;
228
229         return opflags;
230 }
231
232 static loff_t
233 iomap_dio_bio_actor(struct inode *inode, loff_t pos, loff_t length,
234                 struct iomap_dio *dio, struct iomap *iomap)
235 {
236         unsigned int blkbits = blksize_bits(bdev_logical_block_size(iomap->bdev));
237         unsigned int fs_block_size = i_blocksize(inode), pad;
238         unsigned int align = iov_iter_alignment(dio->submit.iter);
239         unsigned int bio_opf;
240         struct bio *bio;
241         bool need_zeroout = false;
242         bool use_fua = false;
243         int nr_pages, ret = 0;
244         size_t copied = 0;
245         size_t orig_count;
246
247         if ((pos | length | align) & ((1 << blkbits) - 1))
248                 return -EINVAL;
249
250         if (iomap->type == IOMAP_UNWRITTEN) {
251                 dio->flags |= IOMAP_DIO_UNWRITTEN;
252                 need_zeroout = true;
253         }
254
255         if (iomap->flags & IOMAP_F_SHARED)
256                 dio->flags |= IOMAP_DIO_COW;
257
258         if (iomap->flags & IOMAP_F_NEW) {
259                 need_zeroout = true;
260         } else if (iomap->type == IOMAP_MAPPED) {
261                 /*
262                  * Use a FUA write if we need datasync semantics, this is a pure
263                  * data IO that doesn't require any metadata updates (including
264                  * after IO completion such as unwritten extent conversion) and
265                  * the underlying device supports FUA. This allows us to avoid
266                  * cache flushes on IO completion.
267                  */
268                 if (!(iomap->flags & (IOMAP_F_SHARED|IOMAP_F_DIRTY)) &&
269                     (dio->flags & IOMAP_DIO_WRITE_FUA) &&
270                     blk_queue_fua(bdev_get_queue(iomap->bdev)))
271                         use_fua = true;
272         }
273
274         /*
275          * Save the original count and trim the iter to just the extent we
276          * are operating on right now.  The iter will be re-expanded once
277          * we are done.
278          */
279         orig_count = iov_iter_count(dio->submit.iter);
280         iov_iter_truncate(dio->submit.iter, length);
281
282         nr_pages = iov_iter_npages(dio->submit.iter, BIO_MAX_PAGES);
283         if (nr_pages <= 0) {
284                 ret = nr_pages;
285                 goto out;
286         }
287
288         if (need_zeroout) {
289                 /* zero out from the start of the block to the write offset */
290                 pad = pos & (fs_block_size - 1);
291                 if (pad)
292                         iomap_dio_zero(dio, iomap, pos - pad, pad);
293         }
294
295         /*
296          * Set the operation flags early so that bio_iov_iter_get_pages
297          * can set up the page vector appropriately for a ZONE_APPEND
298          * operation.
299          */
300         bio_opf = iomap_dio_bio_opflags(dio, iomap, use_fua);
301
302         do {
303                 size_t n;
304                 if (dio->error) {
305                         iov_iter_revert(dio->submit.iter, copied);
306                         copied = ret = 0;
307                         goto out;
308                 }
309
310                 bio = bio_alloc(GFP_KERNEL, nr_pages);
311                 bio_set_dev(bio, iomap->bdev);
312                 bio->bi_iter.bi_sector = iomap_sector(iomap, pos);
313                 bio->bi_write_hint = dio->iocb->ki_hint;
314                 bio->bi_ioprio = dio->iocb->ki_ioprio;
315                 bio->bi_private = dio;
316                 bio->bi_end_io = iomap_dio_bio_end_io;
317                 bio->bi_opf = bio_opf;
318
319                 ret = bio_iov_iter_get_pages(bio, dio->submit.iter);
320                 if (unlikely(ret)) {
321                         /*
322                          * We have to stop part way through an IO. We must fall
323                          * through to the sub-block tail zeroing here, otherwise
324                          * this short IO may expose stale data in the tail of
325                          * the block we haven't written data to.
326                          */
327                         bio_put(bio);
328                         goto zero_tail;
329                 }
330
331                 n = bio->bi_iter.bi_size;
332                 if (dio->flags & IOMAP_DIO_WRITE) {
333                         task_io_account_write(n);
334                 } else {
335                         if (dio->flags & IOMAP_DIO_DIRTY)
336                                 bio_set_pages_dirty(bio);
337                 }
338
339                 dio->size += n;
340                 copied += n;
341
342                 nr_pages = iov_iter_npages(dio->submit.iter, BIO_MAX_PAGES);
343                 iomap_dio_submit_bio(dio, iomap, bio, pos);
344                 pos += n;
345         } while (nr_pages);
346
347         /*
348          * We need to zeroout the tail of a sub-block write if the extent type
349          * requires zeroing or the write extends beyond EOF. If we don't zero
350          * the block tail in the latter case, we can expose stale data via mmap
351          * reads of the EOF block.
352          */
353 zero_tail:
354         if (need_zeroout ||
355             ((dio->flags & IOMAP_DIO_WRITE) && pos >= i_size_read(inode))) {
356                 /* zero out from the end of the write to the end of the block */
357                 pad = pos & (fs_block_size - 1);
358                 if (pad)
359                         iomap_dio_zero(dio, iomap, pos, fs_block_size - pad);
360         }
361 out:
362         /* Undo iter limitation to current extent */
363         iov_iter_reexpand(dio->submit.iter, orig_count - copied);
364         if (copied)
365                 return copied;
366         return ret;
367 }
368
369 static loff_t
370 iomap_dio_hole_actor(loff_t length, struct iomap_dio *dio)
371 {
372         length = iov_iter_zero(length, dio->submit.iter);
373         dio->size += length;
374         return length;
375 }
376
377 static loff_t
378 iomap_dio_inline_actor(struct inode *inode, loff_t pos, loff_t length,
379                 struct iomap_dio *dio, struct iomap *iomap)
380 {
381         struct iov_iter *iter = dio->submit.iter;
382         size_t copied;
383
384         BUG_ON(pos + length > PAGE_SIZE - offset_in_page(iomap->inline_data));
385
386         if (dio->flags & IOMAP_DIO_WRITE) {
387                 loff_t size = inode->i_size;
388
389                 if (pos > size)
390                         memset(iomap->inline_data + size, 0, pos - size);
391                 copied = copy_from_iter(iomap->inline_data + pos, length, iter);
392                 if (copied) {
393                         if (pos + copied > size)
394                                 i_size_write(inode, pos + copied);
395                         mark_inode_dirty(inode);
396                 }
397         } else {
398                 copied = copy_to_iter(iomap->inline_data + pos, length, iter);
399         }
400         dio->size += copied;
401         return copied;
402 }
403
404 static loff_t
405 iomap_dio_actor(struct inode *inode, loff_t pos, loff_t length,
406                 void *data, struct iomap *iomap, struct iomap *srcmap)
407 {
408         struct iomap_dio *dio = data;
409
410         switch (iomap->type) {
411         case IOMAP_HOLE:
412                 if (WARN_ON_ONCE(dio->flags & IOMAP_DIO_WRITE))
413                         return -EIO;
414                 return iomap_dio_hole_actor(length, dio);
415         case IOMAP_UNWRITTEN:
416                 if (!(dio->flags & IOMAP_DIO_WRITE))
417                         return iomap_dio_hole_actor(length, dio);
418                 return iomap_dio_bio_actor(inode, pos, length, dio, iomap);
419         case IOMAP_MAPPED:
420                 return iomap_dio_bio_actor(inode, pos, length, dio, iomap);
421         case IOMAP_INLINE:
422                 return iomap_dio_inline_actor(inode, pos, length, dio, iomap);
423         case IOMAP_DELALLOC:
424                 /*
425                  * DIO is not serialised against mmap() access at all, and so
426                  * if the page_mkwrite occurs between the writeback and the
427                  * iomap_apply() call in the DIO path, then it will see the
428                  * DELALLOC block that the page-mkwrite allocated.
429                  */
430                 pr_warn_ratelimited("Direct I/O collision with buffered writes! File: %pD4 Comm: %.20s\n",
431                                     dio->iocb->ki_filp, current->comm);
432                 return -EIO;
433         default:
434                 WARN_ON_ONCE(1);
435                 return -EIO;
436         }
437 }
438
439 /*
440  * iomap_dio_rw() always completes O_[D]SYNC writes regardless of whether the IO
441  * is being issued as AIO or not.  This allows us to optimise pure data writes
442  * to use REQ_FUA rather than requiring generic_write_sync() to issue a
443  * REQ_FLUSH post write. This is slightly tricky because a single request here
444  * can be mapped into multiple disjoint IOs and only a subset of the IOs issued
445  * may be pure data writes. In that case, we still need to do a full data sync
446  * completion.
447  *
448  * Returns -ENOTBLK In case of a page invalidation invalidation failure for
449  * writes.  The callers needs to fall back to buffered I/O in this case.
450  */
451 struct iomap_dio *
452 __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
453                 const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
454                 bool wait_for_completion)
455 {
456         struct address_space *mapping = iocb->ki_filp->f_mapping;
457         struct inode *inode = file_inode(iocb->ki_filp);
458         size_t count = iov_iter_count(iter);
459         loff_t pos = iocb->ki_pos;
460         loff_t end = iocb->ki_pos + count - 1, ret = 0;
461         unsigned int flags = IOMAP_DIRECT;
462         struct blk_plug plug;
463         struct iomap_dio *dio;
464
465         if (!count)
466                 return NULL;
467
468         if (WARN_ON(is_sync_kiocb(iocb) && !wait_for_completion))
469                 return ERR_PTR(-EIO);
470
471         dio = kmalloc(sizeof(*dio), GFP_KERNEL);
472         if (!dio)
473                 return ERR_PTR(-ENOMEM);
474
475         dio->iocb = iocb;
476         atomic_set(&dio->ref, 1);
477         dio->size = 0;
478         dio->i_size = i_size_read(inode);
479         dio->dops = dops;
480         dio->error = 0;
481         dio->flags = 0;
482
483         dio->submit.iter = iter;
484         dio->submit.waiter = current;
485         dio->submit.cookie = BLK_QC_T_NONE;
486         dio->submit.last_queue = NULL;
487
488         if (iov_iter_rw(iter) == READ) {
489                 if (pos >= dio->i_size)
490                         goto out_free_dio;
491
492                 if (iter_is_iovec(iter))
493                         dio->flags |= IOMAP_DIO_DIRTY;
494         } else {
495                 flags |= IOMAP_WRITE;
496                 dio->flags |= IOMAP_DIO_WRITE;
497
498                 /* for data sync or sync, we need sync completion processing */
499                 if (iocb->ki_flags & IOCB_DSYNC)
500                         dio->flags |= IOMAP_DIO_NEED_SYNC;
501
502                 /*
503                  * For datasync only writes, we optimistically try using FUA for
504                  * this IO.  Any non-FUA write that occurs will clear this flag,
505                  * hence we know before completion whether a cache flush is
506                  * necessary.
507                  */
508                 if ((iocb->ki_flags & (IOCB_DSYNC | IOCB_SYNC)) == IOCB_DSYNC)
509                         dio->flags |= IOMAP_DIO_WRITE_FUA;
510         }
511
512         if (iocb->ki_flags & IOCB_NOWAIT) {
513                 if (filemap_range_has_page(mapping, pos, end)) {
514                         ret = -EAGAIN;
515                         goto out_free_dio;
516                 }
517                 flags |= IOMAP_NOWAIT;
518         }
519
520         ret = filemap_write_and_wait_range(mapping, pos, end);
521         if (ret)
522                 goto out_free_dio;
523
524         if (iov_iter_rw(iter) == WRITE) {
525                 /*
526                  * Try to invalidate cache pages for the range we are writing.
527                  * If this invalidation fails, let the caller fall back to
528                  * buffered I/O.
529                  */
530                 if (invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT,
531                                 end >> PAGE_SHIFT)) {
532                         trace_iomap_dio_invalidate_fail(inode, pos, count);
533                         ret = -ENOTBLK;
534                         goto out_free_dio;
535                 }
536
537                 if (!wait_for_completion && !inode->i_sb->s_dio_done_wq) {
538                         ret = sb_init_dio_done_wq(inode->i_sb);
539                         if (ret < 0)
540                                 goto out_free_dio;
541                 }
542         }
543
544         inode_dio_begin(inode);
545
546         blk_start_plug(&plug);
547         do {
548                 ret = iomap_apply(inode, pos, count, flags, ops, dio,
549                                 iomap_dio_actor);
550                 if (ret <= 0) {
551                         /* magic error code to fall back to buffered I/O */
552                         if (ret == -ENOTBLK) {
553                                 wait_for_completion = true;
554                                 ret = 0;
555                         }
556                         break;
557                 }
558                 pos += ret;
559
560                 if (iov_iter_rw(iter) == READ && pos >= dio->i_size) {
561                         /*
562                          * We only report that we've read data up to i_size.
563                          * Revert iter to a state corresponding to that as
564                          * some callers (such as splice code) rely on it.
565                          */
566                         iov_iter_revert(iter, pos - dio->i_size);
567                         break;
568                 }
569         } while ((count = iov_iter_count(iter)) > 0);
570         blk_finish_plug(&plug);
571
572         if (ret < 0)
573                 iomap_dio_set_error(dio, ret);
574
575         /*
576          * If all the writes we issued were FUA, we don't need to flush the
577          * cache on IO completion. Clear the sync flag for this case.
578          */
579         if (dio->flags & IOMAP_DIO_WRITE_FUA)
580                 dio->flags &= ~IOMAP_DIO_NEED_SYNC;
581
582         WRITE_ONCE(iocb->ki_cookie, dio->submit.cookie);
583         WRITE_ONCE(iocb->private, dio->submit.last_queue);
584
585         /*
586          * We are about to drop our additional submission reference, which
587          * might be the last reference to the dio.  There are three different
588          * ways we can progress here:
589          *
590          *  (a) If this is the last reference we will always complete and free
591          *      the dio ourselves.
592          *  (b) If this is not the last reference, and we serve an asynchronous
593          *      iocb, we must never touch the dio after the decrement, the
594          *      I/O completion handler will complete and free it.
595          *  (c) If this is not the last reference, but we serve a synchronous
596          *      iocb, the I/O completion handler will wake us up on the drop
597          *      of the final reference, and we will complete and free it here
598          *      after we got woken by the I/O completion handler.
599          */
600         dio->wait_for_completion = wait_for_completion;
601         if (!atomic_dec_and_test(&dio->ref)) {
602                 if (!wait_for_completion)
603                         return ERR_PTR(-EIOCBQUEUED);
604
605                 for (;;) {
606                         set_current_state(TASK_UNINTERRUPTIBLE);
607                         if (!READ_ONCE(dio->submit.waiter))
608                                 break;
609
610                         if (!(iocb->ki_flags & IOCB_HIPRI) ||
611                             !dio->submit.last_queue ||
612                             !blk_poll(dio->submit.last_queue,
613                                          dio->submit.cookie, true))
614                                 blk_io_schedule();
615                 }
616                 __set_current_state(TASK_RUNNING);
617         }
618
619         return dio;
620
621 out_free_dio:
622         kfree(dio);
623         if (ret)
624                 return ERR_PTR(ret);
625         return NULL;
626 }
627 EXPORT_SYMBOL_GPL(__iomap_dio_rw);
628
629 ssize_t
630 iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
631                 const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
632                 bool wait_for_completion)
633 {
634         struct iomap_dio *dio;
635
636         dio = __iomap_dio_rw(iocb, iter, ops, dops, wait_for_completion);
637         if (IS_ERR_OR_NULL(dio))
638                 return PTR_ERR_OR_ZERO(dio);
639         return iomap_dio_complete(dio);
640 }
641 EXPORT_SYMBOL_GPL(iomap_dio_rw);