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