xref: /linux/fs/iomap/direct-io.c (revision 7fc2cd2e4b398c57c9cf961cfea05eadbf34c05c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Red Hat, Inc.
4  * Copyright (c) 2016-2025 Christoph Hellwig.
5  */
6 #include <linux/fscrypt.h>
7 #include <linux/pagemap.h>
8 #include <linux/iomap.h>
9 #include <linux/task_io_accounting_ops.h>
10 #include "internal.h"
11 #include "trace.h"
12 
13 #include "../internal.h"
14 
15 /*
16  * Private flags for iomap_dio, must not overlap with the public ones in
17  * iomap.h:
18  */
19 #define IOMAP_DIO_NO_INVALIDATE	(1U << 26)
20 #define IOMAP_DIO_COMP_WORK	(1U << 27)
21 #define IOMAP_DIO_WRITE_THROUGH	(1U << 28)
22 #define IOMAP_DIO_NEED_SYNC	(1U << 29)
23 #define IOMAP_DIO_WRITE		(1U << 30)
24 #define IOMAP_DIO_DIRTY		(1U << 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 	size_t			done_before;
35 	bool			wait_for_completion;
36 
37 	union {
38 		/* used during submission and for synchronous completion: */
39 		struct {
40 			struct iov_iter		*iter;
41 			struct task_struct	*waiter;
42 		} submit;
43 
44 		/* used for aio completion: */
45 		struct {
46 			struct work_struct	work;
47 		} aio;
48 	};
49 };
50 
51 static struct bio *iomap_dio_alloc_bio(const struct iomap_iter *iter,
52 		struct iomap_dio *dio, unsigned short nr_vecs, blk_opf_t opf)
53 {
54 	if (dio->dops && dio->dops->bio_set)
55 		return bio_alloc_bioset(iter->iomap.bdev, nr_vecs, opf,
56 					GFP_KERNEL, dio->dops->bio_set);
57 	return bio_alloc(iter->iomap.bdev, nr_vecs, opf, GFP_KERNEL);
58 }
59 
60 static void iomap_dio_submit_bio(const struct iomap_iter *iter,
61 		struct iomap_dio *dio, struct bio *bio, loff_t pos)
62 {
63 	struct kiocb *iocb = dio->iocb;
64 
65 	atomic_inc(&dio->ref);
66 
67 	/* Sync dio can't be polled reliably */
68 	if ((iocb->ki_flags & IOCB_HIPRI) && !is_sync_kiocb(iocb)) {
69 		bio_set_polled(bio, iocb);
70 		WRITE_ONCE(iocb->private, bio);
71 	}
72 
73 	if (dio->dops && dio->dops->submit_io) {
74 		dio->dops->submit_io(iter, bio, pos);
75 	} else {
76 		WARN_ON_ONCE(iter->iomap.flags & IOMAP_F_ANON_WRITE);
77 		submit_bio(bio);
78 	}
79 }
80 
81 ssize_t iomap_dio_complete(struct iomap_dio *dio)
82 {
83 	const struct iomap_dio_ops *dops = dio->dops;
84 	struct kiocb *iocb = dio->iocb;
85 	loff_t offset = iocb->ki_pos;
86 	ssize_t ret = dio->error;
87 
88 	if (dops && dops->end_io)
89 		ret = dops->end_io(iocb, dio->size, ret, dio->flags);
90 
91 	if (likely(!ret)) {
92 		ret = dio->size;
93 		/* check for short read */
94 		if (offset + ret > dio->i_size &&
95 		    !(dio->flags & IOMAP_DIO_WRITE))
96 			ret = dio->i_size - offset;
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 && (dio->flags & IOMAP_DIO_WRITE) &&
112 	    !(dio->flags & IOMAP_DIO_NO_INVALIDATE))
113 		kiocb_invalidate_post_direct_write(iocb, dio->size);
114 
115 	inode_dio_end(file_inode(iocb->ki_filp));
116 
117 	if (ret > 0) {
118 		iocb->ki_pos += ret;
119 
120 		/*
121 		 * If this is a DSYNC write, make sure we push it to stable
122 		 * storage now that we've written data.
123 		 */
124 		if (dio->flags & IOMAP_DIO_NEED_SYNC)
125 			ret = generic_write_sync(iocb, ret);
126 		if (ret > 0)
127 			ret += dio->done_before;
128 	}
129 	trace_iomap_dio_complete(iocb, dio->error, ret);
130 	kfree(dio);
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));
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 /*
154  * Called when dio->ref reaches zero from an I/O completion.
155  */
156 static void iomap_dio_done(struct iomap_dio *dio)
157 {
158 	struct kiocb *iocb = dio->iocb;
159 
160 	if (dio->wait_for_completion) {
161 		/*
162 		 * Synchronous I/O, task itself will handle any completion work
163 		 * that needs after IO. All we need to do is wake the task.
164 		 */
165 		struct task_struct *waiter = dio->submit.waiter;
166 
167 		WRITE_ONCE(dio->submit.waiter, NULL);
168 		blk_wake_io_task(waiter);
169 		return;
170 	}
171 
172 	/*
173 	 * Always run error completions in user context.  These are not
174 	 * performance critical and some code relies on taking sleeping locks
175 	 * for error handling.
176 	 */
177 	if (dio->error)
178 		dio->flags |= IOMAP_DIO_COMP_WORK;
179 
180 	/*
181 	 * Never invalidate pages from this context to avoid deadlocks with
182 	 * buffered I/O completions when called from the ioend workqueue,
183 	 * or avoid sleeping when called directly from ->bi_end_io.
184 	 * Tough luck if you hit the tiny race with someone dirtying the range
185 	 * right between this check and the actual completion.
186 	 */
187 	if ((dio->flags & IOMAP_DIO_WRITE) &&
188 	    !(dio->flags & IOMAP_DIO_COMP_WORK)) {
189 		if (dio->iocb->ki_filp->f_mapping->nrpages)
190 			dio->flags |= IOMAP_DIO_COMP_WORK;
191 		else
192 			dio->flags |= IOMAP_DIO_NO_INVALIDATE;
193 	}
194 
195 	if (dio->flags & IOMAP_DIO_COMP_WORK) {
196 		struct inode *inode = file_inode(iocb->ki_filp);
197 
198 		/*
199 		 * Async DIO completion that requires filesystem level
200 		 * completion work gets punted to a work queue to complete as
201 		 * the operation may require more IO to be issued to finalise
202 		 * filesystem metadata changes or guarantee data integrity.
203 		 */
204 		INIT_WORK(&dio->aio.work, iomap_dio_complete_work);
205 		queue_work(inode->i_sb->s_dio_done_wq, &dio->aio.work);
206 		return;
207 	}
208 
209 	WRITE_ONCE(iocb->private, NULL);
210 	iomap_dio_complete_work(&dio->aio.work);
211 }
212 
213 void iomap_dio_bio_end_io(struct bio *bio)
214 {
215 	struct iomap_dio *dio = bio->bi_private;
216 	bool should_dirty = (dio->flags & IOMAP_DIO_DIRTY);
217 
218 	if (bio->bi_status)
219 		iomap_dio_set_error(dio, blk_status_to_errno(bio->bi_status));
220 
221 	if (atomic_dec_and_test(&dio->ref))
222 		iomap_dio_done(dio);
223 
224 	if (should_dirty) {
225 		bio_check_pages_dirty(bio);
226 	} else {
227 		bio_release_pages(bio, false);
228 		bio_put(bio);
229 	}
230 }
231 EXPORT_SYMBOL_GPL(iomap_dio_bio_end_io);
232 
233 u32 iomap_finish_ioend_direct(struct iomap_ioend *ioend)
234 {
235 	struct iomap_dio *dio = ioend->io_bio.bi_private;
236 	bool should_dirty = (dio->flags & IOMAP_DIO_DIRTY);
237 	u32 vec_count = ioend->io_bio.bi_vcnt;
238 
239 	if (ioend->io_error)
240 		iomap_dio_set_error(dio, ioend->io_error);
241 
242 	if (atomic_dec_and_test(&dio->ref)) {
243 		/*
244 		 * Try to avoid another context switch for the completion given
245 		 * that we are already called from the ioend completion
246 		 * workqueue.
247 		 */
248 		dio->flags &= ~IOMAP_DIO_COMP_WORK;
249 		iomap_dio_done(dio);
250 	}
251 
252 	if (should_dirty) {
253 		bio_check_pages_dirty(&ioend->io_bio);
254 	} else {
255 		bio_release_pages(&ioend->io_bio, false);
256 		bio_put(&ioend->io_bio);
257 	}
258 
259 	/*
260 	 * Return the number of bvecs completed as even direct I/O completions
261 	 * do significant per-folio work and we'll still want to give up the
262 	 * CPU after a lot of completions.
263 	 */
264 	return vec_count;
265 }
266 
267 static int iomap_dio_zero(const struct iomap_iter *iter, struct iomap_dio *dio,
268 		loff_t pos, unsigned len)
269 {
270 	struct inode *inode = file_inode(dio->iocb->ki_filp);
271 	struct bio *bio;
272 	struct folio *zero_folio = largest_zero_folio();
273 	int nr_vecs = max(1, i_blocksize(inode) / folio_size(zero_folio));
274 
275 	if (!len)
276 		return 0;
277 
278 	/*
279 	 * This limit shall never be reached as most filesystems have a
280 	 * maximum blocksize of 64k.
281 	 */
282 	if (WARN_ON_ONCE(nr_vecs > BIO_MAX_VECS))
283 		return -EINVAL;
284 
285 	bio = iomap_dio_alloc_bio(iter, dio, nr_vecs,
286 				  REQ_OP_WRITE | REQ_SYNC | REQ_IDLE);
287 	fscrypt_set_bio_crypt_ctx(bio, inode, pos >> inode->i_blkbits,
288 				  GFP_KERNEL);
289 	bio->bi_iter.bi_sector = iomap_sector(&iter->iomap, pos);
290 	bio->bi_private = dio;
291 	bio->bi_end_io = iomap_dio_bio_end_io;
292 
293 	while (len > 0) {
294 		unsigned int io_len = min(len, folio_size(zero_folio));
295 
296 		bio_add_folio_nofail(bio, zero_folio, io_len, 0);
297 		len -= io_len;
298 	}
299 	iomap_dio_submit_bio(iter, dio, bio, pos);
300 
301 	return 0;
302 }
303 
304 static int iomap_dio_bio_iter(struct iomap_iter *iter, struct iomap_dio *dio)
305 {
306 	const struct iomap *iomap = &iter->iomap;
307 	struct inode *inode = iter->inode;
308 	unsigned int fs_block_size = i_blocksize(inode), pad;
309 	const loff_t length = iomap_length(iter);
310 	loff_t pos = iter->pos;
311 	blk_opf_t bio_opf = REQ_SYNC | REQ_IDLE;
312 	struct bio *bio;
313 	bool need_zeroout = false;
314 	int nr_pages, ret = 0;
315 	u64 copied = 0;
316 	size_t orig_count;
317 	unsigned int alignment;
318 
319 	/*
320 	 * File systems that write out of place and always allocate new blocks
321 	 * need each bio to be block aligned as that's the unit of allocation.
322 	 */
323 	if (dio->flags & IOMAP_DIO_FSBLOCK_ALIGNED)
324 		alignment = fs_block_size;
325 	else
326 		alignment = bdev_logical_block_size(iomap->bdev);
327 
328 	if ((pos | length) & (alignment - 1))
329 		return -EINVAL;
330 
331 	if (dio->flags & IOMAP_DIO_WRITE) {
332 		bool need_completion_work = true;
333 
334 		switch (iomap->type) {
335 		case IOMAP_MAPPED:
336 			/*
337 			 * Directly mapped I/O does not inherently need to do
338 			 * work at I/O completion time.  But there are various
339 			 * cases below where this will get set again.
340 			 */
341 			need_completion_work = false;
342 			break;
343 		case IOMAP_UNWRITTEN:
344 			dio->flags |= IOMAP_DIO_UNWRITTEN;
345 			need_zeroout = true;
346 			break;
347 		default:
348 			break;
349 		}
350 
351 		if (iomap->flags & IOMAP_F_ATOMIC_BIO) {
352 			/*
353 			 * Ensure that the mapping covers the full write
354 			 * length, otherwise it won't be submitted as a single
355 			 * bio, which is required to use hardware atomics.
356 			 */
357 			if (length != iter->len)
358 				return -EINVAL;
359 			bio_opf |= REQ_ATOMIC;
360 		}
361 
362 		if (iomap->flags & IOMAP_F_SHARED) {
363 			/*
364 			 * Unsharing of needs to update metadata at I/O
365 			 * completion time.
366 			 */
367 			need_completion_work = true;
368 			dio->flags |= IOMAP_DIO_COW;
369 		}
370 
371 		if (iomap->flags & IOMAP_F_NEW) {
372 			/*
373 			 * Newly allocated blocks might need recording in
374 			 * metadata at I/O completion time.
375 			 */
376 			need_completion_work = true;
377 			need_zeroout = true;
378 		}
379 
380 		/*
381 		 * Use a FUA write if we need datasync semantics and this is a
382 		 * pure overwrite that doesn't require any metadata updates.
383 		 *
384 		 * This allows us to avoid cache flushes on I/O completion.
385 		 */
386 		if (dio->flags & IOMAP_DIO_WRITE_THROUGH) {
387 			if (!need_completion_work &&
388 			    !(iomap->flags & IOMAP_F_DIRTY) &&
389 			    (!bdev_write_cache(iomap->bdev) ||
390 			     bdev_fua(iomap->bdev)))
391 				bio_opf |= REQ_FUA;
392 			else
393 				dio->flags &= ~IOMAP_DIO_WRITE_THROUGH;
394 		}
395 
396 		/*
397 		 * We can only do inline completion for pure overwrites that
398 		 * don't require additional I/O at completion time.
399 		 *
400 		 * This rules out writes that need zeroing or metdata updates to
401 		 * convert unwritten or shared extents.
402 		 *
403 		 * Writes that extend i_size are also not supported, but this is
404 		 * handled in __iomap_dio_rw().
405 		 */
406 		if (need_completion_work)
407 			dio->flags |= IOMAP_DIO_COMP_WORK;
408 
409 		bio_opf |= REQ_OP_WRITE;
410 	} else {
411 		bio_opf |= REQ_OP_READ;
412 	}
413 
414 	/*
415 	 * Save the original count and trim the iter to just the extent we
416 	 * are operating on right now.  The iter will be re-expanded once
417 	 * we are done.
418 	 */
419 	orig_count = iov_iter_count(dio->submit.iter);
420 	iov_iter_truncate(dio->submit.iter, length);
421 
422 	if (!iov_iter_count(dio->submit.iter))
423 		goto out;
424 
425 	/*
426 	 * The rules for polled IO completions follow the guidelines as the
427 	 * ones we set for inline and deferred completions. If none of those
428 	 * are available for this IO, clear the polled flag.
429 	 */
430 	if (dio->flags & IOMAP_DIO_COMP_WORK)
431 		dio->iocb->ki_flags &= ~IOCB_HIPRI;
432 
433 	if (need_zeroout) {
434 		/* zero out from the start of the block to the write offset */
435 		pad = pos & (fs_block_size - 1);
436 
437 		ret = iomap_dio_zero(iter, dio, pos - pad, pad);
438 		if (ret)
439 			goto out;
440 	}
441 
442 	nr_pages = bio_iov_vecs_to_alloc(dio->submit.iter, BIO_MAX_VECS);
443 	do {
444 		size_t n;
445 		if (dio->error) {
446 			iov_iter_revert(dio->submit.iter, copied);
447 			copied = ret = 0;
448 			goto out;
449 		}
450 
451 		bio = iomap_dio_alloc_bio(iter, dio, nr_pages, bio_opf);
452 		fscrypt_set_bio_crypt_ctx(bio, inode, pos >> inode->i_blkbits,
453 					  GFP_KERNEL);
454 		bio->bi_iter.bi_sector = iomap_sector(iomap, pos);
455 		bio->bi_write_hint = inode->i_write_hint;
456 		bio->bi_ioprio = dio->iocb->ki_ioprio;
457 		bio->bi_private = dio;
458 		bio->bi_end_io = iomap_dio_bio_end_io;
459 
460 		ret = bio_iov_iter_get_pages(bio, dio->submit.iter,
461 					     alignment - 1);
462 		if (unlikely(ret)) {
463 			/*
464 			 * We have to stop part way through an IO. We must fall
465 			 * through to the sub-block tail zeroing here, otherwise
466 			 * this short IO may expose stale data in the tail of
467 			 * the block we haven't written data to.
468 			 */
469 			bio_put(bio);
470 			goto zero_tail;
471 		}
472 
473 		n = bio->bi_iter.bi_size;
474 		if (WARN_ON_ONCE((bio_opf & REQ_ATOMIC) && n != length)) {
475 			/*
476 			 * An atomic write bio must cover the complete length,
477 			 * which it doesn't, so error. We may need to zero out
478 			 * the tail (complete FS block), similar to when
479 			 * bio_iov_iter_get_pages() returns an error, above.
480 			 */
481 			ret = -EINVAL;
482 			bio_put(bio);
483 			goto zero_tail;
484 		}
485 		if (dio->flags & IOMAP_DIO_WRITE)
486 			task_io_account_write(n);
487 		else if (dio->flags & IOMAP_DIO_DIRTY)
488 			bio_set_pages_dirty(bio);
489 
490 		dio->size += n;
491 		copied += n;
492 
493 		nr_pages = bio_iov_vecs_to_alloc(dio->submit.iter,
494 						 BIO_MAX_VECS);
495 		/*
496 		 * We can only poll for single bio I/Os.
497 		 */
498 		if (nr_pages)
499 			dio->iocb->ki_flags &= ~IOCB_HIPRI;
500 		iomap_dio_submit_bio(iter, dio, bio, pos);
501 		pos += n;
502 	} while (nr_pages);
503 
504 	/*
505 	 * We need to zeroout the tail of a sub-block write if the extent type
506 	 * requires zeroing or the write extends beyond EOF. If we don't zero
507 	 * the block tail in the latter case, we can expose stale data via mmap
508 	 * reads of the EOF block.
509 	 */
510 zero_tail:
511 	if (need_zeroout ||
512 	    ((dio->flags & IOMAP_DIO_WRITE) && pos >= i_size_read(inode))) {
513 		/* zero out from the end of the write to the end of the block */
514 		pad = pos & (fs_block_size - 1);
515 		if (pad)
516 			ret = iomap_dio_zero(iter, dio, pos,
517 					     fs_block_size - pad);
518 	}
519 out:
520 	/* Undo iter limitation to current extent */
521 	iov_iter_reexpand(dio->submit.iter, orig_count - copied);
522 	if (copied)
523 		return iomap_iter_advance(iter, copied);
524 	return ret;
525 }
526 
527 static int iomap_dio_hole_iter(struct iomap_iter *iter, struct iomap_dio *dio)
528 {
529 	loff_t length = iov_iter_zero(iomap_length(iter), dio->submit.iter);
530 
531 	dio->size += length;
532 	if (!length)
533 		return -EFAULT;
534 	return iomap_iter_advance(iter, length);
535 }
536 
537 static int iomap_dio_inline_iter(struct iomap_iter *iomi, struct iomap_dio *dio)
538 {
539 	const struct iomap *iomap = &iomi->iomap;
540 	struct iov_iter *iter = dio->submit.iter;
541 	void *inline_data = iomap_inline_data(iomap, iomi->pos);
542 	loff_t length = iomap_length(iomi);
543 	loff_t pos = iomi->pos;
544 	u64 copied;
545 
546 	if (WARN_ON_ONCE(!inline_data))
547 		return -EIO;
548 
549 	if (WARN_ON_ONCE(!iomap_inline_data_valid(iomap)))
550 		return -EIO;
551 
552 	if (dio->flags & IOMAP_DIO_WRITE) {
553 		loff_t size = iomi->inode->i_size;
554 
555 		if (pos > size)
556 			memset(iomap_inline_data(iomap, size), 0, pos - size);
557 		copied = copy_from_iter(inline_data, length, iter);
558 		if (copied) {
559 			if (pos + copied > size)
560 				i_size_write(iomi->inode, pos + copied);
561 			mark_inode_dirty(iomi->inode);
562 		}
563 	} else {
564 		copied = copy_to_iter(inline_data, length, iter);
565 	}
566 	dio->size += copied;
567 	if (!copied)
568 		return -EFAULT;
569 	return iomap_iter_advance(iomi, copied);
570 }
571 
572 static int iomap_dio_iter(struct iomap_iter *iter, struct iomap_dio *dio)
573 {
574 	switch (iter->iomap.type) {
575 	case IOMAP_HOLE:
576 		if (WARN_ON_ONCE(dio->flags & IOMAP_DIO_WRITE))
577 			return -EIO;
578 		return iomap_dio_hole_iter(iter, dio);
579 	case IOMAP_UNWRITTEN:
580 		if (!(dio->flags & IOMAP_DIO_WRITE))
581 			return iomap_dio_hole_iter(iter, dio);
582 		return iomap_dio_bio_iter(iter, dio);
583 	case IOMAP_MAPPED:
584 		return iomap_dio_bio_iter(iter, dio);
585 	case IOMAP_INLINE:
586 		return iomap_dio_inline_iter(iter, dio);
587 	case IOMAP_DELALLOC:
588 		/*
589 		 * DIO is not serialised against mmap() access at all, and so
590 		 * if the page_mkwrite occurs between the writeback and the
591 		 * iomap_iter() call in the DIO path, then it will see the
592 		 * DELALLOC block that the page-mkwrite allocated.
593 		 */
594 		pr_warn_ratelimited("Direct I/O collision with buffered writes! File: %pD4 Comm: %.20s\n",
595 				    dio->iocb->ki_filp, current->comm);
596 		return -EIO;
597 	default:
598 		WARN_ON_ONCE(1);
599 		return -EIO;
600 	}
601 }
602 
603 /*
604  * iomap_dio_rw() always completes O_[D]SYNC writes regardless of whether the IO
605  * is being issued as AIO or not.  This allows us to optimise pure data writes
606  * to use REQ_FUA rather than requiring generic_write_sync() to issue a
607  * REQ_FLUSH post write. This is slightly tricky because a single request here
608  * can be mapped into multiple disjoint IOs and only a subset of the IOs issued
609  * may be pure data writes. In that case, we still need to do a full data sync
610  * completion.
611  *
612  * When page faults are disabled and @dio_flags includes IOMAP_DIO_PARTIAL,
613  * __iomap_dio_rw can return a partial result if it encounters a non-resident
614  * page in @iter after preparing a transfer.  In that case, the non-resident
615  * pages can be faulted in and the request resumed with @done_before set to the
616  * number of bytes previously transferred.  The request will then complete with
617  * the correct total number of bytes transferred; this is essential for
618  * completing partial requests asynchronously.
619  *
620  * Returns -ENOTBLK In case of a page invalidation invalidation failure for
621  * writes.  The callers needs to fall back to buffered I/O in this case.
622  */
623 struct iomap_dio *
624 __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
625 		const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
626 		unsigned int dio_flags, void *private, size_t done_before)
627 {
628 	struct inode *inode = file_inode(iocb->ki_filp);
629 	struct iomap_iter iomi = {
630 		.inode		= inode,
631 		.pos		= iocb->ki_pos,
632 		.len		= iov_iter_count(iter),
633 		.flags		= IOMAP_DIRECT,
634 		.private	= private,
635 	};
636 	bool wait_for_completion =
637 		is_sync_kiocb(iocb) || (dio_flags & IOMAP_DIO_FORCE_WAIT);
638 	struct blk_plug plug;
639 	struct iomap_dio *dio;
640 	loff_t ret = 0;
641 
642 	trace_iomap_dio_rw_begin(iocb, iter, dio_flags, done_before);
643 
644 	if (!iomi.len)
645 		return NULL;
646 
647 	dio = kmalloc(sizeof(*dio), GFP_KERNEL);
648 	if (!dio)
649 		return ERR_PTR(-ENOMEM);
650 
651 	dio->iocb = iocb;
652 	atomic_set(&dio->ref, 1);
653 	dio->size = 0;
654 	dio->i_size = i_size_read(inode);
655 	dio->dops = dops;
656 	dio->error = 0;
657 	dio->flags = 0;
658 	dio->done_before = done_before;
659 
660 	dio->submit.iter = iter;
661 	dio->submit.waiter = current;
662 
663 	if (iocb->ki_flags & IOCB_NOWAIT)
664 		iomi.flags |= IOMAP_NOWAIT;
665 
666 	if (dio_flags & IOMAP_DIO_FSBLOCK_ALIGNED)
667 		dio->flags |= IOMAP_DIO_FSBLOCK_ALIGNED;
668 
669 	if (iov_iter_rw(iter) == READ) {
670 		if (iomi.pos >= dio->i_size)
671 			goto out_free_dio;
672 
673 		if (user_backed_iter(iter))
674 			dio->flags |= IOMAP_DIO_DIRTY;
675 
676 		ret = kiocb_write_and_wait(iocb, iomi.len);
677 		if (ret)
678 			goto out_free_dio;
679 	} else {
680 		iomi.flags |= IOMAP_WRITE;
681 		dio->flags |= IOMAP_DIO_WRITE;
682 
683 		if (dio_flags & IOMAP_DIO_OVERWRITE_ONLY) {
684 			ret = -EAGAIN;
685 			if (iomi.pos >= dio->i_size ||
686 			    iomi.pos + iomi.len > dio->i_size)
687 				goto out_free_dio;
688 			iomi.flags |= IOMAP_OVERWRITE_ONLY;
689 		}
690 
691 		if (iocb->ki_flags & IOCB_ATOMIC)
692 			iomi.flags |= IOMAP_ATOMIC;
693 
694 		/* for data sync or sync, we need sync completion processing */
695 		if (iocb_is_dsync(iocb)) {
696 			dio->flags |= IOMAP_DIO_NEED_SYNC;
697 
698 		       /*
699 			* For datasync only writes, we optimistically try using
700 			* WRITE_THROUGH for this IO. This flag requires either
701 			* FUA writes through the device's write cache, or a
702 			* normal write to a device without a volatile write
703 			* cache. For the former, Any non-FUA write that occurs
704 			* will clear this flag, hence we know before completion
705 			* whether a cache flush is necessary.
706 			*/
707 			if (!(iocb->ki_flags & IOCB_SYNC))
708 				dio->flags |= IOMAP_DIO_WRITE_THROUGH;
709 		}
710 
711 		/*
712 		 * i_size updates must to happen from process context.
713 		 */
714 		if (iomi.pos + iomi.len > dio->i_size)
715 			dio->flags |= IOMAP_DIO_COMP_WORK;
716 
717 		/*
718 		 * Try to invalidate cache pages for the range we are writing.
719 		 * If this invalidation fails, let the caller fall back to
720 		 * buffered I/O.
721 		 */
722 		ret = kiocb_invalidate_pages(iocb, iomi.len);
723 		if (ret) {
724 			if (ret != -EAGAIN) {
725 				trace_iomap_dio_invalidate_fail(inode, iomi.pos,
726 								iomi.len);
727 				if (iocb->ki_flags & IOCB_ATOMIC) {
728 					/*
729 					 * folio invalidation failed, maybe
730 					 * this is transient, unlock and see if
731 					 * the caller tries again.
732 					 */
733 					ret = -EAGAIN;
734 				} else {
735 					/* fall back to buffered write */
736 					ret = -ENOTBLK;
737 				}
738 			}
739 			goto out_free_dio;
740 		}
741 	}
742 
743 	if (!wait_for_completion && !inode->i_sb->s_dio_done_wq) {
744 		ret = sb_init_dio_done_wq(inode->i_sb);
745 		if (ret < 0)
746 			goto out_free_dio;
747 	}
748 
749 	inode_dio_begin(inode);
750 
751 	blk_start_plug(&plug);
752 	while ((ret = iomap_iter(&iomi, ops)) > 0) {
753 		iomi.status = iomap_dio_iter(&iomi, dio);
754 
755 		/*
756 		 * We can only poll for single bio I/Os.
757 		 */
758 		iocb->ki_flags &= ~IOCB_HIPRI;
759 	}
760 
761 	blk_finish_plug(&plug);
762 
763 	/*
764 	 * We only report that we've read data up to i_size.
765 	 * Revert iter to a state corresponding to that as some callers (such
766 	 * as the splice code) rely on it.
767 	 */
768 	if (iov_iter_rw(iter) == READ && iomi.pos >= dio->i_size)
769 		iov_iter_revert(iter, iomi.pos - dio->i_size);
770 
771 	if (ret == -EFAULT && dio->size && (dio_flags & IOMAP_DIO_PARTIAL)) {
772 		if (!(iocb->ki_flags & IOCB_NOWAIT))
773 			wait_for_completion = true;
774 		ret = 0;
775 	}
776 
777 	/* magic error code to fall back to buffered I/O */
778 	if (ret == -ENOTBLK) {
779 		wait_for_completion = true;
780 		ret = 0;
781 	}
782 	if (ret < 0)
783 		iomap_dio_set_error(dio, ret);
784 
785 	/*
786 	 * If all the writes we issued were already written through to the
787 	 * media, we don't need to flush the cache on IO completion. Clear the
788 	 * sync flag for this case.
789 	 *
790 	 * Otherwise clear the inline completion flag if any sync work is
791 	 * needed, as that needs to be performed from process context.
792 	 */
793 	if (dio->flags & IOMAP_DIO_WRITE_THROUGH)
794 		dio->flags &= ~IOMAP_DIO_NEED_SYNC;
795 	else if (dio->flags & IOMAP_DIO_NEED_SYNC)
796 		dio->flags |= IOMAP_DIO_COMP_WORK;
797 
798 	/*
799 	 * We are about to drop our additional submission reference, which
800 	 * might be the last reference to the dio.  There are three different
801 	 * ways we can progress here:
802 	 *
803 	 *  (a) If this is the last reference we will always complete and free
804 	 *	the dio ourselves.
805 	 *  (b) If this is not the last reference, and we serve an asynchronous
806 	 *	iocb, we must never touch the dio after the decrement, the
807 	 *	I/O completion handler will complete and free it.
808 	 *  (c) If this is not the last reference, but we serve a synchronous
809 	 *	iocb, the I/O completion handler will wake us up on the drop
810 	 *	of the final reference, and we will complete and free it here
811 	 *	after we got woken by the I/O completion handler.
812 	 */
813 	dio->wait_for_completion = wait_for_completion;
814 	if (!atomic_dec_and_test(&dio->ref)) {
815 		if (!wait_for_completion) {
816 			trace_iomap_dio_rw_queued(inode, iomi.pos, iomi.len);
817 			return ERR_PTR(-EIOCBQUEUED);
818 		}
819 
820 		for (;;) {
821 			set_current_state(TASK_UNINTERRUPTIBLE);
822 			if (!READ_ONCE(dio->submit.waiter))
823 				break;
824 
825 			blk_io_schedule();
826 		}
827 		__set_current_state(TASK_RUNNING);
828 	}
829 
830 	return dio;
831 
832 out_free_dio:
833 	kfree(dio);
834 	if (ret)
835 		return ERR_PTR(ret);
836 	return NULL;
837 }
838 EXPORT_SYMBOL_GPL(__iomap_dio_rw);
839 
840 ssize_t
841 iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
842 		const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
843 		unsigned int dio_flags, void *private, size_t done_before)
844 {
845 	struct iomap_dio *dio;
846 
847 	dio = __iomap_dio_rw(iocb, iter, ops, dops, dio_flags, private,
848 			     done_before);
849 	if (IS_ERR_OR_NULL(dio))
850 		return PTR_ERR_OR_ZERO(dio);
851 	return iomap_dio_complete(dio);
852 }
853 EXPORT_SYMBOL_GPL(iomap_dio_rw);
854