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