xref: /linux/fs/iomap/direct-io.c (revision 79de4d9ade7411ffdddf0b69c87020311731d155)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Red Hat, Inc.
4  * Copyright (c) 2016-2021 Christoph Hellwig.
5  */
6 #include <linux/module.h>
7 #include <linux/compiler.h>
8 #include <linux/fs.h>
9 #include <linux/fscrypt.h>
10 #include <linux/pagemap.h>
11 #include <linux/iomap.h>
12 #include <linux/backing-dev.h>
13 #include <linux/uio.h>
14 #include <linux/task_io_accounting_ops.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_CALLER_COMP	(1U << 26)
24 #define IOMAP_DIO_INLINE_COMP	(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_DIRTY		(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 
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 
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_set_polled(bio, iocb);
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 		submit_bio(bio);
81 }
82 
83 ssize_t iomap_dio_complete(struct iomap_dio *dio)
84 {
85 	const struct iomap_dio_ops *dops = dio->dops;
86 	struct kiocb *iocb = dio->iocb;
87 	loff_t offset = iocb->ki_pos;
88 	ssize_t ret = dio->error;
89 
90 	if (dops && dops->end_io)
91 		ret = dops->end_io(iocb, dio->size, ret, dio->flags);
92 
93 	if (likely(!ret)) {
94 		ret = dio->size;
95 		/* check for short read */
96 		if (offset + ret > dio->i_size &&
97 		    !(dio->flags & IOMAP_DIO_WRITE))
98 			ret = dio->i_size - offset;
99 	}
100 
101 	/*
102 	 * Try again to invalidate clean pages which might have been cached by
103 	 * non-direct readahead, or faulted in by get_user_pages() if the source
104 	 * of the write was an mmap'ed region of the file we're writing.  Either
105 	 * one is a pretty crazy thing to do, so we don't support it 100%.  If
106 	 * this invalidation fails, tough, the write still worked...
107 	 *
108 	 * And this page cache invalidation has to be after ->end_io(), as some
109 	 * filesystems convert unwritten extents to real allocations in
110 	 * ->end_io() when necessary, otherwise a racing buffer read would cache
111 	 * zeros from unwritten extents.
112 	 */
113 	if (!dio->error && dio->size && (dio->flags & IOMAP_DIO_WRITE))
114 		kiocb_invalidate_post_direct_write(iocb, dio->size);
115 
116 	inode_dio_end(file_inode(iocb->ki_filp));
117 
118 	if (ret > 0) {
119 		iocb->ki_pos += ret;
120 
121 		/*
122 		 * If this is a DSYNC write, make sure we push it to stable
123 		 * storage now that we've written data.
124 		 */
125 		if (dio->flags & IOMAP_DIO_NEED_SYNC)
126 			ret = generic_write_sync(iocb, ret);
127 		if (ret > 0)
128 			ret += dio->done_before;
129 	}
130 	trace_iomap_dio_complete(iocb, dio->error, ret);
131 	kfree(dio);
132 	return ret;
133 }
134 EXPORT_SYMBOL_GPL(iomap_dio_complete);
135 
136 static ssize_t iomap_dio_deferred_complete(void *data)
137 {
138 	return iomap_dio_complete(data);
139 }
140 
141 static void iomap_dio_complete_work(struct work_struct *work)
142 {
143 	struct iomap_dio *dio = container_of(work, struct iomap_dio, aio.work);
144 	struct kiocb *iocb = dio->iocb;
145 
146 	iocb->ki_complete(iocb, iomap_dio_complete(dio));
147 }
148 
149 /*
150  * Set an error in the dio if none is set yet.  We have to use cmpxchg
151  * as the submission context and the completion context(s) can race to
152  * update the error.
153  */
154 static inline void iomap_dio_set_error(struct iomap_dio *dio, int ret)
155 {
156 	cmpxchg(&dio->error, 0, ret);
157 }
158 
159 void iomap_dio_bio_end_io(struct bio *bio)
160 {
161 	struct iomap_dio *dio = bio->bi_private;
162 	bool should_dirty = (dio->flags & IOMAP_DIO_DIRTY);
163 	struct kiocb *iocb = dio->iocb;
164 
165 	if (bio->bi_status)
166 		iomap_dio_set_error(dio, blk_status_to_errno(bio->bi_status));
167 	if (!atomic_dec_and_test(&dio->ref))
168 		goto release_bio;
169 
170 	/*
171 	 * Synchronous dio, task itself will handle any completion work
172 	 * that needs after IO. All we need to do is wake the task.
173 	 */
174 	if (dio->wait_for_completion) {
175 		struct task_struct *waiter = dio->submit.waiter;
176 
177 		WRITE_ONCE(dio->submit.waiter, NULL);
178 		blk_wake_io_task(waiter);
179 		goto release_bio;
180 	}
181 
182 	/*
183 	 * Flagged with IOMAP_DIO_INLINE_COMP, we can complete it inline
184 	 */
185 	if (dio->flags & IOMAP_DIO_INLINE_COMP) {
186 		WRITE_ONCE(iocb->private, NULL);
187 		iomap_dio_complete_work(&dio->aio.work);
188 		goto release_bio;
189 	}
190 
191 	/*
192 	 * If this dio is flagged with IOMAP_DIO_CALLER_COMP, then schedule
193 	 * our completion that way to avoid an async punt to a workqueue.
194 	 */
195 	if (dio->flags & IOMAP_DIO_CALLER_COMP) {
196 		/* only polled IO cares about private cleared */
197 		iocb->private = dio;
198 		iocb->dio_complete = iomap_dio_deferred_complete;
199 
200 		/*
201 		 * Invoke ->ki_complete() directly. We've assigned our
202 		 * dio_complete callback handler, and since the issuer set
203 		 * IOCB_DIO_CALLER_COMP, we know their ki_complete handler will
204 		 * notice ->dio_complete being set and will defer calling that
205 		 * handler until it can be done from a safe task context.
206 		 *
207 		 * Note that the 'res' being passed in here is not important
208 		 * for this case. The actual completion value of the request
209 		 * will be gotten from dio_complete when that is run by the
210 		 * issuer.
211 		 */
212 		iocb->ki_complete(iocb, 0);
213 		goto release_bio;
214 	}
215 
216 	/*
217 	 * Async DIO completion that requires filesystem level completion work
218 	 * gets punted to a work queue to complete as the operation may require
219 	 * more IO to be issued to finalise filesystem metadata changes or
220 	 * guarantee data integrity.
221 	 */
222 	INIT_WORK(&dio->aio.work, iomap_dio_complete_work);
223 	queue_work(file_inode(iocb->ki_filp)->i_sb->s_dio_done_wq,
224 			&dio->aio.work);
225 release_bio:
226 	if (should_dirty) {
227 		bio_check_pages_dirty(bio);
228 	} else {
229 		bio_release_pages(bio, false);
230 		bio_put(bio);
231 	}
232 }
233 EXPORT_SYMBOL_GPL(iomap_dio_bio_end_io);
234 
235 static void iomap_dio_zero(const struct iomap_iter *iter, struct iomap_dio *dio,
236 		loff_t pos, unsigned len)
237 {
238 	struct inode *inode = file_inode(dio->iocb->ki_filp);
239 	struct page *page = ZERO_PAGE(0);
240 	struct bio *bio;
241 
242 	bio = iomap_dio_alloc_bio(iter, dio, 1, REQ_OP_WRITE | REQ_SYNC | REQ_IDLE);
243 	fscrypt_set_bio_crypt_ctx(bio, inode, pos >> inode->i_blkbits,
244 				  GFP_KERNEL);
245 	bio->bi_iter.bi_sector = iomap_sector(&iter->iomap, pos);
246 	bio->bi_private = dio;
247 	bio->bi_end_io = iomap_dio_bio_end_io;
248 
249 	__bio_add_page(bio, page, len, 0);
250 	iomap_dio_submit_bio(iter, dio, bio, pos);
251 }
252 
253 /*
254  * Figure out the bio's operation flags from the dio request, the
255  * mapping, and whether or not we want FUA.  Note that we can end up
256  * clearing the WRITE_THROUGH flag in the dio request.
257  */
258 static inline blk_opf_t iomap_dio_bio_opflags(struct iomap_dio *dio,
259 		const struct iomap *iomap, bool use_fua)
260 {
261 	blk_opf_t opflags = REQ_SYNC | REQ_IDLE;
262 
263 	if (!(dio->flags & IOMAP_DIO_WRITE))
264 		return REQ_OP_READ;
265 
266 	opflags |= REQ_OP_WRITE;
267 	if (use_fua)
268 		opflags |= REQ_FUA;
269 	else
270 		dio->flags &= ~IOMAP_DIO_WRITE_THROUGH;
271 
272 	return opflags;
273 }
274 
275 static loff_t iomap_dio_bio_iter(const struct iomap_iter *iter,
276 		struct iomap_dio *dio)
277 {
278 	const struct iomap *iomap = &iter->iomap;
279 	struct inode *inode = iter->inode;
280 	unsigned int fs_block_size = i_blocksize(inode), pad;
281 	loff_t length = iomap_length(iter);
282 	loff_t pos = iter->pos;
283 	blk_opf_t bio_opf;
284 	struct bio *bio;
285 	bool need_zeroout = false;
286 	bool use_fua = false;
287 	int nr_pages, ret = 0;
288 	size_t copied = 0;
289 	size_t orig_count;
290 
291 	if ((pos | length) & (bdev_logical_block_size(iomap->bdev) - 1) ||
292 	    !bdev_iter_is_aligned(iomap->bdev, dio->submit.iter))
293 		return -EINVAL;
294 
295 	if (iomap->type == IOMAP_UNWRITTEN) {
296 		dio->flags |= IOMAP_DIO_UNWRITTEN;
297 		need_zeroout = true;
298 	}
299 
300 	if (iomap->flags & IOMAP_F_SHARED)
301 		dio->flags |= IOMAP_DIO_COW;
302 
303 	if (iomap->flags & IOMAP_F_NEW) {
304 		need_zeroout = true;
305 	} else if (iomap->type == IOMAP_MAPPED) {
306 		/*
307 		 * Use a FUA write if we need datasync semantics, this is a pure
308 		 * data IO that doesn't require any metadata updates (including
309 		 * after IO completion such as unwritten extent conversion) and
310 		 * the underlying device either supports FUA or doesn't have
311 		 * a volatile write cache. This allows us to avoid cache flushes
312 		 * on IO completion. If we can't use writethrough and need to
313 		 * sync, disable in-task completions as dio completion will
314 		 * need to call generic_write_sync() which will do a blocking
315 		 * fsync / cache flush call.
316 		 */
317 		if (!(iomap->flags & (IOMAP_F_SHARED|IOMAP_F_DIRTY)) &&
318 		    (dio->flags & IOMAP_DIO_WRITE_THROUGH) &&
319 		    (bdev_fua(iomap->bdev) || !bdev_write_cache(iomap->bdev)))
320 			use_fua = true;
321 		else if (dio->flags & IOMAP_DIO_NEED_SYNC)
322 			dio->flags &= ~IOMAP_DIO_CALLER_COMP;
323 	}
324 
325 	/*
326 	 * Save the original count and trim the iter to just the extent we
327 	 * are operating on right now.  The iter will be re-expanded once
328 	 * we are done.
329 	 */
330 	orig_count = iov_iter_count(dio->submit.iter);
331 	iov_iter_truncate(dio->submit.iter, length);
332 
333 	if (!iov_iter_count(dio->submit.iter))
334 		goto out;
335 
336 	/*
337 	 * We can only do deferred completion for pure overwrites that
338 	 * don't require additional IO at completion. This rules out
339 	 * writes that need zeroing or extent conversion, extend
340 	 * the file size, or issue journal IO or cache flushes
341 	 * during completion processing.
342 	 */
343 	if (need_zeroout ||
344 	    ((dio->flags & IOMAP_DIO_NEED_SYNC) && !use_fua) ||
345 	    ((dio->flags & IOMAP_DIO_WRITE) && pos >= i_size_read(inode)))
346 		dio->flags &= ~IOMAP_DIO_CALLER_COMP;
347 
348 	/*
349 	 * The rules for polled IO completions follow the guidelines as the
350 	 * ones we set for inline and deferred completions. If none of those
351 	 * are available for this IO, clear the polled flag.
352 	 */
353 	if (!(dio->flags & (IOMAP_DIO_INLINE_COMP|IOMAP_DIO_CALLER_COMP)))
354 		dio->iocb->ki_flags &= ~IOCB_HIPRI;
355 
356 	if (need_zeroout) {
357 		/* zero out from the start of the block to the write offset */
358 		pad = pos & (fs_block_size - 1);
359 		if (pad)
360 			iomap_dio_zero(iter, dio, pos - pad, pad);
361 	}
362 
363 	/*
364 	 * Set the operation flags early so that bio_iov_iter_get_pages
365 	 * can set up the page vector appropriately for a ZONE_APPEND
366 	 * operation.
367 	 */
368 	bio_opf = iomap_dio_bio_opflags(dio, iomap, use_fua);
369 
370 	nr_pages = bio_iov_vecs_to_alloc(dio->submit.iter, BIO_MAX_VECS);
371 	do {
372 		size_t n;
373 		if (dio->error) {
374 			iov_iter_revert(dio->submit.iter, copied);
375 			copied = ret = 0;
376 			goto out;
377 		}
378 
379 		bio = iomap_dio_alloc_bio(iter, dio, nr_pages, bio_opf);
380 		fscrypt_set_bio_crypt_ctx(bio, inode, pos >> inode->i_blkbits,
381 					  GFP_KERNEL);
382 		bio->bi_iter.bi_sector = iomap_sector(iomap, pos);
383 		bio->bi_ioprio = dio->iocb->ki_ioprio;
384 		bio->bi_private = dio;
385 		bio->bi_end_io = iomap_dio_bio_end_io;
386 
387 		ret = bio_iov_iter_get_pages(bio, dio->submit.iter);
388 		if (unlikely(ret)) {
389 			/*
390 			 * We have to stop part way through an IO. We must fall
391 			 * through to the sub-block tail zeroing here, otherwise
392 			 * this short IO may expose stale data in the tail of
393 			 * the block we haven't written data to.
394 			 */
395 			bio_put(bio);
396 			goto zero_tail;
397 		}
398 
399 		n = bio->bi_iter.bi_size;
400 		if (dio->flags & IOMAP_DIO_WRITE) {
401 			task_io_account_write(n);
402 		} else {
403 			if (dio->flags & IOMAP_DIO_DIRTY)
404 				bio_set_pages_dirty(bio);
405 		}
406 
407 		dio->size += n;
408 		copied += n;
409 
410 		nr_pages = bio_iov_vecs_to_alloc(dio->submit.iter,
411 						 BIO_MAX_VECS);
412 		/*
413 		 * We can only poll for single bio I/Os.
414 		 */
415 		if (nr_pages)
416 			dio->iocb->ki_flags &= ~IOCB_HIPRI;
417 		iomap_dio_submit_bio(iter, dio, bio, pos);
418 		pos += n;
419 	} while (nr_pages);
420 
421 	/*
422 	 * We need to zeroout the tail of a sub-block write if the extent type
423 	 * requires zeroing or the write extends beyond EOF. If we don't zero
424 	 * the block tail in the latter case, we can expose stale data via mmap
425 	 * reads of the EOF block.
426 	 */
427 zero_tail:
428 	if (need_zeroout ||
429 	    ((dio->flags & IOMAP_DIO_WRITE) && pos >= i_size_read(inode))) {
430 		/* zero out from the end of the write to the end of the block */
431 		pad = pos & (fs_block_size - 1);
432 		if (pad)
433 			iomap_dio_zero(iter, dio, pos, fs_block_size - pad);
434 	}
435 out:
436 	/* Undo iter limitation to current extent */
437 	iov_iter_reexpand(dio->submit.iter, orig_count - copied);
438 	if (copied)
439 		return copied;
440 	return ret;
441 }
442 
443 static loff_t iomap_dio_hole_iter(const struct iomap_iter *iter,
444 		struct iomap_dio *dio)
445 {
446 	loff_t length = iov_iter_zero(iomap_length(iter), dio->submit.iter);
447 
448 	dio->size += length;
449 	if (!length)
450 		return -EFAULT;
451 	return length;
452 }
453 
454 static loff_t iomap_dio_inline_iter(const struct iomap_iter *iomi,
455 		struct iomap_dio *dio)
456 {
457 	const struct iomap *iomap = &iomi->iomap;
458 	struct iov_iter *iter = dio->submit.iter;
459 	void *inline_data = iomap_inline_data(iomap, iomi->pos);
460 	loff_t length = iomap_length(iomi);
461 	loff_t pos = iomi->pos;
462 	size_t copied;
463 
464 	if (WARN_ON_ONCE(!iomap_inline_data_valid(iomap)))
465 		return -EIO;
466 
467 	if (dio->flags & IOMAP_DIO_WRITE) {
468 		loff_t size = iomi->inode->i_size;
469 
470 		if (pos > size)
471 			memset(iomap_inline_data(iomap, size), 0, pos - size);
472 		copied = copy_from_iter(inline_data, length, iter);
473 		if (copied) {
474 			if (pos + copied > size)
475 				i_size_write(iomi->inode, pos + copied);
476 			mark_inode_dirty(iomi->inode);
477 		}
478 	} else {
479 		copied = copy_to_iter(inline_data, length, iter);
480 	}
481 	dio->size += copied;
482 	if (!copied)
483 		return -EFAULT;
484 	return copied;
485 }
486 
487 static loff_t iomap_dio_iter(const struct iomap_iter *iter,
488 		struct iomap_dio *dio)
489 {
490 	switch (iter->iomap.type) {
491 	case IOMAP_HOLE:
492 		if (WARN_ON_ONCE(dio->flags & IOMAP_DIO_WRITE))
493 			return -EIO;
494 		return iomap_dio_hole_iter(iter, dio);
495 	case IOMAP_UNWRITTEN:
496 		if (!(dio->flags & IOMAP_DIO_WRITE))
497 			return iomap_dio_hole_iter(iter, dio);
498 		return iomap_dio_bio_iter(iter, dio);
499 	case IOMAP_MAPPED:
500 		return iomap_dio_bio_iter(iter, dio);
501 	case IOMAP_INLINE:
502 		return iomap_dio_inline_iter(iter, dio);
503 	case IOMAP_DELALLOC:
504 		/*
505 		 * DIO is not serialised against mmap() access at all, and so
506 		 * if the page_mkwrite occurs between the writeback and the
507 		 * iomap_iter() call in the DIO path, then it will see the
508 		 * DELALLOC block that the page-mkwrite allocated.
509 		 */
510 		pr_warn_ratelimited("Direct I/O collision with buffered writes! File: %pD4 Comm: %.20s\n",
511 				    dio->iocb->ki_filp, current->comm);
512 		return -EIO;
513 	default:
514 		WARN_ON_ONCE(1);
515 		return -EIO;
516 	}
517 }
518 
519 /*
520  * iomap_dio_rw() always completes O_[D]SYNC writes regardless of whether the IO
521  * is being issued as AIO or not.  This allows us to optimise pure data writes
522  * to use REQ_FUA rather than requiring generic_write_sync() to issue a
523  * REQ_FLUSH post write. This is slightly tricky because a single request here
524  * can be mapped into multiple disjoint IOs and only a subset of the IOs issued
525  * may be pure data writes. In that case, we still need to do a full data sync
526  * completion.
527  *
528  * When page faults are disabled and @dio_flags includes IOMAP_DIO_PARTIAL,
529  * __iomap_dio_rw can return a partial result if it encounters a non-resident
530  * page in @iter after preparing a transfer.  In that case, the non-resident
531  * pages can be faulted in and the request resumed with @done_before set to the
532  * number of bytes previously transferred.  The request will then complete with
533  * the correct total number of bytes transferred; this is essential for
534  * completing partial requests asynchronously.
535  *
536  * Returns -ENOTBLK In case of a page invalidation invalidation failure for
537  * writes.  The callers needs to fall back to buffered I/O in this case.
538  */
539 struct iomap_dio *
540 __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
541 		const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
542 		unsigned int dio_flags, void *private, size_t done_before)
543 {
544 	struct inode *inode = file_inode(iocb->ki_filp);
545 	struct iomap_iter iomi = {
546 		.inode		= inode,
547 		.pos		= iocb->ki_pos,
548 		.len		= iov_iter_count(iter),
549 		.flags		= IOMAP_DIRECT,
550 		.private	= private,
551 	};
552 	bool wait_for_completion =
553 		is_sync_kiocb(iocb) || (dio_flags & IOMAP_DIO_FORCE_WAIT);
554 	struct blk_plug plug;
555 	struct iomap_dio *dio;
556 	loff_t ret = 0;
557 
558 	trace_iomap_dio_rw_begin(iocb, iter, dio_flags, done_before);
559 
560 	if (!iomi.len)
561 		return NULL;
562 
563 	dio = kmalloc(sizeof(*dio), GFP_KERNEL);
564 	if (!dio)
565 		return ERR_PTR(-ENOMEM);
566 
567 	dio->iocb = iocb;
568 	atomic_set(&dio->ref, 1);
569 	dio->size = 0;
570 	dio->i_size = i_size_read(inode);
571 	dio->dops = dops;
572 	dio->error = 0;
573 	dio->flags = 0;
574 	dio->done_before = done_before;
575 
576 	dio->submit.iter = iter;
577 	dio->submit.waiter = current;
578 
579 	if (iocb->ki_flags & IOCB_NOWAIT)
580 		iomi.flags |= IOMAP_NOWAIT;
581 
582 	if (iov_iter_rw(iter) == READ) {
583 		/* reads can always complete inline */
584 		dio->flags |= IOMAP_DIO_INLINE_COMP;
585 
586 		if (iomi.pos >= dio->i_size)
587 			goto out_free_dio;
588 
589 		if (user_backed_iter(iter))
590 			dio->flags |= IOMAP_DIO_DIRTY;
591 
592 		ret = kiocb_write_and_wait(iocb, iomi.len);
593 		if (ret)
594 			goto out_free_dio;
595 	} else {
596 		iomi.flags |= IOMAP_WRITE;
597 		dio->flags |= IOMAP_DIO_WRITE;
598 
599 		/*
600 		 * Flag as supporting deferred completions, if the issuer
601 		 * groks it. This can avoid a workqueue punt for writes.
602 		 * We may later clear this flag if we need to do other IO
603 		 * as part of this IO completion.
604 		 */
605 		if (iocb->ki_flags & IOCB_DIO_CALLER_COMP)
606 			dio->flags |= IOMAP_DIO_CALLER_COMP;
607 
608 		if (dio_flags & IOMAP_DIO_OVERWRITE_ONLY) {
609 			ret = -EAGAIN;
610 			if (iomi.pos >= dio->i_size ||
611 			    iomi.pos + iomi.len > dio->i_size)
612 				goto out_free_dio;
613 			iomi.flags |= IOMAP_OVERWRITE_ONLY;
614 		}
615 
616 		/* for data sync or sync, we need sync completion processing */
617 		if (iocb_is_dsync(iocb)) {
618 			dio->flags |= IOMAP_DIO_NEED_SYNC;
619 
620 		       /*
621 			* For datasync only writes, we optimistically try using
622 			* WRITE_THROUGH for this IO. This flag requires either
623 			* FUA writes through the device's write cache, or a
624 			* normal write to a device without a volatile write
625 			* cache. For the former, Any non-FUA write that occurs
626 			* will clear this flag, hence we know before completion
627 			* whether a cache flush is necessary.
628 			*/
629 			if (!(iocb->ki_flags & IOCB_SYNC))
630 				dio->flags |= IOMAP_DIO_WRITE_THROUGH;
631 		}
632 
633 		/*
634 		 * Try to invalidate cache pages for the range we are writing.
635 		 * If this invalidation fails, let the caller fall back to
636 		 * buffered I/O.
637 		 */
638 		ret = kiocb_invalidate_pages(iocb, iomi.len);
639 		if (ret) {
640 			if (ret != -EAGAIN) {
641 				trace_iomap_dio_invalidate_fail(inode, iomi.pos,
642 								iomi.len);
643 				ret = -ENOTBLK;
644 			}
645 			goto out_free_dio;
646 		}
647 
648 		if (!wait_for_completion && !inode->i_sb->s_dio_done_wq) {
649 			ret = sb_init_dio_done_wq(inode->i_sb);
650 			if (ret < 0)
651 				goto out_free_dio;
652 		}
653 	}
654 
655 	inode_dio_begin(inode);
656 
657 	blk_start_plug(&plug);
658 	while ((ret = iomap_iter(&iomi, ops)) > 0) {
659 		iomi.processed = iomap_dio_iter(&iomi, dio);
660 
661 		/*
662 		 * We can only poll for single bio I/Os.
663 		 */
664 		iocb->ki_flags &= ~IOCB_HIPRI;
665 	}
666 
667 	blk_finish_plug(&plug);
668 
669 	/*
670 	 * We only report that we've read data up to i_size.
671 	 * Revert iter to a state corresponding to that as some callers (such
672 	 * as the splice code) rely on it.
673 	 */
674 	if (iov_iter_rw(iter) == READ && iomi.pos >= dio->i_size)
675 		iov_iter_revert(iter, iomi.pos - dio->i_size);
676 
677 	if (ret == -EFAULT && dio->size && (dio_flags & IOMAP_DIO_PARTIAL)) {
678 		if (!(iocb->ki_flags & IOCB_NOWAIT))
679 			wait_for_completion = true;
680 		ret = 0;
681 	}
682 
683 	/* magic error code to fall back to buffered I/O */
684 	if (ret == -ENOTBLK) {
685 		wait_for_completion = true;
686 		ret = 0;
687 	}
688 	if (ret < 0)
689 		iomap_dio_set_error(dio, ret);
690 
691 	/*
692 	 * If all the writes we issued were already written through to the
693 	 * media, we don't need to flush the cache on IO completion. Clear the
694 	 * sync flag for this case.
695 	 */
696 	if (dio->flags & IOMAP_DIO_WRITE_THROUGH)
697 		dio->flags &= ~IOMAP_DIO_NEED_SYNC;
698 
699 	/*
700 	 * We are about to drop our additional submission reference, which
701 	 * might be the last reference to the dio.  There are three different
702 	 * ways we can progress here:
703 	 *
704 	 *  (a) If this is the last reference we will always complete and free
705 	 *	the dio ourselves.
706 	 *  (b) If this is not the last reference, and we serve an asynchronous
707 	 *	iocb, we must never touch the dio after the decrement, the
708 	 *	I/O completion handler will complete and free it.
709 	 *  (c) If this is not the last reference, but we serve a synchronous
710 	 *	iocb, the I/O completion handler will wake us up on the drop
711 	 *	of the final reference, and we will complete and free it here
712 	 *	after we got woken by the I/O completion handler.
713 	 */
714 	dio->wait_for_completion = wait_for_completion;
715 	if (!atomic_dec_and_test(&dio->ref)) {
716 		if (!wait_for_completion) {
717 			trace_iomap_dio_rw_queued(inode, iomi.pos, iomi.len);
718 			return ERR_PTR(-EIOCBQUEUED);
719 		}
720 
721 		for (;;) {
722 			set_current_state(TASK_UNINTERRUPTIBLE);
723 			if (!READ_ONCE(dio->submit.waiter))
724 				break;
725 
726 			blk_io_schedule();
727 		}
728 		__set_current_state(TASK_RUNNING);
729 	}
730 
731 	return dio;
732 
733 out_free_dio:
734 	kfree(dio);
735 	if (ret)
736 		return ERR_PTR(ret);
737 	return NULL;
738 }
739 EXPORT_SYMBOL_GPL(__iomap_dio_rw);
740 
741 ssize_t
742 iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
743 		const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
744 		unsigned int dio_flags, void *private, size_t done_before)
745 {
746 	struct iomap_dio *dio;
747 
748 	dio = __iomap_dio_rw(iocb, iter, ops, dops, dio_flags, private,
749 			     done_before);
750 	if (IS_ERR_OR_NULL(dio))
751 		return PTR_ERR_OR_ZERO(dio);
752 	return iomap_dio_complete(dio);
753 }
754 EXPORT_SYMBOL_GPL(iomap_dio_rw);
755