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