xref: /linux/io_uring/wait.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Waiting for completion events
4  */
5 #include <linux/kernel.h>
6 #include <linux/sched/rt.h>
7 #include <linux/sched/signal.h>
8 #include <linux/io_uring.h>
9 #include <linux/time_namespace.h>
10 
11 #include <trace/events/io_uring.h>
12 
13 #include <uapi/linux/io_uring.h>
14 
15 #include "io_uring.h"
16 #include "napi.h"
17 #include "wait.h"
18 
19 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
20 			    int wake_flags, void *key)
21 {
22 	struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
23 
24 	/*
25 	 * Cannot safely flush overflowed CQEs from here, ensure we wake up
26 	 * the task, and the next invocation will do it.
27 	 */
28 	if (io_should_wake(iowq) || io_has_work(iowq->ctx))
29 		return autoremove_wake_function(curr, mode, wake_flags, key);
30 	/* keep going, a waiter further down may be content with less */
31 	return 0;
32 }
33 
34 int io_run_task_work_sig(struct io_ring_ctx *ctx)
35 {
36 	if (io_local_work_pending(ctx)) {
37 		__set_current_state(TASK_RUNNING);
38 		if (io_run_local_work(ctx, INT_MAX, IO_LOCAL_TW_DEFAULT_MAX) > 0)
39 			return 0;
40 	}
41 	if (io_run_task_work() > 0)
42 		return 0;
43 	if (task_sigpending(current))
44 		return -EINTR;
45 	return 0;
46 }
47 
48 static bool current_pending_io(void)
49 {
50 	struct io_uring_task *tctx = current->io_uring;
51 
52 	if (!tctx)
53 		return false;
54 	return percpu_counter_read_positive(&tctx->inflight);
55 }
56 
57 static enum hrtimer_restart io_cqring_timer_wakeup(struct hrtimer *timer)
58 {
59 	struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
60 
61 	WRITE_ONCE(iowq->hit_timeout, 1);
62 	iowq->min_timeout = 0;
63 	wake_up_process(iowq->wq.private);
64 	return HRTIMER_NORESTART;
65 }
66 
67 /*
68  * Doing min_timeout portion. If we saw any timeouts, events, or have work,
69  * wake up. If not, and we have a normal timeout, switch to that and keep
70  * sleeping.
71  */
72 static enum hrtimer_restart io_cqring_min_timer_wakeup(struct hrtimer *timer)
73 {
74 	struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
75 	struct io_ring_ctx *ctx = iowq->ctx;
76 
77 	/* no general timeout, or shorter (or equal), we are done */
78 	if (iowq->timeout == KTIME_MAX ||
79 	    ktime_compare(iowq->min_timeout, iowq->timeout) >= 0)
80 		goto out_wake;
81 	/*
82 	 * Work we need to run. It isn't known if that is going to post a CQE,
83 	 * so this isn't a timeout. Carry on with the normal one if it doesn't.
84 	 */
85 	if (io_has_work(ctx)) {
86 		iowq->min_timeout = 0;
87 		iowq->cq_tail = iowq->cq_min_tail + 1;
88 		wake_up_process(iowq->wq.private);
89 		return HRTIMER_NORESTART;
90 	}
91 	/* got events since we started waiting, min timeout is done */
92 	scoped_guard(rcu) {
93 		struct io_rings *rings = io_get_rings(ctx);
94 
95 		if (iowq->cq_min_tail != READ_ONCE(rings->cq.tail))
96 			goto out_wake;
97 		/* if we have any events and min timeout expired, we're done */
98 		if (io_cqring_events(ctx))
99 			goto out_wake;
100 	}
101 	/*
102 	 * If using deferred task_work running and application is waiting on
103 	 * more than one request, ensure we reset it now where we are switching
104 	 * to normal sleeps. Any request completion post min_wait should wake
105 	 * the task and return.
106 	 */
107 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
108 		atomic_set(&ctx->cq_wait_nr, 1);
109 		smp_mb();
110 		if (io_local_work_pending(ctx))
111 			goto out_wake;
112 	}
113 
114 	/* any generated CQE posted past this time should wake us up */
115 	iowq->cq_tail = iowq->cq_min_tail + 1;
116 
117 	hrtimer_update_function(&iowq->t, io_cqring_timer_wakeup);
118 	hrtimer_set_expires(timer, iowq->timeout);
119 	return HRTIMER_RESTART;
120 out_wake:
121 	return io_cqring_timer_wakeup(timer);
122 }
123 
124 /* Same policy as for hrtimer sleepers, see __hrtimer_setup_sleeper(). */
125 static enum hrtimer_mode io_cqring_timer_mode(void)
126 {
127 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && rt_or_dl_task_policy(current))
128 		return HRTIMER_MODE_ABS_HARD;
129 	return HRTIMER_MODE_ABS;
130 }
131 
132 static int io_cqring_schedule_timeout(struct io_wait_queue *iowq,
133 				      clockid_t clock_id, ktime_t start_time)
134 {
135 	enum hrtimer_mode mode = io_cqring_timer_mode();
136 	ktime_t timeout;
137 
138 	if (iowq->min_timeout) {
139 		timeout = ktime_add_ns(iowq->min_timeout, start_time);
140 		hrtimer_setup_on_stack(&iowq->t, io_cqring_min_timer_wakeup, clock_id,
141 				       mode);
142 	} else {
143 		timeout = iowq->timeout;
144 		hrtimer_setup_on_stack(&iowq->t, io_cqring_timer_wakeup, clock_id,
145 				       mode);
146 	}
147 
148 	hrtimer_set_expires_range_ns(&iowq->t, timeout, 0);
149 	hrtimer_start_expires(&iowq->t, mode);
150 
151 	if (!READ_ONCE(iowq->hit_timeout))
152 		schedule();
153 
154 	hrtimer_cancel(&iowq->t);
155 	destroy_hrtimer_on_stack(&iowq->t);
156 	__set_current_state(TASK_RUNNING);
157 
158 	return READ_ONCE(iowq->hit_timeout) ? -ETIME : 0;
159 }
160 
161 static int __io_cqring_wait_schedule(struct io_ring_ctx *ctx,
162 				     struct io_wait_queue *iowq,
163 				     struct ext_arg *ext_arg,
164 				     ktime_t start_time)
165 {
166 	int ret = 0;
167 
168 	/*
169 	 * Don't arm a timer for a timeout that has already passed, it would
170 	 * only fire to return -ETIME. NAPI busy polling gets here like that.
171 	 */
172 	if (iowq->timeout != KTIME_MAX &&
173 	    ktime_compare(io_get_time(ctx), iowq->timeout) >= 0)
174 		return -ETIME;
175 
176 	/*
177 	 * Mark us as being in io_wait if we have pending requests, so cpufreq
178 	 * can take into account that the task is waiting for IO - turns out
179 	 * to be important for low QD IO.
180 	 */
181 	if (ext_arg->iowait && current_pending_io())
182 		current->in_iowait = 1;
183 	if (iowq->timeout != KTIME_MAX || iowq->min_timeout)
184 		ret = io_cqring_schedule_timeout(iowq, ctx->clockid, start_time);
185 	else
186 		schedule();
187 	current->in_iowait = 0;
188 	return ret;
189 }
190 
191 /* If this returns > 0, the caller should retry */
192 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
193 					  struct io_wait_queue *iowq,
194 					  struct ext_arg *ext_arg,
195 					  ktime_t start_time)
196 {
197 	if (unlikely(READ_ONCE(ctx->check_cq)))
198 		return 1;
199 	if (unlikely(io_local_work_pending(ctx)))
200 		return 1;
201 	if (unlikely(task_work_pending(current)))
202 		return 1;
203 	if (unlikely(task_sigpending(current)))
204 		return -EINTR;
205 	if (unlikely(io_should_wake(iowq)))
206 		return 0;
207 
208 	return __io_cqring_wait_schedule(ctx, iowq, ext_arg, start_time);
209 }
210 
211 /*
212  * Wait until events become available, if we don't already have some. The
213  * application must reap them itself, as they reside on the shared cq ring.
214  */
215 int io_cqring_wait(struct io_ring_ctx *ctx, int min_events, u32 flags,
216 		   struct ext_arg *ext_arg)
217 {
218 	struct io_wait_queue iowq;
219 	struct io_rings *rings;
220 	ktime_t start_time;
221 	int ret, nr_wait;
222 
223 	min_events = min_t(int, min_events, ctx->cq_entries);
224 
225 	if (!io_allowed_run_tw(ctx))
226 		return -EEXIST;
227 	if (io_local_work_pending(ctx))
228 		io_run_local_work(ctx, min_events,
229 				  max(IO_LOCAL_TW_DEFAULT_MAX, min_events));
230 	io_run_task_work();
231 
232 	if (unlikely(test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)))
233 		io_cqring_do_overflow_flush(ctx);
234 
235 	rcu_read_lock();
236 	rings = io_get_rings(ctx);
237 	if (__io_cqring_events_user(ctx) >= min_events) {
238 		rcu_read_unlock();
239 		return 0;
240 	}
241 
242 	init_waitqueue_func_entry(&iowq.wq, io_wake_function);
243 	iowq.wq.private = current;
244 	INIT_LIST_HEAD(&iowq.wq.entry);
245 	iowq.ctx = ctx;
246 	iowq.cq_tail = READ_ONCE(rings->cq.head) + min_events;
247 	iowq.cq_min_tail = READ_ONCE(rings->cq.tail);
248 	nr_wait = (int) iowq.cq_tail - READ_ONCE(rings->cq.tail);
249 	rcu_read_unlock();
250 	rings = NULL;
251 	iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
252 	iowq.hit_timeout = 0;
253 	iowq.min_timeout = ext_arg->min_time;
254 	iowq.timeout = KTIME_MAX;
255 	start_time = io_get_time(ctx);
256 
257 	if (ext_arg->ts_set) {
258 		iowq.timeout = timespec64_to_ktime(ext_arg->ts);
259 		if (flags & IORING_ENTER_ABS_TIMER)
260 			iowq.timeout = timens_ktime_to_host(ctx->clockid,
261 							    iowq.timeout);
262 		else
263 			iowq.timeout = ktime_add(iowq.timeout, start_time);
264 	}
265 
266 	if (ext_arg->sig) {
267 #ifdef CONFIG_COMPAT
268 		if (in_compat_syscall())
269 			ret = set_compat_user_sigmask((const compat_sigset_t __user *)ext_arg->sig,
270 						      ext_arg->argsz);
271 		else
272 #endif
273 			ret = set_user_sigmask(ext_arg->sig, ext_arg->argsz);
274 
275 		if (ret)
276 			return ret;
277 	}
278 
279 	io_napi_busy_loop(ctx, &iowq);
280 
281 	trace_io_uring_cqring_wait(ctx, min_events);
282 	do {
283 		unsigned long check_cq;
284 
285 		if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
286 			io_cq_wait_arm(ctx, nr_wait);
287 		} else {
288 			prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
289 							TASK_INTERRUPTIBLE);
290 		}
291 
292 		ret = io_cqring_wait_schedule(ctx, &iowq, ext_arg, start_time);
293 		__set_current_state(TASK_RUNNING);
294 		atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
295 
296 		/*
297 		 * Run task_work after scheduling and before io_should_wake().
298 		 * If we got woken because of task_work being processed, run it
299 		 * now rather than let the caller do another wait loop.
300 		 */
301 		if (io_local_work_pending(ctx))
302 			io_run_local_work(ctx, nr_wait, nr_wait);
303 		io_run_task_work();
304 
305 		/*
306 		 * Non-local task_work will be run on exit to userspace, but
307 		 * if we're using DEFER_TASKRUN, then we could have waited
308 		 * with a timeout for a number of requests. If the timeout
309 		 * hits, we could have some requests ready to process. Ensure
310 		 * this break is _after_ we have run task_work, to avoid
311 		 * deferring running potentially pending requests until the
312 		 * next time we wait for events.
313 		 */
314 		if (ret < 0)
315 			break;
316 
317 		check_cq = READ_ONCE(ctx->check_cq);
318 		if (unlikely(check_cq)) {
319 			if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)) {
320 				io_cqring_do_overflow_flush(ctx);
321 				/*
322 				 * No room for what has overflown. It takes the
323 				 * application to change that, so return to it.
324 				 */
325 				if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT,
326 					     &ctx->check_cq)) {
327 					ret = 0;
328 					break;
329 				}
330 			}
331 			if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
332 				ret = -EBADR;
333 				break;
334 			}
335 		}
336 
337 		if (io_should_wake(&iowq)) {
338 			ret = 0;
339 			break;
340 		}
341 		cond_resched();
342 
343 		/* if min timeout has been hit, don't reset wait count */
344 		if (!iowq.hit_timeout)
345 			scoped_guard(rcu)
346 				nr_wait = (int) iowq.cq_tail -
347 						READ_ONCE(io_get_rings(ctx)->cq.tail);
348 		else
349 			nr_wait = 1;
350 	} while (1);
351 
352 	if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
353 		finish_wait(&ctx->cq_wait, &iowq.wq);
354 	restore_saved_sigmask_unless(ret == -EINTR);
355 
356 	guard(rcu)();
357 	return READ_ONCE(io_get_rings(ctx)->cq.head) == READ_ONCE(io_get_rings(ctx)->cq.tail) ? ret : 0;
358 }
359