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