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