xref: /linux/io_uring/rw.c (revision f5437ff7299e47e76e52d37a2937a4b0f04e399f)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/fs.h>
5 #include <linux/file.h>
6 #include <linux/blk-mq.h>
7 #include <linux/mm.h>
8 #include <linux/slab.h>
9 #include <linux/fsnotify.h>
10 #include <linux/poll.h>
11 #include <linux/nospec.h>
12 #include <linux/io_uring/cmd.h>
13 #include <linux/indirect_call_wrapper.h>
14 
15 #include <uapi/linux/io_uring.h>
16 
17 #include "filetable.h"
18 #include "io_uring.h"
19 #include "opdef.h"
20 #include "kbuf.h"
21 #include "alloc_cache.h"
22 #include "rsrc.h"
23 #include "poll.h"
24 #include "rw.h"
25 
26 static void io_complete_rw(struct kiocb *kiocb, long res);
27 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res);
28 
29 struct io_rw {
30 	/* NOTE: kiocb has the file as the first member, so don't do it here */
31 	struct kiocb			kiocb;
32 	u64				addr;
33 	u32				len;
34 	rwf_t				flags;
35 };
36 
io_file_supports_nowait(struct io_kiocb * req,__poll_t mask)37 static bool io_file_supports_nowait(struct io_kiocb *req, __poll_t mask)
38 {
39 	/* If FMODE_NOWAIT is set for a file, we're golden */
40 	if (req->flags & REQ_F_SUPPORT_NOWAIT)
41 		return true;
42 	/* No FMODE_NOWAIT, if we can poll, check the status */
43 	if (io_file_can_poll(req)) {
44 		struct poll_table_struct pt = { ._key = mask };
45 
46 		return vfs_poll(req->file, &pt) & mask;
47 	}
48 	/* No FMODE_NOWAIT support, and file isn't pollable. Tough luck. */
49 	return false;
50 }
51 
io_iov_buffer_select_prep(struct io_kiocb * req)52 static int io_iov_buffer_select_prep(struct io_kiocb *req)
53 {
54 	struct iovec __user *uiov;
55 	struct iovec fast_iov, *iov;
56 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
57 
58 	if (rw->len != 1)
59 		return -EINVAL;
60 
61 	uiov = u64_to_user_ptr(rw->addr);
62 	iov = iovec_from_user(uiov, 1, 1, &fast_iov, io_is_compat(req->ctx));
63 	if (IS_ERR(iov))
64 		return PTR_ERR(iov);
65 	rw->len = iov->iov_len;
66 	return 0;
67 }
68 
io_import_vec(int ddir,struct io_kiocb * req,struct io_async_rw * io,const struct iovec __user * uvec,size_t uvec_segs)69 static int io_import_vec(int ddir, struct io_kiocb *req,
70 			 struct io_async_rw *io,
71 			 const struct iovec __user *uvec,
72 			 size_t uvec_segs)
73 {
74 	int ret, nr_segs;
75 	struct iovec *iov;
76 
77 	if (io->vec.iovec) {
78 		nr_segs = io->vec.nr;
79 		iov = io->vec.iovec;
80 	} else {
81 		nr_segs = 1;
82 		iov = &io->fast_iov;
83 	}
84 
85 	ret = __import_iovec(ddir, uvec, uvec_segs, nr_segs, &iov, &io->iter,
86 			     io_is_compat(req->ctx));
87 	if (unlikely(ret < 0))
88 		return ret;
89 	if (iov) {
90 		req->flags |= REQ_F_NEED_CLEANUP;
91 		io_vec_reset_iovec(&io->vec, iov, io->iter.nr_segs);
92 	}
93 	return 0;
94 }
95 
__io_import_rw_buffer(int ddir,struct io_kiocb * req,struct io_async_rw * io,struct io_br_sel * sel,unsigned int issue_flags)96 static int __io_import_rw_buffer(int ddir, struct io_kiocb *req,
97 				 struct io_async_rw *io, struct io_br_sel *sel,
98 				 unsigned int issue_flags)
99 {
100 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
101 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
102 	size_t sqe_len = rw->len;
103 
104 	sel->addr = u64_to_user_ptr(rw->addr);
105 	if (def->vectored && !(req->flags & REQ_F_BUFFER_SELECT))
106 		return io_import_vec(ddir, req, io, sel->addr, sqe_len);
107 
108 	if (io_do_buffer_select(req)) {
109 		*sel = io_buffer_select(req, &sqe_len, io->buf_group, issue_flags);
110 		if (!sel->addr)
111 			return -ENOBUFS;
112 		rw->addr = (unsigned long) sel->addr;
113 		rw->len = sqe_len;
114 	}
115 	return import_ubuf(ddir, sel->addr, sqe_len, &io->iter);
116 }
117 
io_import_rw_buffer(int rw,struct io_kiocb * req,struct io_async_rw * io,struct io_br_sel * sel,unsigned int issue_flags)118 static inline int io_import_rw_buffer(int rw, struct io_kiocb *req,
119 				      struct io_async_rw *io,
120 				      struct io_br_sel *sel,
121 				      unsigned int issue_flags)
122 {
123 	int ret;
124 
125 	ret = __io_import_rw_buffer(rw, req, io, sel, issue_flags);
126 	if (unlikely(ret < 0))
127 		return ret;
128 
129 	iov_iter_save_state(&io->iter, &io->iter_state);
130 	return 0;
131 }
132 
io_rw_recycle(struct io_kiocb * req,unsigned int issue_flags)133 static bool io_rw_recycle(struct io_kiocb *req, unsigned int issue_flags)
134 {
135 	struct io_async_rw *rw = req->async_data;
136 
137 	if (unlikely(issue_flags & IO_URING_F_UNLOCKED))
138 		return false;
139 
140 	io_alloc_cache_vec_kasan(&rw->vec);
141 	if (rw->vec.nr > IO_VEC_CACHE_SOFT_CAP)
142 		io_vec_free(&rw->vec);
143 
144 	if (io_alloc_cache_put(&req->ctx->rw_cache, rw)) {
145 		io_req_async_data_clear(req, 0);
146 		return true;
147 	}
148 	return false;
149 }
150 
io_req_rw_cleanup(struct io_kiocb * req,unsigned int issue_flags)151 static void io_req_rw_cleanup(struct io_kiocb *req, unsigned int issue_flags)
152 {
153 	/*
154 	 * Disable quick recycling for anything that's gone through io-wq.
155 	 * In theory, this should be fine to cleanup. However, some read or
156 	 * write iter handling touches the iovec AFTER having called into the
157 	 * handler, eg to reexpand or revert. This means we can have:
158 	 *
159 	 * task			io-wq
160 	 *   issue
161 	 *     punt to io-wq
162 	 *			issue
163 	 *			  blkdev_write_iter()
164 	 *			    ->ki_complete()
165 	 *			      io_complete_rw()
166 	 *			        queue tw complete
167 	 *  run tw
168 	 *    req_rw_cleanup
169 	 *			iov_iter_count() <- look at iov_iter again
170 	 *
171 	 * which can lead to a UAF. This is only possible for io-wq offload
172 	 * as the cleanup can run in parallel. As io-wq is not the fast path,
173 	 * just leave cleanup to the end.
174 	 *
175 	 * This is really a bug in the core code that does this, any issue
176 	 * path should assume that a successful (or -EIOCBQUEUED) return can
177 	 * mean that the underlying data can be gone at any time. But that
178 	 * should be fixed separately, and then this check could be killed.
179 	 */
180 	if (!(req->flags & (REQ_F_REISSUE | REQ_F_REFCOUNT))) {
181 		req->flags &= ~REQ_F_NEED_CLEANUP;
182 		if (!io_rw_recycle(req, issue_flags)) {
183 			struct io_async_rw *rw = req->async_data;
184 
185 			io_vec_free(&rw->vec);
186 		}
187 	}
188 }
189 
io_rw_alloc_async(struct io_kiocb * req)190 static int io_rw_alloc_async(struct io_kiocb *req)
191 {
192 	struct io_ring_ctx *ctx = req->ctx;
193 	struct io_async_rw *rw;
194 
195 	rw = io_uring_alloc_async_data(&ctx->rw_cache, req);
196 	if (!rw)
197 		return -ENOMEM;
198 	if (rw->vec.iovec)
199 		req->flags |= REQ_F_NEED_CLEANUP;
200 	rw->bytes_done = 0;
201 	return 0;
202 }
203 
io_meta_save_state(struct io_async_rw * io)204 static inline void io_meta_save_state(struct io_async_rw *io)
205 {
206 	io->meta_state.seed = io->meta.seed;
207 	iov_iter_save_state(&io->meta.iter, &io->meta_state.iter_meta);
208 }
209 
io_meta_restore(struct io_async_rw * io,struct kiocb * kiocb)210 static inline void io_meta_restore(struct io_async_rw *io, struct kiocb *kiocb)
211 {
212 	if (kiocb->ki_flags & IOCB_HAS_METADATA) {
213 		io->meta.seed = io->meta_state.seed;
214 		iov_iter_restore(&io->meta.iter, &io->meta_state.iter_meta);
215 	}
216 }
217 
io_prep_rw_pi(struct io_kiocb * req,struct io_rw * rw,int ddir,u64 attr_ptr)218 static int io_prep_rw_pi(struct io_kiocb *req, struct io_rw *rw, int ddir,
219 			 u64 attr_ptr)
220 {
221 	struct io_uring_attr_pi pi_attr;
222 	struct io_async_rw *io;
223 	int ret;
224 
225 	if (copy_from_user(&pi_attr, u64_to_user_ptr(attr_ptr),
226 	    sizeof(pi_attr)))
227 		return -EFAULT;
228 
229 	if (pi_attr.rsvd)
230 		return -EINVAL;
231 
232 	io = req->async_data;
233 	io->meta.flags = pi_attr.flags;
234 	io->meta.app_tag = pi_attr.app_tag;
235 	io->meta.seed = pi_attr.seed;
236 	ret = import_ubuf(ddir, u64_to_user_ptr(pi_attr.addr),
237 			  pi_attr.len, &io->meta.iter);
238 	if (unlikely(ret < 0))
239 		return ret;
240 	req->flags |= REQ_F_HAS_METADATA;
241 	io_meta_save_state(io);
242 	return ret;
243 }
244 
__io_prep_rw(struct io_kiocb * req,const struct io_uring_sqe * sqe,int ddir)245 static int __io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
246 			int ddir)
247 {
248 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
249 	struct io_async_rw *io;
250 	unsigned ioprio;
251 	u64 attr_type_mask;
252 	int ret;
253 
254 	if (io_rw_alloc_async(req))
255 		return -ENOMEM;
256 	io = req->async_data;
257 
258 	rw->kiocb.ki_pos = READ_ONCE(sqe->off);
259 	/* used for fixed read/write too - just read unconditionally */
260 	req->buf_index = READ_ONCE(sqe->buf_index);
261 	io->buf_group = req->buf_index;
262 
263 	ioprio = READ_ONCE(sqe->ioprio);
264 	if (ioprio) {
265 		ret = ioprio_check_cap(ioprio);
266 		if (ret)
267 			return ret;
268 
269 		rw->kiocb.ki_ioprio = ioprio;
270 	} else {
271 		rw->kiocb.ki_ioprio = get_current_ioprio();
272 	}
273 	rw->kiocb.ki_flags = 0;
274 	rw->kiocb.ki_write_stream = READ_ONCE(sqe->write_stream);
275 
276 	if (req->ctx->flags & IORING_SETUP_IOPOLL)
277 		rw->kiocb.ki_complete = io_complete_rw_iopoll;
278 	else
279 		rw->kiocb.ki_complete = io_complete_rw;
280 
281 	rw->addr = READ_ONCE(sqe->addr);
282 	rw->len = READ_ONCE(sqe->len);
283 	rw->flags = (__force rwf_t) READ_ONCE(sqe->rw_flags);
284 
285 	attr_type_mask = READ_ONCE(sqe->attr_type_mask);
286 	if (attr_type_mask) {
287 		u64 attr_ptr;
288 
289 		/* only PI attribute is supported currently */
290 		if (attr_type_mask != IORING_RW_ATTR_FLAG_PI)
291 			return -EINVAL;
292 
293 		attr_ptr = READ_ONCE(sqe->attr_ptr);
294 		return io_prep_rw_pi(req, rw, ddir, attr_ptr);
295 	}
296 	return 0;
297 }
298 
io_rw_do_import(struct io_kiocb * req,int ddir)299 static int io_rw_do_import(struct io_kiocb *req, int ddir)
300 {
301 	struct io_br_sel sel = { };
302 
303 	if (io_do_buffer_select(req))
304 		return 0;
305 
306 	return io_import_rw_buffer(ddir, req, req->async_data, &sel, 0);
307 }
308 
io_prep_rw(struct io_kiocb * req,const struct io_uring_sqe * sqe,int ddir)309 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
310 		      int ddir)
311 {
312 	int ret;
313 
314 	ret = __io_prep_rw(req, sqe, ddir);
315 	if (unlikely(ret))
316 		return ret;
317 
318 	return io_rw_do_import(req, ddir);
319 }
320 
io_prep_read(struct io_kiocb * req,const struct io_uring_sqe * sqe)321 int io_prep_read(struct io_kiocb *req, const struct io_uring_sqe *sqe)
322 {
323 	return io_prep_rw(req, sqe, ITER_DEST);
324 }
325 
io_prep_write(struct io_kiocb * req,const struct io_uring_sqe * sqe)326 int io_prep_write(struct io_kiocb *req, const struct io_uring_sqe *sqe)
327 {
328 	return io_prep_rw(req, sqe, ITER_SOURCE);
329 }
330 
io_prep_rwv(struct io_kiocb * req,const struct io_uring_sqe * sqe,int ddir)331 static int io_prep_rwv(struct io_kiocb *req, const struct io_uring_sqe *sqe,
332 		       int ddir)
333 {
334 	int ret;
335 
336 	ret = io_prep_rw(req, sqe, ddir);
337 	if (unlikely(ret))
338 		return ret;
339 	if (!(req->flags & REQ_F_BUFFER_SELECT))
340 		return 0;
341 
342 	/*
343 	 * Have to do this validation here, as this is in io_read() rw->len
344 	 * might have changed due to buffer selection
345 	 */
346 	return io_iov_buffer_select_prep(req);
347 }
348 
io_prep_readv(struct io_kiocb * req,const struct io_uring_sqe * sqe)349 int io_prep_readv(struct io_kiocb *req, const struct io_uring_sqe *sqe)
350 {
351 	return io_prep_rwv(req, sqe, ITER_DEST);
352 }
353 
io_prep_writev(struct io_kiocb * req,const struct io_uring_sqe * sqe)354 int io_prep_writev(struct io_kiocb *req, const struct io_uring_sqe *sqe)
355 {
356 	return io_prep_rwv(req, sqe, ITER_SOURCE);
357 }
358 
io_init_rw_fixed(struct io_kiocb * req,unsigned int issue_flags,int ddir)359 static int io_init_rw_fixed(struct io_kiocb *req, unsigned int issue_flags,
360 			    int ddir)
361 {
362 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
363 	struct io_async_rw *io = req->async_data;
364 	int ret;
365 
366 	if (io->bytes_done)
367 		return 0;
368 
369 	ret = io_import_reg_buf(req, &io->iter, rw->addr, rw->len, ddir,
370 				issue_flags);
371 	iov_iter_save_state(&io->iter, &io->iter_state);
372 	return ret;
373 }
374 
io_prep_read_fixed(struct io_kiocb * req,const struct io_uring_sqe * sqe)375 int io_prep_read_fixed(struct io_kiocb *req, const struct io_uring_sqe *sqe)
376 {
377 	return __io_prep_rw(req, sqe, ITER_DEST);
378 }
379 
io_prep_write_fixed(struct io_kiocb * req,const struct io_uring_sqe * sqe)380 int io_prep_write_fixed(struct io_kiocb *req, const struct io_uring_sqe *sqe)
381 {
382 	return __io_prep_rw(req, sqe, ITER_SOURCE);
383 }
384 
io_rw_import_reg_vec(struct io_kiocb * req,struct io_async_rw * io,int ddir,unsigned int issue_flags)385 static int io_rw_import_reg_vec(struct io_kiocb *req,
386 				struct io_async_rw *io,
387 				int ddir, unsigned int issue_flags)
388 {
389 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
390 	unsigned uvec_segs = rw->len;
391 	int ret;
392 
393 	ret = io_import_reg_vec(ddir, &io->iter, req, &io->vec,
394 				uvec_segs, issue_flags);
395 	if (unlikely(ret))
396 		return ret;
397 	iov_iter_save_state(&io->iter, &io->iter_state);
398 	req->flags &= ~REQ_F_IMPORT_BUFFER;
399 	return 0;
400 }
401 
io_rw_prep_reg_vec(struct io_kiocb * req)402 static int io_rw_prep_reg_vec(struct io_kiocb *req)
403 {
404 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
405 	struct io_async_rw *io = req->async_data;
406 	const struct iovec __user *uvec;
407 
408 	uvec = u64_to_user_ptr(rw->addr);
409 	return io_prep_reg_iovec(req, &io->vec, uvec, rw->len);
410 }
411 
io_prep_readv_fixed(struct io_kiocb * req,const struct io_uring_sqe * sqe)412 int io_prep_readv_fixed(struct io_kiocb *req, const struct io_uring_sqe *sqe)
413 {
414 	int ret;
415 
416 	ret = __io_prep_rw(req, sqe, ITER_DEST);
417 	if (unlikely(ret))
418 		return ret;
419 	return io_rw_prep_reg_vec(req);
420 }
421 
io_prep_writev_fixed(struct io_kiocb * req,const struct io_uring_sqe * sqe)422 int io_prep_writev_fixed(struct io_kiocb *req, const struct io_uring_sqe *sqe)
423 {
424 	int ret;
425 
426 	ret = __io_prep_rw(req, sqe, ITER_SOURCE);
427 	if (unlikely(ret))
428 		return ret;
429 	return io_rw_prep_reg_vec(req);
430 }
431 
432 /*
433  * Multishot read is prepared just like a normal read/write request, only
434  * difference is that we set the MULTISHOT flag.
435  */
io_read_mshot_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)436 int io_read_mshot_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
437 {
438 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
439 	int ret;
440 
441 	/* must be used with provided buffers */
442 	if (!(req->flags & REQ_F_BUFFER_SELECT))
443 		return -EINVAL;
444 
445 	ret = __io_prep_rw(req, sqe, ITER_DEST);
446 	if (unlikely(ret))
447 		return ret;
448 
449 	if (rw->addr || rw->len)
450 		return -EINVAL;
451 
452 	req->flags |= REQ_F_APOLL_MULTISHOT;
453 	return 0;
454 }
455 
io_readv_writev_cleanup(struct io_kiocb * req)456 void io_readv_writev_cleanup(struct io_kiocb *req)
457 {
458 	struct io_async_rw *rw = req->async_data;
459 
460 	lockdep_assert_held(&req->ctx->uring_lock);
461 	io_vec_free(&rw->vec);
462 	io_rw_recycle(req, 0);
463 }
464 
io_kiocb_update_pos(struct io_kiocb * req)465 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
466 {
467 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
468 
469 	if (rw->kiocb.ki_pos != -1)
470 		return &rw->kiocb.ki_pos;
471 
472 	if (!(req->file->f_mode & FMODE_STREAM)) {
473 		req->flags |= REQ_F_CUR_POS;
474 		rw->kiocb.ki_pos = req->file->f_pos;
475 		return &rw->kiocb.ki_pos;
476 	}
477 
478 	rw->kiocb.ki_pos = 0;
479 	return NULL;
480 }
481 
io_rw_should_reissue(struct io_kiocb * req)482 static bool io_rw_should_reissue(struct io_kiocb *req)
483 {
484 #ifdef CONFIG_BLOCK
485 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
486 	umode_t mode = file_inode(req->file)->i_mode;
487 	struct io_async_rw *io = req->async_data;
488 	struct io_ring_ctx *ctx = req->ctx;
489 
490 	if (!S_ISBLK(mode) && !S_ISREG(mode))
491 		return false;
492 	if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
493 	    !(req->flags & REQ_F_IOPOLL)))
494 		return false;
495 	/*
496 	 * If ref is dying, we might be running poll reap from the exit work.
497 	 * Don't attempt to reissue from that path, just let it fail with
498 	 * -EAGAIN.
499 	 */
500 	if (percpu_ref_is_dying(&ctx->refs))
501 		return false;
502 
503 	io_meta_restore(io, &rw->kiocb);
504 	iov_iter_restore(&io->iter, &io->iter_state);
505 	return true;
506 #else
507 	return false;
508 #endif
509 }
510 
io_req_end_write(struct io_kiocb * req)511 static void io_req_end_write(struct io_kiocb *req)
512 {
513 	if (req->flags & REQ_F_ISREG) {
514 		struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
515 
516 		kiocb_end_write(&rw->kiocb);
517 	}
518 }
519 
520 /*
521  * Trigger the notifications after having done some IO, and finish the write
522  * accounting, if any.
523  */
io_req_io_end(struct io_kiocb * req)524 static void io_req_io_end(struct io_kiocb *req)
525 {
526 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
527 
528 	if (rw->kiocb.ki_flags & IOCB_WRITE) {
529 		io_req_end_write(req);
530 		fsnotify_modify(req->file);
531 	} else {
532 		fsnotify_access(req->file);
533 	}
534 }
535 
__io_complete_rw_common(struct io_kiocb * req,long res)536 static void __io_complete_rw_common(struct io_kiocb *req, long res)
537 {
538 	if (res == req->cqe.res)
539 		return;
540 	if ((res == -EOPNOTSUPP || res == -EAGAIN) && io_rw_should_reissue(req)) {
541 		req->flags |= REQ_F_REISSUE | REQ_F_BL_NO_RECYCLE;
542 	} else {
543 		req_set_fail(req);
544 		req->cqe.res = res;
545 	}
546 }
547 
io_fixup_rw_res(struct io_kiocb * req,long res)548 static inline int io_fixup_rw_res(struct io_kiocb *req, long res)
549 {
550 	struct io_async_rw *io = req->async_data;
551 
552 	/* add previously done IO, if any */
553 	if (req_has_async_data(req) && io->bytes_done > 0) {
554 		if (res < 0)
555 			res = io->bytes_done;
556 		else
557 			res += io->bytes_done;
558 	}
559 	return res;
560 }
561 
io_req_rw_complete(struct io_tw_req tw_req,io_tw_token_t tw)562 void io_req_rw_complete(struct io_tw_req tw_req, io_tw_token_t tw)
563 {
564 	struct io_kiocb *req = tw_req.req;
565 
566 	io_req_io_end(req);
567 
568 	if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING))
569 		req->cqe.flags |= io_put_kbuf(req, max(req->cqe.res, 0), NULL);
570 
571 	io_req_rw_cleanup(req, 0);
572 	io_req_task_complete(tw_req, tw);
573 }
574 
io_complete_rw(struct kiocb * kiocb,long res)575 static void io_complete_rw(struct kiocb *kiocb, long res)
576 {
577 	struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
578 	struct io_kiocb *req = cmd_to_io_kiocb(rw);
579 
580 	__io_complete_rw_common(req, res);
581 	io_req_set_res(req, io_fixup_rw_res(req, res), 0);
582 	req->io_task_work.func = io_req_rw_complete;
583 	__io_req_task_work_add(req, IOU_F_TWQ_LAZY_WAKE);
584 }
585 
io_complete_rw_iopoll(struct kiocb * kiocb,long res)586 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
587 {
588 	struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
589 	struct io_kiocb *req = cmd_to_io_kiocb(rw);
590 	int final_res = io_fixup_rw_res(req, res);
591 
592 	if (kiocb->ki_flags & IOCB_WRITE)
593 		io_req_end_write(req);
594 
595 	if (res == -EAGAIN && io_rw_should_reissue(req))
596 		req->flags |= REQ_F_REISSUE | REQ_F_BL_NO_RECYCLE;
597 	else if (unlikely(final_res != req->cqe.res))
598 		req->cqe.res = final_res;
599 
600 	/* order with io_iopoll_complete() checking ->iopoll_completed */
601 	smp_store_release(&req->iopoll_completed, 1);
602 }
603 
io_fixup_restart_res(ssize_t ret)604 static inline ssize_t io_fixup_restart_res(ssize_t ret)
605 {
606 	switch (ret) {
607 	case -ERESTARTSYS:
608 	case -ERESTARTNOINTR:
609 	case -ERESTARTNOHAND:
610 	case -ERESTART_RESTARTBLOCK:
611 		/*
612 		 * We can't just restart the syscall, since previously
613 		 * submitted sqes may already be in progress. Just fail
614 		 * this IO with EINTR.
615 		 */
616 		return -EINTR;
617 	default:
618 		return ret;
619 	}
620 }
621 
io_rw_done(struct io_kiocb * req,ssize_t ret)622 static inline void io_rw_done(struct io_kiocb *req, ssize_t ret)
623 {
624 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
625 
626 	/* IO was queued async, completion will happen later */
627 	if (ret == -EIOCBQUEUED)
628 		return;
629 
630 	/* transform internal restart error codes */
631 	if (unlikely(ret < 0))
632 		ret = io_fixup_restart_res(ret);
633 
634 	if (req->flags & REQ_F_IOPOLL)
635 		io_complete_rw_iopoll(&rw->kiocb, ret);
636 	else
637 		io_complete_rw(&rw->kiocb, ret);
638 }
639 
kiocb_done(struct io_kiocb * req,ssize_t ret,struct io_br_sel * sel,unsigned int issue_flags)640 static int kiocb_done(struct io_kiocb *req, ssize_t ret,
641 		      struct io_br_sel *sel, unsigned int issue_flags)
642 {
643 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
644 	unsigned final_ret = io_fixup_rw_res(req, ret);
645 
646 	if (ret >= 0 && req->flags & REQ_F_CUR_POS)
647 		req->file->f_pos = rw->kiocb.ki_pos;
648 	if (ret >= 0 && !(req->flags & REQ_F_IOPOLL)) {
649 		u32 cflags = 0;
650 
651 		__io_complete_rw_common(req, ret);
652 		/*
653 		 * Safe to call io_end from here as we're inline
654 		 * from the submission path.
655 		 */
656 		io_req_io_end(req);
657 		if (sel)
658 			cflags = io_put_kbuf(req, ret, sel->buf_list);
659 		io_req_set_res(req, final_ret, cflags);
660 		io_req_rw_cleanup(req, issue_flags);
661 		return IOU_COMPLETE;
662 	} else {
663 		io_rw_done(req, ret);
664 	}
665 
666 	return IOU_ISSUE_SKIP_COMPLETE;
667 }
668 
io_kiocb_ppos(struct kiocb * kiocb)669 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
670 {
671 	return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
672 }
673 
674 /*
675  * For files that don't have ->read_iter() and ->write_iter(), handle them
676  * by looping over ->read() or ->write() manually.
677  */
loop_rw_iter(int ddir,struct io_rw * rw,struct iov_iter * iter)678 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
679 {
680 	struct io_kiocb *req = cmd_to_io_kiocb(rw);
681 	struct kiocb *kiocb = &rw->kiocb;
682 	struct file *file = kiocb->ki_filp;
683 	ssize_t ret = 0;
684 	loff_t *ppos;
685 
686 	/*
687 	 * Don't support polled IO through this interface, and we can't
688 	 * support non-blocking either. For the latter, this just causes
689 	 * the kiocb to be handled from an async context.
690 	 */
691 	if (kiocb->ki_flags & IOCB_HIPRI)
692 		return -EOPNOTSUPP;
693 	if ((kiocb->ki_flags & IOCB_NOWAIT) &&
694 	    !(kiocb->ki_filp->f_flags & O_NONBLOCK))
695 		return -EAGAIN;
696 	if ((req->flags & REQ_F_BUF_NODE) &&
697 	     (req->buf_node->buf->flags & IO_REGBUF_F_KBUF))
698 		return -EFAULT;
699 
700 	ppos = io_kiocb_ppos(kiocb);
701 
702 	while (iov_iter_count(iter)) {
703 		void __user *addr;
704 		size_t len;
705 		ssize_t nr;
706 
707 		if (iter_is_ubuf(iter)) {
708 			addr = iter->ubuf + iter->iov_offset;
709 			len = iov_iter_count(iter);
710 		} else if (!iov_iter_is_bvec(iter)) {
711 			addr = iter_iov_addr(iter);
712 			len = iter_iov_len(iter);
713 		} else {
714 			addr = u64_to_user_ptr(rw->addr);
715 			len = rw->len;
716 		}
717 
718 		if (ddir == READ)
719 			nr = file->f_op->read(file, addr, len, ppos);
720 		else
721 			nr = file->f_op->write(file, addr, len, ppos);
722 
723 		if (nr < 0) {
724 			if (!ret)
725 				ret = nr;
726 			break;
727 		}
728 		ret += nr;
729 		if (!iov_iter_is_bvec(iter)) {
730 			iov_iter_advance(iter, nr);
731 		} else {
732 			rw->addr += nr;
733 			rw->len -= nr;
734 			if (!rw->len)
735 				break;
736 		}
737 		if (nr != len)
738 			break;
739 	}
740 
741 	return ret;
742 }
743 
744 /*
745  * This is our waitqueue callback handler, registered through __folio_lock_async()
746  * when we initially tried to do the IO with the iocb armed our waitqueue.
747  * This gets called when the page is unlocked, and we generally expect that to
748  * happen when the page IO is completed and the page is now uptodate. This will
749  * queue a task_work based retry of the operation, attempting to copy the data
750  * again. If the latter fails because the page was NOT uptodate, then we will
751  * do a thread based blocking retry of the operation. That's the unexpected
752  * slow path.
753  */
io_async_buf_func(struct wait_queue_entry * wait,unsigned mode,int sync,void * arg)754 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
755 			     int sync, void *arg)
756 {
757 	struct wait_page_queue *wpq;
758 	struct io_kiocb *req = wait->private;
759 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
760 	struct wait_page_key *key = arg;
761 
762 	wpq = container_of(wait, struct wait_page_queue, wait);
763 
764 	if (!wake_page_match(wpq, key))
765 		return 0;
766 
767 	rw->kiocb.ki_flags &= ~IOCB_WAITQ;
768 	list_del_init(&wait->entry);
769 	io_req_task_queue(req);
770 	return 1;
771 }
772 
773 /*
774  * This controls whether a given IO request should be armed for async page
775  * based retry. If we return false here, the request is handed to the async
776  * worker threads for retry. If we're doing buffered reads on a regular file,
777  * we prepare a private wait_page_queue entry and retry the operation. This
778  * will either succeed because the page is now uptodate and unlocked, or it
779  * will register a callback when the page is unlocked at IO completion. Through
780  * that callback, io_uring uses task_work to setup a retry of the operation.
781  * That retry will attempt the buffered read again. The retry will generally
782  * succeed, or in rare cases where it fails, we then fall back to using the
783  * async worker threads for a blocking retry.
784  */
io_rw_should_retry(struct io_kiocb * req)785 static bool io_rw_should_retry(struct io_kiocb *req)
786 {
787 	struct io_async_rw *io = req->async_data;
788 	struct wait_page_queue *wait = &io->wpq;
789 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
790 	struct kiocb *kiocb = &rw->kiocb;
791 
792 	/*
793 	 * Never retry for NOWAIT or a request with metadata, we just complete
794 	 * with -EAGAIN.
795 	 */
796 	if (req->flags & (REQ_F_NOWAIT | REQ_F_HAS_METADATA))
797 		return false;
798 
799 	/* Only for buffered IO */
800 	if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
801 		return false;
802 
803 	/*
804 	 * just use poll if we can, and don't attempt if the fs doesn't
805 	 * support callback based unlocks
806 	 */
807 	if (io_file_can_poll(req) ||
808 	    !(req->file->f_op->fop_flags & FOP_BUFFER_RASYNC))
809 		return false;
810 
811 	wait->wait.func = io_async_buf_func;
812 	wait->wait.private = req;
813 	wait->wait.flags = 0;
814 	INIT_LIST_HEAD(&wait->wait.entry);
815 	kiocb->ki_flags |= IOCB_WAITQ;
816 	kiocb->ki_flags &= ~IOCB_NOWAIT;
817 	kiocb->ki_waitq = wait;
818 	return true;
819 }
820 
io_iter_do_read(struct io_rw * rw,struct iov_iter * iter)821 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
822 {
823 	struct file *file = rw->kiocb.ki_filp;
824 
825 	if (likely(file->f_op->read_iter))
826 		return file->f_op->read_iter(&rw->kiocb, iter);
827 	else if (file->f_op->read)
828 		return loop_rw_iter(READ, rw, iter);
829 	else
830 		return -EINVAL;
831 }
832 
need_complete_io(struct io_kiocb * req)833 static bool need_complete_io(struct io_kiocb *req)
834 {
835 	return req->flags & REQ_F_ISREG ||
836 		S_ISBLK(file_inode(req->file)->i_mode);
837 }
838 
io_rw_init_file(struct io_kiocb * req,fmode_t mode,int rw_type)839 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode, int rw_type)
840 {
841 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
842 	struct kiocb *kiocb = &rw->kiocb;
843 	struct io_ring_ctx *ctx = req->ctx;
844 	struct file *file = req->file;
845 	int ret;
846 
847 	if (unlikely(!(file->f_mode & mode)))
848 		return -EBADF;
849 
850 	if (!(req->flags & REQ_F_FIXED_FILE))
851 		req->flags |= io_file_get_flags(file);
852 
853 	kiocb->ki_flags = file->f_iocb_flags;
854 	ret = kiocb_set_rw_flags(kiocb, rw->flags, rw_type);
855 	if (unlikely(ret))
856 		return ret;
857 
858 	/*
859 	 * If the file is marked O_NONBLOCK, still allow retry for it if it
860 	 * supports async. Otherwise it's impossible to use O_NONBLOCK files
861 	 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
862 	 */
863 	if (kiocb->ki_flags & IOCB_NOWAIT ||
864 	    ((file->f_flags & O_NONBLOCK && !(req->flags & REQ_F_SUPPORT_NOWAIT))))
865 		req->flags |= REQ_F_NOWAIT;
866 
867 	if (ctx->flags & IORING_SETUP_IOPOLL) {
868 		if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
869 			return -EOPNOTSUPP;
870 		req->flags |= REQ_F_IOPOLL;
871 		kiocb->private = NULL;
872 		kiocb->ki_flags |= IOCB_HIPRI;
873 		req->iopoll_completed = 0;
874 		if (ctx->flags & IORING_SETUP_HYBRID_IOPOLL) {
875 			/* make sure every req only blocks once*/
876 			req->flags &= ~REQ_F_IOPOLL_STATE;
877 			req->iopoll_start = ktime_get_ns();
878 		}
879 	} else {
880 		if (kiocb->ki_flags & IOCB_HIPRI)
881 			return -EINVAL;
882 	}
883 
884 	if (req->flags & REQ_F_HAS_METADATA) {
885 		struct io_async_rw *io = req->async_data;
886 
887 		if (!(file->f_mode & FMODE_HAS_METADATA))
888 			return -EINVAL;
889 
890 		/*
891 		 * We have a union of meta fields with wpq used for buffered-io
892 		 * in io_async_rw, so fail it here.
893 		 */
894 		if (!(file->f_flags & O_DIRECT))
895 			return -EOPNOTSUPP;
896 		kiocb->ki_flags |= IOCB_HAS_METADATA;
897 		kiocb->private = &io->meta;
898 	}
899 
900 	return 0;
901 }
902 
__io_read(struct io_kiocb * req,struct io_br_sel * sel,unsigned int issue_flags)903 static int __io_read(struct io_kiocb *req, struct io_br_sel *sel,
904 		     unsigned int issue_flags)
905 {
906 	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
907 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
908 	struct io_async_rw *io = req->async_data;
909 	struct kiocb *kiocb = &rw->kiocb;
910 	ssize_t ret;
911 	loff_t *ppos;
912 
913 	if (req->flags & REQ_F_IMPORT_BUFFER) {
914 		ret = io_rw_import_reg_vec(req, io, ITER_DEST, issue_flags);
915 		if (unlikely(ret))
916 			return ret;
917 	} else if (io_do_buffer_select(req)) {
918 		ret = io_import_rw_buffer(ITER_DEST, req, io, sel, issue_flags);
919 		if (unlikely(ret < 0))
920 			return ret;
921 	}
922 	ret = io_rw_init_file(req, FMODE_READ, READ);
923 	if (unlikely(ret))
924 		return ret;
925 	req->cqe.res = iov_iter_count(&io->iter);
926 
927 	if (force_nonblock) {
928 		/* If the file doesn't support async, just async punt */
929 		if (unlikely(!io_file_supports_nowait(req, EPOLLIN)))
930 			return -EAGAIN;
931 		kiocb->ki_flags |= IOCB_NOWAIT;
932 	} else {
933 		/* Ensure we clear previously set non-block flag */
934 		kiocb->ki_flags &= ~IOCB_NOWAIT;
935 	}
936 
937 	ppos = io_kiocb_update_pos(req);
938 
939 	ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
940 	if (unlikely(ret))
941 		return ret;
942 
943 	ret = io_iter_do_read(rw, &io->iter);
944 
945 	/*
946 	 * Some file systems like to return -EOPNOTSUPP for an IOCB_NOWAIT
947 	 * issue, even though they should be returning -EAGAIN. To be safe,
948 	 * retry from blocking context for either.
949 	 */
950 	if (ret == -EOPNOTSUPP && force_nonblock)
951 		ret = -EAGAIN;
952 
953 	if (ret == -EAGAIN) {
954 		/* If we can poll, just do that. */
955 		if (io_file_can_poll(req))
956 			return ret;
957 		/* IOPOLL retry should happen for io-wq threads */
958 		if (!force_nonblock && !(req->flags & REQ_F_IOPOLL))
959 			return ret;
960 		/* no retry on NONBLOCK nor RWF_NOWAIT */
961 		if (req->flags & REQ_F_NOWAIT)
962 			return ret;
963 		ret = 0;
964 	} else if (ret == -EIOCBQUEUED) {
965 		return IOU_ISSUE_SKIP_COMPLETE;
966 	} else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
967 		   (req->flags & REQ_F_NOWAIT) || !need_complete_io(req) ||
968 		   (issue_flags & IO_URING_F_MULTISHOT)) {
969 		/* read all, failed, already did sync or don't want to retry */
970 		return ret;
971 	}
972 
973 	/*
974 	 * Don't depend on the iter state matching what was consumed, or being
975 	 * untouched in case of error. Restore it and we'll advance it
976 	 * manually if we need to.
977 	 */
978 	iov_iter_restore(&io->iter, &io->iter_state);
979 	io_meta_restore(io, kiocb);
980 
981 	do {
982 		/*
983 		 * We end up here because of a partial read, either from
984 		 * above or inside this loop. Advance the iter by the bytes
985 		 * that were consumed.
986 		 */
987 		iov_iter_advance(&io->iter, ret);
988 		if (!iov_iter_count(&io->iter))
989 			break;
990 		io->bytes_done += ret;
991 		iov_iter_save_state(&io->iter, &io->iter_state);
992 
993 		/* if we can retry, do so with the callbacks armed */
994 		if (!io_rw_should_retry(req)) {
995 			kiocb->ki_flags &= ~IOCB_WAITQ;
996 			return -EAGAIN;
997 		}
998 
999 		req->cqe.res = iov_iter_count(&io->iter);
1000 		/*
1001 		 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
1002 		 * we get -EIOCBQUEUED, then we'll get a notification when the
1003 		 * desired page gets unlocked. We can also get a partial read
1004 		 * here, and if we do, then just retry at the new offset.
1005 		 */
1006 		ret = io_iter_do_read(rw, &io->iter);
1007 		if (ret == -EIOCBQUEUED)
1008 			return IOU_ISSUE_SKIP_COMPLETE;
1009 		/* we got some bytes, but not all. retry. */
1010 		kiocb->ki_flags &= ~IOCB_WAITQ;
1011 		iov_iter_restore(&io->iter, &io->iter_state);
1012 	} while (ret > 0);
1013 
1014 	return ret;
1015 }
1016 
io_read(struct io_kiocb * req,unsigned int issue_flags)1017 int io_read(struct io_kiocb *req, unsigned int issue_flags)
1018 {
1019 	struct io_br_sel sel = { };
1020 	int ret;
1021 
1022 	ret = __io_read(req, &sel, issue_flags);
1023 	if (ret >= 0)
1024 		return kiocb_done(req, ret, &sel, issue_flags);
1025 
1026 	if (req->flags & REQ_F_BUFFERS_COMMIT)
1027 		io_kbuf_recycle(req, sel.buf_list, issue_flags);
1028 
1029 	return io_fixup_restart_res(ret);
1030 }
1031 
io_read_mshot(struct io_kiocb * req,unsigned int issue_flags)1032 int io_read_mshot(struct io_kiocb *req, unsigned int issue_flags)
1033 {
1034 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
1035 	struct io_br_sel sel = { };
1036 	unsigned int cflags = 0;
1037 	int ret;
1038 
1039 	/*
1040 	 * Multishot MUST be used on a pollable file
1041 	 */
1042 	if (!io_file_can_poll(req))
1043 		return -EBADFD;
1044 
1045 	/* make it sync, multishot doesn't support async execution */
1046 	rw->kiocb.ki_complete = NULL;
1047 	ret = __io_read(req, &sel, issue_flags);
1048 
1049 	/*
1050 	 * If we get -EAGAIN, recycle our buffer and just let normal poll
1051 	 * handling arm it.
1052 	 */
1053 	if (ret == -EAGAIN) {
1054 		/*
1055 		 * Reset rw->len to 0 again to avoid clamping future mshot
1056 		 * reads, in case the buffer size varies.
1057 		 */
1058 		if (io_kbuf_recycle(req, sel.buf_list, issue_flags))
1059 			rw->len = 0;
1060 		return IOU_RETRY;
1061 	} else if (ret <= 0) {
1062 		io_kbuf_recycle(req, sel.buf_list, issue_flags);
1063 		if (ret < 0) {
1064 			ret = io_fixup_restart_res(ret);
1065 			req_set_fail(req);
1066 		}
1067 	} else if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
1068 		cflags = io_put_kbuf(req, ret, sel.buf_list);
1069 	} else {
1070 		/*
1071 		 * Any successful return value will keep the multishot read
1072 		 * armed, if it's still set. Put our buffer and post a CQE. If
1073 		 * we fail to post a CQE, or multishot is no longer set, then
1074 		 * jump to the termination path. This request is then done.
1075 		 */
1076 		cflags = io_put_kbuf(req, ret, sel.buf_list);
1077 		rw->len = 0; /* similarly to above, reset len to 0 */
1078 
1079 		if (io_req_post_cqe(req, ret, cflags | IORING_CQE_F_MORE)) {
1080 			if (issue_flags & IO_URING_F_MULTISHOT)
1081 				/*
1082 				 * Force retry, as we might have more data to
1083 				 * be read and otherwise it won't get retried
1084 				 * until (if ever) another poll is triggered.
1085 				 */
1086 				io_poll_multishot_retry(req);
1087 
1088 			return IOU_RETRY;
1089 		}
1090 	}
1091 
1092 	/*
1093 	 * Either an error, or we've hit overflow posting the CQE. For any
1094 	 * multishot request, hitting overflow will terminate it.
1095 	 */
1096 	io_req_set_res(req, ret, cflags);
1097 	io_req_rw_cleanup(req, issue_flags);
1098 	return IOU_COMPLETE;
1099 }
1100 
io_kiocb_start_write(struct io_kiocb * req,struct kiocb * kiocb)1101 static bool io_kiocb_start_write(struct io_kiocb *req, struct kiocb *kiocb)
1102 {
1103 	struct inode *inode;
1104 	bool ret;
1105 
1106 	if (!(req->flags & REQ_F_ISREG))
1107 		return true;
1108 	if (!(kiocb->ki_flags & IOCB_NOWAIT)) {
1109 		kiocb_start_write(kiocb);
1110 		return true;
1111 	}
1112 
1113 	inode = file_inode(kiocb->ki_filp);
1114 	ret = sb_start_write_trylock(inode->i_sb);
1115 	if (ret)
1116 		__sb_writers_release(inode->i_sb, SB_FREEZE_WRITE);
1117 	return ret;
1118 }
1119 
io_write(struct io_kiocb * req,unsigned int issue_flags)1120 int io_write(struct io_kiocb *req, unsigned int issue_flags)
1121 {
1122 	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
1123 	struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
1124 	struct io_async_rw *io = req->async_data;
1125 	struct kiocb *kiocb = &rw->kiocb;
1126 	ssize_t ret, ret2;
1127 	loff_t *ppos;
1128 
1129 	if (req->flags & REQ_F_IMPORT_BUFFER) {
1130 		ret = io_rw_import_reg_vec(req, io, ITER_SOURCE, issue_flags);
1131 		if (unlikely(ret))
1132 			return ret;
1133 	}
1134 
1135 	ret = io_rw_init_file(req, FMODE_WRITE, WRITE);
1136 	if (unlikely(ret))
1137 		return ret;
1138 	req->cqe.res = iov_iter_count(&io->iter);
1139 
1140 	if (force_nonblock) {
1141 		/* If the file doesn't support async, just async punt */
1142 		if (unlikely(!io_file_supports_nowait(req, EPOLLOUT)))
1143 			goto ret_eagain;
1144 
1145 		/* Check if we can support NOWAIT. */
1146 		if (!(kiocb->ki_flags & IOCB_DIRECT) &&
1147 		    !(req->file->f_op->fop_flags & FOP_BUFFER_WASYNC) &&
1148 		    (req->flags & REQ_F_ISREG))
1149 			goto ret_eagain;
1150 
1151 		kiocb->ki_flags |= IOCB_NOWAIT;
1152 	} else {
1153 		/* Ensure we clear previously set non-block flag */
1154 		kiocb->ki_flags &= ~IOCB_NOWAIT;
1155 	}
1156 
1157 	ppos = io_kiocb_update_pos(req);
1158 
1159 	ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
1160 	if (unlikely(ret))
1161 		return ret;
1162 
1163 	if (unlikely(!io_kiocb_start_write(req, kiocb)))
1164 		return -EAGAIN;
1165 	kiocb->ki_flags |= IOCB_WRITE;
1166 
1167 	if (likely(req->file->f_op->write_iter))
1168 		ret2 = req->file->f_op->write_iter(kiocb, &io->iter);
1169 	else if (req->file->f_op->write)
1170 		ret2 = loop_rw_iter(WRITE, rw, &io->iter);
1171 	else
1172 		ret2 = -EINVAL;
1173 
1174 	/*
1175 	 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
1176 	 * retry them without IOCB_NOWAIT.
1177 	 */
1178 	if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
1179 		ret2 = -EAGAIN;
1180 	/* no retry on NONBLOCK nor RWF_NOWAIT */
1181 	if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
1182 		goto done;
1183 	if (!force_nonblock || ret2 != -EAGAIN) {
1184 		/* IOPOLL retry should happen for io-wq threads */
1185 		if (ret2 == -EAGAIN && (req->flags & REQ_F_IOPOLL))
1186 			goto ret_eagain;
1187 
1188 		if (ret2 != req->cqe.res && ret2 >= 0 && need_complete_io(req)) {
1189 			trace_io_uring_short_write(req->ctx, kiocb->ki_pos - ret2,
1190 						req->cqe.res, ret2);
1191 
1192 			/* This is a partial write. The file pos has already been
1193 			 * updated, setup the async struct to complete the request
1194 			 * in the worker. Also update bytes_done to account for
1195 			 * the bytes already written.
1196 			 */
1197 			iov_iter_save_state(&io->iter, &io->iter_state);
1198 			io->bytes_done += ret2;
1199 
1200 			if (kiocb->ki_flags & IOCB_WRITE)
1201 				io_req_end_write(req);
1202 			return -EAGAIN;
1203 		}
1204 done:
1205 		return kiocb_done(req, ret2, NULL, issue_flags);
1206 	} else {
1207 ret_eagain:
1208 		iov_iter_restore(&io->iter, &io->iter_state);
1209 		io_meta_restore(io, kiocb);
1210 		if (kiocb->ki_flags & IOCB_WRITE)
1211 			io_req_end_write(req);
1212 		return -EAGAIN;
1213 	}
1214 }
1215 
io_read_fixed(struct io_kiocb * req,unsigned int issue_flags)1216 int io_read_fixed(struct io_kiocb *req, unsigned int issue_flags)
1217 {
1218 	int ret;
1219 
1220 	ret = io_init_rw_fixed(req, issue_flags, ITER_DEST);
1221 	if (unlikely(ret))
1222 		return ret;
1223 
1224 	return io_read(req, issue_flags);
1225 }
1226 
io_write_fixed(struct io_kiocb * req,unsigned int issue_flags)1227 int io_write_fixed(struct io_kiocb *req, unsigned int issue_flags)
1228 {
1229 	int ret;
1230 
1231 	ret = io_init_rw_fixed(req, issue_flags, ITER_SOURCE);
1232 	if (unlikely(ret))
1233 		return ret;
1234 
1235 	return io_write(req, issue_flags);
1236 }
1237 
io_rw_fail(struct io_kiocb * req)1238 void io_rw_fail(struct io_kiocb *req)
1239 {
1240 	int res;
1241 
1242 	res = io_fixup_rw_res(req, req->cqe.res);
1243 	io_req_set_res(req, res, req->cqe.flags);
1244 }
1245 
io_uring_classic_poll(struct io_kiocb * req,struct io_comp_batch * iob,unsigned int poll_flags)1246 static int io_uring_classic_poll(struct io_kiocb *req, struct io_comp_batch *iob,
1247 				unsigned int poll_flags)
1248 {
1249 	struct file *file = req->file;
1250 
1251 	if (io_is_uring_cmd(req)) {
1252 		struct io_uring_cmd *ioucmd;
1253 
1254 		ioucmd = io_kiocb_to_cmd(req, struct io_uring_cmd);
1255 		return file->f_op->uring_cmd_iopoll(ioucmd, iob, poll_flags);
1256 	} else {
1257 		struct io_rw *rw = io_kiocb_to_cmd(req, struct io_rw);
1258 
1259 		return file->f_op->iopoll(&rw->kiocb, iob, poll_flags);
1260 	}
1261 }
1262 
io_hybrid_iopoll_delay(struct io_ring_ctx * ctx,struct io_kiocb * req)1263 static u64 io_hybrid_iopoll_delay(struct io_ring_ctx *ctx, struct io_kiocb *req)
1264 {
1265 	struct hrtimer_sleeper timer;
1266 	enum hrtimer_mode mode;
1267 	ktime_t kt;
1268 	u64 sleep_time;
1269 
1270 	if (req->flags & REQ_F_IOPOLL_STATE)
1271 		return 0;
1272 
1273 	if (ctx->hybrid_poll_time == LLONG_MAX)
1274 		return 0;
1275 
1276 	/* Using half the running time to do schedule */
1277 	sleep_time = ctx->hybrid_poll_time / 2;
1278 
1279 	kt = ktime_set(0, sleep_time);
1280 	req->flags |= REQ_F_IOPOLL_STATE;
1281 
1282 	mode = HRTIMER_MODE_REL;
1283 	hrtimer_setup_sleeper_on_stack(&timer, CLOCK_MONOTONIC, mode);
1284 	hrtimer_set_expires(&timer.timer, kt);
1285 	set_current_state(TASK_INTERRUPTIBLE);
1286 	hrtimer_sleeper_start_expires(&timer, mode);
1287 
1288 	if (timer.task)
1289 		io_schedule();
1290 
1291 	hrtimer_cancel(&timer.timer);
1292 	__set_current_state(TASK_RUNNING);
1293 	destroy_hrtimer_on_stack(&timer.timer);
1294 	return sleep_time;
1295 }
1296 
io_uring_hybrid_poll(struct io_kiocb * req,struct io_comp_batch * iob,unsigned int poll_flags)1297 static int io_uring_hybrid_poll(struct io_kiocb *req,
1298 				struct io_comp_batch *iob, unsigned int poll_flags)
1299 {
1300 	struct io_ring_ctx *ctx = req->ctx;
1301 	u64 runtime, sleep_time, iopoll_start;
1302 	int ret;
1303 
1304 	iopoll_start = READ_ONCE(req->iopoll_start);
1305 	sleep_time = io_hybrid_iopoll_delay(ctx, req);
1306 	ret = io_uring_classic_poll(req, iob, poll_flags);
1307 	runtime = ktime_get_ns() - iopoll_start - sleep_time;
1308 
1309 	/*
1310 	 * Use minimum sleep time if we're polling devices with different
1311 	 * latencies. We could get more completions from the faster ones.
1312 	 */
1313 	if (ctx->hybrid_poll_time > runtime)
1314 		ctx->hybrid_poll_time = runtime;
1315 
1316 	return ret;
1317 }
1318 
io_do_iopoll(struct io_ring_ctx * ctx,bool force_nonspin)1319 int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
1320 {
1321 	unsigned int poll_flags = 0;
1322 	DEFINE_IO_COMP_BATCH(iob);
1323 	struct io_kiocb *req, *tmp;
1324 	int nr_events = 0;
1325 
1326 	/*
1327 	 * Store the polling io_ring_ctx so drivers can detect if they're
1328 	 * completing a request in the same ring context that's polling.
1329 	 */
1330 	iob.poll_ctx = ctx;
1331 
1332 	/*
1333 	 * Only spin for completions if we don't have multiple devices hanging
1334 	 * off our complete list.
1335 	 */
1336 	if (ctx->poll_multi_queue || force_nonspin)
1337 		poll_flags |= BLK_POLL_ONESHOT;
1338 
1339 	list_for_each_entry(req, &ctx->iopoll_list, iopoll_node) {
1340 		int ret;
1341 
1342 		/*
1343 		 * Move completed and retryable entries to our local lists.
1344 		 * If we find a request that requires polling, break out
1345 		 * and complete those lists first, if we have entries there.
1346 		 */
1347 		if (READ_ONCE(req->iopoll_completed))
1348 			break;
1349 
1350 		if (ctx->flags & IORING_SETUP_HYBRID_IOPOLL)
1351 			ret = io_uring_hybrid_poll(req, &iob, poll_flags);
1352 		else
1353 			ret = io_uring_classic_poll(req, &iob, poll_flags);
1354 
1355 		if (unlikely(ret < 0))
1356 			return ret;
1357 		else if (ret)
1358 			poll_flags |= BLK_POLL_ONESHOT;
1359 
1360 		/* iopoll may have completed current req */
1361 		if (!rq_list_empty(&iob.req_list) ||
1362 		    READ_ONCE(req->iopoll_completed))
1363 			break;
1364 	}
1365 
1366 	if (!rq_list_empty(&iob.req_list))
1367 		iob.complete(&iob);
1368 
1369 	list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, iopoll_node) {
1370 		/* order with io_complete_rw_iopoll(), e.g. ->result updates */
1371 		if (!smp_load_acquire(&req->iopoll_completed))
1372 			continue;
1373 		list_del(&req->iopoll_node);
1374 		wq_list_add_tail(&req->comp_list, &ctx->submit_state.compl_reqs);
1375 		nr_events++;
1376 		req->cqe.flags = io_put_kbuf(req, max(req->cqe.res, 0), NULL);
1377 		if (!io_is_uring_cmd(req))
1378 			io_req_rw_cleanup(req, 0);
1379 	}
1380 	if (nr_events)
1381 		__io_submit_flush_completions(ctx);
1382 	return nr_events;
1383 }
1384 
io_rw_cache_free(const void * entry)1385 void io_rw_cache_free(const void *entry)
1386 {
1387 	struct io_async_rw *rw = (struct io_async_rw *) entry;
1388 
1389 	io_vec_free(&rw->vec);
1390 	kfree(rw);
1391 }
1392