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