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