xref: /linux/io_uring/loop.c (revision 8257f6ec45ee07c6ed933c59d8982b03cc7bc1ca)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include "io_uring.h"
3 #include "wait.h"
4 #include "loop.h"
5 #include "tctx.h"
6 
7 static inline int io_loop_nr_cqes(const struct io_ring_ctx *ctx,
8 				  const struct iou_loop_params *lp)
9 {
10 	return lp->cq_wait_idx - READ_ONCE(ctx->rings->cq.tail);
11 }
12 
13 static inline void io_loop_wait_finish(struct io_ring_ctx *ctx)
14 {
15 	__set_current_state(TASK_RUNNING);
16 	atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
17 }
18 
19 static void io_loop_wait(struct io_ring_ctx *ctx, struct iou_loop_params *lp,
20 			 unsigned nr_wait)
21 {
22 	io_cq_wait_arm(ctx, nr_wait);
23 
24 	if (unlikely(io_local_work_pending(ctx) ||
25 		     io_loop_nr_cqes(ctx, lp) <= 0) ||
26 		     READ_ONCE(ctx->check_cq)) {
27 		io_loop_wait_finish(ctx);
28 		return;
29 	}
30 
31 	mutex_unlock(&ctx->uring_lock);
32 	schedule();
33 	io_loop_wait_finish(ctx);
34 	mutex_lock(&ctx->uring_lock);
35 }
36 
37 static int __io_run_loop(struct io_ring_ctx *ctx)
38 {
39 	struct iou_loop_params lp = {};
40 
41 	while (true) {
42 		int nr_wait, step_res;
43 
44 		if (unlikely(!ctx->loop_step))
45 			return -EFAULT;
46 
47 		step_res = ctx->loop_step(io_loop_mangle_ctx(ctx), &lp);
48 		if (step_res == IOU_LOOP_STOP)
49 			break;
50 		if (step_res != IOU_LOOP_CONTINUE)
51 			return -EINVAL;
52 
53 		nr_wait = io_loop_nr_cqes(ctx, &lp);
54 		if (nr_wait > 0)
55 			io_loop_wait(ctx, &lp, nr_wait);
56 		else
57 			nr_wait = 0;
58 
59 		if (task_work_pending(current)) {
60 			mutex_unlock(&ctx->uring_lock);
61 			io_run_task_work();
62 			mutex_lock(&ctx->uring_lock);
63 		}
64 		if (unlikely(task_sigpending(current)))
65 			return -EINTR;
66 		io_run_local_work_locked(ctx, nr_wait);
67 
68 		if (READ_ONCE(ctx->check_cq) & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
69 			io_cqring_overflow_flush_locked(ctx);
70 	}
71 
72 	return 0;
73 }
74 
75 int io_run_loop(struct io_ring_ctx *ctx)
76 {
77 	int ret;
78 
79 	ret = io_uring_add_tctx_node(ctx);
80 	if (unlikely(ret))
81 		return ret;
82 
83 	if (!io_allowed_run_tw(ctx))
84 		return -EEXIST;
85 
86 	mutex_lock(&ctx->uring_lock);
87 	ret = __io_run_loop(ctx);
88 	mutex_unlock(&ctx->uring_lock);
89 	return ret;
90 }
91