1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
41 */
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <net/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
49 #include <linux/bits.h>
50
51 #include <linux/sched/signal.h>
52 #include <linux/fs.h>
53 #include <linux/file.h>
54 #include <linux/mm.h>
55 #include <linux/mman.h>
56 #include <linux/percpu.h>
57 #include <linux/slab.h>
58 #include <linux/bvec.h>
59 #include <linux/net.h>
60 #include <net/sock.h>
61 #include <linux/anon_inodes.h>
62 #include <linux/sched/mm.h>
63 #include <linux/uaccess.h>
64 #include <linux/nospec.h>
65 #include <linux/fsnotify.h>
66 #include <linux/fadvise.h>
67 #include <linux/task_work.h>
68 #include <linux/io_uring.h>
69 #include <linux/io_uring/cmd.h>
70 #include <linux/audit.h>
71 #include <linux/security.h>
72 #include <linux/jump_label.h>
73 #include <asm/shmparam.h>
74
75 #define CREATE_TRACE_POINTS
76 #include <trace/events/io_uring.h>
77
78 #include <uapi/linux/io_uring.h>
79
80 #include "io-wq.h"
81
82 #include "io_uring.h"
83 #include "opdef.h"
84 #include "refs.h"
85 #include "tctx.h"
86 #include "register.h"
87 #include "sqpoll.h"
88 #include "fdinfo.h"
89 #include "kbuf.h"
90 #include "rsrc.h"
91 #include "cancel.h"
92 #include "net.h"
93 #include "notif.h"
94 #include "waitid.h"
95 #include "futex.h"
96 #include "napi.h"
97 #include "uring_cmd.h"
98 #include "msg_ring.h"
99 #include "memmap.h"
100 #include "zcrx.h"
101
102 #include "timeout.h"
103 #include "poll.h"
104 #include "rw.h"
105 #include "alloc_cache.h"
106 #include "eventfd.h"
107
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113
114 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
115
116 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
117 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
118 REQ_F_ASYNC_DATA)
119
120 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | IO_REQ_LINK_FLAGS | \
121 REQ_F_REISSUE | IO_REQ_CLEAN_FLAGS)
122
123 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
124
125 #define IO_COMPL_BATCH 32
126 #define IO_REQ_ALLOC_BATCH 8
127 #define IO_LOCAL_TW_DEFAULT_MAX 20
128
129 struct io_defer_entry {
130 struct list_head list;
131 struct io_kiocb *req;
132 };
133
134 /* requests with any of those set should undergo io_disarm_next() */
135 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
136
137 /*
138 * No waiters. It's larger than any valid value of the tw counter
139 * so that tests against ->cq_wait_nr would fail and skip wake_up().
140 */
141 #define IO_CQ_WAKE_INIT (-1U)
142 /* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
143 #define IO_CQ_WAKE_FORCE (IO_CQ_WAKE_INIT >> 1)
144
145 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
146 struct io_uring_task *tctx,
147 bool cancel_all,
148 bool is_sqpoll_thread);
149
150 static void io_queue_sqe(struct io_kiocb *req);
151 static void __io_req_caches_free(struct io_ring_ctx *ctx);
152
153 static __read_mostly DEFINE_STATIC_KEY_FALSE(io_key_has_sqarray);
154
155 struct kmem_cache *req_cachep;
156 static struct workqueue_struct *iou_wq __ro_after_init;
157
158 static int __read_mostly sysctl_io_uring_disabled;
159 static int __read_mostly sysctl_io_uring_group = -1;
160
161 #ifdef CONFIG_SYSCTL
162 static const struct ctl_table kernel_io_uring_disabled_table[] = {
163 {
164 .procname = "io_uring_disabled",
165 .data = &sysctl_io_uring_disabled,
166 .maxlen = sizeof(sysctl_io_uring_disabled),
167 .mode = 0644,
168 .proc_handler = proc_dointvec_minmax,
169 .extra1 = SYSCTL_ZERO,
170 .extra2 = SYSCTL_TWO,
171 },
172 {
173 .procname = "io_uring_group",
174 .data = &sysctl_io_uring_group,
175 .maxlen = sizeof(gid_t),
176 .mode = 0644,
177 .proc_handler = proc_dointvec,
178 },
179 };
180 #endif
181
__io_cqring_events(struct io_ring_ctx * ctx)182 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
183 {
184 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
185 }
186
__io_cqring_events_user(struct io_ring_ctx * ctx)187 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
188 {
189 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
190 }
191
io_match_linked(struct io_kiocb * head)192 static bool io_match_linked(struct io_kiocb *head)
193 {
194 struct io_kiocb *req;
195
196 io_for_each_link(req, head) {
197 if (req->flags & REQ_F_INFLIGHT)
198 return true;
199 }
200 return false;
201 }
202
203 /*
204 * As io_match_task() but protected against racing with linked timeouts.
205 * User must not hold timeout_lock.
206 */
io_match_task_safe(struct io_kiocb * head,struct io_uring_task * tctx,bool cancel_all)207 bool io_match_task_safe(struct io_kiocb *head, struct io_uring_task *tctx,
208 bool cancel_all)
209 {
210 bool matched;
211
212 if (tctx && head->tctx != tctx)
213 return false;
214 if (cancel_all)
215 return true;
216
217 if (head->flags & REQ_F_LINK_TIMEOUT) {
218 struct io_ring_ctx *ctx = head->ctx;
219
220 /* protect against races with linked timeouts */
221 raw_spin_lock_irq(&ctx->timeout_lock);
222 matched = io_match_linked(head);
223 raw_spin_unlock_irq(&ctx->timeout_lock);
224 } else {
225 matched = io_match_linked(head);
226 }
227 return matched;
228 }
229
req_fail_link_node(struct io_kiocb * req,int res)230 static inline void req_fail_link_node(struct io_kiocb *req, int res)
231 {
232 req_set_fail(req);
233 io_req_set_res(req, res, 0);
234 }
235
io_req_add_to_cache(struct io_kiocb * req,struct io_ring_ctx * ctx)236 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
237 {
238 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
239 }
240
io_ring_ctx_ref_free(struct percpu_ref * ref)241 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
242 {
243 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
244
245 complete(&ctx->ref_comp);
246 }
247
io_fallback_req_func(struct work_struct * work)248 static __cold void io_fallback_req_func(struct work_struct *work)
249 {
250 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
251 fallback_work.work);
252 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
253 struct io_kiocb *req, *tmp;
254 struct io_tw_state ts = {};
255
256 percpu_ref_get(&ctx->refs);
257 mutex_lock(&ctx->uring_lock);
258 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
259 req->io_task_work.func(req, ts);
260 io_submit_flush_completions(ctx);
261 mutex_unlock(&ctx->uring_lock);
262 percpu_ref_put(&ctx->refs);
263 }
264
io_alloc_hash_table(struct io_hash_table * table,unsigned bits)265 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
266 {
267 unsigned int hash_buckets;
268 int i;
269
270 do {
271 hash_buckets = 1U << bits;
272 table->hbs = kvmalloc_array(hash_buckets, sizeof(table->hbs[0]),
273 GFP_KERNEL_ACCOUNT);
274 if (table->hbs)
275 break;
276 if (bits == 1)
277 return -ENOMEM;
278 bits--;
279 } while (1);
280
281 table->hash_bits = bits;
282 for (i = 0; i < hash_buckets; i++)
283 INIT_HLIST_HEAD(&table->hbs[i].list);
284 return 0;
285 }
286
io_free_alloc_caches(struct io_ring_ctx * ctx)287 static void io_free_alloc_caches(struct io_ring_ctx *ctx)
288 {
289 io_alloc_cache_free(&ctx->apoll_cache, kfree);
290 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
291 io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
292 io_alloc_cache_free(&ctx->cmd_cache, io_cmd_cache_free);
293 io_alloc_cache_free(&ctx->msg_cache, kfree);
294 io_futex_cache_free(ctx);
295 io_rsrc_cache_free(ctx);
296 }
297
io_ring_ctx_alloc(struct io_uring_params * p)298 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
299 {
300 struct io_ring_ctx *ctx;
301 int hash_bits;
302 bool ret;
303
304 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
305 if (!ctx)
306 return NULL;
307
308 xa_init(&ctx->io_bl_xa);
309
310 /*
311 * Use 5 bits less than the max cq entries, that should give us around
312 * 32 entries per hash list if totally full and uniformly spread, but
313 * don't keep too many buckets to not overconsume memory.
314 */
315 hash_bits = ilog2(p->cq_entries) - 5;
316 hash_bits = clamp(hash_bits, 1, 8);
317 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
318 goto err;
319 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
320 0, GFP_KERNEL))
321 goto err;
322
323 ctx->flags = p->flags;
324 ctx->hybrid_poll_time = LLONG_MAX;
325 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
326 init_waitqueue_head(&ctx->sqo_sq_wait);
327 INIT_LIST_HEAD(&ctx->sqd_list);
328 INIT_LIST_HEAD(&ctx->cq_overflow_list);
329 ret = io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX,
330 sizeof(struct async_poll), 0);
331 ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
332 sizeof(struct io_async_msghdr),
333 offsetof(struct io_async_msghdr, clear));
334 ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX,
335 sizeof(struct io_async_rw),
336 offsetof(struct io_async_rw, clear));
337 ret |= io_alloc_cache_init(&ctx->cmd_cache, IO_ALLOC_CACHE_MAX,
338 sizeof(struct io_async_cmd),
339 sizeof(struct io_async_cmd));
340 spin_lock_init(&ctx->msg_lock);
341 ret |= io_alloc_cache_init(&ctx->msg_cache, IO_ALLOC_CACHE_MAX,
342 sizeof(struct io_kiocb), 0);
343 ret |= io_futex_cache_init(ctx);
344 ret |= io_rsrc_cache_init(ctx);
345 if (ret)
346 goto free_ref;
347 init_completion(&ctx->ref_comp);
348 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
349 mutex_init(&ctx->uring_lock);
350 init_waitqueue_head(&ctx->cq_wait);
351 init_waitqueue_head(&ctx->poll_wq);
352 spin_lock_init(&ctx->completion_lock);
353 raw_spin_lock_init(&ctx->timeout_lock);
354 INIT_WQ_LIST(&ctx->iopoll_list);
355 INIT_LIST_HEAD(&ctx->defer_list);
356 INIT_LIST_HEAD(&ctx->timeout_list);
357 INIT_LIST_HEAD(&ctx->ltimeout_list);
358 init_llist_head(&ctx->work_llist);
359 INIT_LIST_HEAD(&ctx->tctx_list);
360 ctx->submit_state.free_list.next = NULL;
361 INIT_HLIST_HEAD(&ctx->waitid_list);
362 xa_init_flags(&ctx->zcrx_ctxs, XA_FLAGS_ALLOC);
363 #ifdef CONFIG_FUTEX
364 INIT_HLIST_HEAD(&ctx->futex_list);
365 #endif
366 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
367 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
368 INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
369 io_napi_init(ctx);
370 mutex_init(&ctx->mmap_lock);
371
372 return ctx;
373
374 free_ref:
375 percpu_ref_exit(&ctx->refs);
376 err:
377 io_free_alloc_caches(ctx);
378 kvfree(ctx->cancel_table.hbs);
379 xa_destroy(&ctx->io_bl_xa);
380 kfree(ctx);
381 return NULL;
382 }
383
io_clean_op(struct io_kiocb * req)384 static void io_clean_op(struct io_kiocb *req)
385 {
386 if (unlikely(req->flags & REQ_F_BUFFER_SELECTED))
387 io_kbuf_drop_legacy(req);
388
389 if (req->flags & REQ_F_NEED_CLEANUP) {
390 const struct io_cold_def *def = &io_cold_defs[req->opcode];
391
392 if (def->cleanup)
393 def->cleanup(req);
394 }
395 if ((req->flags & REQ_F_POLLED) && req->apoll) {
396 kfree(req->apoll->double_poll);
397 kfree(req->apoll);
398 req->apoll = NULL;
399 }
400 if (req->flags & REQ_F_INFLIGHT)
401 atomic_dec(&req->tctx->inflight_tracked);
402 if (req->flags & REQ_F_CREDS)
403 put_cred(req->creds);
404 if (req->flags & REQ_F_ASYNC_DATA) {
405 kfree(req->async_data);
406 req->async_data = NULL;
407 }
408 req->flags &= ~IO_REQ_CLEAN_FLAGS;
409 }
410
411 /*
412 * Mark the request as inflight, so that file cancelation will find it.
413 * Can be used if the file is an io_uring instance, or if the request itself
414 * relies on ->mm being alive for the duration of the request.
415 */
io_req_track_inflight(struct io_kiocb * req)416 inline void io_req_track_inflight(struct io_kiocb *req)
417 {
418 if (!(req->flags & REQ_F_INFLIGHT)) {
419 req->flags |= REQ_F_INFLIGHT;
420 atomic_inc(&req->tctx->inflight_tracked);
421 }
422 }
423
__io_prep_linked_timeout(struct io_kiocb * req)424 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
425 {
426 if (WARN_ON_ONCE(!req->link))
427 return NULL;
428
429 req->flags &= ~REQ_F_ARM_LTIMEOUT;
430 req->flags |= REQ_F_LINK_TIMEOUT;
431
432 /* linked timeouts should have two refs once prep'ed */
433 io_req_set_refcount(req);
434 __io_req_set_refcount(req->link, 2);
435 return req->link;
436 }
437
io_prep_async_work(struct io_kiocb * req)438 static void io_prep_async_work(struct io_kiocb *req)
439 {
440 const struct io_issue_def *def = &io_issue_defs[req->opcode];
441 struct io_ring_ctx *ctx = req->ctx;
442
443 if (!(req->flags & REQ_F_CREDS)) {
444 req->flags |= REQ_F_CREDS;
445 req->creds = get_current_cred();
446 }
447
448 req->work.list.next = NULL;
449 atomic_set(&req->work.flags, 0);
450 if (req->flags & REQ_F_FORCE_ASYNC)
451 atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
452
453 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
454 req->flags |= io_file_get_flags(req->file);
455
456 if (req->file && (req->flags & REQ_F_ISREG)) {
457 bool should_hash = def->hash_reg_file;
458
459 /* don't serialize this request if the fs doesn't need it */
460 if (should_hash && (req->file->f_flags & O_DIRECT) &&
461 (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
462 should_hash = false;
463 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
464 io_wq_hash_work(&req->work, file_inode(req->file));
465 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
466 if (def->unbound_nonreg_file)
467 atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
468 }
469 }
470
io_prep_async_link(struct io_kiocb * req)471 static void io_prep_async_link(struct io_kiocb *req)
472 {
473 struct io_kiocb *cur;
474
475 if (req->flags & REQ_F_LINK_TIMEOUT) {
476 struct io_ring_ctx *ctx = req->ctx;
477
478 raw_spin_lock_irq(&ctx->timeout_lock);
479 io_for_each_link(cur, req)
480 io_prep_async_work(cur);
481 raw_spin_unlock_irq(&ctx->timeout_lock);
482 } else {
483 io_for_each_link(cur, req)
484 io_prep_async_work(cur);
485 }
486 }
487
io_queue_iowq(struct io_kiocb * req)488 static void io_queue_iowq(struct io_kiocb *req)
489 {
490 struct io_uring_task *tctx = req->tctx;
491
492 BUG_ON(!tctx);
493
494 if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
495 io_req_task_queue_fail(req, -ECANCELED);
496 return;
497 }
498
499 /* init ->work of the whole link before punting */
500 io_prep_async_link(req);
501
502 /*
503 * Not expected to happen, but if we do have a bug where this _can_
504 * happen, catch it here and ensure the request is marked as
505 * canceled. That will make io-wq go through the usual work cancel
506 * procedure rather than attempt to run this request (or create a new
507 * worker for it).
508 */
509 if (WARN_ON_ONCE(!same_thread_group(tctx->task, current)))
510 atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
511
512 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
513 io_wq_enqueue(tctx->io_wq, &req->work);
514 }
515
io_req_queue_iowq_tw(struct io_kiocb * req,io_tw_token_t tw)516 static void io_req_queue_iowq_tw(struct io_kiocb *req, io_tw_token_t tw)
517 {
518 io_queue_iowq(req);
519 }
520
io_req_queue_iowq(struct io_kiocb * req)521 void io_req_queue_iowq(struct io_kiocb *req)
522 {
523 req->io_task_work.func = io_req_queue_iowq_tw;
524 io_req_task_work_add(req);
525 }
526
io_linked_nr(struct io_kiocb * req)527 static unsigned io_linked_nr(struct io_kiocb *req)
528 {
529 struct io_kiocb *tmp;
530 unsigned nr = 0;
531
532 io_for_each_link(tmp, req)
533 nr++;
534 return nr;
535 }
536
io_queue_deferred(struct io_ring_ctx * ctx)537 static __cold noinline void io_queue_deferred(struct io_ring_ctx *ctx)
538 {
539 bool drain_seen = false, first = true;
540
541 lockdep_assert_held(&ctx->uring_lock);
542 __io_req_caches_free(ctx);
543
544 while (!list_empty(&ctx->defer_list)) {
545 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
546 struct io_defer_entry, list);
547
548 drain_seen |= de->req->flags & REQ_F_IO_DRAIN;
549 if ((drain_seen || first) && ctx->nr_req_allocated != ctx->nr_drained)
550 return;
551
552 list_del_init(&de->list);
553 ctx->nr_drained -= io_linked_nr(de->req);
554 io_req_task_queue(de->req);
555 kfree(de);
556 first = false;
557 }
558 }
559
__io_commit_cqring_flush(struct io_ring_ctx * ctx)560 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
561 {
562 if (ctx->poll_activated)
563 io_poll_wq_wake(ctx);
564 if (ctx->off_timeout_used)
565 io_flush_timeouts(ctx);
566 if (ctx->has_evfd)
567 io_eventfd_signal(ctx, true);
568 }
569
__io_cq_lock(struct io_ring_ctx * ctx)570 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
571 {
572 if (!ctx->lockless_cq)
573 spin_lock(&ctx->completion_lock);
574 }
575
io_cq_lock(struct io_ring_ctx * ctx)576 static inline void io_cq_lock(struct io_ring_ctx *ctx)
577 __acquires(ctx->completion_lock)
578 {
579 spin_lock(&ctx->completion_lock);
580 }
581
__io_cq_unlock_post(struct io_ring_ctx * ctx)582 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
583 {
584 io_commit_cqring(ctx);
585 if (!ctx->task_complete) {
586 if (!ctx->lockless_cq)
587 spin_unlock(&ctx->completion_lock);
588 /* IOPOLL rings only need to wake up if it's also SQPOLL */
589 if (!ctx->syscall_iopoll)
590 io_cqring_wake(ctx);
591 }
592 io_commit_cqring_flush(ctx);
593 }
594
io_cq_unlock_post(struct io_ring_ctx * ctx)595 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
596 __releases(ctx->completion_lock)
597 {
598 io_commit_cqring(ctx);
599 spin_unlock(&ctx->completion_lock);
600 io_cqring_wake(ctx);
601 io_commit_cqring_flush(ctx);
602 }
603
__io_cqring_overflow_flush(struct io_ring_ctx * ctx,bool dying)604 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
605 {
606 size_t cqe_size = sizeof(struct io_uring_cqe);
607
608 lockdep_assert_held(&ctx->uring_lock);
609
610 /* don't abort if we're dying, entries must get freed */
611 if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
612 return;
613
614 if (ctx->flags & IORING_SETUP_CQE32)
615 cqe_size <<= 1;
616
617 io_cq_lock(ctx);
618 while (!list_empty(&ctx->cq_overflow_list)) {
619 struct io_uring_cqe *cqe;
620 struct io_overflow_cqe *ocqe;
621
622 ocqe = list_first_entry(&ctx->cq_overflow_list,
623 struct io_overflow_cqe, list);
624
625 if (!dying) {
626 if (!io_get_cqe_overflow(ctx, &cqe, true))
627 break;
628 memcpy(cqe, &ocqe->cqe, cqe_size);
629 }
630 list_del(&ocqe->list);
631 kfree(ocqe);
632
633 /*
634 * For silly syzbot cases that deliberately overflow by huge
635 * amounts, check if we need to resched and drop and
636 * reacquire the locks if so. Nothing real would ever hit this.
637 * Ideally we'd have a non-posting unlock for this, but hard
638 * to care for a non-real case.
639 */
640 if (need_resched()) {
641 ctx->cqe_sentinel = ctx->cqe_cached;
642 io_cq_unlock_post(ctx);
643 mutex_unlock(&ctx->uring_lock);
644 cond_resched();
645 mutex_lock(&ctx->uring_lock);
646 io_cq_lock(ctx);
647 }
648 }
649
650 if (list_empty(&ctx->cq_overflow_list)) {
651 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
652 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
653 }
654 io_cq_unlock_post(ctx);
655 }
656
io_cqring_overflow_kill(struct io_ring_ctx * ctx)657 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
658 {
659 if (ctx->rings)
660 __io_cqring_overflow_flush(ctx, true);
661 }
662
io_cqring_do_overflow_flush(struct io_ring_ctx * ctx)663 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
664 {
665 mutex_lock(&ctx->uring_lock);
666 __io_cqring_overflow_flush(ctx, false);
667 mutex_unlock(&ctx->uring_lock);
668 }
669
670 /* must to be called somewhat shortly after putting a request */
io_put_task(struct io_kiocb * req)671 static inline void io_put_task(struct io_kiocb *req)
672 {
673 struct io_uring_task *tctx = req->tctx;
674
675 if (likely(tctx->task == current)) {
676 tctx->cached_refs++;
677 } else {
678 percpu_counter_sub(&tctx->inflight, 1);
679 if (unlikely(atomic_read(&tctx->in_cancel)))
680 wake_up(&tctx->wait);
681 put_task_struct(tctx->task);
682 }
683 }
684
io_task_refs_refill(struct io_uring_task * tctx)685 void io_task_refs_refill(struct io_uring_task *tctx)
686 {
687 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
688
689 percpu_counter_add(&tctx->inflight, refill);
690 refcount_add(refill, ¤t->usage);
691 tctx->cached_refs += refill;
692 }
693
io_uring_drop_tctx_refs(struct task_struct * task)694 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
695 {
696 struct io_uring_task *tctx = task->io_uring;
697 unsigned int refs = tctx->cached_refs;
698
699 if (refs) {
700 tctx->cached_refs = 0;
701 percpu_counter_sub(&tctx->inflight, refs);
702 put_task_struct_many(task, refs);
703 }
704 }
705
io_cqring_add_overflow(struct io_ring_ctx * ctx,struct io_overflow_cqe * ocqe)706 static __cold bool io_cqring_add_overflow(struct io_ring_ctx *ctx,
707 struct io_overflow_cqe *ocqe)
708 {
709 lockdep_assert_held(&ctx->completion_lock);
710
711 if (!ocqe) {
712 struct io_rings *r = ctx->rings;
713
714 /*
715 * If we're in ring overflow flush mode, or in task cancel mode,
716 * or cannot allocate an overflow entry, then we need to drop it
717 * on the floor.
718 */
719 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
720 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
721 return false;
722 }
723 if (list_empty(&ctx->cq_overflow_list)) {
724 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
725 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
726
727 }
728 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
729 return true;
730 }
731
io_alloc_ocqe(struct io_ring_ctx * ctx,struct io_cqe * cqe,struct io_big_cqe * big_cqe,gfp_t gfp)732 static struct io_overflow_cqe *io_alloc_ocqe(struct io_ring_ctx *ctx,
733 struct io_cqe *cqe,
734 struct io_big_cqe *big_cqe, gfp_t gfp)
735 {
736 struct io_overflow_cqe *ocqe;
737 size_t ocq_size = sizeof(struct io_overflow_cqe);
738 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
739
740 if (is_cqe32)
741 ocq_size += sizeof(struct io_uring_cqe);
742
743 ocqe = kzalloc(ocq_size, gfp | __GFP_ACCOUNT);
744 trace_io_uring_cqe_overflow(ctx, cqe->user_data, cqe->res, cqe->flags, ocqe);
745 if (ocqe) {
746 ocqe->cqe.user_data = cqe->user_data;
747 ocqe->cqe.res = cqe->res;
748 ocqe->cqe.flags = cqe->flags;
749 if (is_cqe32 && big_cqe) {
750 ocqe->cqe.big_cqe[0] = big_cqe->extra1;
751 ocqe->cqe.big_cqe[1] = big_cqe->extra2;
752 }
753 }
754 if (big_cqe)
755 big_cqe->extra1 = big_cqe->extra2 = 0;
756 return ocqe;
757 }
758
759 /*
760 * writes to the cq entry need to come after reading head; the
761 * control dependency is enough as we're using WRITE_ONCE to
762 * fill the cq entry
763 */
io_cqe_cache_refill(struct io_ring_ctx * ctx,bool overflow)764 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
765 {
766 struct io_rings *rings = ctx->rings;
767 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
768 unsigned int free, queued, len;
769
770 /*
771 * Posting into the CQ when there are pending overflowed CQEs may break
772 * ordering guarantees, which will affect links, F_MORE users and more.
773 * Force overflow the completion.
774 */
775 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
776 return false;
777
778 /* userspace may cheat modifying the tail, be safe and do min */
779 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
780 free = ctx->cq_entries - queued;
781 /* we need a contiguous range, limit based on the current array offset */
782 len = min(free, ctx->cq_entries - off);
783 if (!len)
784 return false;
785
786 if (ctx->flags & IORING_SETUP_CQE32) {
787 off <<= 1;
788 len <<= 1;
789 }
790
791 ctx->cqe_cached = &rings->cqes[off];
792 ctx->cqe_sentinel = ctx->cqe_cached + len;
793 return true;
794 }
795
io_fill_cqe_aux(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)796 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
797 u32 cflags)
798 {
799 struct io_uring_cqe *cqe;
800
801 if (likely(io_get_cqe(ctx, &cqe))) {
802 WRITE_ONCE(cqe->user_data, user_data);
803 WRITE_ONCE(cqe->res, res);
804 WRITE_ONCE(cqe->flags, cflags);
805
806 if (ctx->flags & IORING_SETUP_CQE32) {
807 WRITE_ONCE(cqe->big_cqe[0], 0);
808 WRITE_ONCE(cqe->big_cqe[1], 0);
809 }
810
811 trace_io_uring_complete(ctx, NULL, cqe);
812 return true;
813 }
814 return false;
815 }
816
io_init_cqe(u64 user_data,s32 res,u32 cflags)817 static inline struct io_cqe io_init_cqe(u64 user_data, s32 res, u32 cflags)
818 {
819 return (struct io_cqe) { .user_data = user_data, .res = res, .flags = cflags };
820 }
821
io_cqe_overflow(struct io_ring_ctx * ctx,struct io_cqe * cqe,struct io_big_cqe * big_cqe)822 static __cold void io_cqe_overflow(struct io_ring_ctx *ctx, struct io_cqe *cqe,
823 struct io_big_cqe *big_cqe)
824 {
825 struct io_overflow_cqe *ocqe;
826
827 ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_KERNEL);
828 spin_lock(&ctx->completion_lock);
829 io_cqring_add_overflow(ctx, ocqe);
830 spin_unlock(&ctx->completion_lock);
831 }
832
io_cqe_overflow_locked(struct io_ring_ctx * ctx,struct io_cqe * cqe,struct io_big_cqe * big_cqe)833 static __cold bool io_cqe_overflow_locked(struct io_ring_ctx *ctx,
834 struct io_cqe *cqe,
835 struct io_big_cqe *big_cqe)
836 {
837 struct io_overflow_cqe *ocqe;
838
839 ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_ATOMIC);
840 return io_cqring_add_overflow(ctx, ocqe);
841 }
842
io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)843 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
844 {
845 bool filled;
846
847 io_cq_lock(ctx);
848 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
849 if (unlikely(!filled)) {
850 struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
851
852 filled = io_cqe_overflow_locked(ctx, &cqe, NULL);
853 }
854 io_cq_unlock_post(ctx);
855 return filled;
856 }
857
858 /*
859 * Must be called from inline task_work so we now a flush will happen later,
860 * and obviously with ctx->uring_lock held (tw always has that).
861 */
io_add_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)862 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
863 {
864 lockdep_assert_held(&ctx->uring_lock);
865 lockdep_assert(ctx->lockless_cq);
866
867 if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
868 struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
869
870 io_cqe_overflow(ctx, &cqe, NULL);
871 }
872 ctx->submit_state.cq_flush = true;
873 }
874
875 /*
876 * A helper for multishot requests posting additional CQEs.
877 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
878 */
io_req_post_cqe(struct io_kiocb * req,s32 res,u32 cflags)879 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
880 {
881 struct io_ring_ctx *ctx = req->ctx;
882 bool posted;
883
884 /*
885 * If multishot has already posted deferred completions, ensure that
886 * those are flushed first before posting this one. If not, CQEs
887 * could get reordered.
888 */
889 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
890 __io_submit_flush_completions(ctx);
891
892 lockdep_assert(!io_wq_current_is_worker());
893 lockdep_assert_held(&ctx->uring_lock);
894
895 if (!ctx->lockless_cq) {
896 spin_lock(&ctx->completion_lock);
897 posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
898 spin_unlock(&ctx->completion_lock);
899 } else {
900 posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
901 }
902
903 ctx->submit_state.cq_flush = true;
904 return posted;
905 }
906
io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)907 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
908 {
909 struct io_ring_ctx *ctx = req->ctx;
910 bool completed = true;
911
912 /*
913 * All execution paths but io-wq use the deferred completions by
914 * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
915 */
916 if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
917 return;
918
919 /*
920 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
921 * the submitter task context, IOPOLL protects with uring_lock.
922 */
923 if (ctx->lockless_cq || (req->flags & REQ_F_REISSUE)) {
924 defer_complete:
925 req->io_task_work.func = io_req_task_complete;
926 io_req_task_work_add(req);
927 return;
928 }
929
930 io_cq_lock(ctx);
931 if (!(req->flags & REQ_F_CQE_SKIP))
932 completed = io_fill_cqe_req(ctx, req);
933 io_cq_unlock_post(ctx);
934
935 if (!completed)
936 goto defer_complete;
937
938 /*
939 * We don't free the request here because we know it's called from
940 * io-wq only, which holds a reference, so it cannot be the last put.
941 */
942 req_ref_put(req);
943 }
944
io_req_defer_failed(struct io_kiocb * req,s32 res)945 void io_req_defer_failed(struct io_kiocb *req, s32 res)
946 __must_hold(&ctx->uring_lock)
947 {
948 const struct io_cold_def *def = &io_cold_defs[req->opcode];
949
950 lockdep_assert_held(&req->ctx->uring_lock);
951
952 req_set_fail(req);
953 io_req_set_res(req, res, io_put_kbuf(req, res, IO_URING_F_UNLOCKED));
954 if (def->fail)
955 def->fail(req);
956 io_req_complete_defer(req);
957 }
958
959 /*
960 * A request might get retired back into the request caches even before opcode
961 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
962 * Because of that, io_alloc_req() should be called only under ->uring_lock
963 * and with extra caution to not get a request that is still worked on.
964 */
__io_alloc_req_refill(struct io_ring_ctx * ctx)965 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
966 __must_hold(&ctx->uring_lock)
967 {
968 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO;
969 void *reqs[IO_REQ_ALLOC_BATCH];
970 int ret;
971
972 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
973
974 /*
975 * Bulk alloc is all-or-nothing. If we fail to get a batch,
976 * retry single alloc to be on the safe side.
977 */
978 if (unlikely(ret <= 0)) {
979 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
980 if (!reqs[0])
981 return false;
982 ret = 1;
983 }
984
985 percpu_ref_get_many(&ctx->refs, ret);
986 ctx->nr_req_allocated += ret;
987
988 while (ret--) {
989 struct io_kiocb *req = reqs[ret];
990
991 io_req_add_to_cache(req, ctx);
992 }
993 return true;
994 }
995
io_free_req(struct io_kiocb * req)996 __cold void io_free_req(struct io_kiocb *req)
997 {
998 /* refs were already put, restore them for io_req_task_complete() */
999 req->flags &= ~REQ_F_REFCOUNT;
1000 /* we only want to free it, don't post CQEs */
1001 req->flags |= REQ_F_CQE_SKIP;
1002 req->io_task_work.func = io_req_task_complete;
1003 io_req_task_work_add(req);
1004 }
1005
__io_req_find_next_prep(struct io_kiocb * req)1006 static void __io_req_find_next_prep(struct io_kiocb *req)
1007 {
1008 struct io_ring_ctx *ctx = req->ctx;
1009
1010 spin_lock(&ctx->completion_lock);
1011 io_disarm_next(req);
1012 spin_unlock(&ctx->completion_lock);
1013 }
1014
io_req_find_next(struct io_kiocb * req)1015 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1016 {
1017 struct io_kiocb *nxt;
1018
1019 /*
1020 * If LINK is set, we have dependent requests in this chain. If we
1021 * didn't fail this request, queue the first one up, moving any other
1022 * dependencies to the next request. In case of failure, fail the rest
1023 * of the chain.
1024 */
1025 if (unlikely(req->flags & IO_DISARM_MASK))
1026 __io_req_find_next_prep(req);
1027 nxt = req->link;
1028 req->link = NULL;
1029 return nxt;
1030 }
1031
ctx_flush_and_put(struct io_ring_ctx * ctx,io_tw_token_t tw)1032 static void ctx_flush_and_put(struct io_ring_ctx *ctx, io_tw_token_t tw)
1033 {
1034 if (!ctx)
1035 return;
1036 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1037 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1038
1039 io_submit_flush_completions(ctx);
1040 mutex_unlock(&ctx->uring_lock);
1041 percpu_ref_put(&ctx->refs);
1042 }
1043
1044 /*
1045 * Run queued task_work, returning the number of entries processed in *count.
1046 * If more entries than max_entries are available, stop processing once this
1047 * is reached and return the rest of the list.
1048 */
io_handle_tw_list(struct llist_node * node,unsigned int * count,unsigned int max_entries)1049 struct llist_node *io_handle_tw_list(struct llist_node *node,
1050 unsigned int *count,
1051 unsigned int max_entries)
1052 {
1053 struct io_ring_ctx *ctx = NULL;
1054 struct io_tw_state ts = { };
1055
1056 do {
1057 struct llist_node *next = node->next;
1058 struct io_kiocb *req = container_of(node, struct io_kiocb,
1059 io_task_work.node);
1060
1061 if (req->ctx != ctx) {
1062 ctx_flush_and_put(ctx, ts);
1063 ctx = req->ctx;
1064 mutex_lock(&ctx->uring_lock);
1065 percpu_ref_get(&ctx->refs);
1066 }
1067 INDIRECT_CALL_2(req->io_task_work.func,
1068 io_poll_task_func, io_req_rw_complete,
1069 req, ts);
1070 node = next;
1071 (*count)++;
1072 if (unlikely(need_resched())) {
1073 ctx_flush_and_put(ctx, ts);
1074 ctx = NULL;
1075 cond_resched();
1076 }
1077 } while (node && *count < max_entries);
1078
1079 ctx_flush_and_put(ctx, ts);
1080 return node;
1081 }
1082
__io_fallback_tw(struct llist_node * node,bool sync)1083 static __cold void __io_fallback_tw(struct llist_node *node, bool sync)
1084 {
1085 struct io_ring_ctx *last_ctx = NULL;
1086 struct io_kiocb *req;
1087
1088 while (node) {
1089 req = container_of(node, struct io_kiocb, io_task_work.node);
1090 node = node->next;
1091 if (last_ctx != req->ctx) {
1092 if (last_ctx) {
1093 if (sync)
1094 flush_delayed_work(&last_ctx->fallback_work);
1095 percpu_ref_put(&last_ctx->refs);
1096 }
1097 last_ctx = req->ctx;
1098 percpu_ref_get(&last_ctx->refs);
1099 }
1100 if (llist_add(&req->io_task_work.node, &last_ctx->fallback_llist))
1101 schedule_delayed_work(&last_ctx->fallback_work, 1);
1102 }
1103
1104 if (last_ctx) {
1105 if (sync)
1106 flush_delayed_work(&last_ctx->fallback_work);
1107 percpu_ref_put(&last_ctx->refs);
1108 }
1109 }
1110
io_fallback_tw(struct io_uring_task * tctx,bool sync)1111 static void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1112 {
1113 struct llist_node *node = llist_del_all(&tctx->task_list);
1114
1115 __io_fallback_tw(node, sync);
1116 }
1117
tctx_task_work_run(struct io_uring_task * tctx,unsigned int max_entries,unsigned int * count)1118 struct llist_node *tctx_task_work_run(struct io_uring_task *tctx,
1119 unsigned int max_entries,
1120 unsigned int *count)
1121 {
1122 struct llist_node *node;
1123
1124 if (unlikely(current->flags & PF_EXITING)) {
1125 io_fallback_tw(tctx, true);
1126 return NULL;
1127 }
1128
1129 node = llist_del_all(&tctx->task_list);
1130 if (node) {
1131 node = llist_reverse_order(node);
1132 node = io_handle_tw_list(node, count, max_entries);
1133 }
1134
1135 /* relaxed read is enough as only the task itself sets ->in_cancel */
1136 if (unlikely(atomic_read(&tctx->in_cancel)))
1137 io_uring_drop_tctx_refs(current);
1138
1139 trace_io_uring_task_work_run(tctx, *count);
1140 return node;
1141 }
1142
tctx_task_work(struct callback_head * cb)1143 void tctx_task_work(struct callback_head *cb)
1144 {
1145 struct io_uring_task *tctx;
1146 struct llist_node *ret;
1147 unsigned int count = 0;
1148
1149 tctx = container_of(cb, struct io_uring_task, task_work);
1150 ret = tctx_task_work_run(tctx, UINT_MAX, &count);
1151 /* can't happen */
1152 WARN_ON_ONCE(ret);
1153 }
1154
io_req_local_work_add(struct io_kiocb * req,unsigned flags)1155 static void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1156 {
1157 struct io_ring_ctx *ctx = req->ctx;
1158 unsigned nr_wait, nr_tw, nr_tw_prev;
1159 struct llist_node *head;
1160
1161 /* See comment above IO_CQ_WAKE_INIT */
1162 BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
1163
1164 /*
1165 * We don't know how many reuqests is there in the link and whether
1166 * they can even be queued lazily, fall back to non-lazy.
1167 */
1168 if (req->flags & IO_REQ_LINK_FLAGS)
1169 flags &= ~IOU_F_TWQ_LAZY_WAKE;
1170
1171 guard(rcu)();
1172
1173 head = READ_ONCE(ctx->work_llist.first);
1174 do {
1175 nr_tw_prev = 0;
1176 if (head) {
1177 struct io_kiocb *first_req = container_of(head,
1178 struct io_kiocb,
1179 io_task_work.node);
1180 /*
1181 * Might be executed at any moment, rely on
1182 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1183 */
1184 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1185 }
1186
1187 /*
1188 * Theoretically, it can overflow, but that's fine as one of
1189 * previous adds should've tried to wake the task.
1190 */
1191 nr_tw = nr_tw_prev + 1;
1192 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1193 nr_tw = IO_CQ_WAKE_FORCE;
1194
1195 req->nr_tw = nr_tw;
1196 req->io_task_work.node.next = head;
1197 } while (!try_cmpxchg(&ctx->work_llist.first, &head,
1198 &req->io_task_work.node));
1199
1200 /*
1201 * cmpxchg implies a full barrier, which pairs with the barrier
1202 * in set_current_state() on the io_cqring_wait() side. It's used
1203 * to ensure that either we see updated ->cq_wait_nr, or waiters
1204 * going to sleep will observe the work added to the list, which
1205 * is similar to the wait/wawke task state sync.
1206 */
1207
1208 if (!head) {
1209 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1210 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1211 if (ctx->has_evfd)
1212 io_eventfd_signal(ctx, false);
1213 }
1214
1215 nr_wait = atomic_read(&ctx->cq_wait_nr);
1216 /* not enough or no one is waiting */
1217 if (nr_tw < nr_wait)
1218 return;
1219 /* the previous add has already woken it up */
1220 if (nr_tw_prev >= nr_wait)
1221 return;
1222 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1223 }
1224
io_req_normal_work_add(struct io_kiocb * req)1225 static void io_req_normal_work_add(struct io_kiocb *req)
1226 {
1227 struct io_uring_task *tctx = req->tctx;
1228 struct io_ring_ctx *ctx = req->ctx;
1229
1230 /* task_work already pending, we're done */
1231 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1232 return;
1233
1234 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1235 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1236
1237 /* SQPOLL doesn't need the task_work added, it'll run it itself */
1238 if (ctx->flags & IORING_SETUP_SQPOLL) {
1239 __set_notify_signal(tctx->task);
1240 return;
1241 }
1242
1243 if (likely(!task_work_add(tctx->task, &tctx->task_work, ctx->notify_method)))
1244 return;
1245
1246 io_fallback_tw(tctx, false);
1247 }
1248
__io_req_task_work_add(struct io_kiocb * req,unsigned flags)1249 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1250 {
1251 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN)
1252 io_req_local_work_add(req, flags);
1253 else
1254 io_req_normal_work_add(req);
1255 }
1256
io_req_task_work_add_remote(struct io_kiocb * req,unsigned flags)1257 void io_req_task_work_add_remote(struct io_kiocb *req, unsigned flags)
1258 {
1259 if (WARN_ON_ONCE(!(req->ctx->flags & IORING_SETUP_DEFER_TASKRUN)))
1260 return;
1261 __io_req_task_work_add(req, flags);
1262 }
1263
io_move_task_work_from_local(struct io_ring_ctx * ctx)1264 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1265 {
1266 struct llist_node *node = llist_del_all(&ctx->work_llist);
1267
1268 __io_fallback_tw(node, false);
1269 node = llist_del_all(&ctx->retry_llist);
1270 __io_fallback_tw(node, false);
1271 }
1272
io_run_local_work_continue(struct io_ring_ctx * ctx,int events,int min_events)1273 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1274 int min_events)
1275 {
1276 if (!io_local_work_pending(ctx))
1277 return false;
1278 if (events < min_events)
1279 return true;
1280 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1281 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1282 return false;
1283 }
1284
__io_run_local_work_loop(struct llist_node ** node,io_tw_token_t tw,int events)1285 static int __io_run_local_work_loop(struct llist_node **node,
1286 io_tw_token_t tw,
1287 int events)
1288 {
1289 int ret = 0;
1290
1291 while (*node) {
1292 struct llist_node *next = (*node)->next;
1293 struct io_kiocb *req = container_of(*node, struct io_kiocb,
1294 io_task_work.node);
1295 INDIRECT_CALL_2(req->io_task_work.func,
1296 io_poll_task_func, io_req_rw_complete,
1297 req, tw);
1298 *node = next;
1299 if (++ret >= events)
1300 break;
1301 }
1302
1303 return ret;
1304 }
1305
__io_run_local_work(struct io_ring_ctx * ctx,io_tw_token_t tw,int min_events,int max_events)1306 static int __io_run_local_work(struct io_ring_ctx *ctx, io_tw_token_t tw,
1307 int min_events, int max_events)
1308 {
1309 struct llist_node *node;
1310 unsigned int loops = 0;
1311 int ret = 0;
1312
1313 if (WARN_ON_ONCE(ctx->submitter_task != current))
1314 return -EEXIST;
1315 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1316 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1317 again:
1318 min_events -= ret;
1319 ret = __io_run_local_work_loop(&ctx->retry_llist.first, tw, max_events);
1320 if (ctx->retry_llist.first)
1321 goto retry_done;
1322
1323 /*
1324 * llists are in reverse order, flip it back the right way before
1325 * running the pending items.
1326 */
1327 node = llist_reverse_order(llist_del_all(&ctx->work_llist));
1328 ret += __io_run_local_work_loop(&node, tw, max_events - ret);
1329 ctx->retry_llist.first = node;
1330 loops++;
1331
1332 if (io_run_local_work_continue(ctx, ret, min_events))
1333 goto again;
1334 retry_done:
1335 io_submit_flush_completions(ctx);
1336 if (io_run_local_work_continue(ctx, ret, min_events))
1337 goto again;
1338
1339 trace_io_uring_local_work_run(ctx, ret, loops);
1340 return ret;
1341 }
1342
io_run_local_work_locked(struct io_ring_ctx * ctx,int min_events)1343 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1344 int min_events)
1345 {
1346 struct io_tw_state ts = {};
1347
1348 if (!io_local_work_pending(ctx))
1349 return 0;
1350 return __io_run_local_work(ctx, ts, min_events,
1351 max(IO_LOCAL_TW_DEFAULT_MAX, min_events));
1352 }
1353
io_run_local_work(struct io_ring_ctx * ctx,int min_events,int max_events)1354 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events,
1355 int max_events)
1356 {
1357 struct io_tw_state ts = {};
1358 int ret;
1359
1360 mutex_lock(&ctx->uring_lock);
1361 ret = __io_run_local_work(ctx, ts, min_events, max_events);
1362 mutex_unlock(&ctx->uring_lock);
1363 return ret;
1364 }
1365
io_req_task_cancel(struct io_kiocb * req,io_tw_token_t tw)1366 static void io_req_task_cancel(struct io_kiocb *req, io_tw_token_t tw)
1367 {
1368 io_tw_lock(req->ctx, tw);
1369 io_req_defer_failed(req, req->cqe.res);
1370 }
1371
io_req_task_submit(struct io_kiocb * req,io_tw_token_t tw)1372 void io_req_task_submit(struct io_kiocb *req, io_tw_token_t tw)
1373 {
1374 io_tw_lock(req->ctx, tw);
1375 if (unlikely(io_should_terminate_tw()))
1376 io_req_defer_failed(req, -EFAULT);
1377 else if (req->flags & REQ_F_FORCE_ASYNC)
1378 io_queue_iowq(req);
1379 else
1380 io_queue_sqe(req);
1381 }
1382
io_req_task_queue_fail(struct io_kiocb * req,int ret)1383 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1384 {
1385 io_req_set_res(req, ret, 0);
1386 req->io_task_work.func = io_req_task_cancel;
1387 io_req_task_work_add(req);
1388 }
1389
io_req_task_queue(struct io_kiocb * req)1390 void io_req_task_queue(struct io_kiocb *req)
1391 {
1392 req->io_task_work.func = io_req_task_submit;
1393 io_req_task_work_add(req);
1394 }
1395
io_queue_next(struct io_kiocb * req)1396 void io_queue_next(struct io_kiocb *req)
1397 {
1398 struct io_kiocb *nxt = io_req_find_next(req);
1399
1400 if (nxt)
1401 io_req_task_queue(nxt);
1402 }
1403
io_req_put_rsrc_nodes(struct io_kiocb * req)1404 static inline void io_req_put_rsrc_nodes(struct io_kiocb *req)
1405 {
1406 if (req->file_node) {
1407 io_put_rsrc_node(req->ctx, req->file_node);
1408 req->file_node = NULL;
1409 }
1410 if (req->flags & REQ_F_BUF_NODE)
1411 io_put_rsrc_node(req->ctx, req->buf_node);
1412 }
1413
io_free_batch_list(struct io_ring_ctx * ctx,struct io_wq_work_node * node)1414 static void io_free_batch_list(struct io_ring_ctx *ctx,
1415 struct io_wq_work_node *node)
1416 __must_hold(&ctx->uring_lock)
1417 {
1418 do {
1419 struct io_kiocb *req = container_of(node, struct io_kiocb,
1420 comp_list);
1421
1422 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1423 if (req->flags & REQ_F_REISSUE) {
1424 node = req->comp_list.next;
1425 req->flags &= ~REQ_F_REISSUE;
1426 io_queue_iowq(req);
1427 continue;
1428 }
1429 if (req->flags & REQ_F_REFCOUNT) {
1430 node = req->comp_list.next;
1431 if (!req_ref_put_and_test(req))
1432 continue;
1433 }
1434 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1435 struct async_poll *apoll = req->apoll;
1436
1437 if (apoll->double_poll)
1438 kfree(apoll->double_poll);
1439 io_cache_free(&ctx->apoll_cache, apoll);
1440 req->flags &= ~REQ_F_POLLED;
1441 }
1442 if (req->flags & IO_REQ_LINK_FLAGS)
1443 io_queue_next(req);
1444 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1445 io_clean_op(req);
1446 }
1447 io_put_file(req);
1448 io_req_put_rsrc_nodes(req);
1449 io_put_task(req);
1450
1451 node = req->comp_list.next;
1452 io_req_add_to_cache(req, ctx);
1453 } while (node);
1454 }
1455
__io_submit_flush_completions(struct io_ring_ctx * ctx)1456 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1457 __must_hold(&ctx->uring_lock)
1458 {
1459 struct io_submit_state *state = &ctx->submit_state;
1460 struct io_wq_work_node *node;
1461
1462 __io_cq_lock(ctx);
1463 __wq_list_for_each(node, &state->compl_reqs) {
1464 struct io_kiocb *req = container_of(node, struct io_kiocb,
1465 comp_list);
1466
1467 /*
1468 * Requests marked with REQUEUE should not post a CQE, they
1469 * will go through the io-wq retry machinery and post one
1470 * later.
1471 */
1472 if (!(req->flags & (REQ_F_CQE_SKIP | REQ_F_REISSUE)) &&
1473 unlikely(!io_fill_cqe_req(ctx, req))) {
1474 if (ctx->lockless_cq)
1475 io_cqe_overflow(ctx, &req->cqe, &req->big_cqe);
1476 else
1477 io_cqe_overflow_locked(ctx, &req->cqe, &req->big_cqe);
1478 }
1479 }
1480 __io_cq_unlock_post(ctx);
1481
1482 if (!wq_list_empty(&state->compl_reqs)) {
1483 io_free_batch_list(ctx, state->compl_reqs.first);
1484 INIT_WQ_LIST(&state->compl_reqs);
1485 }
1486
1487 if (unlikely(ctx->drain_active))
1488 io_queue_deferred(ctx);
1489
1490 ctx->submit_state.cq_flush = false;
1491 }
1492
io_cqring_events(struct io_ring_ctx * ctx)1493 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1494 {
1495 /* See comment at the top of this file */
1496 smp_rmb();
1497 return __io_cqring_events(ctx);
1498 }
1499
1500 /*
1501 * We can't just wait for polled events to come to us, we have to actively
1502 * find and complete them.
1503 */
io_iopoll_try_reap_events(struct io_ring_ctx * ctx)1504 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1505 {
1506 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1507 return;
1508
1509 mutex_lock(&ctx->uring_lock);
1510 while (!wq_list_empty(&ctx->iopoll_list)) {
1511 /* let it sleep and repeat later if can't complete a request */
1512 if (io_do_iopoll(ctx, true) == 0)
1513 break;
1514 /*
1515 * Ensure we allow local-to-the-cpu processing to take place,
1516 * in this case we need to ensure that we reap all events.
1517 * Also let task_work, etc. to progress by releasing the mutex
1518 */
1519 if (need_resched()) {
1520 mutex_unlock(&ctx->uring_lock);
1521 cond_resched();
1522 mutex_lock(&ctx->uring_lock);
1523 }
1524 }
1525 mutex_unlock(&ctx->uring_lock);
1526
1527 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
1528 io_move_task_work_from_local(ctx);
1529 }
1530
io_iopoll_check(struct io_ring_ctx * ctx,unsigned int min_events)1531 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned int min_events)
1532 {
1533 unsigned int nr_events = 0;
1534 unsigned long check_cq;
1535
1536 min_events = min(min_events, ctx->cq_entries);
1537
1538 lockdep_assert_held(&ctx->uring_lock);
1539
1540 if (!io_allowed_run_tw(ctx))
1541 return -EEXIST;
1542
1543 check_cq = READ_ONCE(ctx->check_cq);
1544 if (unlikely(check_cq)) {
1545 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1546 __io_cqring_overflow_flush(ctx, false);
1547 /*
1548 * Similarly do not spin if we have not informed the user of any
1549 * dropped CQE.
1550 */
1551 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1552 return -EBADR;
1553 }
1554 /*
1555 * Don't enter poll loop if we already have events pending.
1556 * If we do, we can potentially be spinning for commands that
1557 * already triggered a CQE (eg in error).
1558 */
1559 if (io_cqring_events(ctx))
1560 return 0;
1561
1562 do {
1563 int ret = 0;
1564
1565 /*
1566 * If a submit got punted to a workqueue, we can have the
1567 * application entering polling for a command before it gets
1568 * issued. That app will hold the uring_lock for the duration
1569 * of the poll right here, so we need to take a breather every
1570 * now and then to ensure that the issue has a chance to add
1571 * the poll to the issued list. Otherwise we can spin here
1572 * forever, while the workqueue is stuck trying to acquire the
1573 * very same mutex.
1574 */
1575 if (wq_list_empty(&ctx->iopoll_list) ||
1576 io_task_work_pending(ctx)) {
1577 u32 tail = ctx->cached_cq_tail;
1578
1579 (void) io_run_local_work_locked(ctx, min_events);
1580
1581 if (task_work_pending(current) ||
1582 wq_list_empty(&ctx->iopoll_list)) {
1583 mutex_unlock(&ctx->uring_lock);
1584 io_run_task_work();
1585 mutex_lock(&ctx->uring_lock);
1586 }
1587 /* some requests don't go through iopoll_list */
1588 if (tail != ctx->cached_cq_tail ||
1589 wq_list_empty(&ctx->iopoll_list))
1590 break;
1591 }
1592 ret = io_do_iopoll(ctx, !min_events);
1593 if (unlikely(ret < 0))
1594 return ret;
1595
1596 if (task_sigpending(current))
1597 return -EINTR;
1598 if (need_resched())
1599 break;
1600
1601 nr_events += ret;
1602 } while (nr_events < min_events);
1603
1604 return 0;
1605 }
1606
io_req_task_complete(struct io_kiocb * req,io_tw_token_t tw)1607 void io_req_task_complete(struct io_kiocb *req, io_tw_token_t tw)
1608 {
1609 io_req_complete_defer(req);
1610 }
1611
1612 /*
1613 * After the iocb has been issued, it's safe to be found on the poll list.
1614 * Adding the kiocb to the list AFTER submission ensures that we don't
1615 * find it from a io_do_iopoll() thread before the issuer is done
1616 * accessing the kiocb cookie.
1617 */
io_iopoll_req_issued(struct io_kiocb * req,unsigned int issue_flags)1618 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1619 {
1620 struct io_ring_ctx *ctx = req->ctx;
1621 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1622
1623 /* workqueue context doesn't hold uring_lock, grab it now */
1624 if (unlikely(needs_lock))
1625 mutex_lock(&ctx->uring_lock);
1626
1627 /*
1628 * Track whether we have multiple files in our lists. This will impact
1629 * how we do polling eventually, not spinning if we're on potentially
1630 * different devices.
1631 */
1632 if (wq_list_empty(&ctx->iopoll_list)) {
1633 ctx->poll_multi_queue = false;
1634 } else if (!ctx->poll_multi_queue) {
1635 struct io_kiocb *list_req;
1636
1637 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1638 comp_list);
1639 if (list_req->file != req->file)
1640 ctx->poll_multi_queue = true;
1641 }
1642
1643 /*
1644 * For fast devices, IO may have already completed. If it has, add
1645 * it to the front so we find it first.
1646 */
1647 if (READ_ONCE(req->iopoll_completed))
1648 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1649 else
1650 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1651
1652 if (unlikely(needs_lock)) {
1653 /*
1654 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1655 * in sq thread task context or in io worker task context. If
1656 * current task context is sq thread, we don't need to check
1657 * whether should wake up sq thread.
1658 */
1659 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1660 wq_has_sleeper(&ctx->sq_data->wait))
1661 wake_up(&ctx->sq_data->wait);
1662
1663 mutex_unlock(&ctx->uring_lock);
1664 }
1665 }
1666
io_file_get_flags(struct file * file)1667 io_req_flags_t io_file_get_flags(struct file *file)
1668 {
1669 io_req_flags_t res = 0;
1670
1671 BUILD_BUG_ON(REQ_F_ISREG_BIT != REQ_F_SUPPORT_NOWAIT_BIT + 1);
1672
1673 if (S_ISREG(file_inode(file)->i_mode))
1674 res |= REQ_F_ISREG;
1675 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1676 res |= REQ_F_SUPPORT_NOWAIT;
1677 return res;
1678 }
1679
io_drain_req(struct io_kiocb * req)1680 static __cold void io_drain_req(struct io_kiocb *req)
1681 __must_hold(&ctx->uring_lock)
1682 {
1683 struct io_ring_ctx *ctx = req->ctx;
1684 bool drain = req->flags & IOSQE_IO_DRAIN;
1685 struct io_defer_entry *de;
1686
1687 de = kmalloc(sizeof(*de), GFP_KERNEL_ACCOUNT);
1688 if (!de) {
1689 io_req_defer_failed(req, -ENOMEM);
1690 return;
1691 }
1692
1693 io_prep_async_link(req);
1694 trace_io_uring_defer(req);
1695 de->req = req;
1696
1697 ctx->nr_drained += io_linked_nr(req);
1698 list_add_tail(&de->list, &ctx->defer_list);
1699 io_queue_deferred(ctx);
1700 if (!drain && list_empty(&ctx->defer_list))
1701 ctx->drain_active = false;
1702 }
1703
io_assign_file(struct io_kiocb * req,const struct io_issue_def * def,unsigned int issue_flags)1704 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1705 unsigned int issue_flags)
1706 {
1707 if (req->file || !def->needs_file)
1708 return true;
1709
1710 if (req->flags & REQ_F_FIXED_FILE)
1711 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1712 else
1713 req->file = io_file_get_normal(req, req->cqe.fd);
1714
1715 return !!req->file;
1716 }
1717
1718 #define REQ_ISSUE_SLOW_FLAGS (REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)
1719
__io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags,const struct io_issue_def * def)1720 static inline int __io_issue_sqe(struct io_kiocb *req,
1721 unsigned int issue_flags,
1722 const struct io_issue_def *def)
1723 {
1724 const struct cred *creds = NULL;
1725 struct io_kiocb *link = NULL;
1726 int ret;
1727
1728 if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) {
1729 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
1730 creds = override_creds(req->creds);
1731 if (req->flags & REQ_F_ARM_LTIMEOUT)
1732 link = __io_prep_linked_timeout(req);
1733 }
1734
1735 if (!def->audit_skip)
1736 audit_uring_entry(req->opcode);
1737
1738 ret = def->issue(req, issue_flags);
1739
1740 if (!def->audit_skip)
1741 audit_uring_exit(!ret, ret);
1742
1743 if (unlikely(creds || link)) {
1744 if (creds)
1745 revert_creds(creds);
1746 if (link)
1747 io_queue_linked_timeout(link);
1748 }
1749
1750 return ret;
1751 }
1752
io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags)1753 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1754 {
1755 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1756 int ret;
1757
1758 if (unlikely(!io_assign_file(req, def, issue_flags)))
1759 return -EBADF;
1760
1761 ret = __io_issue_sqe(req, issue_flags, def);
1762
1763 if (ret == IOU_COMPLETE) {
1764 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1765 io_req_complete_defer(req);
1766 else
1767 io_req_complete_post(req, issue_flags);
1768
1769 return 0;
1770 }
1771
1772 if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1773 ret = 0;
1774
1775 /* If the op doesn't have a file, we're not polling for it */
1776 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1777 io_iopoll_req_issued(req, issue_flags);
1778 }
1779 return ret;
1780 }
1781
io_poll_issue(struct io_kiocb * req,io_tw_token_t tw)1782 int io_poll_issue(struct io_kiocb *req, io_tw_token_t tw)
1783 {
1784 const unsigned int issue_flags = IO_URING_F_NONBLOCK |
1785 IO_URING_F_MULTISHOT |
1786 IO_URING_F_COMPLETE_DEFER;
1787 int ret;
1788
1789 io_tw_lock(req->ctx, tw);
1790
1791 WARN_ON_ONCE(!req->file);
1792 if (WARN_ON_ONCE(req->ctx->flags & IORING_SETUP_IOPOLL))
1793 return -EFAULT;
1794
1795 ret = __io_issue_sqe(req, issue_flags, &io_issue_defs[req->opcode]);
1796
1797 WARN_ON_ONCE(ret == IOU_ISSUE_SKIP_COMPLETE);
1798 return ret;
1799 }
1800
io_wq_free_work(struct io_wq_work * work)1801 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1802 {
1803 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1804 struct io_kiocb *nxt = NULL;
1805
1806 if (req_ref_put_and_test_atomic(req)) {
1807 if (req->flags & IO_REQ_LINK_FLAGS)
1808 nxt = io_req_find_next(req);
1809 io_free_req(req);
1810 }
1811 return nxt ? &nxt->work : NULL;
1812 }
1813
io_wq_submit_work(struct io_wq_work * work)1814 void io_wq_submit_work(struct io_wq_work *work)
1815 {
1816 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1817 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1818 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1819 bool needs_poll = false;
1820 int ret = 0, err = -ECANCELED;
1821
1822 /* one will be dropped by io_wq_free_work() after returning to io-wq */
1823 if (!(req->flags & REQ_F_REFCOUNT))
1824 __io_req_set_refcount(req, 2);
1825 else
1826 req_ref_get(req);
1827
1828 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1829 if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
1830 fail:
1831 io_req_task_queue_fail(req, err);
1832 return;
1833 }
1834 if (!io_assign_file(req, def, issue_flags)) {
1835 err = -EBADF;
1836 atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1837 goto fail;
1838 }
1839
1840 /*
1841 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1842 * submitter task context. Final request completions are handed to the
1843 * right context, however this is not the case of auxiliary CQEs,
1844 * which is the main mean of operation for multishot requests.
1845 * Don't allow any multishot execution from io-wq. It's more restrictive
1846 * than necessary and also cleaner.
1847 */
1848 if (req->flags & (REQ_F_MULTISHOT|REQ_F_APOLL_MULTISHOT)) {
1849 err = -EBADFD;
1850 if (!io_file_can_poll(req))
1851 goto fail;
1852 if (req->file->f_flags & O_NONBLOCK ||
1853 req->file->f_mode & FMODE_NOWAIT) {
1854 err = -ECANCELED;
1855 if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1856 goto fail;
1857 return;
1858 } else {
1859 req->flags &= ~(REQ_F_APOLL_MULTISHOT|REQ_F_MULTISHOT);
1860 }
1861 }
1862
1863 if (req->flags & REQ_F_FORCE_ASYNC) {
1864 bool opcode_poll = def->pollin || def->pollout;
1865
1866 if (opcode_poll && io_file_can_poll(req)) {
1867 needs_poll = true;
1868 issue_flags |= IO_URING_F_NONBLOCK;
1869 }
1870 }
1871
1872 do {
1873 ret = io_issue_sqe(req, issue_flags);
1874 if (ret != -EAGAIN)
1875 break;
1876
1877 /*
1878 * If REQ_F_NOWAIT is set, then don't wait or retry with
1879 * poll. -EAGAIN is final for that case.
1880 */
1881 if (req->flags & REQ_F_NOWAIT)
1882 break;
1883
1884 /*
1885 * We can get EAGAIN for iopolled IO even though we're
1886 * forcing a sync submission from here, since we can't
1887 * wait for request slots on the block side.
1888 */
1889 if (!needs_poll) {
1890 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1891 break;
1892 if (io_wq_worker_stopped())
1893 break;
1894 cond_resched();
1895 continue;
1896 }
1897
1898 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1899 return;
1900 /* aborted or ready, in either case retry blocking */
1901 needs_poll = false;
1902 issue_flags &= ~IO_URING_F_NONBLOCK;
1903 } while (1);
1904
1905 /* avoid locking problems by failing it from a clean context */
1906 if (ret)
1907 io_req_task_queue_fail(req, ret);
1908 }
1909
io_file_get_fixed(struct io_kiocb * req,int fd,unsigned int issue_flags)1910 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1911 unsigned int issue_flags)
1912 {
1913 struct io_ring_ctx *ctx = req->ctx;
1914 struct io_rsrc_node *node;
1915 struct file *file = NULL;
1916
1917 io_ring_submit_lock(ctx, issue_flags);
1918 node = io_rsrc_node_lookup(&ctx->file_table.data, fd);
1919 if (node) {
1920 node->refs++;
1921 req->file_node = node;
1922 req->flags |= io_slot_flags(node);
1923 file = io_slot_file(node);
1924 }
1925 io_ring_submit_unlock(ctx, issue_flags);
1926 return file;
1927 }
1928
io_file_get_normal(struct io_kiocb * req,int fd)1929 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1930 {
1931 struct file *file = fget(fd);
1932
1933 trace_io_uring_file_get(req, fd);
1934
1935 /* we don't allow fixed io_uring files */
1936 if (file && io_is_uring_fops(file))
1937 io_req_track_inflight(req);
1938 return file;
1939 }
1940
io_queue_async(struct io_kiocb * req,int ret)1941 static void io_queue_async(struct io_kiocb *req, int ret)
1942 __must_hold(&req->ctx->uring_lock)
1943 {
1944 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1945 io_req_defer_failed(req, ret);
1946 return;
1947 }
1948
1949 switch (io_arm_poll_handler(req, 0)) {
1950 case IO_APOLL_READY:
1951 io_kbuf_recycle(req, 0);
1952 io_req_task_queue(req);
1953 break;
1954 case IO_APOLL_ABORTED:
1955 io_kbuf_recycle(req, 0);
1956 io_queue_iowq(req);
1957 break;
1958 case IO_APOLL_OK:
1959 break;
1960 }
1961 }
1962
io_queue_sqe(struct io_kiocb * req)1963 static inline void io_queue_sqe(struct io_kiocb *req)
1964 __must_hold(&req->ctx->uring_lock)
1965 {
1966 int ret;
1967
1968 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
1969
1970 /*
1971 * We async punt it if the file wasn't marked NOWAIT, or if the file
1972 * doesn't support non-blocking read/write attempts
1973 */
1974 if (unlikely(ret))
1975 io_queue_async(req, ret);
1976 }
1977
io_queue_sqe_fallback(struct io_kiocb * req)1978 static void io_queue_sqe_fallback(struct io_kiocb *req)
1979 __must_hold(&req->ctx->uring_lock)
1980 {
1981 if (unlikely(req->flags & REQ_F_FAIL)) {
1982 /*
1983 * We don't submit, fail them all, for that replace hardlinks
1984 * with normal links. Extra REQ_F_LINK is tolerated.
1985 */
1986 req->flags &= ~REQ_F_HARDLINK;
1987 req->flags |= REQ_F_LINK;
1988 io_req_defer_failed(req, req->cqe.res);
1989 } else {
1990 if (unlikely(req->ctx->drain_active))
1991 io_drain_req(req);
1992 else
1993 io_queue_iowq(req);
1994 }
1995 }
1996
1997 /*
1998 * Check SQE restrictions (opcode and flags).
1999 *
2000 * Returns 'true' if SQE is allowed, 'false' otherwise.
2001 */
io_check_restriction(struct io_ring_ctx * ctx,struct io_kiocb * req,unsigned int sqe_flags)2002 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2003 struct io_kiocb *req,
2004 unsigned int sqe_flags)
2005 {
2006 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2007 return false;
2008
2009 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2010 ctx->restrictions.sqe_flags_required)
2011 return false;
2012
2013 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2014 ctx->restrictions.sqe_flags_required))
2015 return false;
2016
2017 return true;
2018 }
2019
io_init_drain(struct io_ring_ctx * ctx)2020 static void io_init_drain(struct io_ring_ctx *ctx)
2021 {
2022 struct io_kiocb *head = ctx->submit_state.link.head;
2023
2024 ctx->drain_active = true;
2025 if (head) {
2026 /*
2027 * If we need to drain a request in the middle of a link, drain
2028 * the head request and the next request/link after the current
2029 * link. Considering sequential execution of links,
2030 * REQ_F_IO_DRAIN will be maintained for every request of our
2031 * link.
2032 */
2033 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2034 ctx->drain_next = true;
2035 }
2036 }
2037
io_init_fail_req(struct io_kiocb * req,int err)2038 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2039 {
2040 /* ensure per-opcode data is cleared if we fail before prep */
2041 memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2042 return err;
2043 }
2044
io_init_req(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2045 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2046 const struct io_uring_sqe *sqe)
2047 __must_hold(&ctx->uring_lock)
2048 {
2049 const struct io_issue_def *def;
2050 unsigned int sqe_flags;
2051 int personality;
2052 u8 opcode;
2053
2054 req->ctx = ctx;
2055 req->opcode = opcode = READ_ONCE(sqe->opcode);
2056 /* same numerical values with corresponding REQ_F_*, safe to copy */
2057 sqe_flags = READ_ONCE(sqe->flags);
2058 req->flags = (__force io_req_flags_t) sqe_flags;
2059 req->cqe.user_data = READ_ONCE(sqe->user_data);
2060 req->file = NULL;
2061 req->tctx = current->io_uring;
2062 req->cancel_seq_set = false;
2063
2064 if (unlikely(opcode >= IORING_OP_LAST)) {
2065 req->opcode = 0;
2066 return io_init_fail_req(req, -EINVAL);
2067 }
2068 opcode = array_index_nospec(opcode, IORING_OP_LAST);
2069
2070 def = &io_issue_defs[opcode];
2071 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2072 /* enforce forwards compatibility on users */
2073 if (sqe_flags & ~SQE_VALID_FLAGS)
2074 return io_init_fail_req(req, -EINVAL);
2075 if (sqe_flags & IOSQE_BUFFER_SELECT) {
2076 if (!def->buffer_select)
2077 return io_init_fail_req(req, -EOPNOTSUPP);
2078 req->buf_index = READ_ONCE(sqe->buf_group);
2079 }
2080 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2081 ctx->drain_disabled = true;
2082 if (sqe_flags & IOSQE_IO_DRAIN) {
2083 if (ctx->drain_disabled)
2084 return io_init_fail_req(req, -EOPNOTSUPP);
2085 io_init_drain(ctx);
2086 }
2087 }
2088 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2089 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2090 return io_init_fail_req(req, -EACCES);
2091 /* knock it to the slow queue path, will be drained there */
2092 if (ctx->drain_active)
2093 req->flags |= REQ_F_FORCE_ASYNC;
2094 /* if there is no link, we're at "next" request and need to drain */
2095 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2096 ctx->drain_next = false;
2097 ctx->drain_active = true;
2098 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2099 }
2100 }
2101
2102 if (!def->ioprio && sqe->ioprio)
2103 return io_init_fail_req(req, -EINVAL);
2104 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2105 return io_init_fail_req(req, -EINVAL);
2106
2107 if (def->needs_file) {
2108 struct io_submit_state *state = &ctx->submit_state;
2109
2110 req->cqe.fd = READ_ONCE(sqe->fd);
2111
2112 /*
2113 * Plug now if we have more than 2 IO left after this, and the
2114 * target is potentially a read/write to block based storage.
2115 */
2116 if (state->need_plug && def->plug) {
2117 state->plug_started = true;
2118 state->need_plug = false;
2119 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2120 }
2121 }
2122
2123 personality = READ_ONCE(sqe->personality);
2124 if (personality) {
2125 int ret;
2126
2127 req->creds = xa_load(&ctx->personalities, personality);
2128 if (!req->creds)
2129 return io_init_fail_req(req, -EINVAL);
2130 get_cred(req->creds);
2131 ret = security_uring_override_creds(req->creds);
2132 if (ret) {
2133 put_cred(req->creds);
2134 return io_init_fail_req(req, ret);
2135 }
2136 req->flags |= REQ_F_CREDS;
2137 }
2138
2139 return def->prep(req, sqe);
2140 }
2141
io_submit_fail_init(const struct io_uring_sqe * sqe,struct io_kiocb * req,int ret)2142 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2143 struct io_kiocb *req, int ret)
2144 {
2145 struct io_ring_ctx *ctx = req->ctx;
2146 struct io_submit_link *link = &ctx->submit_state.link;
2147 struct io_kiocb *head = link->head;
2148
2149 trace_io_uring_req_failed(sqe, req, ret);
2150
2151 /*
2152 * Avoid breaking links in the middle as it renders links with SQPOLL
2153 * unusable. Instead of failing eagerly, continue assembling the link if
2154 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2155 * should find the flag and handle the rest.
2156 */
2157 req_fail_link_node(req, ret);
2158 if (head && !(head->flags & REQ_F_FAIL))
2159 req_fail_link_node(head, -ECANCELED);
2160
2161 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2162 if (head) {
2163 link->last->link = req;
2164 link->head = NULL;
2165 req = head;
2166 }
2167 io_queue_sqe_fallback(req);
2168 return ret;
2169 }
2170
2171 if (head)
2172 link->last->link = req;
2173 else
2174 link->head = req;
2175 link->last = req;
2176 return 0;
2177 }
2178
io_submit_sqe(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2179 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2180 const struct io_uring_sqe *sqe)
2181 __must_hold(&ctx->uring_lock)
2182 {
2183 struct io_submit_link *link = &ctx->submit_state.link;
2184 int ret;
2185
2186 ret = io_init_req(ctx, req, sqe);
2187 if (unlikely(ret))
2188 return io_submit_fail_init(sqe, req, ret);
2189
2190 trace_io_uring_submit_req(req);
2191
2192 /*
2193 * If we already have a head request, queue this one for async
2194 * submittal once the head completes. If we don't have a head but
2195 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2196 * submitted sync once the chain is complete. If none of those
2197 * conditions are true (normal request), then just queue it.
2198 */
2199 if (unlikely(link->head)) {
2200 trace_io_uring_link(req, link->last);
2201 link->last->link = req;
2202 link->last = req;
2203
2204 if (req->flags & IO_REQ_LINK_FLAGS)
2205 return 0;
2206 /* last request of the link, flush it */
2207 req = link->head;
2208 link->head = NULL;
2209 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2210 goto fallback;
2211
2212 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2213 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2214 if (req->flags & IO_REQ_LINK_FLAGS) {
2215 link->head = req;
2216 link->last = req;
2217 } else {
2218 fallback:
2219 io_queue_sqe_fallback(req);
2220 }
2221 return 0;
2222 }
2223
2224 io_queue_sqe(req);
2225 return 0;
2226 }
2227
2228 /*
2229 * Batched submission is done, ensure local IO is flushed out.
2230 */
io_submit_state_end(struct io_ring_ctx * ctx)2231 static void io_submit_state_end(struct io_ring_ctx *ctx)
2232 {
2233 struct io_submit_state *state = &ctx->submit_state;
2234
2235 if (unlikely(state->link.head))
2236 io_queue_sqe_fallback(state->link.head);
2237 /* flush only after queuing links as they can generate completions */
2238 io_submit_flush_completions(ctx);
2239 if (state->plug_started)
2240 blk_finish_plug(&state->plug);
2241 }
2242
2243 /*
2244 * Start submission side cache.
2245 */
io_submit_state_start(struct io_submit_state * state,unsigned int max_ios)2246 static void io_submit_state_start(struct io_submit_state *state,
2247 unsigned int max_ios)
2248 {
2249 state->plug_started = false;
2250 state->need_plug = max_ios > 2;
2251 state->submit_nr = max_ios;
2252 /* set only head, no need to init link_last in advance */
2253 state->link.head = NULL;
2254 }
2255
io_commit_sqring(struct io_ring_ctx * ctx)2256 static void io_commit_sqring(struct io_ring_ctx *ctx)
2257 {
2258 struct io_rings *rings = ctx->rings;
2259
2260 /*
2261 * Ensure any loads from the SQEs are done at this point,
2262 * since once we write the new head, the application could
2263 * write new data to them.
2264 */
2265 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2266 }
2267
2268 /*
2269 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2270 * that is mapped by userspace. This means that care needs to be taken to
2271 * ensure that reads are stable, as we cannot rely on userspace always
2272 * being a good citizen. If members of the sqe are validated and then later
2273 * used, it's important that those reads are done through READ_ONCE() to
2274 * prevent a re-load down the line.
2275 */
io_get_sqe(struct io_ring_ctx * ctx,const struct io_uring_sqe ** sqe)2276 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2277 {
2278 unsigned mask = ctx->sq_entries - 1;
2279 unsigned head = ctx->cached_sq_head++ & mask;
2280
2281 if (static_branch_unlikely(&io_key_has_sqarray) &&
2282 (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) {
2283 head = READ_ONCE(ctx->sq_array[head]);
2284 if (unlikely(head >= ctx->sq_entries)) {
2285 WRITE_ONCE(ctx->rings->sq_dropped,
2286 READ_ONCE(ctx->rings->sq_dropped) + 1);
2287 return false;
2288 }
2289 head = array_index_nospec(head, ctx->sq_entries);
2290 }
2291
2292 /*
2293 * The cached sq head (or cq tail) serves two purposes:
2294 *
2295 * 1) allows us to batch the cost of updating the user visible
2296 * head updates.
2297 * 2) allows the kernel side to track the head on its own, even
2298 * though the application is the one updating it.
2299 */
2300
2301 /* double index for 128-byte SQEs, twice as long */
2302 if (ctx->flags & IORING_SETUP_SQE128)
2303 head <<= 1;
2304 *sqe = &ctx->sq_sqes[head];
2305 return true;
2306 }
2307
io_submit_sqes(struct io_ring_ctx * ctx,unsigned int nr)2308 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2309 __must_hold(&ctx->uring_lock)
2310 {
2311 unsigned int entries = io_sqring_entries(ctx);
2312 unsigned int left;
2313 int ret;
2314
2315 if (unlikely(!entries))
2316 return 0;
2317 /* make sure SQ entry isn't read before tail */
2318 ret = left = min(nr, entries);
2319 io_get_task_refs(left);
2320 io_submit_state_start(&ctx->submit_state, left);
2321
2322 do {
2323 const struct io_uring_sqe *sqe;
2324 struct io_kiocb *req;
2325
2326 if (unlikely(!io_alloc_req(ctx, &req)))
2327 break;
2328 if (unlikely(!io_get_sqe(ctx, &sqe))) {
2329 io_req_add_to_cache(req, ctx);
2330 break;
2331 }
2332
2333 /*
2334 * Continue submitting even for sqe failure if the
2335 * ring was setup with IORING_SETUP_SUBMIT_ALL
2336 */
2337 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2338 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2339 left--;
2340 break;
2341 }
2342 } while (--left);
2343
2344 if (unlikely(left)) {
2345 ret -= left;
2346 /* try again if it submitted nothing and can't allocate a req */
2347 if (!ret && io_req_cache_empty(ctx))
2348 ret = -EAGAIN;
2349 current->io_uring->cached_refs += left;
2350 }
2351
2352 io_submit_state_end(ctx);
2353 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2354 io_commit_sqring(ctx);
2355 return ret;
2356 }
2357
io_wake_function(struct wait_queue_entry * curr,unsigned int mode,int wake_flags,void * key)2358 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2359 int wake_flags, void *key)
2360 {
2361 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2362
2363 /*
2364 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2365 * the task, and the next invocation will do it.
2366 */
2367 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2368 return autoremove_wake_function(curr, mode, wake_flags, key);
2369 return -1;
2370 }
2371
io_run_task_work_sig(struct io_ring_ctx * ctx)2372 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2373 {
2374 if (io_local_work_pending(ctx)) {
2375 __set_current_state(TASK_RUNNING);
2376 if (io_run_local_work(ctx, INT_MAX, IO_LOCAL_TW_DEFAULT_MAX) > 0)
2377 return 0;
2378 }
2379 if (io_run_task_work() > 0)
2380 return 0;
2381 if (task_sigpending(current))
2382 return -EINTR;
2383 return 0;
2384 }
2385
current_pending_io(void)2386 static bool current_pending_io(void)
2387 {
2388 struct io_uring_task *tctx = current->io_uring;
2389
2390 if (!tctx)
2391 return false;
2392 return percpu_counter_read_positive(&tctx->inflight);
2393 }
2394
io_cqring_timer_wakeup(struct hrtimer * timer)2395 static enum hrtimer_restart io_cqring_timer_wakeup(struct hrtimer *timer)
2396 {
2397 struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
2398
2399 WRITE_ONCE(iowq->hit_timeout, 1);
2400 iowq->min_timeout = 0;
2401 wake_up_process(iowq->wq.private);
2402 return HRTIMER_NORESTART;
2403 }
2404
2405 /*
2406 * Doing min_timeout portion. If we saw any timeouts, events, or have work,
2407 * wake up. If not, and we have a normal timeout, switch to that and keep
2408 * sleeping.
2409 */
io_cqring_min_timer_wakeup(struct hrtimer * timer)2410 static enum hrtimer_restart io_cqring_min_timer_wakeup(struct hrtimer *timer)
2411 {
2412 struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
2413 struct io_ring_ctx *ctx = iowq->ctx;
2414
2415 /* no general timeout, or shorter (or equal), we are done */
2416 if (iowq->timeout == KTIME_MAX ||
2417 ktime_compare(iowq->min_timeout, iowq->timeout) >= 0)
2418 goto out_wake;
2419 /* work we may need to run, wake function will see if we need to wake */
2420 if (io_has_work(ctx))
2421 goto out_wake;
2422 /* got events since we started waiting, min timeout is done */
2423 if (iowq->cq_min_tail != READ_ONCE(ctx->rings->cq.tail))
2424 goto out_wake;
2425 /* if we have any events and min timeout expired, we're done */
2426 if (io_cqring_events(ctx))
2427 goto out_wake;
2428
2429 /*
2430 * If using deferred task_work running and application is waiting on
2431 * more than one request, ensure we reset it now where we are switching
2432 * to normal sleeps. Any request completion post min_wait should wake
2433 * the task and return.
2434 */
2435 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2436 atomic_set(&ctx->cq_wait_nr, 1);
2437 smp_mb();
2438 if (!llist_empty(&ctx->work_llist))
2439 goto out_wake;
2440 }
2441
2442 hrtimer_update_function(&iowq->t, io_cqring_timer_wakeup);
2443 hrtimer_set_expires(timer, iowq->timeout);
2444 return HRTIMER_RESTART;
2445 out_wake:
2446 return io_cqring_timer_wakeup(timer);
2447 }
2448
io_cqring_schedule_timeout(struct io_wait_queue * iowq,clockid_t clock_id,ktime_t start_time)2449 static int io_cqring_schedule_timeout(struct io_wait_queue *iowq,
2450 clockid_t clock_id, ktime_t start_time)
2451 {
2452 ktime_t timeout;
2453
2454 if (iowq->min_timeout) {
2455 timeout = ktime_add_ns(iowq->min_timeout, start_time);
2456 hrtimer_setup_on_stack(&iowq->t, io_cqring_min_timer_wakeup, clock_id,
2457 HRTIMER_MODE_ABS);
2458 } else {
2459 timeout = iowq->timeout;
2460 hrtimer_setup_on_stack(&iowq->t, io_cqring_timer_wakeup, clock_id,
2461 HRTIMER_MODE_ABS);
2462 }
2463
2464 hrtimer_set_expires_range_ns(&iowq->t, timeout, 0);
2465 hrtimer_start_expires(&iowq->t, HRTIMER_MODE_ABS);
2466
2467 if (!READ_ONCE(iowq->hit_timeout))
2468 schedule();
2469
2470 hrtimer_cancel(&iowq->t);
2471 destroy_hrtimer_on_stack(&iowq->t);
2472 __set_current_state(TASK_RUNNING);
2473
2474 return READ_ONCE(iowq->hit_timeout) ? -ETIME : 0;
2475 }
2476
2477 struct ext_arg {
2478 size_t argsz;
2479 struct timespec64 ts;
2480 const sigset_t __user *sig;
2481 ktime_t min_time;
2482 bool ts_set;
2483 bool iowait;
2484 };
2485
__io_cqring_wait_schedule(struct io_ring_ctx * ctx,struct io_wait_queue * iowq,struct ext_arg * ext_arg,ktime_t start_time)2486 static int __io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2487 struct io_wait_queue *iowq,
2488 struct ext_arg *ext_arg,
2489 ktime_t start_time)
2490 {
2491 int ret = 0;
2492
2493 /*
2494 * Mark us as being in io_wait if we have pending requests, so cpufreq
2495 * can take into account that the task is waiting for IO - turns out
2496 * to be important for low QD IO.
2497 */
2498 if (ext_arg->iowait && current_pending_io())
2499 current->in_iowait = 1;
2500 if (iowq->timeout != KTIME_MAX || iowq->min_timeout)
2501 ret = io_cqring_schedule_timeout(iowq, ctx->clockid, start_time);
2502 else
2503 schedule();
2504 current->in_iowait = 0;
2505 return ret;
2506 }
2507
2508 /* If this returns > 0, the caller should retry */
io_cqring_wait_schedule(struct io_ring_ctx * ctx,struct io_wait_queue * iowq,struct ext_arg * ext_arg,ktime_t start_time)2509 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2510 struct io_wait_queue *iowq,
2511 struct ext_arg *ext_arg,
2512 ktime_t start_time)
2513 {
2514 if (unlikely(READ_ONCE(ctx->check_cq)))
2515 return 1;
2516 if (unlikely(io_local_work_pending(ctx)))
2517 return 1;
2518 if (unlikely(task_work_pending(current)))
2519 return 1;
2520 if (unlikely(task_sigpending(current)))
2521 return -EINTR;
2522 if (unlikely(io_should_wake(iowq)))
2523 return 0;
2524
2525 return __io_cqring_wait_schedule(ctx, iowq, ext_arg, start_time);
2526 }
2527
2528 /*
2529 * Wait until events become available, if we don't already have some. The
2530 * application must reap them itself, as they reside on the shared cq ring.
2531 */
io_cqring_wait(struct io_ring_ctx * ctx,int min_events,u32 flags,struct ext_arg * ext_arg)2532 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events, u32 flags,
2533 struct ext_arg *ext_arg)
2534 {
2535 struct io_wait_queue iowq;
2536 struct io_rings *rings = ctx->rings;
2537 ktime_t start_time;
2538 int ret;
2539
2540 min_events = min_t(int, min_events, ctx->cq_entries);
2541
2542 if (!io_allowed_run_tw(ctx))
2543 return -EEXIST;
2544 if (io_local_work_pending(ctx))
2545 io_run_local_work(ctx, min_events,
2546 max(IO_LOCAL_TW_DEFAULT_MAX, min_events));
2547 io_run_task_work();
2548
2549 if (unlikely(test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)))
2550 io_cqring_do_overflow_flush(ctx);
2551 if (__io_cqring_events_user(ctx) >= min_events)
2552 return 0;
2553
2554 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2555 iowq.wq.private = current;
2556 INIT_LIST_HEAD(&iowq.wq.entry);
2557 iowq.ctx = ctx;
2558 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2559 iowq.cq_min_tail = READ_ONCE(ctx->rings->cq.tail);
2560 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2561 iowq.hit_timeout = 0;
2562 iowq.min_timeout = ext_arg->min_time;
2563 iowq.timeout = KTIME_MAX;
2564 start_time = io_get_time(ctx);
2565
2566 if (ext_arg->ts_set) {
2567 iowq.timeout = timespec64_to_ktime(ext_arg->ts);
2568 if (!(flags & IORING_ENTER_ABS_TIMER))
2569 iowq.timeout = ktime_add(iowq.timeout, start_time);
2570 }
2571
2572 if (ext_arg->sig) {
2573 #ifdef CONFIG_COMPAT
2574 if (in_compat_syscall())
2575 ret = set_compat_user_sigmask((const compat_sigset_t __user *)ext_arg->sig,
2576 ext_arg->argsz);
2577 else
2578 #endif
2579 ret = set_user_sigmask(ext_arg->sig, ext_arg->argsz);
2580
2581 if (ret)
2582 return ret;
2583 }
2584
2585 io_napi_busy_loop(ctx, &iowq);
2586
2587 trace_io_uring_cqring_wait(ctx, min_events);
2588 do {
2589 unsigned long check_cq;
2590 int nr_wait;
2591
2592 /* if min timeout has been hit, don't reset wait count */
2593 if (!iowq.hit_timeout)
2594 nr_wait = (int) iowq.cq_tail -
2595 READ_ONCE(ctx->rings->cq.tail);
2596 else
2597 nr_wait = 1;
2598
2599 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2600 atomic_set(&ctx->cq_wait_nr, nr_wait);
2601 set_current_state(TASK_INTERRUPTIBLE);
2602 } else {
2603 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2604 TASK_INTERRUPTIBLE);
2605 }
2606
2607 ret = io_cqring_wait_schedule(ctx, &iowq, ext_arg, start_time);
2608 __set_current_state(TASK_RUNNING);
2609 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
2610
2611 /*
2612 * Run task_work after scheduling and before io_should_wake().
2613 * If we got woken because of task_work being processed, run it
2614 * now rather than let the caller do another wait loop.
2615 */
2616 if (io_local_work_pending(ctx))
2617 io_run_local_work(ctx, nr_wait, nr_wait);
2618 io_run_task_work();
2619
2620 /*
2621 * Non-local task_work will be run on exit to userspace, but
2622 * if we're using DEFER_TASKRUN, then we could have waited
2623 * with a timeout for a number of requests. If the timeout
2624 * hits, we could have some requests ready to process. Ensure
2625 * this break is _after_ we have run task_work, to avoid
2626 * deferring running potentially pending requests until the
2627 * next time we wait for events.
2628 */
2629 if (ret < 0)
2630 break;
2631
2632 check_cq = READ_ONCE(ctx->check_cq);
2633 if (unlikely(check_cq)) {
2634 /* let the caller flush overflows, retry */
2635 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2636 io_cqring_do_overflow_flush(ctx);
2637 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2638 ret = -EBADR;
2639 break;
2640 }
2641 }
2642
2643 if (io_should_wake(&iowq)) {
2644 ret = 0;
2645 break;
2646 }
2647 cond_resched();
2648 } while (1);
2649
2650 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2651 finish_wait(&ctx->cq_wait, &iowq.wq);
2652 restore_saved_sigmask_unless(ret == -EINTR);
2653
2654 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2655 }
2656
io_rings_free(struct io_ring_ctx * ctx)2657 static void io_rings_free(struct io_ring_ctx *ctx)
2658 {
2659 io_free_region(ctx, &ctx->sq_region);
2660 io_free_region(ctx, &ctx->ring_region);
2661 ctx->rings = NULL;
2662 ctx->sq_sqes = NULL;
2663 }
2664
rings_size(unsigned int flags,unsigned int sq_entries,unsigned int cq_entries,size_t * sq_offset)2665 unsigned long rings_size(unsigned int flags, unsigned int sq_entries,
2666 unsigned int cq_entries, size_t *sq_offset)
2667 {
2668 struct io_rings *rings;
2669 size_t off, sq_array_size;
2670
2671 off = struct_size(rings, cqes, cq_entries);
2672 if (off == SIZE_MAX)
2673 return SIZE_MAX;
2674 if (flags & IORING_SETUP_CQE32) {
2675 if (check_shl_overflow(off, 1, &off))
2676 return SIZE_MAX;
2677 }
2678
2679 #ifdef CONFIG_SMP
2680 off = ALIGN(off, SMP_CACHE_BYTES);
2681 if (off == 0)
2682 return SIZE_MAX;
2683 #endif
2684
2685 if (flags & IORING_SETUP_NO_SQARRAY) {
2686 *sq_offset = SIZE_MAX;
2687 return off;
2688 }
2689
2690 *sq_offset = off;
2691
2692 sq_array_size = array_size(sizeof(u32), sq_entries);
2693 if (sq_array_size == SIZE_MAX)
2694 return SIZE_MAX;
2695
2696 if (check_add_overflow(off, sq_array_size, &off))
2697 return SIZE_MAX;
2698
2699 return off;
2700 }
2701
__io_req_caches_free(struct io_ring_ctx * ctx)2702 static __cold void __io_req_caches_free(struct io_ring_ctx *ctx)
2703 {
2704 struct io_kiocb *req;
2705 int nr = 0;
2706
2707 while (!io_req_cache_empty(ctx)) {
2708 req = io_extract_req(ctx);
2709 kmem_cache_free(req_cachep, req);
2710 nr++;
2711 }
2712 if (nr) {
2713 ctx->nr_req_allocated -= nr;
2714 percpu_ref_put_many(&ctx->refs, nr);
2715 }
2716 }
2717
io_req_caches_free(struct io_ring_ctx * ctx)2718 static __cold void io_req_caches_free(struct io_ring_ctx *ctx)
2719 {
2720 guard(mutex)(&ctx->uring_lock);
2721 __io_req_caches_free(ctx);
2722 }
2723
io_ring_ctx_free(struct io_ring_ctx * ctx)2724 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2725 {
2726 io_sq_thread_finish(ctx);
2727
2728 mutex_lock(&ctx->uring_lock);
2729 io_sqe_buffers_unregister(ctx);
2730 io_sqe_files_unregister(ctx);
2731 io_unregister_zcrx_ifqs(ctx);
2732 io_cqring_overflow_kill(ctx);
2733 io_eventfd_unregister(ctx);
2734 io_free_alloc_caches(ctx);
2735 io_destroy_buffers(ctx);
2736 io_free_region(ctx, &ctx->param_region);
2737 mutex_unlock(&ctx->uring_lock);
2738 if (ctx->sq_creds)
2739 put_cred(ctx->sq_creds);
2740 if (ctx->submitter_task)
2741 put_task_struct(ctx->submitter_task);
2742
2743 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2744
2745 if (ctx->mm_account) {
2746 mmdrop(ctx->mm_account);
2747 ctx->mm_account = NULL;
2748 }
2749 io_rings_free(ctx);
2750
2751 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2752 static_branch_dec(&io_key_has_sqarray);
2753
2754 percpu_ref_exit(&ctx->refs);
2755 free_uid(ctx->user);
2756 io_req_caches_free(ctx);
2757
2758 WARN_ON_ONCE(ctx->nr_req_allocated);
2759
2760 if (ctx->hash_map)
2761 io_wq_put_hash(ctx->hash_map);
2762 io_napi_free(ctx);
2763 kvfree(ctx->cancel_table.hbs);
2764 xa_destroy(&ctx->io_bl_xa);
2765 kfree(ctx);
2766 }
2767
io_activate_pollwq_cb(struct callback_head * cb)2768 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2769 {
2770 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2771 poll_wq_task_work);
2772
2773 mutex_lock(&ctx->uring_lock);
2774 ctx->poll_activated = true;
2775 mutex_unlock(&ctx->uring_lock);
2776
2777 /*
2778 * Wake ups for some events between start of polling and activation
2779 * might've been lost due to loose synchronisation.
2780 */
2781 wake_up_all(&ctx->poll_wq);
2782 percpu_ref_put(&ctx->refs);
2783 }
2784
io_activate_pollwq(struct io_ring_ctx * ctx)2785 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2786 {
2787 spin_lock(&ctx->completion_lock);
2788 /* already activated or in progress */
2789 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2790 goto out;
2791 if (WARN_ON_ONCE(!ctx->task_complete))
2792 goto out;
2793 if (!ctx->submitter_task)
2794 goto out;
2795 /*
2796 * with ->submitter_task only the submitter task completes requests, we
2797 * only need to sync with it, which is done by injecting a tw
2798 */
2799 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2800 percpu_ref_get(&ctx->refs);
2801 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2802 percpu_ref_put(&ctx->refs);
2803 out:
2804 spin_unlock(&ctx->completion_lock);
2805 }
2806
io_uring_poll(struct file * file,poll_table * wait)2807 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2808 {
2809 struct io_ring_ctx *ctx = file->private_data;
2810 __poll_t mask = 0;
2811
2812 if (unlikely(!ctx->poll_activated))
2813 io_activate_pollwq(ctx);
2814 /*
2815 * provides mb() which pairs with barrier from wq_has_sleeper
2816 * call in io_commit_cqring
2817 */
2818 poll_wait(file, &ctx->poll_wq, wait);
2819
2820 if (!io_sqring_full(ctx))
2821 mask |= EPOLLOUT | EPOLLWRNORM;
2822
2823 /*
2824 * Don't flush cqring overflow list here, just do a simple check.
2825 * Otherwise there could possible be ABBA deadlock:
2826 * CPU0 CPU1
2827 * ---- ----
2828 * lock(&ctx->uring_lock);
2829 * lock(&ep->mtx);
2830 * lock(&ctx->uring_lock);
2831 * lock(&ep->mtx);
2832 *
2833 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2834 * pushes them to do the flush.
2835 */
2836
2837 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2838 mask |= EPOLLIN | EPOLLRDNORM;
2839
2840 return mask;
2841 }
2842
2843 struct io_tctx_exit {
2844 struct callback_head task_work;
2845 struct completion completion;
2846 struct io_ring_ctx *ctx;
2847 };
2848
io_tctx_exit_cb(struct callback_head * cb)2849 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2850 {
2851 struct io_uring_task *tctx = current->io_uring;
2852 struct io_tctx_exit *work;
2853
2854 work = container_of(cb, struct io_tctx_exit, task_work);
2855 /*
2856 * When @in_cancel, we're in cancellation and it's racy to remove the
2857 * node. It'll be removed by the end of cancellation, just ignore it.
2858 * tctx can be NULL if the queueing of this task_work raced with
2859 * work cancelation off the exec path.
2860 */
2861 if (tctx && !atomic_read(&tctx->in_cancel))
2862 io_uring_del_tctx_node((unsigned long)work->ctx);
2863 complete(&work->completion);
2864 }
2865
io_cancel_ctx_cb(struct io_wq_work * work,void * data)2866 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
2867 {
2868 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2869
2870 return req->ctx == data;
2871 }
2872
io_ring_exit_work(struct work_struct * work)2873 static __cold void io_ring_exit_work(struct work_struct *work)
2874 {
2875 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2876 unsigned long timeout = jiffies + HZ * 60 * 5;
2877 unsigned long interval = HZ / 20;
2878 struct io_tctx_exit exit;
2879 struct io_tctx_node *node;
2880 int ret;
2881
2882 /*
2883 * If we're doing polled IO and end up having requests being
2884 * submitted async (out-of-line), then completions can come in while
2885 * we're waiting for refs to drop. We need to reap these manually,
2886 * as nobody else will be looking for them.
2887 */
2888 do {
2889 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2890 mutex_lock(&ctx->uring_lock);
2891 io_cqring_overflow_kill(ctx);
2892 mutex_unlock(&ctx->uring_lock);
2893 }
2894 if (!xa_empty(&ctx->zcrx_ctxs)) {
2895 mutex_lock(&ctx->uring_lock);
2896 io_shutdown_zcrx_ifqs(ctx);
2897 mutex_unlock(&ctx->uring_lock);
2898 }
2899
2900 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2901 io_move_task_work_from_local(ctx);
2902
2903 /* The SQPOLL thread never reaches this path */
2904 while (io_uring_try_cancel_requests(ctx, NULL, true, false))
2905 cond_resched();
2906
2907 if (ctx->sq_data) {
2908 struct io_sq_data *sqd = ctx->sq_data;
2909 struct task_struct *tsk;
2910
2911 io_sq_thread_park(sqd);
2912 tsk = sqpoll_task_locked(sqd);
2913 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2914 io_wq_cancel_cb(tsk->io_uring->io_wq,
2915 io_cancel_ctx_cb, ctx, true);
2916 io_sq_thread_unpark(sqd);
2917 }
2918
2919 io_req_caches_free(ctx);
2920
2921 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2922 /* there is little hope left, don't run it too often */
2923 interval = HZ * 60;
2924 }
2925 /*
2926 * This is really an uninterruptible wait, as it has to be
2927 * complete. But it's also run from a kworker, which doesn't
2928 * take signals, so it's fine to make it interruptible. This
2929 * avoids scenarios where we knowingly can wait much longer
2930 * on completions, for example if someone does a SIGSTOP on
2931 * a task that needs to finish task_work to make this loop
2932 * complete. That's a synthetic situation that should not
2933 * cause a stuck task backtrace, and hence a potential panic
2934 * on stuck tasks if that is enabled.
2935 */
2936 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
2937
2938 init_completion(&exit.completion);
2939 init_task_work(&exit.task_work, io_tctx_exit_cb);
2940 exit.ctx = ctx;
2941
2942 mutex_lock(&ctx->uring_lock);
2943 while (!list_empty(&ctx->tctx_list)) {
2944 WARN_ON_ONCE(time_after(jiffies, timeout));
2945
2946 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2947 ctx_node);
2948 /* don't spin on a single task if cancellation failed */
2949 list_rotate_left(&ctx->tctx_list);
2950 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2951 if (WARN_ON_ONCE(ret))
2952 continue;
2953
2954 mutex_unlock(&ctx->uring_lock);
2955 /*
2956 * See comment above for
2957 * wait_for_completion_interruptible_timeout() on why this
2958 * wait is marked as interruptible.
2959 */
2960 wait_for_completion_interruptible(&exit.completion);
2961 mutex_lock(&ctx->uring_lock);
2962 }
2963 mutex_unlock(&ctx->uring_lock);
2964 spin_lock(&ctx->completion_lock);
2965 spin_unlock(&ctx->completion_lock);
2966
2967 /* pairs with RCU read section in io_req_local_work_add() */
2968 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2969 synchronize_rcu();
2970
2971 io_ring_ctx_free(ctx);
2972 }
2973
io_ring_ctx_wait_and_kill(struct io_ring_ctx * ctx)2974 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2975 {
2976 unsigned long index;
2977 struct creds *creds;
2978
2979 mutex_lock(&ctx->uring_lock);
2980 percpu_ref_kill(&ctx->refs);
2981 xa_for_each(&ctx->personalities, index, creds)
2982 io_unregister_personality(ctx, index);
2983 mutex_unlock(&ctx->uring_lock);
2984
2985 flush_delayed_work(&ctx->fallback_work);
2986
2987 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2988 /*
2989 * Use system_unbound_wq to avoid spawning tons of event kworkers
2990 * if we're exiting a ton of rings at the same time. It just adds
2991 * noise and overhead, there's no discernable change in runtime
2992 * over using system_wq.
2993 */
2994 queue_work(iou_wq, &ctx->exit_work);
2995 }
2996
io_uring_release(struct inode * inode,struct file * file)2997 static int io_uring_release(struct inode *inode, struct file *file)
2998 {
2999 struct io_ring_ctx *ctx = file->private_data;
3000
3001 file->private_data = NULL;
3002 io_ring_ctx_wait_and_kill(ctx);
3003 return 0;
3004 }
3005
3006 struct io_task_cancel {
3007 struct io_uring_task *tctx;
3008 bool all;
3009 };
3010
io_cancel_task_cb(struct io_wq_work * work,void * data)3011 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3012 {
3013 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3014 struct io_task_cancel *cancel = data;
3015
3016 return io_match_task_safe(req, cancel->tctx, cancel->all);
3017 }
3018
io_cancel_defer_files(struct io_ring_ctx * ctx,struct io_uring_task * tctx,bool cancel_all)3019 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3020 struct io_uring_task *tctx,
3021 bool cancel_all)
3022 {
3023 struct io_defer_entry *de;
3024 LIST_HEAD(list);
3025
3026 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
3027 if (io_match_task_safe(de->req, tctx, cancel_all)) {
3028 list_cut_position(&list, &ctx->defer_list, &de->list);
3029 break;
3030 }
3031 }
3032 if (list_empty(&list))
3033 return false;
3034
3035 while (!list_empty(&list)) {
3036 de = list_first_entry(&list, struct io_defer_entry, list);
3037 list_del_init(&de->list);
3038 ctx->nr_drained -= io_linked_nr(de->req);
3039 io_req_task_queue_fail(de->req, -ECANCELED);
3040 kfree(de);
3041 }
3042 return true;
3043 }
3044
io_uring_try_cancel_iowq(struct io_ring_ctx * ctx)3045 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3046 {
3047 struct io_tctx_node *node;
3048 enum io_wq_cancel cret;
3049 bool ret = false;
3050
3051 mutex_lock(&ctx->uring_lock);
3052 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3053 struct io_uring_task *tctx = node->task->io_uring;
3054
3055 /*
3056 * io_wq will stay alive while we hold uring_lock, because it's
3057 * killed after ctx nodes, which requires to take the lock.
3058 */
3059 if (!tctx || !tctx->io_wq)
3060 continue;
3061 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3062 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3063 }
3064 mutex_unlock(&ctx->uring_lock);
3065
3066 return ret;
3067 }
3068
io_uring_try_cancel_requests(struct io_ring_ctx * ctx,struct io_uring_task * tctx,bool cancel_all,bool is_sqpoll_thread)3069 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3070 struct io_uring_task *tctx,
3071 bool cancel_all,
3072 bool is_sqpoll_thread)
3073 {
3074 struct io_task_cancel cancel = { .tctx = tctx, .all = cancel_all, };
3075 enum io_wq_cancel cret;
3076 bool ret = false;
3077
3078 /* set it so io_req_local_work_add() would wake us up */
3079 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3080 atomic_set(&ctx->cq_wait_nr, 1);
3081 smp_mb();
3082 }
3083
3084 /* failed during ring init, it couldn't have issued any requests */
3085 if (!ctx->rings)
3086 return false;
3087
3088 if (!tctx) {
3089 ret |= io_uring_try_cancel_iowq(ctx);
3090 } else if (tctx->io_wq) {
3091 /*
3092 * Cancels requests of all rings, not only @ctx, but
3093 * it's fine as the task is in exit/exec.
3094 */
3095 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3096 &cancel, true);
3097 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3098 }
3099
3100 /* SQPOLL thread does its own polling */
3101 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3102 is_sqpoll_thread) {
3103 while (!wq_list_empty(&ctx->iopoll_list)) {
3104 io_iopoll_try_reap_events(ctx);
3105 ret = true;
3106 cond_resched();
3107 }
3108 }
3109
3110 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3111 io_allowed_defer_tw_run(ctx))
3112 ret |= io_run_local_work(ctx, INT_MAX, INT_MAX) > 0;
3113 mutex_lock(&ctx->uring_lock);
3114 ret |= io_cancel_defer_files(ctx, tctx, cancel_all);
3115 ret |= io_poll_remove_all(ctx, tctx, cancel_all);
3116 ret |= io_waitid_remove_all(ctx, tctx, cancel_all);
3117 ret |= io_futex_remove_all(ctx, tctx, cancel_all);
3118 ret |= io_uring_try_cancel_uring_cmd(ctx, tctx, cancel_all);
3119 mutex_unlock(&ctx->uring_lock);
3120 ret |= io_kill_timeouts(ctx, tctx, cancel_all);
3121 if (tctx)
3122 ret |= io_run_task_work() > 0;
3123 else
3124 ret |= flush_delayed_work(&ctx->fallback_work);
3125 return ret;
3126 }
3127
tctx_inflight(struct io_uring_task * tctx,bool tracked)3128 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3129 {
3130 if (tracked)
3131 return atomic_read(&tctx->inflight_tracked);
3132 return percpu_counter_sum(&tctx->inflight);
3133 }
3134
3135 /*
3136 * Find any io_uring ctx that this task has registered or done IO on, and cancel
3137 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3138 */
io_uring_cancel_generic(bool cancel_all,struct io_sq_data * sqd)3139 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3140 {
3141 struct io_uring_task *tctx = current->io_uring;
3142 struct io_ring_ctx *ctx;
3143 struct io_tctx_node *node;
3144 unsigned long index;
3145 s64 inflight;
3146 DEFINE_WAIT(wait);
3147
3148 WARN_ON_ONCE(sqd && sqpoll_task_locked(sqd) != current);
3149
3150 if (!current->io_uring)
3151 return;
3152 if (tctx->io_wq)
3153 io_wq_exit_start(tctx->io_wq);
3154
3155 atomic_inc(&tctx->in_cancel);
3156 do {
3157 bool loop = false;
3158
3159 io_uring_drop_tctx_refs(current);
3160 if (!tctx_inflight(tctx, !cancel_all))
3161 break;
3162
3163 /* read completions before cancelations */
3164 inflight = tctx_inflight(tctx, false);
3165 if (!inflight)
3166 break;
3167
3168 if (!sqd) {
3169 xa_for_each(&tctx->xa, index, node) {
3170 /* sqpoll task will cancel all its requests */
3171 if (node->ctx->sq_data)
3172 continue;
3173 loop |= io_uring_try_cancel_requests(node->ctx,
3174 current->io_uring,
3175 cancel_all,
3176 false);
3177 }
3178 } else {
3179 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3180 loop |= io_uring_try_cancel_requests(ctx,
3181 current->io_uring,
3182 cancel_all,
3183 true);
3184 }
3185
3186 if (loop) {
3187 cond_resched();
3188 continue;
3189 }
3190
3191 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3192 io_run_task_work();
3193 io_uring_drop_tctx_refs(current);
3194 xa_for_each(&tctx->xa, index, node) {
3195 if (io_local_work_pending(node->ctx)) {
3196 WARN_ON_ONCE(node->ctx->submitter_task &&
3197 node->ctx->submitter_task != current);
3198 goto end_wait;
3199 }
3200 }
3201 /*
3202 * If we've seen completions, retry without waiting. This
3203 * avoids a race where a completion comes in before we did
3204 * prepare_to_wait().
3205 */
3206 if (inflight == tctx_inflight(tctx, !cancel_all))
3207 schedule();
3208 end_wait:
3209 finish_wait(&tctx->wait, &wait);
3210 } while (1);
3211
3212 io_uring_clean_tctx(tctx);
3213 if (cancel_all) {
3214 /*
3215 * We shouldn't run task_works after cancel, so just leave
3216 * ->in_cancel set for normal exit.
3217 */
3218 atomic_dec(&tctx->in_cancel);
3219 /* for exec all current's requests should be gone, kill tctx */
3220 __io_uring_free(current);
3221 }
3222 }
3223
__io_uring_cancel(bool cancel_all)3224 void __io_uring_cancel(bool cancel_all)
3225 {
3226 io_uring_unreg_ringfd();
3227 io_uring_cancel_generic(cancel_all, NULL);
3228 }
3229
io_get_ext_arg_reg(struct io_ring_ctx * ctx,const struct io_uring_getevents_arg __user * uarg)3230 static struct io_uring_reg_wait *io_get_ext_arg_reg(struct io_ring_ctx *ctx,
3231 const struct io_uring_getevents_arg __user *uarg)
3232 {
3233 unsigned long size = sizeof(struct io_uring_reg_wait);
3234 unsigned long offset = (uintptr_t)uarg;
3235 unsigned long end;
3236
3237 if (unlikely(offset % sizeof(long)))
3238 return ERR_PTR(-EFAULT);
3239
3240 /* also protects from NULL ->cq_wait_arg as the size would be 0 */
3241 if (unlikely(check_add_overflow(offset, size, &end) ||
3242 end > ctx->cq_wait_size))
3243 return ERR_PTR(-EFAULT);
3244
3245 offset = array_index_nospec(offset, ctx->cq_wait_size - size);
3246 return ctx->cq_wait_arg + offset;
3247 }
3248
io_validate_ext_arg(struct io_ring_ctx * ctx,unsigned flags,const void __user * argp,size_t argsz)3249 static int io_validate_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
3250 const void __user *argp, size_t argsz)
3251 {
3252 struct io_uring_getevents_arg arg;
3253
3254 if (!(flags & IORING_ENTER_EXT_ARG))
3255 return 0;
3256 if (flags & IORING_ENTER_EXT_ARG_REG)
3257 return -EINVAL;
3258 if (argsz != sizeof(arg))
3259 return -EINVAL;
3260 if (copy_from_user(&arg, argp, sizeof(arg)))
3261 return -EFAULT;
3262 return 0;
3263 }
3264
io_get_ext_arg(struct io_ring_ctx * ctx,unsigned flags,const void __user * argp,struct ext_arg * ext_arg)3265 static int io_get_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
3266 const void __user *argp, struct ext_arg *ext_arg)
3267 {
3268 const struct io_uring_getevents_arg __user *uarg = argp;
3269 struct io_uring_getevents_arg arg;
3270
3271 ext_arg->iowait = !(flags & IORING_ENTER_NO_IOWAIT);
3272
3273 /*
3274 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3275 * is just a pointer to the sigset_t.
3276 */
3277 if (!(flags & IORING_ENTER_EXT_ARG)) {
3278 ext_arg->sig = (const sigset_t __user *) argp;
3279 return 0;
3280 }
3281
3282 if (flags & IORING_ENTER_EXT_ARG_REG) {
3283 struct io_uring_reg_wait *w;
3284
3285 if (ext_arg->argsz != sizeof(struct io_uring_reg_wait))
3286 return -EINVAL;
3287 w = io_get_ext_arg_reg(ctx, argp);
3288 if (IS_ERR(w))
3289 return PTR_ERR(w);
3290
3291 if (w->flags & ~IORING_REG_WAIT_TS)
3292 return -EINVAL;
3293 ext_arg->min_time = READ_ONCE(w->min_wait_usec) * NSEC_PER_USEC;
3294 ext_arg->sig = u64_to_user_ptr(READ_ONCE(w->sigmask));
3295 ext_arg->argsz = READ_ONCE(w->sigmask_sz);
3296 if (w->flags & IORING_REG_WAIT_TS) {
3297 ext_arg->ts.tv_sec = READ_ONCE(w->ts.tv_sec);
3298 ext_arg->ts.tv_nsec = READ_ONCE(w->ts.tv_nsec);
3299 ext_arg->ts_set = true;
3300 }
3301 return 0;
3302 }
3303
3304 /*
3305 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3306 * timespec and sigset_t pointers if good.
3307 */
3308 if (ext_arg->argsz != sizeof(arg))
3309 return -EINVAL;
3310 #ifdef CONFIG_64BIT
3311 if (!user_access_begin(uarg, sizeof(*uarg)))
3312 return -EFAULT;
3313 unsafe_get_user(arg.sigmask, &uarg->sigmask, uaccess_end);
3314 unsafe_get_user(arg.sigmask_sz, &uarg->sigmask_sz, uaccess_end);
3315 unsafe_get_user(arg.min_wait_usec, &uarg->min_wait_usec, uaccess_end);
3316 unsafe_get_user(arg.ts, &uarg->ts, uaccess_end);
3317 user_access_end();
3318 #else
3319 if (copy_from_user(&arg, uarg, sizeof(arg)))
3320 return -EFAULT;
3321 #endif
3322 ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC;
3323 ext_arg->sig = u64_to_user_ptr(arg.sigmask);
3324 ext_arg->argsz = arg.sigmask_sz;
3325 if (arg.ts) {
3326 if (get_timespec64(&ext_arg->ts, u64_to_user_ptr(arg.ts)))
3327 return -EFAULT;
3328 ext_arg->ts_set = true;
3329 }
3330 return 0;
3331 #ifdef CONFIG_64BIT
3332 uaccess_end:
3333 user_access_end();
3334 return -EFAULT;
3335 #endif
3336 }
3337
SYSCALL_DEFINE6(io_uring_enter,unsigned int,fd,u32,to_submit,u32,min_complete,u32,flags,const void __user *,argp,size_t,argsz)3338 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3339 u32, min_complete, u32, flags, const void __user *, argp,
3340 size_t, argsz)
3341 {
3342 struct io_ring_ctx *ctx;
3343 struct file *file;
3344 long ret;
3345
3346 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3347 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3348 IORING_ENTER_REGISTERED_RING |
3349 IORING_ENTER_ABS_TIMER |
3350 IORING_ENTER_EXT_ARG_REG |
3351 IORING_ENTER_NO_IOWAIT)))
3352 return -EINVAL;
3353
3354 /*
3355 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3356 * need only dereference our task private array to find it.
3357 */
3358 if (flags & IORING_ENTER_REGISTERED_RING) {
3359 struct io_uring_task *tctx = current->io_uring;
3360
3361 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3362 return -EINVAL;
3363 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3364 file = tctx->registered_rings[fd];
3365 if (unlikely(!file))
3366 return -EBADF;
3367 } else {
3368 file = fget(fd);
3369 if (unlikely(!file))
3370 return -EBADF;
3371 ret = -EOPNOTSUPP;
3372 if (unlikely(!io_is_uring_fops(file)))
3373 goto out;
3374 }
3375
3376 ctx = file->private_data;
3377 ret = -EBADFD;
3378 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3379 goto out;
3380
3381 /*
3382 * For SQ polling, the thread will do all submissions and completions.
3383 * Just return the requested submit count, and wake the thread if
3384 * we were asked to.
3385 */
3386 ret = 0;
3387 if (ctx->flags & IORING_SETUP_SQPOLL) {
3388 if (unlikely(ctx->sq_data->thread == NULL)) {
3389 ret = -EOWNERDEAD;
3390 goto out;
3391 }
3392 if (flags & IORING_ENTER_SQ_WAKEUP)
3393 wake_up(&ctx->sq_data->wait);
3394 if (flags & IORING_ENTER_SQ_WAIT)
3395 io_sqpoll_wait_sq(ctx);
3396
3397 ret = to_submit;
3398 } else if (to_submit) {
3399 ret = io_uring_add_tctx_node(ctx);
3400 if (unlikely(ret))
3401 goto out;
3402
3403 mutex_lock(&ctx->uring_lock);
3404 ret = io_submit_sqes(ctx, to_submit);
3405 if (ret != to_submit) {
3406 mutex_unlock(&ctx->uring_lock);
3407 goto out;
3408 }
3409 if (flags & IORING_ENTER_GETEVENTS) {
3410 if (ctx->syscall_iopoll)
3411 goto iopoll_locked;
3412 /*
3413 * Ignore errors, we'll soon call io_cqring_wait() and
3414 * it should handle ownership problems if any.
3415 */
3416 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3417 (void)io_run_local_work_locked(ctx, min_complete);
3418 }
3419 mutex_unlock(&ctx->uring_lock);
3420 }
3421
3422 if (flags & IORING_ENTER_GETEVENTS) {
3423 int ret2;
3424
3425 if (ctx->syscall_iopoll) {
3426 /*
3427 * We disallow the app entering submit/complete with
3428 * polling, but we still need to lock the ring to
3429 * prevent racing with polled issue that got punted to
3430 * a workqueue.
3431 */
3432 mutex_lock(&ctx->uring_lock);
3433 iopoll_locked:
3434 ret2 = io_validate_ext_arg(ctx, flags, argp, argsz);
3435 if (likely(!ret2))
3436 ret2 = io_iopoll_check(ctx, min_complete);
3437 mutex_unlock(&ctx->uring_lock);
3438 } else {
3439 struct ext_arg ext_arg = { .argsz = argsz };
3440
3441 ret2 = io_get_ext_arg(ctx, flags, argp, &ext_arg);
3442 if (likely(!ret2))
3443 ret2 = io_cqring_wait(ctx, min_complete, flags,
3444 &ext_arg);
3445 }
3446
3447 if (!ret) {
3448 ret = ret2;
3449
3450 /*
3451 * EBADR indicates that one or more CQE were dropped.
3452 * Once the user has been informed we can clear the bit
3453 * as they are obviously ok with those drops.
3454 */
3455 if (unlikely(ret2 == -EBADR))
3456 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3457 &ctx->check_cq);
3458 }
3459 }
3460 out:
3461 if (!(flags & IORING_ENTER_REGISTERED_RING))
3462 fput(file);
3463 return ret;
3464 }
3465
3466 static const struct file_operations io_uring_fops = {
3467 .release = io_uring_release,
3468 .mmap = io_uring_mmap,
3469 .get_unmapped_area = io_uring_get_unmapped_area,
3470 #ifndef CONFIG_MMU
3471 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3472 #endif
3473 .poll = io_uring_poll,
3474 #ifdef CONFIG_PROC_FS
3475 .show_fdinfo = io_uring_show_fdinfo,
3476 #endif
3477 };
3478
io_is_uring_fops(struct file * file)3479 bool io_is_uring_fops(struct file *file)
3480 {
3481 return file->f_op == &io_uring_fops;
3482 }
3483
io_allocate_scq_urings(struct io_ring_ctx * ctx,struct io_uring_params * p)3484 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3485 struct io_uring_params *p)
3486 {
3487 struct io_uring_region_desc rd;
3488 struct io_rings *rings;
3489 size_t size, sq_array_offset;
3490 int ret;
3491
3492 /* make sure these are sane, as we already accounted them */
3493 ctx->sq_entries = p->sq_entries;
3494 ctx->cq_entries = p->cq_entries;
3495
3496 size = rings_size(ctx->flags, p->sq_entries, p->cq_entries,
3497 &sq_array_offset);
3498 if (size == SIZE_MAX)
3499 return -EOVERFLOW;
3500
3501 memset(&rd, 0, sizeof(rd));
3502 rd.size = PAGE_ALIGN(size);
3503 if (ctx->flags & IORING_SETUP_NO_MMAP) {
3504 rd.user_addr = p->cq_off.user_addr;
3505 rd.flags |= IORING_MEM_REGION_TYPE_USER;
3506 }
3507 ret = io_create_region(ctx, &ctx->ring_region, &rd, IORING_OFF_CQ_RING);
3508 if (ret)
3509 return ret;
3510 ctx->rings = rings = io_region_get_ptr(&ctx->ring_region);
3511
3512 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3513 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3514 rings->sq_ring_mask = p->sq_entries - 1;
3515 rings->cq_ring_mask = p->cq_entries - 1;
3516 rings->sq_ring_entries = p->sq_entries;
3517 rings->cq_ring_entries = p->cq_entries;
3518
3519 if (p->flags & IORING_SETUP_SQE128)
3520 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3521 else
3522 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3523 if (size == SIZE_MAX) {
3524 io_rings_free(ctx);
3525 return -EOVERFLOW;
3526 }
3527
3528 memset(&rd, 0, sizeof(rd));
3529 rd.size = PAGE_ALIGN(size);
3530 if (ctx->flags & IORING_SETUP_NO_MMAP) {
3531 rd.user_addr = p->sq_off.user_addr;
3532 rd.flags |= IORING_MEM_REGION_TYPE_USER;
3533 }
3534 ret = io_create_region(ctx, &ctx->sq_region, &rd, IORING_OFF_SQES);
3535 if (ret) {
3536 io_rings_free(ctx);
3537 return ret;
3538 }
3539 ctx->sq_sqes = io_region_get_ptr(&ctx->sq_region);
3540 return 0;
3541 }
3542
io_uring_install_fd(struct file * file)3543 static int io_uring_install_fd(struct file *file)
3544 {
3545 int fd;
3546
3547 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3548 if (fd < 0)
3549 return fd;
3550 fd_install(fd, file);
3551 return fd;
3552 }
3553
3554 /*
3555 * Allocate an anonymous fd, this is what constitutes the application
3556 * visible backing of an io_uring instance. The application mmaps this
3557 * fd to gain access to the SQ/CQ ring details.
3558 */
io_uring_get_file(struct io_ring_ctx * ctx)3559 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3560 {
3561 /* Create a new inode so that the LSM can block the creation. */
3562 return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
3563 O_RDWR | O_CLOEXEC, NULL);
3564 }
3565
io_uring_sanitise_params(struct io_uring_params * p)3566 static int io_uring_sanitise_params(struct io_uring_params *p)
3567 {
3568 unsigned flags = p->flags;
3569
3570 /* There is no way to mmap rings without a real fd */
3571 if ((flags & IORING_SETUP_REGISTERED_FD_ONLY) &&
3572 !(flags & IORING_SETUP_NO_MMAP))
3573 return -EINVAL;
3574
3575 if (flags & IORING_SETUP_SQPOLL) {
3576 /* IPI related flags don't make sense with SQPOLL */
3577 if (flags & (IORING_SETUP_COOP_TASKRUN |
3578 IORING_SETUP_TASKRUN_FLAG |
3579 IORING_SETUP_DEFER_TASKRUN))
3580 return -EINVAL;
3581 }
3582
3583 if (flags & IORING_SETUP_TASKRUN_FLAG) {
3584 if (!(flags & (IORING_SETUP_COOP_TASKRUN |
3585 IORING_SETUP_DEFER_TASKRUN)))
3586 return -EINVAL;
3587 }
3588
3589 /* HYBRID_IOPOLL only valid with IOPOLL */
3590 if ((flags & IORING_SETUP_HYBRID_IOPOLL) && !(flags & IORING_SETUP_IOPOLL))
3591 return -EINVAL;
3592
3593 /*
3594 * For DEFER_TASKRUN we require the completion task to be the same as
3595 * the submission task. This implies that there is only one submitter.
3596 */
3597 if ((flags & IORING_SETUP_DEFER_TASKRUN) &&
3598 !(flags & IORING_SETUP_SINGLE_ISSUER))
3599 return -EINVAL;
3600
3601 return 0;
3602 }
3603
io_uring_fill_params(unsigned entries,struct io_uring_params * p)3604 int io_uring_fill_params(unsigned entries, struct io_uring_params *p)
3605 {
3606 if (!entries)
3607 return -EINVAL;
3608 if (entries > IORING_MAX_ENTRIES) {
3609 if (!(p->flags & IORING_SETUP_CLAMP))
3610 return -EINVAL;
3611 entries = IORING_MAX_ENTRIES;
3612 }
3613
3614 /*
3615 * Use twice as many entries for the CQ ring. It's possible for the
3616 * application to drive a higher depth than the size of the SQ ring,
3617 * since the sqes are only used at submission time. This allows for
3618 * some flexibility in overcommitting a bit. If the application has
3619 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3620 * of CQ ring entries manually.
3621 */
3622 p->sq_entries = roundup_pow_of_two(entries);
3623 if (p->flags & IORING_SETUP_CQSIZE) {
3624 /*
3625 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3626 * to a power-of-two, if it isn't already. We do NOT impose
3627 * any cq vs sq ring sizing.
3628 */
3629 if (!p->cq_entries)
3630 return -EINVAL;
3631 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3632 if (!(p->flags & IORING_SETUP_CLAMP))
3633 return -EINVAL;
3634 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3635 }
3636 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3637 if (p->cq_entries < p->sq_entries)
3638 return -EINVAL;
3639 } else {
3640 p->cq_entries = 2 * p->sq_entries;
3641 }
3642
3643 p->sq_off.head = offsetof(struct io_rings, sq.head);
3644 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3645 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3646 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3647 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3648 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3649 p->sq_off.resv1 = 0;
3650 if (!(p->flags & IORING_SETUP_NO_MMAP))
3651 p->sq_off.user_addr = 0;
3652
3653 p->cq_off.head = offsetof(struct io_rings, cq.head);
3654 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3655 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3656 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3657 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3658 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3659 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3660 p->cq_off.resv1 = 0;
3661 if (!(p->flags & IORING_SETUP_NO_MMAP))
3662 p->cq_off.user_addr = 0;
3663
3664 return 0;
3665 }
3666
io_uring_create(unsigned entries,struct io_uring_params * p,struct io_uring_params __user * params)3667 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3668 struct io_uring_params __user *params)
3669 {
3670 struct io_ring_ctx *ctx;
3671 struct io_uring_task *tctx;
3672 struct file *file;
3673 int ret;
3674
3675 ret = io_uring_sanitise_params(p);
3676 if (ret)
3677 return ret;
3678
3679 ret = io_uring_fill_params(entries, p);
3680 if (unlikely(ret))
3681 return ret;
3682
3683 ctx = io_ring_ctx_alloc(p);
3684 if (!ctx)
3685 return -ENOMEM;
3686
3687 ctx->clockid = CLOCK_MONOTONIC;
3688 ctx->clock_offset = 0;
3689
3690 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3691 static_branch_inc(&io_key_has_sqarray);
3692
3693 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3694 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3695 !(ctx->flags & IORING_SETUP_SQPOLL))
3696 ctx->task_complete = true;
3697
3698 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3699 ctx->lockless_cq = true;
3700
3701 /*
3702 * lazy poll_wq activation relies on ->task_complete for synchronisation
3703 * purposes, see io_activate_pollwq()
3704 */
3705 if (!ctx->task_complete)
3706 ctx->poll_activated = true;
3707
3708 /*
3709 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3710 * space applications don't need to do io completion events
3711 * polling again, they can rely on io_sq_thread to do polling
3712 * work, which can reduce cpu usage and uring_lock contention.
3713 */
3714 if (ctx->flags & IORING_SETUP_IOPOLL &&
3715 !(ctx->flags & IORING_SETUP_SQPOLL))
3716 ctx->syscall_iopoll = 1;
3717
3718 ctx->compat = in_compat_syscall();
3719 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3720 ctx->user = get_uid(current_user());
3721
3722 /*
3723 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3724 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3725 */
3726 if (ctx->flags & (IORING_SETUP_SQPOLL|IORING_SETUP_COOP_TASKRUN))
3727 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3728 else
3729 ctx->notify_method = TWA_SIGNAL;
3730
3731 /*
3732 * This is just grabbed for accounting purposes. When a process exits,
3733 * the mm is exited and dropped before the files, hence we need to hang
3734 * on to this mm purely for the purposes of being able to unaccount
3735 * memory (locked/pinned vm). It's not used for anything else.
3736 */
3737 mmgrab(current->mm);
3738 ctx->mm_account = current->mm;
3739
3740 ret = io_allocate_scq_urings(ctx, p);
3741 if (ret)
3742 goto err;
3743
3744 if (!(p->flags & IORING_SETUP_NO_SQARRAY))
3745 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3746
3747 ret = io_sq_offload_create(ctx, p);
3748 if (ret)
3749 goto err;
3750
3751 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3752 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
3753 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
3754 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
3755 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
3756 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
3757 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING |
3758 IORING_FEAT_RECVSEND_BUNDLE | IORING_FEAT_MIN_TIMEOUT |
3759 IORING_FEAT_RW_ATTR | IORING_FEAT_NO_IOWAIT;
3760
3761 if (copy_to_user(params, p, sizeof(*p))) {
3762 ret = -EFAULT;
3763 goto err;
3764 }
3765
3766 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
3767 && !(ctx->flags & IORING_SETUP_R_DISABLED))
3768 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
3769
3770 file = io_uring_get_file(ctx);
3771 if (IS_ERR(file)) {
3772 ret = PTR_ERR(file);
3773 goto err;
3774 }
3775
3776 ret = __io_uring_add_tctx_node(ctx);
3777 if (ret)
3778 goto err_fput;
3779 tctx = current->io_uring;
3780
3781 /*
3782 * Install ring fd as the very last thing, so we don't risk someone
3783 * having closed it before we finish setup
3784 */
3785 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3786 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
3787 else
3788 ret = io_uring_install_fd(file);
3789 if (ret < 0)
3790 goto err_fput;
3791
3792 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3793 return ret;
3794 err:
3795 io_ring_ctx_wait_and_kill(ctx);
3796 return ret;
3797 err_fput:
3798 fput(file);
3799 return ret;
3800 }
3801
3802 /*
3803 * Sets up an aio uring context, and returns the fd. Applications asks for a
3804 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3805 * params structure passed in.
3806 */
io_uring_setup(u32 entries,struct io_uring_params __user * params)3807 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3808 {
3809 struct io_uring_params p;
3810 int i;
3811
3812 if (copy_from_user(&p, params, sizeof(p)))
3813 return -EFAULT;
3814 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3815 if (p.resv[i])
3816 return -EINVAL;
3817 }
3818
3819 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3820 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
3821 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
3822 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
3823 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
3824 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
3825 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
3826 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
3827 IORING_SETUP_NO_SQARRAY | IORING_SETUP_HYBRID_IOPOLL))
3828 return -EINVAL;
3829
3830 return io_uring_create(entries, &p, params);
3831 }
3832
io_uring_allowed(void)3833 static inline int io_uring_allowed(void)
3834 {
3835 int disabled = READ_ONCE(sysctl_io_uring_disabled);
3836 kgid_t io_uring_group;
3837
3838 if (disabled == 2)
3839 return -EPERM;
3840
3841 if (disabled == 0 || capable(CAP_SYS_ADMIN))
3842 goto allowed_lsm;
3843
3844 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
3845 if (!gid_valid(io_uring_group))
3846 return -EPERM;
3847
3848 if (!in_group_p(io_uring_group))
3849 return -EPERM;
3850
3851 allowed_lsm:
3852 return security_uring_allowed();
3853 }
3854
SYSCALL_DEFINE2(io_uring_setup,u32,entries,struct io_uring_params __user *,params)3855 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3856 struct io_uring_params __user *, params)
3857 {
3858 int ret;
3859
3860 ret = io_uring_allowed();
3861 if (ret)
3862 return ret;
3863
3864 return io_uring_setup(entries, params);
3865 }
3866
io_uring_init(void)3867 static int __init io_uring_init(void)
3868 {
3869 struct kmem_cache_args kmem_args = {
3870 .useroffset = offsetof(struct io_kiocb, cmd.data),
3871 .usersize = sizeof_field(struct io_kiocb, cmd.data),
3872 .freeptr_offset = offsetof(struct io_kiocb, work),
3873 .use_freeptr_offset = true,
3874 };
3875
3876 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
3877 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
3878 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
3879 } while (0)
3880
3881 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
3882 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
3883 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
3884 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
3885 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
3886 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
3887 BUILD_BUG_SQE_ELEM(1, __u8, flags);
3888 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
3889 BUILD_BUG_SQE_ELEM(4, __s32, fd);
3890 BUILD_BUG_SQE_ELEM(8, __u64, off);
3891 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
3892 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
3893 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
3894 BUILD_BUG_SQE_ELEM(16, __u64, addr);
3895 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
3896 BUILD_BUG_SQE_ELEM(24, __u32, len);
3897 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
3898 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
3899 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
3900 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
3901 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
3902 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
3903 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
3904 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
3905 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
3906 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
3907 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
3908 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
3909 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
3910 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
3911 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
3912 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
3913 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
3914 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
3915 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
3916 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
3917 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
3918 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
3919 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
3920 BUILD_BUG_SQE_ELEM(42, __u16, personality);
3921 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
3922 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
3923 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
3924 BUILD_BUG_SQE_ELEM(44, __u8, write_stream);
3925 BUILD_BUG_SQE_ELEM(45, __u8, __pad4[0]);
3926 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
3927 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
3928 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
3929 BUILD_BUG_SQE_ELEM(48, __u64, attr_ptr);
3930 BUILD_BUG_SQE_ELEM(56, __u64, attr_type_mask);
3931 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
3932
3933 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3934 sizeof(struct io_uring_rsrc_update));
3935 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3936 sizeof(struct io_uring_rsrc_update2));
3937
3938 /* ->buf_index is u16 */
3939 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3940 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3941 offsetof(struct io_uring_buf_ring, tail));
3942
3943 /* should fit into one byte */
3944 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
3945 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
3946 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
3947
3948 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
3949
3950 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
3951
3952 /* top 8bits are for internal use */
3953 BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
3954
3955 io_uring_optable_init();
3956
3957 /* imu->dir is u8 */
3958 BUILD_BUG_ON((IO_IMU_DEST | IO_IMU_SOURCE) > U8_MAX);
3959
3960 /*
3961 * Allow user copy in the per-command field, which starts after the
3962 * file in io_kiocb and until the opcode field. The openat2 handling
3963 * requires copying in user memory into the io_kiocb object in that
3964 * range, and HARDENED_USERCOPY will complain if we haven't
3965 * correctly annotated this range.
3966 */
3967 req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
3968 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
3969 SLAB_TYPESAFE_BY_RCU);
3970
3971 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
3972 BUG_ON(!iou_wq);
3973
3974 #ifdef CONFIG_SYSCTL
3975 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
3976 #endif
3977
3978 return 0;
3979 };
3980 __initcall(io_uring_init);
3981