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