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/fdtable.h>
55 #include <linux/mm.h>
56 #include <linux/mman.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/bvec.h>
60 #include <linux/net.h>
61 #include <net/sock.h>
62 #include <net/af_unix.h>
63 #include <linux/anon_inodes.h>
64 #include <linux/sched/mm.h>
65 #include <linux/uaccess.h>
66 #include <linux/nospec.h>
67 #include <linux/highmem.h>
68 #include <linux/fsnotify.h>
69 #include <linux/fadvise.h>
70 #include <linux/task_work.h>
71 #include <linux/io_uring.h>
72 #include <linux/audit.h>
73 #include <linux/security.h>
74 #include <asm/shmparam.h>
75
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
78
79 #include <uapi/linux/io_uring.h>
80
81 #include "io-wq.h"
82
83 #include "io_uring.h"
84 #include "opdef.h"
85 #include "refs.h"
86 #include "tctx.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
95 #include "timeout.h"
96 #include "poll.h"
97 #include "rw.h"
98 #include "alloc_cache.h"
99
100 #define IORING_MAX_ENTRIES 32768
101 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
102
103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
104 IORING_REGISTER_LAST + IORING_OP_LAST)
105
106 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
108
109 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
110 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
111
112 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
113 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
114 REQ_F_ASYNC_DATA)
115
116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
117 IO_REQ_CLEAN_FLAGS)
118
119 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
120
121 #define IO_COMPL_BATCH 32
122 #define IO_REQ_ALLOC_BATCH 8
123
124 enum {
125 IO_CHECK_CQ_OVERFLOW_BIT,
126 IO_CHECK_CQ_DROPPED_BIT,
127 };
128
129 enum {
130 IO_EVENTFD_OP_SIGNAL_BIT,
131 IO_EVENTFD_OP_FREE_BIT,
132 };
133
134 struct io_defer_entry {
135 struct list_head list;
136 struct io_kiocb *req;
137 u32 seq;
138 };
139
140 /* requests with any of those set should undergo io_disarm_next() */
141 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
142 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
143
144 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
145 struct task_struct *task,
146 bool cancel_all);
147
148 static void io_queue_sqe(struct io_kiocb *req);
149
150 struct kmem_cache *req_cachep;
151 static struct workqueue_struct *iou_wq __ro_after_init;
152
153 static int __read_mostly sysctl_io_uring_disabled;
154 static int __read_mostly sysctl_io_uring_group = -1;
155
156 #ifdef CONFIG_SYSCTL
157 static struct ctl_table kernel_io_uring_disabled_table[] = {
158 {
159 .procname = "io_uring_disabled",
160 .data = &sysctl_io_uring_disabled,
161 .maxlen = sizeof(sysctl_io_uring_disabled),
162 .mode = 0644,
163 .proc_handler = proc_dointvec_minmax,
164 .extra1 = SYSCTL_ZERO,
165 .extra2 = SYSCTL_TWO,
166 },
167 {
168 .procname = "io_uring_group",
169 .data = &sysctl_io_uring_group,
170 .maxlen = sizeof(gid_t),
171 .mode = 0644,
172 .proc_handler = proc_dointvec,
173 },
174 {},
175 };
176 #endif
177
io_submit_flush_completions(struct io_ring_ctx * ctx)178 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
179 {
180 if (!wq_list_empty(&ctx->submit_state.compl_reqs) ||
181 ctx->submit_state.cqes_count)
182 __io_submit_flush_completions(ctx);
183 }
184
__io_cqring_events(struct io_ring_ctx * ctx)185 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
186 {
187 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
188 }
189
__io_cqring_events_user(struct io_ring_ctx * ctx)190 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
191 {
192 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
193 }
194
io_match_linked(struct io_kiocb * head)195 static bool io_match_linked(struct io_kiocb *head)
196 {
197 struct io_kiocb *req;
198
199 io_for_each_link(req, head) {
200 if (req->flags & REQ_F_INFLIGHT)
201 return true;
202 }
203 return false;
204 }
205
206 /*
207 * As io_match_task() but protected against racing with linked timeouts.
208 * User must not hold timeout_lock.
209 */
io_match_task_safe(struct io_kiocb * head,struct task_struct * task,bool cancel_all)210 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
211 bool cancel_all)
212 {
213 bool matched;
214
215 if (task && head->task != task)
216 return false;
217 if (cancel_all)
218 return true;
219
220 if (head->flags & REQ_F_LINK_TIMEOUT) {
221 struct io_ring_ctx *ctx = head->ctx;
222
223 /* protect against races with linked timeouts */
224 spin_lock_irq(&ctx->timeout_lock);
225 matched = io_match_linked(head);
226 spin_unlock_irq(&ctx->timeout_lock);
227 } else {
228 matched = io_match_linked(head);
229 }
230 return matched;
231 }
232
req_fail_link_node(struct io_kiocb * req,int res)233 static inline void req_fail_link_node(struct io_kiocb *req, int res)
234 {
235 req_set_fail(req);
236 io_req_set_res(req, res, 0);
237 }
238
io_req_add_to_cache(struct io_kiocb * req,struct io_ring_ctx * ctx)239 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
240 {
241 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
242 }
243
io_ring_ctx_ref_free(struct percpu_ref * ref)244 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
245 {
246 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
247
248 complete(&ctx->ref_comp);
249 }
250
io_fallback_req_func(struct work_struct * work)251 static __cold void io_fallback_req_func(struct work_struct *work)
252 {
253 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
254 fallback_work.work);
255 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
256 struct io_kiocb *req, *tmp;
257 struct io_tw_state ts = { .locked = true, };
258
259 percpu_ref_get(&ctx->refs);
260 mutex_lock(&ctx->uring_lock);
261 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
262 req->io_task_work.func(req, &ts);
263 if (WARN_ON_ONCE(!ts.locked))
264 return;
265 io_submit_flush_completions(ctx);
266 mutex_unlock(&ctx->uring_lock);
267 percpu_ref_put(&ctx->refs);
268 }
269
io_alloc_hash_table(struct io_hash_table * table,unsigned bits)270 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
271 {
272 unsigned hash_buckets = 1U << bits;
273 size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
274
275 table->hbs = kmalloc(hash_size, GFP_KERNEL);
276 if (!table->hbs)
277 return -ENOMEM;
278
279 table->hash_bits = bits;
280 init_hash_table(table, hash_buckets);
281 return 0;
282 }
283
io_ring_ctx_alloc(struct io_uring_params * p)284 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
285 {
286 struct io_ring_ctx *ctx;
287 int hash_bits;
288
289 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
290 if (!ctx)
291 return NULL;
292
293 xa_init(&ctx->io_bl_xa);
294
295 /*
296 * Use 5 bits less than the max cq entries, that should give us around
297 * 32 entries per hash list if totally full and uniformly spread, but
298 * don't keep too many buckets to not overconsume memory.
299 */
300 hash_bits = ilog2(p->cq_entries) - 5;
301 hash_bits = clamp(hash_bits, 1, 8);
302 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
303 goto err;
304 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
305 goto err;
306 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
307 0, GFP_KERNEL))
308 goto err;
309
310 ctx->flags = p->flags;
311 init_waitqueue_head(&ctx->sqo_sq_wait);
312 INIT_LIST_HEAD(&ctx->sqd_list);
313 INIT_LIST_HEAD(&ctx->cq_overflow_list);
314 INIT_LIST_HEAD(&ctx->io_buffers_cache);
315 INIT_HLIST_HEAD(&ctx->io_buf_list);
316 io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
317 sizeof(struct io_rsrc_node));
318 io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX,
319 sizeof(struct async_poll));
320 io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
321 sizeof(struct io_async_msghdr));
322 init_completion(&ctx->ref_comp);
323 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
324 mutex_init(&ctx->uring_lock);
325 init_waitqueue_head(&ctx->cq_wait);
326 init_waitqueue_head(&ctx->poll_wq);
327 init_waitqueue_head(&ctx->rsrc_quiesce_wq);
328 spin_lock_init(&ctx->completion_lock);
329 spin_lock_init(&ctx->timeout_lock);
330 INIT_WQ_LIST(&ctx->iopoll_list);
331 INIT_LIST_HEAD(&ctx->io_buffers_pages);
332 INIT_LIST_HEAD(&ctx->io_buffers_comp);
333 INIT_LIST_HEAD(&ctx->defer_list);
334 INIT_LIST_HEAD(&ctx->timeout_list);
335 INIT_LIST_HEAD(&ctx->ltimeout_list);
336 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
337 init_llist_head(&ctx->work_llist);
338 INIT_LIST_HEAD(&ctx->tctx_list);
339 ctx->submit_state.free_list.next = NULL;
340 INIT_WQ_LIST(&ctx->locked_free_list);
341 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
342 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
343 return ctx;
344 err:
345 kfree(ctx->cancel_table.hbs);
346 kfree(ctx->cancel_table_locked.hbs);
347 xa_destroy(&ctx->io_bl_xa);
348 kfree(ctx);
349 return NULL;
350 }
351
io_account_cq_overflow(struct io_ring_ctx * ctx)352 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
353 {
354 struct io_rings *r = ctx->rings;
355
356 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
357 ctx->cq_extra--;
358 }
359
req_need_defer(struct io_kiocb * req,u32 seq)360 static bool req_need_defer(struct io_kiocb *req, u32 seq)
361 {
362 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
363 struct io_ring_ctx *ctx = req->ctx;
364
365 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
366 }
367
368 return false;
369 }
370
io_clean_op(struct io_kiocb * req)371 static void io_clean_op(struct io_kiocb *req)
372 {
373 if (req->flags & REQ_F_BUFFER_SELECTED) {
374 spin_lock(&req->ctx->completion_lock);
375 io_put_kbuf_comp(req);
376 spin_unlock(&req->ctx->completion_lock);
377 }
378
379 if (req->flags & REQ_F_NEED_CLEANUP) {
380 const struct io_cold_def *def = &io_cold_defs[req->opcode];
381
382 if (def->cleanup)
383 def->cleanup(req);
384 }
385 if ((req->flags & REQ_F_POLLED) && req->apoll) {
386 kfree(req->apoll->double_poll);
387 kfree(req->apoll);
388 req->apoll = NULL;
389 }
390 if (req->flags & REQ_F_INFLIGHT) {
391 struct io_uring_task *tctx = req->task->io_uring;
392
393 atomic_dec(&tctx->inflight_tracked);
394 }
395 if (req->flags & REQ_F_CREDS)
396 put_cred(req->creds);
397 if (req->flags & REQ_F_ASYNC_DATA) {
398 kfree(req->async_data);
399 req->async_data = NULL;
400 }
401 req->flags &= ~IO_REQ_CLEAN_FLAGS;
402 }
403
io_req_track_inflight(struct io_kiocb * req)404 static inline void io_req_track_inflight(struct io_kiocb *req)
405 {
406 if (!(req->flags & REQ_F_INFLIGHT)) {
407 req->flags |= REQ_F_INFLIGHT;
408 atomic_inc(&req->task->io_uring->inflight_tracked);
409 }
410 }
411
__io_prep_linked_timeout(struct io_kiocb * req)412 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
413 {
414 if (WARN_ON_ONCE(!req->link))
415 return NULL;
416
417 req->flags &= ~REQ_F_ARM_LTIMEOUT;
418 req->flags |= REQ_F_LINK_TIMEOUT;
419
420 /* linked timeouts should have two refs once prep'ed */
421 io_req_set_refcount(req);
422 __io_req_set_refcount(req->link, 2);
423 return req->link;
424 }
425
io_prep_linked_timeout(struct io_kiocb * req)426 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
427 {
428 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
429 return NULL;
430 return __io_prep_linked_timeout(req);
431 }
432
__io_arm_ltimeout(struct io_kiocb * req)433 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
434 {
435 io_queue_linked_timeout(__io_prep_linked_timeout(req));
436 }
437
io_arm_ltimeout(struct io_kiocb * req)438 static inline void io_arm_ltimeout(struct io_kiocb *req)
439 {
440 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
441 __io_arm_ltimeout(req);
442 }
443
io_prep_async_work(struct io_kiocb * req)444 static void io_prep_async_work(struct io_kiocb *req)
445 {
446 const struct io_issue_def *def = &io_issue_defs[req->opcode];
447 struct io_ring_ctx *ctx = req->ctx;
448
449 if (!(req->flags & REQ_F_CREDS)) {
450 req->flags |= REQ_F_CREDS;
451 req->creds = get_current_cred();
452 }
453
454 req->work.list.next = NULL;
455 req->work.flags = 0;
456 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
457 if (req->flags & REQ_F_FORCE_ASYNC)
458 req->work.flags |= IO_WQ_WORK_CONCURRENT;
459
460 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
461 req->flags |= io_file_get_flags(req->file);
462
463 if (req->file && (req->flags & REQ_F_ISREG)) {
464 bool should_hash = def->hash_reg_file;
465
466 /* don't serialize this request if the fs doesn't need it */
467 if (should_hash && (req->file->f_flags & O_DIRECT) &&
468 (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE))
469 should_hash = false;
470 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
471 io_wq_hash_work(&req->work, file_inode(req->file));
472 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
473 if (def->unbound_nonreg_file)
474 req->work.flags |= IO_WQ_WORK_UNBOUND;
475 }
476 }
477
io_prep_async_link(struct io_kiocb * req)478 static void io_prep_async_link(struct io_kiocb *req)
479 {
480 struct io_kiocb *cur;
481
482 if (req->flags & REQ_F_LINK_TIMEOUT) {
483 struct io_ring_ctx *ctx = req->ctx;
484
485 spin_lock_irq(&ctx->timeout_lock);
486 io_for_each_link(cur, req)
487 io_prep_async_work(cur);
488 spin_unlock_irq(&ctx->timeout_lock);
489 } else {
490 io_for_each_link(cur, req)
491 io_prep_async_work(cur);
492 }
493 }
494
io_queue_iowq(struct io_kiocb * req,struct io_tw_state * ts_dont_use)495 void io_queue_iowq(struct io_kiocb *req, struct io_tw_state *ts_dont_use)
496 {
497 struct io_kiocb *link = io_prep_linked_timeout(req);
498 struct io_uring_task *tctx = req->task->io_uring;
499
500 BUG_ON(!tctx);
501 BUG_ON(!tctx->io_wq);
502
503 /* init ->work of the whole link before punting */
504 io_prep_async_link(req);
505
506 /*
507 * Not expected to happen, but if we do have a bug where this _can_
508 * happen, catch it here and ensure the request is marked as
509 * canceled. That will make io-wq go through the usual work cancel
510 * procedure rather than attempt to run this request (or create a new
511 * worker for it).
512 */
513 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
514 req->work.flags |= IO_WQ_WORK_CANCEL;
515
516 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
517 io_wq_enqueue(tctx->io_wq, &req->work);
518 if (link)
519 io_queue_linked_timeout(link);
520 }
521
io_queue_deferred(struct io_ring_ctx * ctx)522 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
523 {
524 while (!list_empty(&ctx->defer_list)) {
525 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
526 struct io_defer_entry, list);
527
528 if (req_need_defer(de->req, de->seq))
529 break;
530 list_del_init(&de->list);
531 io_req_task_queue(de->req);
532 kfree(de);
533 }
534 }
535
536
io_eventfd_ops(struct rcu_head * rcu)537 static void io_eventfd_ops(struct rcu_head *rcu)
538 {
539 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
540 int ops = atomic_xchg(&ev_fd->ops, 0);
541
542 if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT))
543 eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE);
544
545 /* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback
546 * ordering in a race but if references are 0 we know we have to free
547 * it regardless.
548 */
549 if (atomic_dec_and_test(&ev_fd->refs)) {
550 eventfd_ctx_put(ev_fd->cq_ev_fd);
551 kfree(ev_fd);
552 }
553 }
554
io_eventfd_signal(struct io_ring_ctx * ctx)555 static void io_eventfd_signal(struct io_ring_ctx *ctx)
556 {
557 struct io_ev_fd *ev_fd = NULL;
558
559 rcu_read_lock();
560 /*
561 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
562 * and eventfd_signal
563 */
564 ev_fd = rcu_dereference(ctx->io_ev_fd);
565
566 /*
567 * Check again if ev_fd exists incase an io_eventfd_unregister call
568 * completed between the NULL check of ctx->io_ev_fd at the start of
569 * the function and rcu_read_lock.
570 */
571 if (unlikely(!ev_fd))
572 goto out;
573 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
574 goto out;
575 if (ev_fd->eventfd_async && !io_wq_current_is_worker())
576 goto out;
577
578 if (likely(eventfd_signal_allowed())) {
579 eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE);
580 } else {
581 atomic_inc(&ev_fd->refs);
582 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops))
583 call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops);
584 else
585 atomic_dec(&ev_fd->refs);
586 }
587
588 out:
589 rcu_read_unlock();
590 }
591
io_eventfd_flush_signal(struct io_ring_ctx * ctx)592 static void io_eventfd_flush_signal(struct io_ring_ctx *ctx)
593 {
594 bool skip;
595
596 spin_lock(&ctx->completion_lock);
597
598 /*
599 * Eventfd should only get triggered when at least one event has been
600 * posted. Some applications rely on the eventfd notification count
601 * only changing IFF a new CQE has been added to the CQ ring. There's
602 * no depedency on 1:1 relationship between how many times this
603 * function is called (and hence the eventfd count) and number of CQEs
604 * posted to the CQ ring.
605 */
606 skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail;
607 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
608 spin_unlock(&ctx->completion_lock);
609 if (skip)
610 return;
611
612 io_eventfd_signal(ctx);
613 }
614
__io_commit_cqring_flush(struct io_ring_ctx * ctx)615 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
616 {
617 if (ctx->poll_activated)
618 io_poll_wq_wake(ctx);
619 if (ctx->off_timeout_used)
620 io_flush_timeouts(ctx);
621 if (ctx->drain_active) {
622 spin_lock(&ctx->completion_lock);
623 io_queue_deferred(ctx);
624 spin_unlock(&ctx->completion_lock);
625 }
626 if (ctx->has_evfd)
627 io_eventfd_flush_signal(ctx);
628 }
629
__io_cq_lock(struct io_ring_ctx * ctx)630 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
631 {
632 if (!ctx->lockless_cq)
633 spin_lock(&ctx->completion_lock);
634 }
635
io_cq_lock(struct io_ring_ctx * ctx)636 static inline void io_cq_lock(struct io_ring_ctx *ctx)
637 __acquires(ctx->completion_lock)
638 {
639 spin_lock(&ctx->completion_lock);
640 }
641
__io_cq_unlock_post(struct io_ring_ctx * ctx)642 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
643 {
644 io_commit_cqring(ctx);
645 if (!ctx->task_complete) {
646 if (!ctx->lockless_cq)
647 spin_unlock(&ctx->completion_lock);
648 /* IOPOLL rings only need to wake up if it's also SQPOLL */
649 if (!ctx->syscall_iopoll)
650 io_cqring_wake(ctx);
651 }
652 io_commit_cqring_flush(ctx);
653 }
654
io_cq_unlock_post(struct io_ring_ctx * ctx)655 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
656 __releases(ctx->completion_lock)
657 {
658 io_commit_cqring(ctx);
659 spin_unlock(&ctx->completion_lock);
660 io_cqring_wake(ctx);
661 io_commit_cqring_flush(ctx);
662 }
663
664 /* Returns true if there are no backlogged entries after the flush */
io_cqring_overflow_kill(struct io_ring_ctx * ctx)665 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
666 {
667 struct io_overflow_cqe *ocqe;
668 LIST_HEAD(list);
669
670 lockdep_assert_held(&ctx->uring_lock);
671
672 spin_lock(&ctx->completion_lock);
673 list_splice_init(&ctx->cq_overflow_list, &list);
674 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
675 spin_unlock(&ctx->completion_lock);
676
677 while (!list_empty(&list)) {
678 ocqe = list_first_entry(&list, struct io_overflow_cqe, list);
679 list_del(&ocqe->list);
680 kfree(ocqe);
681 }
682 }
683
__io_cqring_overflow_flush(struct io_ring_ctx * ctx)684 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx)
685 {
686 size_t cqe_size = sizeof(struct io_uring_cqe);
687
688 lockdep_assert_held(&ctx->uring_lock);
689
690 if (__io_cqring_events(ctx) == ctx->cq_entries)
691 return;
692
693 if (ctx->flags & IORING_SETUP_CQE32)
694 cqe_size <<= 1;
695
696 io_cq_lock(ctx);
697 while (!list_empty(&ctx->cq_overflow_list)) {
698 struct io_uring_cqe *cqe;
699 struct io_overflow_cqe *ocqe;
700
701 if (!io_get_cqe_overflow(ctx, &cqe, true))
702 break;
703 ocqe = list_first_entry(&ctx->cq_overflow_list,
704 struct io_overflow_cqe, list);
705 memcpy(cqe, &ocqe->cqe, cqe_size);
706 list_del(&ocqe->list);
707 kfree(ocqe);
708
709 /*
710 * For silly syzbot cases that deliberately overflow by huge
711 * amounts, check if we need to resched and drop and
712 * reacquire the locks if so. Nothing real would ever hit this.
713 * Ideally we'd have a non-posting unlock for this, but hard
714 * to care for a non-real case.
715 */
716 if (need_resched()) {
717 io_cq_unlock_post(ctx);
718 mutex_unlock(&ctx->uring_lock);
719 cond_resched();
720 mutex_lock(&ctx->uring_lock);
721 io_cq_lock(ctx);
722 }
723 }
724
725 if (list_empty(&ctx->cq_overflow_list)) {
726 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
727 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
728 }
729 io_cq_unlock_post(ctx);
730 }
731
io_cqring_do_overflow_flush(struct io_ring_ctx * ctx)732 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
733 {
734 mutex_lock(&ctx->uring_lock);
735 __io_cqring_overflow_flush(ctx);
736 mutex_unlock(&ctx->uring_lock);
737 }
738
io_cqring_overflow_flush(struct io_ring_ctx * ctx)739 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx)
740 {
741 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
742 io_cqring_do_overflow_flush(ctx);
743 }
744
745 /* can be called by any task */
io_put_task_remote(struct task_struct * task)746 static void io_put_task_remote(struct task_struct *task)
747 {
748 struct io_uring_task *tctx = task->io_uring;
749
750 percpu_counter_sub(&tctx->inflight, 1);
751 if (unlikely(atomic_read(&tctx->in_cancel)))
752 wake_up(&tctx->wait);
753 put_task_struct(task);
754 }
755
756 /* used by a task to put its own references */
io_put_task_local(struct task_struct * task)757 static void io_put_task_local(struct task_struct *task)
758 {
759 task->io_uring->cached_refs++;
760 }
761
762 /* must to be called somewhat shortly after putting a request */
io_put_task(struct task_struct * task)763 static inline void io_put_task(struct task_struct *task)
764 {
765 if (likely(task == current))
766 io_put_task_local(task);
767 else
768 io_put_task_remote(task);
769 }
770
io_task_refs_refill(struct io_uring_task * tctx)771 void io_task_refs_refill(struct io_uring_task *tctx)
772 {
773 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
774
775 percpu_counter_add(&tctx->inflight, refill);
776 refcount_add(refill, ¤t->usage);
777 tctx->cached_refs += refill;
778 }
779
io_uring_drop_tctx_refs(struct task_struct * task)780 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
781 {
782 struct io_uring_task *tctx = task->io_uring;
783 unsigned int refs = tctx->cached_refs;
784
785 if (refs) {
786 tctx->cached_refs = 0;
787 percpu_counter_sub(&tctx->inflight, refs);
788 put_task_struct_many(task, refs);
789 }
790 }
791
io_cqring_event_overflow(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,u64 extra1,u64 extra2)792 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
793 s32 res, u32 cflags, u64 extra1, u64 extra2)
794 {
795 struct io_overflow_cqe *ocqe;
796 size_t ocq_size = sizeof(struct io_overflow_cqe);
797 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
798
799 lockdep_assert_held(&ctx->completion_lock);
800
801 if (is_cqe32)
802 ocq_size += sizeof(struct io_uring_cqe);
803
804 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
805 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
806 if (!ocqe) {
807 /*
808 * If we're in ring overflow flush mode, or in task cancel mode,
809 * or cannot allocate an overflow entry, then we need to drop it
810 * on the floor.
811 */
812 io_account_cq_overflow(ctx);
813 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
814 return false;
815 }
816 if (list_empty(&ctx->cq_overflow_list)) {
817 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
818 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
819
820 }
821 ocqe->cqe.user_data = user_data;
822 ocqe->cqe.res = res;
823 ocqe->cqe.flags = cflags;
824 if (is_cqe32) {
825 ocqe->cqe.big_cqe[0] = extra1;
826 ocqe->cqe.big_cqe[1] = extra2;
827 }
828 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
829 return true;
830 }
831
io_req_cqe_overflow(struct io_kiocb * req)832 void io_req_cqe_overflow(struct io_kiocb *req)
833 {
834 io_cqring_event_overflow(req->ctx, req->cqe.user_data,
835 req->cqe.res, req->cqe.flags,
836 req->big_cqe.extra1, req->big_cqe.extra2);
837 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
838 }
839
840 /*
841 * writes to the cq entry need to come after reading head; the
842 * control dependency is enough as we're using WRITE_ONCE to
843 * fill the cq entry
844 */
io_cqe_cache_refill(struct io_ring_ctx * ctx,bool overflow)845 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
846 {
847 struct io_rings *rings = ctx->rings;
848 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
849 unsigned int free, queued, len;
850
851 /*
852 * Posting into the CQ when there are pending overflowed CQEs may break
853 * ordering guarantees, which will affect links, F_MORE users and more.
854 * Force overflow the completion.
855 */
856 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
857 return false;
858
859 /* userspace may cheat modifying the tail, be safe and do min */
860 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
861 free = ctx->cq_entries - queued;
862 /* we need a contiguous range, limit based on the current array offset */
863 len = min(free, ctx->cq_entries - off);
864 if (!len)
865 return false;
866
867 if (ctx->flags & IORING_SETUP_CQE32) {
868 off <<= 1;
869 len <<= 1;
870 }
871
872 ctx->cqe_cached = &rings->cqes[off];
873 ctx->cqe_sentinel = ctx->cqe_cached + len;
874 return true;
875 }
876
io_fill_cqe_aux(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)877 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
878 u32 cflags)
879 {
880 struct io_uring_cqe *cqe;
881
882 ctx->cq_extra++;
883
884 /*
885 * If we can't get a cq entry, userspace overflowed the
886 * submission (by quite a lot). Increment the overflow count in
887 * the ring.
888 */
889 if (likely(io_get_cqe(ctx, &cqe))) {
890 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
891
892 WRITE_ONCE(cqe->user_data, user_data);
893 WRITE_ONCE(cqe->res, res);
894 WRITE_ONCE(cqe->flags, cflags);
895
896 if (ctx->flags & IORING_SETUP_CQE32) {
897 WRITE_ONCE(cqe->big_cqe[0], 0);
898 WRITE_ONCE(cqe->big_cqe[1], 0);
899 }
900 return true;
901 }
902 return false;
903 }
904
__io_flush_post_cqes(struct io_ring_ctx * ctx)905 static void __io_flush_post_cqes(struct io_ring_ctx *ctx)
906 __must_hold(&ctx->uring_lock)
907 {
908 struct io_submit_state *state = &ctx->submit_state;
909 unsigned int i;
910
911 lockdep_assert_held(&ctx->uring_lock);
912 for (i = 0; i < state->cqes_count; i++) {
913 struct io_uring_cqe *cqe = &ctx->completion_cqes[i];
914
915 if (!io_fill_cqe_aux(ctx, cqe->user_data, cqe->res, cqe->flags)) {
916 if (ctx->lockless_cq) {
917 spin_lock(&ctx->completion_lock);
918 io_cqring_event_overflow(ctx, cqe->user_data,
919 cqe->res, cqe->flags, 0, 0);
920 spin_unlock(&ctx->completion_lock);
921 } else {
922 io_cqring_event_overflow(ctx, cqe->user_data,
923 cqe->res, cqe->flags, 0, 0);
924 }
925 }
926 }
927 state->cqes_count = 0;
928 }
929
__io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,bool allow_overflow)930 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags,
931 bool allow_overflow)
932 {
933 bool filled;
934
935 io_cq_lock(ctx);
936 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
937 if (!filled && allow_overflow)
938 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
939
940 io_cq_unlock_post(ctx);
941 return filled;
942 }
943
io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)944 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
945 {
946 return __io_post_aux_cqe(ctx, user_data, res, cflags, true);
947 }
948
949 /*
950 * A helper for multishot requests posting additional CQEs.
951 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
952 */
io_fill_cqe_req_aux(struct io_kiocb * req,bool defer,s32 res,u32 cflags)953 bool io_fill_cqe_req_aux(struct io_kiocb *req, bool defer, s32 res, u32 cflags)
954 {
955 struct io_ring_ctx *ctx = req->ctx;
956 u64 user_data = req->cqe.user_data;
957 struct io_uring_cqe *cqe;
958
959 if (!defer)
960 return __io_post_aux_cqe(ctx, user_data, res, cflags, false);
961
962 lockdep_assert_held(&ctx->uring_lock);
963
964 if (ctx->submit_state.cqes_count == ARRAY_SIZE(ctx->completion_cqes)) {
965 __io_cq_lock(ctx);
966 __io_flush_post_cqes(ctx);
967 /* no need to flush - flush is deferred */
968 __io_cq_unlock_post(ctx);
969 }
970
971 /* For defered completions this is not as strict as it is otherwise,
972 * however it's main job is to prevent unbounded posted completions,
973 * and in that it works just as well.
974 */
975 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
976 return false;
977
978 cqe = &ctx->completion_cqes[ctx->submit_state.cqes_count++];
979 cqe->user_data = user_data;
980 cqe->res = res;
981 cqe->flags = cflags;
982 return true;
983 }
984
__io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)985 static void __io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
986 {
987 struct io_ring_ctx *ctx = req->ctx;
988 struct io_rsrc_node *rsrc_node = NULL;
989
990 io_cq_lock(ctx);
991 if (!(req->flags & REQ_F_CQE_SKIP)) {
992 if (!io_fill_cqe_req(ctx, req))
993 io_req_cqe_overflow(req);
994 }
995
996 /*
997 * If we're the last reference to this request, add to our locked
998 * free_list cache.
999 */
1000 if (req_ref_put_and_test(req)) {
1001 if (req->flags & IO_REQ_LINK_FLAGS) {
1002 if (req->flags & IO_DISARM_MASK)
1003 io_disarm_next(req);
1004 if (req->link) {
1005 io_req_task_queue(req->link);
1006 req->link = NULL;
1007 }
1008 }
1009 io_put_kbuf_comp(req);
1010 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1011 io_clean_op(req);
1012 io_put_file(req);
1013
1014 rsrc_node = req->rsrc_node;
1015 /*
1016 * Selected buffer deallocation in io_clean_op() assumes that
1017 * we don't hold ->completion_lock. Clean them here to avoid
1018 * deadlocks.
1019 */
1020 io_put_task_remote(req->task);
1021 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1022 ctx->locked_free_nr++;
1023 }
1024 io_cq_unlock_post(ctx);
1025
1026 if (rsrc_node) {
1027 io_ring_submit_lock(ctx, issue_flags);
1028 io_put_rsrc_node(ctx, rsrc_node);
1029 io_ring_submit_unlock(ctx, issue_flags);
1030 }
1031 }
1032
io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)1033 void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
1034 {
1035 if (req->ctx->task_complete && req->ctx->submitter_task != current) {
1036 req->io_task_work.func = io_req_task_complete;
1037 io_req_task_work_add(req);
1038 } else if (!(issue_flags & IO_URING_F_UNLOCKED) ||
1039 !(req->ctx->flags & IORING_SETUP_IOPOLL)) {
1040 __io_req_complete_post(req, issue_flags);
1041 } else {
1042 struct io_ring_ctx *ctx = req->ctx;
1043
1044 mutex_lock(&ctx->uring_lock);
1045 __io_req_complete_post(req, issue_flags & ~IO_URING_F_UNLOCKED);
1046 mutex_unlock(&ctx->uring_lock);
1047 }
1048 }
1049
io_req_defer_failed(struct io_kiocb * req,s32 res)1050 void io_req_defer_failed(struct io_kiocb *req, s32 res)
1051 __must_hold(&ctx->uring_lock)
1052 {
1053 const struct io_cold_def *def = &io_cold_defs[req->opcode];
1054
1055 lockdep_assert_held(&req->ctx->uring_lock);
1056
1057 req_set_fail(req);
1058 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1059 if (def->fail)
1060 def->fail(req);
1061 io_req_complete_defer(req);
1062 }
1063
1064 /*
1065 * Don't initialise the fields below on every allocation, but do that in
1066 * advance and keep them valid across allocations.
1067 */
io_preinit_req(struct io_kiocb * req,struct io_ring_ctx * ctx)1068 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1069 {
1070 req->ctx = ctx;
1071 req->link = NULL;
1072 req->async_data = NULL;
1073 /* not necessary, but safer to zero */
1074 memset(&req->cqe, 0, sizeof(req->cqe));
1075 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
1076 }
1077
io_flush_cached_locked_reqs(struct io_ring_ctx * ctx,struct io_submit_state * state)1078 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1079 struct io_submit_state *state)
1080 {
1081 spin_lock(&ctx->completion_lock);
1082 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1083 ctx->locked_free_nr = 0;
1084 spin_unlock(&ctx->completion_lock);
1085 }
1086
1087 /*
1088 * A request might get retired back into the request caches even before opcode
1089 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1090 * Because of that, io_alloc_req() should be called only under ->uring_lock
1091 * and with extra caution to not get a request that is still worked on.
1092 */
__io_alloc_req_refill(struct io_ring_ctx * ctx)1093 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1094 __must_hold(&ctx->uring_lock)
1095 {
1096 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1097 void *reqs[IO_REQ_ALLOC_BATCH];
1098 int ret, i;
1099
1100 /*
1101 * If we have more than a batch's worth of requests in our IRQ side
1102 * locked cache, grab the lock and move them over to our submission
1103 * side cache.
1104 */
1105 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1106 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1107 if (!io_req_cache_empty(ctx))
1108 return true;
1109 }
1110
1111 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1112
1113 /*
1114 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1115 * retry single alloc to be on the safe side.
1116 */
1117 if (unlikely(ret <= 0)) {
1118 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1119 if (!reqs[0])
1120 return false;
1121 ret = 1;
1122 }
1123
1124 percpu_ref_get_many(&ctx->refs, ret);
1125 for (i = 0; i < ret; i++) {
1126 struct io_kiocb *req = reqs[i];
1127
1128 io_preinit_req(req, ctx);
1129 io_req_add_to_cache(req, ctx);
1130 }
1131 return true;
1132 }
1133
io_free_req(struct io_kiocb * req)1134 __cold void io_free_req(struct io_kiocb *req)
1135 {
1136 /* refs were already put, restore them for io_req_task_complete() */
1137 req->flags &= ~REQ_F_REFCOUNT;
1138 /* we only want to free it, don't post CQEs */
1139 req->flags |= REQ_F_CQE_SKIP;
1140 req->io_task_work.func = io_req_task_complete;
1141 io_req_task_work_add(req);
1142 }
1143
__io_req_find_next_prep(struct io_kiocb * req)1144 static void __io_req_find_next_prep(struct io_kiocb *req)
1145 {
1146 struct io_ring_ctx *ctx = req->ctx;
1147
1148 spin_lock(&ctx->completion_lock);
1149 io_disarm_next(req);
1150 spin_unlock(&ctx->completion_lock);
1151 }
1152
io_req_find_next(struct io_kiocb * req)1153 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1154 {
1155 struct io_kiocb *nxt;
1156
1157 /*
1158 * If LINK is set, we have dependent requests in this chain. If we
1159 * didn't fail this request, queue the first one up, moving any other
1160 * dependencies to the next request. In case of failure, fail the rest
1161 * of the chain.
1162 */
1163 if (unlikely(req->flags & IO_DISARM_MASK))
1164 __io_req_find_next_prep(req);
1165 nxt = req->link;
1166 req->link = NULL;
1167 return nxt;
1168 }
1169
ctx_flush_and_put(struct io_ring_ctx * ctx,struct io_tw_state * ts)1170 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
1171 {
1172 if (!ctx)
1173 return;
1174 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1175 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1176 if (ts->locked) {
1177 io_submit_flush_completions(ctx);
1178 mutex_unlock(&ctx->uring_lock);
1179 ts->locked = false;
1180 }
1181 percpu_ref_put(&ctx->refs);
1182 }
1183
handle_tw_list(struct llist_node * node,struct io_ring_ctx ** ctx,struct io_tw_state * ts)1184 static unsigned int handle_tw_list(struct llist_node *node,
1185 struct io_ring_ctx **ctx,
1186 struct io_tw_state *ts)
1187 {
1188 unsigned int count = 0;
1189
1190 do {
1191 struct llist_node *next = node->next;
1192 struct io_kiocb *req = container_of(node, struct io_kiocb,
1193 io_task_work.node);
1194
1195 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1196
1197 if (req->ctx != *ctx) {
1198 ctx_flush_and_put(*ctx, ts);
1199 *ctx = req->ctx;
1200 /* if not contended, grab and improve batching */
1201 ts->locked = mutex_trylock(&(*ctx)->uring_lock);
1202 percpu_ref_get(&(*ctx)->refs);
1203 }
1204 INDIRECT_CALL_2(req->io_task_work.func,
1205 io_poll_task_func, io_req_rw_complete,
1206 req, ts);
1207 node = next;
1208 count++;
1209 if (unlikely(need_resched())) {
1210 ctx_flush_and_put(*ctx, ts);
1211 *ctx = NULL;
1212 cond_resched();
1213 }
1214 } while (node);
1215
1216 return count;
1217 }
1218
1219 /**
1220 * io_llist_xchg - swap all entries in a lock-less list
1221 * @head: the head of lock-less list to delete all entries
1222 * @new: new entry as the head of the list
1223 *
1224 * If list is empty, return NULL, otherwise, return the pointer to the first entry.
1225 * The order of entries returned is from the newest to the oldest added one.
1226 */
io_llist_xchg(struct llist_head * head,struct llist_node * new)1227 static inline struct llist_node *io_llist_xchg(struct llist_head *head,
1228 struct llist_node *new)
1229 {
1230 return xchg(&head->first, new);
1231 }
1232
io_fallback_tw(struct io_uring_task * tctx,bool sync)1233 static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1234 {
1235 struct llist_node *node = llist_del_all(&tctx->task_list);
1236 struct io_ring_ctx *last_ctx = NULL;
1237 struct io_kiocb *req;
1238
1239 while (node) {
1240 req = container_of(node, struct io_kiocb, io_task_work.node);
1241 node = node->next;
1242 if (sync && last_ctx != req->ctx) {
1243 if (last_ctx) {
1244 flush_delayed_work(&last_ctx->fallback_work);
1245 percpu_ref_put(&last_ctx->refs);
1246 }
1247 last_ctx = req->ctx;
1248 percpu_ref_get(&last_ctx->refs);
1249 }
1250 if (llist_add(&req->io_task_work.node,
1251 &req->ctx->fallback_llist))
1252 schedule_delayed_work(&req->ctx->fallback_work, 1);
1253 }
1254
1255 if (last_ctx) {
1256 flush_delayed_work(&last_ctx->fallback_work);
1257 percpu_ref_put(&last_ctx->refs);
1258 }
1259 }
1260
tctx_task_work(struct callback_head * cb)1261 void tctx_task_work(struct callback_head *cb)
1262 {
1263 struct io_tw_state ts = {};
1264 struct io_ring_ctx *ctx = NULL;
1265 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1266 task_work);
1267 struct llist_node *node;
1268 unsigned int count = 0;
1269
1270 if (unlikely(current->flags & PF_EXITING)) {
1271 io_fallback_tw(tctx, true);
1272 return;
1273 }
1274
1275 node = llist_del_all(&tctx->task_list);
1276 if (node)
1277 count = handle_tw_list(node, &ctx, &ts);
1278
1279 ctx_flush_and_put(ctx, &ts);
1280
1281 /* relaxed read is enough as only the task itself sets ->in_cancel */
1282 if (unlikely(atomic_read(&tctx->in_cancel)))
1283 io_uring_drop_tctx_refs(current);
1284
1285 trace_io_uring_task_work_run(tctx, count, 1);
1286 }
1287
io_req_local_work_add(struct io_kiocb * req,unsigned flags)1288 static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1289 {
1290 struct io_ring_ctx *ctx = req->ctx;
1291 unsigned nr_wait, nr_tw, nr_tw_prev;
1292 struct llist_node *first;
1293
1294 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1295 flags &= ~IOU_F_TWQ_LAZY_WAKE;
1296
1297 first = READ_ONCE(ctx->work_llist.first);
1298 do {
1299 nr_tw_prev = 0;
1300 if (first) {
1301 struct io_kiocb *first_req = container_of(first,
1302 struct io_kiocb,
1303 io_task_work.node);
1304 /*
1305 * Might be executed at any moment, rely on
1306 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1307 */
1308 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1309 }
1310 nr_tw = nr_tw_prev + 1;
1311 /* Large enough to fail the nr_wait comparison below */
1312 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1313 nr_tw = INT_MAX;
1314
1315 req->nr_tw = nr_tw;
1316 req->io_task_work.node.next = first;
1317 } while (!try_cmpxchg(&ctx->work_llist.first, &first,
1318 &req->io_task_work.node));
1319
1320 if (!first) {
1321 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1322 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1323 if (ctx->has_evfd)
1324 io_eventfd_signal(ctx);
1325 }
1326
1327 nr_wait = atomic_read(&ctx->cq_wait_nr);
1328 /* no one is waiting */
1329 if (!nr_wait)
1330 return;
1331 /* either not enough or the previous add has already woken it up */
1332 if (nr_wait > nr_tw || nr_tw_prev >= nr_wait)
1333 return;
1334 /* pairs with set_current_state() in io_cqring_wait() */
1335 smp_mb__after_atomic();
1336 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1337 }
1338
io_req_normal_work_add(struct io_kiocb * req)1339 static void io_req_normal_work_add(struct io_kiocb *req)
1340 {
1341 struct io_uring_task *tctx = req->task->io_uring;
1342 struct io_ring_ctx *ctx = req->ctx;
1343
1344 /* task_work already pending, we're done */
1345 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1346 return;
1347
1348 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1349 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1350
1351 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1352 return;
1353
1354 io_fallback_tw(tctx, false);
1355 }
1356
__io_req_task_work_add(struct io_kiocb * req,unsigned flags)1357 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1358 {
1359 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
1360 rcu_read_lock();
1361 io_req_local_work_add(req, flags);
1362 rcu_read_unlock();
1363 } else {
1364 io_req_normal_work_add(req);
1365 }
1366 }
1367
io_move_task_work_from_local(struct io_ring_ctx * ctx)1368 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1369 {
1370 struct llist_node *node;
1371
1372 node = llist_del_all(&ctx->work_llist);
1373 while (node) {
1374 struct io_kiocb *req = container_of(node, struct io_kiocb,
1375 io_task_work.node);
1376
1377 node = node->next;
1378 io_req_normal_work_add(req);
1379 }
1380 }
1381
io_run_local_work_continue(struct io_ring_ctx * ctx,int events,int min_events)1382 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1383 int min_events)
1384 {
1385 if (llist_empty(&ctx->work_llist))
1386 return false;
1387 if (events < min_events)
1388 return true;
1389 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1390 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1391 return false;
1392 }
1393
__io_run_local_work(struct io_ring_ctx * ctx,struct io_tw_state * ts,int min_events)1394 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1395 int min_events)
1396 {
1397 struct llist_node *node;
1398 unsigned int loops = 0;
1399 int ret = 0;
1400
1401 if (WARN_ON_ONCE(ctx->submitter_task != current))
1402 return -EEXIST;
1403 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1404 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1405 again:
1406 /*
1407 * llists are in reverse order, flip it back the right way before
1408 * running the pending items.
1409 */
1410 node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
1411 while (node) {
1412 struct llist_node *next = node->next;
1413 struct io_kiocb *req = container_of(node, struct io_kiocb,
1414 io_task_work.node);
1415 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1416 INDIRECT_CALL_2(req->io_task_work.func,
1417 io_poll_task_func, io_req_rw_complete,
1418 req, ts);
1419 ret++;
1420 node = next;
1421 }
1422 loops++;
1423
1424 if (io_run_local_work_continue(ctx, ret, min_events))
1425 goto again;
1426 if (ts->locked) {
1427 io_submit_flush_completions(ctx);
1428 if (io_run_local_work_continue(ctx, ret, min_events))
1429 goto again;
1430 }
1431
1432 trace_io_uring_local_work_run(ctx, ret, loops);
1433 return ret;
1434 }
1435
io_run_local_work_locked(struct io_ring_ctx * ctx,int min_events)1436 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1437 int min_events)
1438 {
1439 struct io_tw_state ts = { .locked = true, };
1440 int ret;
1441
1442 if (llist_empty(&ctx->work_llist))
1443 return 0;
1444
1445 ret = __io_run_local_work(ctx, &ts, min_events);
1446 /* shouldn't happen! */
1447 if (WARN_ON_ONCE(!ts.locked))
1448 mutex_lock(&ctx->uring_lock);
1449 return ret;
1450 }
1451
io_run_local_work(struct io_ring_ctx * ctx,int min_events)1452 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
1453 {
1454 struct io_tw_state ts = {};
1455 int ret;
1456
1457 ts.locked = mutex_trylock(&ctx->uring_lock);
1458 ret = __io_run_local_work(ctx, &ts, min_events);
1459 if (ts.locked)
1460 mutex_unlock(&ctx->uring_lock);
1461
1462 return ret;
1463 }
1464
io_req_task_cancel(struct io_kiocb * req,struct io_tw_state * ts)1465 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
1466 {
1467 io_tw_lock(req->ctx, ts);
1468 io_req_defer_failed(req, req->cqe.res);
1469 }
1470
io_req_task_submit(struct io_kiocb * req,struct io_tw_state * ts)1471 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
1472 {
1473 io_tw_lock(req->ctx, ts);
1474 /* req->task == current here, checking PF_EXITING is safe */
1475 if (unlikely(req->task->flags & PF_EXITING))
1476 io_req_defer_failed(req, -EFAULT);
1477 else if (req->flags & REQ_F_FORCE_ASYNC)
1478 io_queue_iowq(req, ts);
1479 else
1480 io_queue_sqe(req);
1481 }
1482
io_req_task_queue_fail(struct io_kiocb * req,int ret)1483 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1484 {
1485 io_req_set_res(req, ret, 0);
1486 req->io_task_work.func = io_req_task_cancel;
1487 io_req_task_work_add(req);
1488 }
1489
io_req_task_queue(struct io_kiocb * req)1490 void io_req_task_queue(struct io_kiocb *req)
1491 {
1492 req->io_task_work.func = io_req_task_submit;
1493 io_req_task_work_add(req);
1494 }
1495
io_queue_next(struct io_kiocb * req)1496 void io_queue_next(struct io_kiocb *req)
1497 {
1498 struct io_kiocb *nxt = io_req_find_next(req);
1499
1500 if (nxt)
1501 io_req_task_queue(nxt);
1502 }
1503
io_free_batch_list(struct io_ring_ctx * ctx,struct io_wq_work_node * node)1504 static void io_free_batch_list(struct io_ring_ctx *ctx,
1505 struct io_wq_work_node *node)
1506 __must_hold(&ctx->uring_lock)
1507 {
1508 do {
1509 struct io_kiocb *req = container_of(node, struct io_kiocb,
1510 comp_list);
1511
1512 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1513 if (req->flags & REQ_F_REFCOUNT) {
1514 node = req->comp_list.next;
1515 if (!req_ref_put_and_test(req))
1516 continue;
1517 }
1518 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1519 struct async_poll *apoll = req->apoll;
1520
1521 if (apoll->double_poll)
1522 kfree(apoll->double_poll);
1523 if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache))
1524 kfree(apoll);
1525 req->flags &= ~REQ_F_POLLED;
1526 }
1527 if (req->flags & IO_REQ_LINK_FLAGS)
1528 io_queue_next(req);
1529 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1530 io_clean_op(req);
1531 }
1532 io_put_file(req);
1533
1534 io_req_put_rsrc_locked(req, ctx);
1535
1536 io_put_task(req->task);
1537 node = req->comp_list.next;
1538 io_req_add_to_cache(req, ctx);
1539 } while (node);
1540 }
1541
__io_submit_flush_completions(struct io_ring_ctx * ctx)1542 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1543 __must_hold(&ctx->uring_lock)
1544 {
1545 struct io_submit_state *state = &ctx->submit_state;
1546 struct io_wq_work_node *node;
1547
1548 __io_cq_lock(ctx);
1549 /* must come first to preserve CQE ordering in failure cases */
1550 if (state->cqes_count)
1551 __io_flush_post_cqes(ctx);
1552 __wq_list_for_each(node, &state->compl_reqs) {
1553 struct io_kiocb *req = container_of(node, struct io_kiocb,
1554 comp_list);
1555
1556 if (!(req->flags & REQ_F_CQE_SKIP) &&
1557 unlikely(!io_fill_cqe_req(ctx, req))) {
1558 if (ctx->lockless_cq) {
1559 spin_lock(&ctx->completion_lock);
1560 io_req_cqe_overflow(req);
1561 spin_unlock(&ctx->completion_lock);
1562 } else {
1563 io_req_cqe_overflow(req);
1564 }
1565 }
1566 }
1567 __io_cq_unlock_post(ctx);
1568
1569 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) {
1570 io_free_batch_list(ctx, state->compl_reqs.first);
1571 INIT_WQ_LIST(&state->compl_reqs);
1572 }
1573 }
1574
io_cqring_events(struct io_ring_ctx * ctx)1575 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1576 {
1577 /* See comment at the top of this file */
1578 smp_rmb();
1579 return __io_cqring_events(ctx);
1580 }
1581
1582 /*
1583 * We can't just wait for polled events to come to us, we have to actively
1584 * find and complete them.
1585 */
io_iopoll_try_reap_events(struct io_ring_ctx * ctx)1586 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1587 {
1588 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1589 return;
1590
1591 mutex_lock(&ctx->uring_lock);
1592 while (!wq_list_empty(&ctx->iopoll_list)) {
1593 /* let it sleep and repeat later if can't complete a request */
1594 if (io_do_iopoll(ctx, true) == 0)
1595 break;
1596 /*
1597 * Ensure we allow local-to-the-cpu processing to take place,
1598 * in this case we need to ensure that we reap all events.
1599 * Also let task_work, etc. to progress by releasing the mutex
1600 */
1601 if (need_resched()) {
1602 mutex_unlock(&ctx->uring_lock);
1603 cond_resched();
1604 mutex_lock(&ctx->uring_lock);
1605 }
1606 }
1607 mutex_unlock(&ctx->uring_lock);
1608 }
1609
io_iopoll_check(struct io_ring_ctx * ctx,long min)1610 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1611 {
1612 unsigned int nr_events = 0;
1613 unsigned long check_cq;
1614
1615 lockdep_assert_held(&ctx->uring_lock);
1616
1617 if (!io_allowed_run_tw(ctx))
1618 return -EEXIST;
1619
1620 check_cq = READ_ONCE(ctx->check_cq);
1621 if (unlikely(check_cq)) {
1622 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1623 __io_cqring_overflow_flush(ctx);
1624 /*
1625 * Similarly do not spin if we have not informed the user of any
1626 * dropped CQE.
1627 */
1628 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1629 return -EBADR;
1630 }
1631 /*
1632 * Don't enter poll loop if we already have events pending.
1633 * If we do, we can potentially be spinning for commands that
1634 * already triggered a CQE (eg in error).
1635 */
1636 if (io_cqring_events(ctx))
1637 return 0;
1638
1639 do {
1640 int ret = 0;
1641
1642 /*
1643 * If a submit got punted to a workqueue, we can have the
1644 * application entering polling for a command before it gets
1645 * issued. That app will hold the uring_lock for the duration
1646 * of the poll right here, so we need to take a breather every
1647 * now and then to ensure that the issue has a chance to add
1648 * the poll to the issued list. Otherwise we can spin here
1649 * forever, while the workqueue is stuck trying to acquire the
1650 * very same mutex.
1651 */
1652 if (wq_list_empty(&ctx->iopoll_list) ||
1653 io_task_work_pending(ctx)) {
1654 u32 tail = ctx->cached_cq_tail;
1655
1656 (void) io_run_local_work_locked(ctx, min);
1657
1658 if (task_work_pending(current) ||
1659 wq_list_empty(&ctx->iopoll_list)) {
1660 mutex_unlock(&ctx->uring_lock);
1661 io_run_task_work();
1662 mutex_lock(&ctx->uring_lock);
1663 }
1664 /* some requests don't go through iopoll_list */
1665 if (tail != ctx->cached_cq_tail ||
1666 wq_list_empty(&ctx->iopoll_list))
1667 break;
1668 }
1669 ret = io_do_iopoll(ctx, !min);
1670 if (unlikely(ret < 0))
1671 return ret;
1672
1673 if (task_sigpending(current))
1674 return -EINTR;
1675 if (need_resched())
1676 break;
1677
1678 nr_events += ret;
1679 } while (nr_events < min);
1680
1681 return 0;
1682 }
1683
io_req_task_complete(struct io_kiocb * req,struct io_tw_state * ts)1684 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
1685 {
1686 if (ts->locked)
1687 io_req_complete_defer(req);
1688 else
1689 io_req_complete_post(req, IO_URING_F_UNLOCKED);
1690 }
1691
1692 /*
1693 * After the iocb has been issued, it's safe to be found on the poll list.
1694 * Adding the kiocb to the list AFTER submission ensures that we don't
1695 * find it from a io_do_iopoll() thread before the issuer is done
1696 * accessing the kiocb cookie.
1697 */
io_iopoll_req_issued(struct io_kiocb * req,unsigned int issue_flags)1698 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1699 {
1700 struct io_ring_ctx *ctx = req->ctx;
1701 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1702
1703 /* workqueue context doesn't hold uring_lock, grab it now */
1704 if (unlikely(needs_lock))
1705 mutex_lock(&ctx->uring_lock);
1706
1707 /*
1708 * Track whether we have multiple files in our lists. This will impact
1709 * how we do polling eventually, not spinning if we're on potentially
1710 * different devices.
1711 */
1712 if (wq_list_empty(&ctx->iopoll_list)) {
1713 ctx->poll_multi_queue = false;
1714 } else if (!ctx->poll_multi_queue) {
1715 struct io_kiocb *list_req;
1716
1717 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1718 comp_list);
1719 if (list_req->file != req->file)
1720 ctx->poll_multi_queue = true;
1721 }
1722
1723 /*
1724 * For fast devices, IO may have already completed. If it has, add
1725 * it to the front so we find it first.
1726 */
1727 if (READ_ONCE(req->iopoll_completed))
1728 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1729 else
1730 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1731
1732 if (unlikely(needs_lock)) {
1733 /*
1734 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1735 * in sq thread task context or in io worker task context. If
1736 * current task context is sq thread, we don't need to check
1737 * whether should wake up sq thread.
1738 */
1739 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1740 wq_has_sleeper(&ctx->sq_data->wait))
1741 wake_up(&ctx->sq_data->wait);
1742
1743 mutex_unlock(&ctx->uring_lock);
1744 }
1745 }
1746
io_file_get_flags(struct file * file)1747 unsigned int io_file_get_flags(struct file *file)
1748 {
1749 unsigned int res = 0;
1750
1751 if (S_ISREG(file_inode(file)->i_mode))
1752 res |= REQ_F_ISREG;
1753 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1754 res |= REQ_F_SUPPORT_NOWAIT;
1755 return res;
1756 }
1757
io_alloc_async_data(struct io_kiocb * req)1758 bool io_alloc_async_data(struct io_kiocb *req)
1759 {
1760 WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size);
1761 req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL);
1762 if (req->async_data) {
1763 req->flags |= REQ_F_ASYNC_DATA;
1764 return false;
1765 }
1766 return true;
1767 }
1768
io_req_prep_async(struct io_kiocb * req)1769 int io_req_prep_async(struct io_kiocb *req)
1770 {
1771 const struct io_cold_def *cdef = &io_cold_defs[req->opcode];
1772 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1773
1774 /* assign early for deferred execution for non-fixed file */
1775 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file)
1776 req->file = io_file_get_normal(req, req->cqe.fd);
1777 if (!cdef->prep_async)
1778 return 0;
1779 if (WARN_ON_ONCE(req_has_async_data(req)))
1780 return -EFAULT;
1781 if (!def->manual_alloc) {
1782 if (io_alloc_async_data(req))
1783 return -EAGAIN;
1784 }
1785 return cdef->prep_async(req);
1786 }
1787
io_get_sequence(struct io_kiocb * req)1788 static u32 io_get_sequence(struct io_kiocb *req)
1789 {
1790 u32 seq = req->ctx->cached_sq_head;
1791 struct io_kiocb *cur;
1792
1793 /* need original cached_sq_head, but it was increased for each req */
1794 io_for_each_link(cur, req)
1795 seq--;
1796 return seq;
1797 }
1798
io_drain_req(struct io_kiocb * req)1799 static __cold void io_drain_req(struct io_kiocb *req)
1800 __must_hold(&ctx->uring_lock)
1801 {
1802 struct io_ring_ctx *ctx = req->ctx;
1803 struct io_defer_entry *de;
1804 int ret;
1805 u32 seq = io_get_sequence(req);
1806
1807 /* Still need defer if there is pending req in defer list. */
1808 spin_lock(&ctx->completion_lock);
1809 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1810 spin_unlock(&ctx->completion_lock);
1811 queue:
1812 ctx->drain_active = false;
1813 io_req_task_queue(req);
1814 return;
1815 }
1816 spin_unlock(&ctx->completion_lock);
1817
1818 io_prep_async_link(req);
1819 de = kmalloc(sizeof(*de), GFP_KERNEL);
1820 if (!de) {
1821 ret = -ENOMEM;
1822 io_req_defer_failed(req, ret);
1823 return;
1824 }
1825
1826 spin_lock(&ctx->completion_lock);
1827 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1828 spin_unlock(&ctx->completion_lock);
1829 kfree(de);
1830 goto queue;
1831 }
1832
1833 trace_io_uring_defer(req);
1834 de->req = req;
1835 de->seq = seq;
1836 list_add_tail(&de->list, &ctx->defer_list);
1837 spin_unlock(&ctx->completion_lock);
1838 }
1839
io_assign_file(struct io_kiocb * req,const struct io_issue_def * def,unsigned int issue_flags)1840 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1841 unsigned int issue_flags)
1842 {
1843 if (req->file || !def->needs_file)
1844 return true;
1845
1846 if (req->flags & REQ_F_FIXED_FILE)
1847 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1848 else
1849 req->file = io_file_get_normal(req, req->cqe.fd);
1850
1851 return !!req->file;
1852 }
1853
io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags)1854 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1855 {
1856 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1857 const struct cred *creds = NULL;
1858 int ret;
1859
1860 if (unlikely(!io_assign_file(req, def, issue_flags)))
1861 return -EBADF;
1862
1863 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1864 creds = override_creds(req->creds);
1865
1866 if (!def->audit_skip)
1867 audit_uring_entry(req->opcode);
1868
1869 ret = def->issue(req, issue_flags);
1870
1871 if (!def->audit_skip)
1872 audit_uring_exit(!ret, ret);
1873
1874 if (creds)
1875 revert_creds(creds);
1876
1877 if (ret == IOU_OK) {
1878 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1879 io_req_complete_defer(req);
1880 else
1881 io_req_complete_post(req, issue_flags);
1882
1883 return 0;
1884 }
1885
1886 if (ret != IOU_ISSUE_SKIP_COMPLETE)
1887 return ret;
1888
1889 /* If the op doesn't have a file, we're not polling for it */
1890 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1891 io_iopoll_req_issued(req, issue_flags);
1892
1893 return 0;
1894 }
1895
io_poll_issue(struct io_kiocb * req,struct io_tw_state * ts)1896 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
1897 {
1898 io_tw_lock(req->ctx, ts);
1899 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1900 IO_URING_F_COMPLETE_DEFER);
1901 }
1902
io_wq_free_work(struct io_wq_work * work)1903 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1904 {
1905 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1906 struct io_kiocb *nxt = NULL;
1907
1908 if (req_ref_put_and_test(req)) {
1909 if (req->flags & IO_REQ_LINK_FLAGS)
1910 nxt = io_req_find_next(req);
1911 io_free_req(req);
1912 }
1913 return nxt ? &nxt->work : NULL;
1914 }
1915
io_wq_submit_work(struct io_wq_work * work)1916 void io_wq_submit_work(struct io_wq_work *work)
1917 {
1918 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1919 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1920 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1921 bool needs_poll = false;
1922 int ret = 0, err = -ECANCELED;
1923
1924 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1925 if (!(req->flags & REQ_F_REFCOUNT))
1926 __io_req_set_refcount(req, 2);
1927 else
1928 req_ref_get(req);
1929
1930 io_arm_ltimeout(req);
1931
1932 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1933 if (work->flags & IO_WQ_WORK_CANCEL) {
1934 fail:
1935 io_req_task_queue_fail(req, err);
1936 return;
1937 }
1938 if (!io_assign_file(req, def, issue_flags)) {
1939 err = -EBADF;
1940 work->flags |= IO_WQ_WORK_CANCEL;
1941 goto fail;
1942 }
1943
1944 if (req->flags & REQ_F_FORCE_ASYNC) {
1945 bool opcode_poll = def->pollin || def->pollout;
1946
1947 if (opcode_poll && file_can_poll(req->file)) {
1948 needs_poll = true;
1949 issue_flags |= IO_URING_F_NONBLOCK;
1950 }
1951 }
1952
1953 do {
1954 ret = io_issue_sqe(req, issue_flags);
1955 if (ret != -EAGAIN)
1956 break;
1957
1958 /*
1959 * If REQ_F_NOWAIT is set, then don't wait or retry with
1960 * poll. -EAGAIN is final for that case.
1961 */
1962 if (req->flags & REQ_F_NOWAIT)
1963 break;
1964
1965 /*
1966 * We can get EAGAIN for iopolled IO even though we're
1967 * forcing a sync submission from here, since we can't
1968 * wait for request slots on the block side.
1969 */
1970 if (!needs_poll) {
1971 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1972 break;
1973 if (io_wq_worker_stopped())
1974 break;
1975 cond_resched();
1976 continue;
1977 }
1978
1979 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1980 return;
1981 /* aborted or ready, in either case retry blocking */
1982 needs_poll = false;
1983 issue_flags &= ~IO_URING_F_NONBLOCK;
1984 } while (1);
1985
1986 /* avoid locking problems by failing it from a clean context */
1987 if (ret < 0)
1988 io_req_task_queue_fail(req, ret);
1989 }
1990
io_file_get_fixed(struct io_kiocb * req,int fd,unsigned int issue_flags)1991 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1992 unsigned int issue_flags)
1993 {
1994 struct io_ring_ctx *ctx = req->ctx;
1995 struct io_fixed_file *slot;
1996 struct file *file = NULL;
1997
1998 io_ring_submit_lock(ctx, issue_flags);
1999
2000 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
2001 goto out;
2002 fd = array_index_nospec(fd, ctx->nr_user_files);
2003 slot = io_fixed_file_slot(&ctx->file_table, fd);
2004 file = io_slot_file(slot);
2005 req->flags |= io_slot_flags(slot);
2006 io_req_set_rsrc_node(req, ctx, 0);
2007 out:
2008 io_ring_submit_unlock(ctx, issue_flags);
2009 return file;
2010 }
2011
io_file_get_normal(struct io_kiocb * req,int fd)2012 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
2013 {
2014 struct file *file = fget(fd);
2015
2016 trace_io_uring_file_get(req, fd);
2017
2018 /* we don't allow fixed io_uring files */
2019 if (file && io_is_uring_fops(file))
2020 io_req_track_inflight(req);
2021 return file;
2022 }
2023
io_queue_async(struct io_kiocb * req,int ret)2024 static void io_queue_async(struct io_kiocb *req, int ret)
2025 __must_hold(&req->ctx->uring_lock)
2026 {
2027 struct io_kiocb *linked_timeout;
2028
2029 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
2030 io_req_defer_failed(req, ret);
2031 return;
2032 }
2033
2034 linked_timeout = io_prep_linked_timeout(req);
2035
2036 switch (io_arm_poll_handler(req, 0)) {
2037 case IO_APOLL_READY:
2038 io_kbuf_recycle(req, 0);
2039 io_req_task_queue(req);
2040 break;
2041 case IO_APOLL_ABORTED:
2042 io_kbuf_recycle(req, 0);
2043 io_queue_iowq(req, NULL);
2044 break;
2045 case IO_APOLL_OK:
2046 break;
2047 }
2048
2049 if (linked_timeout)
2050 io_queue_linked_timeout(linked_timeout);
2051 }
2052
io_queue_sqe(struct io_kiocb * req)2053 static inline void io_queue_sqe(struct io_kiocb *req)
2054 __must_hold(&req->ctx->uring_lock)
2055 {
2056 int ret;
2057
2058 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
2059
2060 /*
2061 * We async punt it if the file wasn't marked NOWAIT, or if the file
2062 * doesn't support non-blocking read/write attempts
2063 */
2064 if (likely(!ret))
2065 io_arm_ltimeout(req);
2066 else
2067 io_queue_async(req, ret);
2068 }
2069
io_queue_sqe_fallback(struct io_kiocb * req)2070 static void io_queue_sqe_fallback(struct io_kiocb *req)
2071 __must_hold(&req->ctx->uring_lock)
2072 {
2073 if (unlikely(req->flags & REQ_F_FAIL)) {
2074 /*
2075 * We don't submit, fail them all, for that replace hardlinks
2076 * with normal links. Extra REQ_F_LINK is tolerated.
2077 */
2078 req->flags &= ~REQ_F_HARDLINK;
2079 req->flags |= REQ_F_LINK;
2080 io_req_defer_failed(req, req->cqe.res);
2081 } else {
2082 int ret = io_req_prep_async(req);
2083
2084 if (unlikely(ret)) {
2085 io_req_defer_failed(req, ret);
2086 return;
2087 }
2088
2089 if (unlikely(req->ctx->drain_active))
2090 io_drain_req(req);
2091 else
2092 io_queue_iowq(req, NULL);
2093 }
2094 }
2095
2096 /*
2097 * Check SQE restrictions (opcode and flags).
2098 *
2099 * Returns 'true' if SQE is allowed, 'false' otherwise.
2100 */
io_check_restriction(struct io_ring_ctx * ctx,struct io_kiocb * req,unsigned int sqe_flags)2101 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2102 struct io_kiocb *req,
2103 unsigned int sqe_flags)
2104 {
2105 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2106 return false;
2107
2108 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2109 ctx->restrictions.sqe_flags_required)
2110 return false;
2111
2112 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2113 ctx->restrictions.sqe_flags_required))
2114 return false;
2115
2116 return true;
2117 }
2118
io_init_req_drain(struct io_kiocb * req)2119 static void io_init_req_drain(struct io_kiocb *req)
2120 {
2121 struct io_ring_ctx *ctx = req->ctx;
2122 struct io_kiocb *head = ctx->submit_state.link.head;
2123
2124 ctx->drain_active = true;
2125 if (head) {
2126 /*
2127 * If we need to drain a request in the middle of a link, drain
2128 * the head request and the next request/link after the current
2129 * link. Considering sequential execution of links,
2130 * REQ_F_IO_DRAIN will be maintained for every request of our
2131 * link.
2132 */
2133 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2134 ctx->drain_next = true;
2135 }
2136 }
2137
io_init_fail_req(struct io_kiocb * req,int err)2138 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2139 {
2140 /* ensure per-opcode data is cleared if we fail before prep */
2141 memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2142 return err;
2143 }
2144
io_init_req(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2145 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2146 const struct io_uring_sqe *sqe)
2147 __must_hold(&ctx->uring_lock)
2148 {
2149 const struct io_issue_def *def;
2150 unsigned int sqe_flags;
2151 int personality;
2152 u8 opcode;
2153
2154 /* req is partially pre-initialised, see io_preinit_req() */
2155 req->opcode = opcode = READ_ONCE(sqe->opcode);
2156 /* same numerical values with corresponding REQ_F_*, safe to copy */
2157 req->flags = sqe_flags = READ_ONCE(sqe->flags);
2158 req->cqe.user_data = READ_ONCE(sqe->user_data);
2159 req->file = NULL;
2160 req->rsrc_node = NULL;
2161 req->task = current;
2162
2163 if (unlikely(opcode >= IORING_OP_LAST)) {
2164 req->opcode = 0;
2165 return io_init_fail_req(req, -EINVAL);
2166 }
2167 def = &io_issue_defs[opcode];
2168 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2169 /* enforce forwards compatibility on users */
2170 if (sqe_flags & ~SQE_VALID_FLAGS)
2171 return io_init_fail_req(req, -EINVAL);
2172 if (sqe_flags & IOSQE_BUFFER_SELECT) {
2173 if (!def->buffer_select)
2174 return io_init_fail_req(req, -EOPNOTSUPP);
2175 req->buf_index = READ_ONCE(sqe->buf_group);
2176 }
2177 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2178 ctx->drain_disabled = true;
2179 if (sqe_flags & IOSQE_IO_DRAIN) {
2180 if (ctx->drain_disabled)
2181 return io_init_fail_req(req, -EOPNOTSUPP);
2182 io_init_req_drain(req);
2183 }
2184 }
2185 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2186 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2187 return io_init_fail_req(req, -EACCES);
2188 /* knock it to the slow queue path, will be drained there */
2189 if (ctx->drain_active)
2190 req->flags |= REQ_F_FORCE_ASYNC;
2191 /* if there is no link, we're at "next" request and need to drain */
2192 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2193 ctx->drain_next = false;
2194 ctx->drain_active = true;
2195 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2196 }
2197 }
2198
2199 if (!def->ioprio && sqe->ioprio)
2200 return io_init_fail_req(req, -EINVAL);
2201 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2202 return io_init_fail_req(req, -EINVAL);
2203
2204 if (def->needs_file) {
2205 struct io_submit_state *state = &ctx->submit_state;
2206
2207 req->cqe.fd = READ_ONCE(sqe->fd);
2208
2209 /*
2210 * Plug now if we have more than 2 IO left after this, and the
2211 * target is potentially a read/write to block based storage.
2212 */
2213 if (state->need_plug && def->plug) {
2214 state->plug_started = true;
2215 state->need_plug = false;
2216 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2217 }
2218 }
2219
2220 personality = READ_ONCE(sqe->personality);
2221 if (personality) {
2222 int ret;
2223
2224 req->creds = xa_load(&ctx->personalities, personality);
2225 if (!req->creds)
2226 return io_init_fail_req(req, -EINVAL);
2227 get_cred(req->creds);
2228 ret = security_uring_override_creds(req->creds);
2229 if (ret) {
2230 put_cred(req->creds);
2231 return io_init_fail_req(req, ret);
2232 }
2233 req->flags |= REQ_F_CREDS;
2234 }
2235
2236 return def->prep(req, sqe);
2237 }
2238
io_submit_fail_init(const struct io_uring_sqe * sqe,struct io_kiocb * req,int ret)2239 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2240 struct io_kiocb *req, int ret)
2241 {
2242 struct io_ring_ctx *ctx = req->ctx;
2243 struct io_submit_link *link = &ctx->submit_state.link;
2244 struct io_kiocb *head = link->head;
2245
2246 trace_io_uring_req_failed(sqe, req, ret);
2247
2248 /*
2249 * Avoid breaking links in the middle as it renders links with SQPOLL
2250 * unusable. Instead of failing eagerly, continue assembling the link if
2251 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2252 * should find the flag and handle the rest.
2253 */
2254 req_fail_link_node(req, ret);
2255 if (head && !(head->flags & REQ_F_FAIL))
2256 req_fail_link_node(head, -ECANCELED);
2257
2258 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2259 if (head) {
2260 link->last->link = req;
2261 link->head = NULL;
2262 req = head;
2263 }
2264 io_queue_sqe_fallback(req);
2265 return ret;
2266 }
2267
2268 if (head)
2269 link->last->link = req;
2270 else
2271 link->head = req;
2272 link->last = req;
2273 return 0;
2274 }
2275
io_submit_sqe(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2276 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2277 const struct io_uring_sqe *sqe)
2278 __must_hold(&ctx->uring_lock)
2279 {
2280 struct io_submit_link *link = &ctx->submit_state.link;
2281 int ret;
2282
2283 ret = io_init_req(ctx, req, sqe);
2284 if (unlikely(ret))
2285 return io_submit_fail_init(sqe, req, ret);
2286
2287 trace_io_uring_submit_req(req);
2288
2289 /*
2290 * If we already have a head request, queue this one for async
2291 * submittal once the head completes. If we don't have a head but
2292 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2293 * submitted sync once the chain is complete. If none of those
2294 * conditions are true (normal request), then just queue it.
2295 */
2296 if (unlikely(link->head)) {
2297 ret = io_req_prep_async(req);
2298 if (unlikely(ret))
2299 return io_submit_fail_init(sqe, req, ret);
2300
2301 trace_io_uring_link(req, link->head);
2302 link->last->link = req;
2303 link->last = req;
2304
2305 if (req->flags & IO_REQ_LINK_FLAGS)
2306 return 0;
2307 /* last request of the link, flush it */
2308 req = link->head;
2309 link->head = NULL;
2310 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2311 goto fallback;
2312
2313 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2314 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2315 if (req->flags & IO_REQ_LINK_FLAGS) {
2316 link->head = req;
2317 link->last = req;
2318 } else {
2319 fallback:
2320 io_queue_sqe_fallback(req);
2321 }
2322 return 0;
2323 }
2324
2325 io_queue_sqe(req);
2326 return 0;
2327 }
2328
2329 /*
2330 * Batched submission is done, ensure local IO is flushed out.
2331 */
io_submit_state_end(struct io_ring_ctx * ctx)2332 static void io_submit_state_end(struct io_ring_ctx *ctx)
2333 {
2334 struct io_submit_state *state = &ctx->submit_state;
2335
2336 if (unlikely(state->link.head))
2337 io_queue_sqe_fallback(state->link.head);
2338 /* flush only after queuing links as they can generate completions */
2339 io_submit_flush_completions(ctx);
2340 if (state->plug_started)
2341 blk_finish_plug(&state->plug);
2342 }
2343
2344 /*
2345 * Start submission side cache.
2346 */
io_submit_state_start(struct io_submit_state * state,unsigned int max_ios)2347 static void io_submit_state_start(struct io_submit_state *state,
2348 unsigned int max_ios)
2349 {
2350 state->plug_started = false;
2351 state->need_plug = max_ios > 2;
2352 state->submit_nr = max_ios;
2353 /* set only head, no need to init link_last in advance */
2354 state->link.head = NULL;
2355 }
2356
io_commit_sqring(struct io_ring_ctx * ctx)2357 static void io_commit_sqring(struct io_ring_ctx *ctx)
2358 {
2359 struct io_rings *rings = ctx->rings;
2360
2361 /*
2362 * Ensure any loads from the SQEs are done at this point,
2363 * since once we write the new head, the application could
2364 * write new data to them.
2365 */
2366 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2367 }
2368
2369 /*
2370 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2371 * that is mapped by userspace. This means that care needs to be taken to
2372 * ensure that reads are stable, as we cannot rely on userspace always
2373 * being a good citizen. If members of the sqe are validated and then later
2374 * used, it's important that those reads are done through READ_ONCE() to
2375 * prevent a re-load down the line.
2376 */
io_get_sqe(struct io_ring_ctx * ctx,const struct io_uring_sqe ** sqe)2377 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2378 {
2379 unsigned mask = ctx->sq_entries - 1;
2380 unsigned head = ctx->cached_sq_head++ & mask;
2381
2382 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
2383 head = READ_ONCE(ctx->sq_array[head]);
2384 if (unlikely(head >= ctx->sq_entries)) {
2385 /* drop invalid entries */
2386 spin_lock(&ctx->completion_lock);
2387 ctx->cq_extra--;
2388 spin_unlock(&ctx->completion_lock);
2389 WRITE_ONCE(ctx->rings->sq_dropped,
2390 READ_ONCE(ctx->rings->sq_dropped) + 1);
2391 return false;
2392 }
2393 }
2394
2395 /*
2396 * The cached sq head (or cq tail) serves two purposes:
2397 *
2398 * 1) allows us to batch the cost of updating the user visible
2399 * head updates.
2400 * 2) allows the kernel side to track the head on its own, even
2401 * though the application is the one updating it.
2402 */
2403
2404 /* double index for 128-byte SQEs, twice as long */
2405 if (ctx->flags & IORING_SETUP_SQE128)
2406 head <<= 1;
2407 *sqe = &ctx->sq_sqes[head];
2408 return true;
2409 }
2410
io_submit_sqes(struct io_ring_ctx * ctx,unsigned int nr)2411 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2412 __must_hold(&ctx->uring_lock)
2413 {
2414 unsigned int entries = io_sqring_entries(ctx);
2415 unsigned int left;
2416 int ret;
2417
2418 if (unlikely(!entries))
2419 return 0;
2420 /* make sure SQ entry isn't read before tail */
2421 ret = left = min(nr, entries);
2422 io_get_task_refs(left);
2423 io_submit_state_start(&ctx->submit_state, left);
2424
2425 do {
2426 const struct io_uring_sqe *sqe;
2427 struct io_kiocb *req;
2428
2429 if (unlikely(!io_alloc_req(ctx, &req)))
2430 break;
2431 if (unlikely(!io_get_sqe(ctx, &sqe))) {
2432 io_req_add_to_cache(req, ctx);
2433 break;
2434 }
2435
2436 /*
2437 * Continue submitting even for sqe failure if the
2438 * ring was setup with IORING_SETUP_SUBMIT_ALL
2439 */
2440 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2441 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2442 left--;
2443 break;
2444 }
2445 } while (--left);
2446
2447 if (unlikely(left)) {
2448 ret -= left;
2449 /* try again if it submitted nothing and can't allocate a req */
2450 if (!ret && io_req_cache_empty(ctx))
2451 ret = -EAGAIN;
2452 current->io_uring->cached_refs += left;
2453 }
2454
2455 io_submit_state_end(ctx);
2456 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2457 io_commit_sqring(ctx);
2458 return ret;
2459 }
2460
2461 struct io_wait_queue {
2462 struct wait_queue_entry wq;
2463 struct io_ring_ctx *ctx;
2464 unsigned cq_tail;
2465 unsigned nr_timeouts;
2466 ktime_t timeout;
2467 };
2468
io_has_work(struct io_ring_ctx * ctx)2469 static inline bool io_has_work(struct io_ring_ctx *ctx)
2470 {
2471 return test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq) ||
2472 !llist_empty(&ctx->work_llist);
2473 }
2474
io_should_wake(struct io_wait_queue * iowq)2475 static inline bool io_should_wake(struct io_wait_queue *iowq)
2476 {
2477 struct io_ring_ctx *ctx = iowq->ctx;
2478 int dist = READ_ONCE(ctx->rings->cq.tail) - (int) iowq->cq_tail;
2479
2480 /*
2481 * Wake up if we have enough events, or if a timeout occurred since we
2482 * started waiting. For timeouts, we always want to return to userspace,
2483 * regardless of event count.
2484 */
2485 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2486 }
2487
io_wake_function(struct wait_queue_entry * curr,unsigned int mode,int wake_flags,void * key)2488 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2489 int wake_flags, void *key)
2490 {
2491 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2492
2493 /*
2494 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2495 * the task, and the next invocation will do it.
2496 */
2497 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2498 return autoremove_wake_function(curr, mode, wake_flags, key);
2499 return -1;
2500 }
2501
io_run_task_work_sig(struct io_ring_ctx * ctx)2502 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2503 {
2504 if (!llist_empty(&ctx->work_llist)) {
2505 __set_current_state(TASK_RUNNING);
2506 if (io_run_local_work(ctx, INT_MAX) > 0)
2507 return 0;
2508 }
2509 if (io_run_task_work() > 0)
2510 return 0;
2511 if (task_sigpending(current))
2512 return -EINTR;
2513 return 0;
2514 }
2515
current_pending_io(void)2516 static bool current_pending_io(void)
2517 {
2518 struct io_uring_task *tctx = current->io_uring;
2519
2520 if (!tctx)
2521 return false;
2522 return percpu_counter_read_positive(&tctx->inflight);
2523 }
2524
2525 /* when returns >0, the caller should retry */
io_cqring_wait_schedule(struct io_ring_ctx * ctx,struct io_wait_queue * iowq)2526 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2527 struct io_wait_queue *iowq)
2528 {
2529 int ret;
2530
2531 if (unlikely(READ_ONCE(ctx->check_cq)))
2532 return 1;
2533 if (unlikely(!llist_empty(&ctx->work_llist)))
2534 return 1;
2535 if (unlikely(task_work_pending(current)))
2536 return 1;
2537 if (unlikely(task_sigpending(current)))
2538 return -EINTR;
2539 if (unlikely(io_should_wake(iowq)))
2540 return 0;
2541
2542 /*
2543 * Mark us as being in io_wait if we have pending requests, so cpufreq
2544 * can take into account that the task is waiting for IO - turns out
2545 * to be important for low QD IO.
2546 */
2547 if (current_pending_io())
2548 current->in_iowait = 1;
2549 ret = 0;
2550 if (iowq->timeout == KTIME_MAX)
2551 schedule();
2552 else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS))
2553 ret = -ETIME;
2554 current->in_iowait = 0;
2555 return ret;
2556 }
2557
2558 /*
2559 * Wait until events become available, if we don't already have some. The
2560 * application must reap them itself, as they reside on the shared cq ring.
2561 */
io_cqring_wait(struct io_ring_ctx * ctx,int min_events,const sigset_t __user * sig,size_t sigsz,struct __kernel_timespec __user * uts)2562 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2563 const sigset_t __user *sig, size_t sigsz,
2564 struct __kernel_timespec __user *uts)
2565 {
2566 struct io_wait_queue iowq;
2567 struct io_rings *rings = ctx->rings;
2568 int ret;
2569
2570 if (!io_allowed_run_tw(ctx))
2571 return -EEXIST;
2572 if (!llist_empty(&ctx->work_llist))
2573 io_run_local_work(ctx, min_events);
2574 io_run_task_work();
2575 io_cqring_overflow_flush(ctx);
2576 /* if user messes with these they will just get an early return */
2577 if (__io_cqring_events_user(ctx) >= min_events)
2578 return 0;
2579
2580 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2581 iowq.wq.private = current;
2582 INIT_LIST_HEAD(&iowq.wq.entry);
2583 iowq.ctx = ctx;
2584 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2585 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2586 iowq.timeout = KTIME_MAX;
2587
2588 if (uts) {
2589 struct timespec64 ts;
2590
2591 if (get_timespec64(&ts, uts))
2592 return -EFAULT;
2593 iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2594 }
2595
2596 if (sig) {
2597 #ifdef CONFIG_COMPAT
2598 if (in_compat_syscall())
2599 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2600 sigsz);
2601 else
2602 #endif
2603 ret = set_user_sigmask(sig, sigsz);
2604
2605 if (ret)
2606 return ret;
2607 }
2608
2609 trace_io_uring_cqring_wait(ctx, min_events);
2610 do {
2611 int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail);
2612 unsigned long check_cq;
2613
2614 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2615 atomic_set(&ctx->cq_wait_nr, nr_wait);
2616 set_current_state(TASK_INTERRUPTIBLE);
2617 } else {
2618 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2619 TASK_INTERRUPTIBLE);
2620 }
2621
2622 ret = io_cqring_wait_schedule(ctx, &iowq);
2623 __set_current_state(TASK_RUNNING);
2624 atomic_set(&ctx->cq_wait_nr, 0);
2625
2626 /*
2627 * Run task_work after scheduling and before io_should_wake().
2628 * If we got woken because of task_work being processed, run it
2629 * now rather than let the caller do another wait loop.
2630 */
2631 if (!llist_empty(&ctx->work_llist))
2632 io_run_local_work(ctx, nr_wait);
2633 io_run_task_work();
2634
2635 /*
2636 * Non-local task_work will be run on exit to userspace, but
2637 * if we're using DEFER_TASKRUN, then we could have waited
2638 * with a timeout for a number of requests. If the timeout
2639 * hits, we could have some requests ready to process. Ensure
2640 * this break is _after_ we have run task_work, to avoid
2641 * deferring running potentially pending requests until the
2642 * next time we wait for events.
2643 */
2644 if (ret < 0)
2645 break;
2646
2647 check_cq = READ_ONCE(ctx->check_cq);
2648 if (unlikely(check_cq)) {
2649 /* let the caller flush overflows, retry */
2650 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2651 io_cqring_do_overflow_flush(ctx);
2652 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2653 ret = -EBADR;
2654 break;
2655 }
2656 }
2657
2658 if (io_should_wake(&iowq)) {
2659 ret = 0;
2660 break;
2661 }
2662 cond_resched();
2663 } while (1);
2664
2665 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2666 finish_wait(&ctx->cq_wait, &iowq.wq);
2667 restore_saved_sigmask_unless(ret == -EINTR);
2668
2669 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2670 }
2671
io_mem_free(void * ptr)2672 void io_mem_free(void *ptr)
2673 {
2674 if (!ptr)
2675 return;
2676
2677 folio_put(virt_to_folio(ptr));
2678 }
2679
io_pages_free(struct page *** pages,int npages)2680 static void io_pages_free(struct page ***pages, int npages)
2681 {
2682 struct page **page_array;
2683 int i;
2684
2685 if (!pages)
2686 return;
2687
2688 page_array = *pages;
2689 if (!page_array)
2690 return;
2691
2692 for (i = 0; i < npages; i++)
2693 unpin_user_page(page_array[i]);
2694 kvfree(page_array);
2695 *pages = NULL;
2696 }
2697
__io_uaddr_map(struct page *** pages,unsigned short * npages,unsigned long uaddr,size_t size)2698 static void *__io_uaddr_map(struct page ***pages, unsigned short *npages,
2699 unsigned long uaddr, size_t size)
2700 {
2701 struct page **page_array;
2702 unsigned int nr_pages;
2703 void *page_addr;
2704 int ret, i, pinned;
2705
2706 *npages = 0;
2707
2708 if (uaddr & (PAGE_SIZE - 1) || !size)
2709 return ERR_PTR(-EINVAL);
2710
2711 nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2712 if (nr_pages > USHRT_MAX)
2713 return ERR_PTR(-EINVAL);
2714 page_array = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
2715 if (!page_array)
2716 return ERR_PTR(-ENOMEM);
2717
2718
2719 pinned = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
2720 page_array);
2721 if (pinned != nr_pages) {
2722 ret = (pinned < 0) ? pinned : -EFAULT;
2723 goto free_pages;
2724 }
2725
2726 page_addr = page_address(page_array[0]);
2727 for (i = 0; i < nr_pages; i++) {
2728 ret = -EINVAL;
2729
2730 /*
2731 * Can't support mapping user allocated ring memory on 32-bit
2732 * archs where it could potentially reside in highmem. Just
2733 * fail those with -EINVAL, just like we did on kernels that
2734 * didn't support this feature.
2735 */
2736 if (PageHighMem(page_array[i]))
2737 goto free_pages;
2738
2739 /*
2740 * No support for discontig pages for now, should either be a
2741 * single normal page, or a huge page. Later on we can add
2742 * support for remapping discontig pages, for now we will
2743 * just fail them with EINVAL.
2744 */
2745 if (page_address(page_array[i]) != page_addr)
2746 goto free_pages;
2747 page_addr += PAGE_SIZE;
2748 }
2749
2750 *pages = page_array;
2751 *npages = nr_pages;
2752 return page_to_virt(page_array[0]);
2753
2754 free_pages:
2755 io_pages_free(&page_array, pinned > 0 ? pinned : 0);
2756 return ERR_PTR(ret);
2757 }
2758
io_rings_map(struct io_ring_ctx * ctx,unsigned long uaddr,size_t size)2759 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2760 size_t size)
2761 {
2762 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2763 size);
2764 }
2765
io_sqes_map(struct io_ring_ctx * ctx,unsigned long uaddr,size_t size)2766 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2767 size_t size)
2768 {
2769 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2770 size);
2771 }
2772
io_rings_free(struct io_ring_ctx * ctx)2773 static void io_rings_free(struct io_ring_ctx *ctx)
2774 {
2775 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2776 io_mem_free(ctx->rings);
2777 io_mem_free(ctx->sq_sqes);
2778 } else {
2779 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
2780 ctx->n_ring_pages = 0;
2781 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
2782 ctx->n_sqe_pages = 0;
2783 }
2784
2785 ctx->rings = NULL;
2786 ctx->sq_sqes = NULL;
2787 }
2788
io_mem_alloc(size_t size)2789 void *io_mem_alloc(size_t size)
2790 {
2791 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2792 void *ret;
2793
2794 ret = (void *) __get_free_pages(gfp, get_order(size));
2795 if (ret)
2796 return ret;
2797 return ERR_PTR(-ENOMEM);
2798 }
2799
rings_size(struct io_ring_ctx * ctx,unsigned int sq_entries,unsigned int cq_entries,size_t * sq_offset)2800 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2801 unsigned int cq_entries, size_t *sq_offset)
2802 {
2803 struct io_rings *rings;
2804 size_t off, sq_array_size;
2805
2806 off = struct_size(rings, cqes, cq_entries);
2807 if (off == SIZE_MAX)
2808 return SIZE_MAX;
2809 if (ctx->flags & IORING_SETUP_CQE32) {
2810 if (check_shl_overflow(off, 1, &off))
2811 return SIZE_MAX;
2812 }
2813
2814 #ifdef CONFIG_SMP
2815 off = ALIGN(off, SMP_CACHE_BYTES);
2816 if (off == 0)
2817 return SIZE_MAX;
2818 #endif
2819
2820 if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
2821 if (sq_offset)
2822 *sq_offset = SIZE_MAX;
2823 return off;
2824 }
2825
2826 if (sq_offset)
2827 *sq_offset = off;
2828
2829 sq_array_size = array_size(sizeof(u32), sq_entries);
2830 if (sq_array_size == SIZE_MAX)
2831 return SIZE_MAX;
2832
2833 if (check_add_overflow(off, sq_array_size, &off))
2834 return SIZE_MAX;
2835
2836 return off;
2837 }
2838
io_eventfd_register(struct io_ring_ctx * ctx,void __user * arg,unsigned int eventfd_async)2839 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
2840 unsigned int eventfd_async)
2841 {
2842 struct io_ev_fd *ev_fd;
2843 __s32 __user *fds = arg;
2844 int fd;
2845
2846 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2847 lockdep_is_held(&ctx->uring_lock));
2848 if (ev_fd)
2849 return -EBUSY;
2850
2851 if (copy_from_user(&fd, fds, sizeof(*fds)))
2852 return -EFAULT;
2853
2854 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
2855 if (!ev_fd)
2856 return -ENOMEM;
2857
2858 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
2859 if (IS_ERR(ev_fd->cq_ev_fd)) {
2860 int ret = PTR_ERR(ev_fd->cq_ev_fd);
2861 kfree(ev_fd);
2862 return ret;
2863 }
2864
2865 spin_lock(&ctx->completion_lock);
2866 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
2867 spin_unlock(&ctx->completion_lock);
2868
2869 ev_fd->eventfd_async = eventfd_async;
2870 ctx->has_evfd = true;
2871 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
2872 atomic_set(&ev_fd->refs, 1);
2873 atomic_set(&ev_fd->ops, 0);
2874 return 0;
2875 }
2876
io_eventfd_unregister(struct io_ring_ctx * ctx)2877 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2878 {
2879 struct io_ev_fd *ev_fd;
2880
2881 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2882 lockdep_is_held(&ctx->uring_lock));
2883 if (ev_fd) {
2884 ctx->has_evfd = false;
2885 rcu_assign_pointer(ctx->io_ev_fd, NULL);
2886 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_FREE_BIT), &ev_fd->ops))
2887 call_rcu(&ev_fd->rcu, io_eventfd_ops);
2888 return 0;
2889 }
2890
2891 return -ENXIO;
2892 }
2893
io_req_caches_free(struct io_ring_ctx * ctx)2894 static void io_req_caches_free(struct io_ring_ctx *ctx)
2895 {
2896 struct io_kiocb *req;
2897 int nr = 0;
2898
2899 mutex_lock(&ctx->uring_lock);
2900 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2901
2902 while (!io_req_cache_empty(ctx)) {
2903 req = io_extract_req(ctx);
2904 kmem_cache_free(req_cachep, req);
2905 nr++;
2906 }
2907 if (nr)
2908 percpu_ref_put_many(&ctx->refs, nr);
2909 mutex_unlock(&ctx->uring_lock);
2910 }
2911
io_rsrc_node_cache_free(struct io_cache_entry * entry)2912 static void io_rsrc_node_cache_free(struct io_cache_entry *entry)
2913 {
2914 kfree(container_of(entry, struct io_rsrc_node, cache));
2915 }
2916
io_ring_ctx_free(struct io_ring_ctx * ctx)2917 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2918 {
2919 io_sq_thread_finish(ctx);
2920 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
2921 if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
2922 return;
2923
2924 mutex_lock(&ctx->uring_lock);
2925 if (ctx->buf_data)
2926 __io_sqe_buffers_unregister(ctx);
2927 if (ctx->file_data)
2928 __io_sqe_files_unregister(ctx);
2929 io_cqring_overflow_kill(ctx);
2930 io_eventfd_unregister(ctx);
2931 io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free);
2932 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
2933 io_destroy_buffers(ctx);
2934 mutex_unlock(&ctx->uring_lock);
2935 if (ctx->sq_creds)
2936 put_cred(ctx->sq_creds);
2937 if (ctx->submitter_task)
2938 put_task_struct(ctx->submitter_task);
2939
2940 /* there are no registered resources left, nobody uses it */
2941 if (ctx->rsrc_node)
2942 io_rsrc_node_destroy(ctx, ctx->rsrc_node);
2943
2944 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
2945 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2946
2947 io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free);
2948 if (ctx->mm_account) {
2949 mmdrop(ctx->mm_account);
2950 ctx->mm_account = NULL;
2951 }
2952 io_rings_free(ctx);
2953 io_kbuf_mmap_list_free(ctx);
2954
2955 percpu_ref_exit(&ctx->refs);
2956 free_uid(ctx->user);
2957 io_req_caches_free(ctx);
2958 if (ctx->hash_map)
2959 io_wq_put_hash(ctx->hash_map);
2960 kfree(ctx->cancel_table.hbs);
2961 kfree(ctx->cancel_table_locked.hbs);
2962 xa_destroy(&ctx->io_bl_xa);
2963 kfree(ctx);
2964 }
2965
io_activate_pollwq_cb(struct callback_head * cb)2966 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2967 {
2968 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2969 poll_wq_task_work);
2970
2971 mutex_lock(&ctx->uring_lock);
2972 ctx->poll_activated = true;
2973 mutex_unlock(&ctx->uring_lock);
2974
2975 /*
2976 * Wake ups for some events between start of polling and activation
2977 * might've been lost due to loose synchronisation.
2978 */
2979 wake_up_all(&ctx->poll_wq);
2980 percpu_ref_put(&ctx->refs);
2981 }
2982
io_activate_pollwq(struct io_ring_ctx * ctx)2983 static __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2984 {
2985 spin_lock(&ctx->completion_lock);
2986 /* already activated or in progress */
2987 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2988 goto out;
2989 if (WARN_ON_ONCE(!ctx->task_complete))
2990 goto out;
2991 if (!ctx->submitter_task)
2992 goto out;
2993 /*
2994 * with ->submitter_task only the submitter task completes requests, we
2995 * only need to sync with it, which is done by injecting a tw
2996 */
2997 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2998 percpu_ref_get(&ctx->refs);
2999 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
3000 percpu_ref_put(&ctx->refs);
3001 out:
3002 spin_unlock(&ctx->completion_lock);
3003 }
3004
io_uring_poll(struct file * file,poll_table * wait)3005 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3006 {
3007 struct io_ring_ctx *ctx = file->private_data;
3008 __poll_t mask = 0;
3009
3010 if (unlikely(!ctx->poll_activated))
3011 io_activate_pollwq(ctx);
3012
3013 poll_wait(file, &ctx->poll_wq, wait);
3014 /*
3015 * synchronizes with barrier from wq_has_sleeper call in
3016 * io_commit_cqring
3017 */
3018 smp_rmb();
3019 if (!io_sqring_full(ctx))
3020 mask |= EPOLLOUT | EPOLLWRNORM;
3021
3022 /*
3023 * Don't flush cqring overflow list here, just do a simple check.
3024 * Otherwise there could possible be ABBA deadlock:
3025 * CPU0 CPU1
3026 * ---- ----
3027 * lock(&ctx->uring_lock);
3028 * lock(&ep->mtx);
3029 * lock(&ctx->uring_lock);
3030 * lock(&ep->mtx);
3031 *
3032 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
3033 * pushes them to do the flush.
3034 */
3035
3036 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
3037 mask |= EPOLLIN | EPOLLRDNORM;
3038
3039 return mask;
3040 }
3041
io_unregister_personality(struct io_ring_ctx * ctx,unsigned id)3042 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
3043 {
3044 const struct cred *creds;
3045
3046 creds = xa_erase(&ctx->personalities, id);
3047 if (creds) {
3048 put_cred(creds);
3049 return 0;
3050 }
3051
3052 return -EINVAL;
3053 }
3054
3055 struct io_tctx_exit {
3056 struct callback_head task_work;
3057 struct completion completion;
3058 struct io_ring_ctx *ctx;
3059 };
3060
io_tctx_exit_cb(struct callback_head * cb)3061 static __cold void io_tctx_exit_cb(struct callback_head *cb)
3062 {
3063 struct io_uring_task *tctx = current->io_uring;
3064 struct io_tctx_exit *work;
3065
3066 work = container_of(cb, struct io_tctx_exit, task_work);
3067 /*
3068 * When @in_cancel, we're in cancellation and it's racy to remove the
3069 * node. It'll be removed by the end of cancellation, just ignore it.
3070 * tctx can be NULL if the queueing of this task_work raced with
3071 * work cancelation off the exec path.
3072 */
3073 if (tctx && !atomic_read(&tctx->in_cancel))
3074 io_uring_del_tctx_node((unsigned long)work->ctx);
3075 complete(&work->completion);
3076 }
3077
io_cancel_ctx_cb(struct io_wq_work * work,void * data)3078 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
3079 {
3080 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3081
3082 return req->ctx == data;
3083 }
3084
io_ring_exit_work(struct work_struct * work)3085 static __cold void io_ring_exit_work(struct work_struct *work)
3086 {
3087 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
3088 unsigned long timeout = jiffies + HZ * 60 * 5;
3089 unsigned long interval = HZ / 20;
3090 struct io_tctx_exit exit;
3091 struct io_tctx_node *node;
3092 int ret;
3093
3094 /*
3095 * If we're doing polled IO and end up having requests being
3096 * submitted async (out-of-line), then completions can come in while
3097 * we're waiting for refs to drop. We need to reap these manually,
3098 * as nobody else will be looking for them.
3099 */
3100 do {
3101 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
3102 mutex_lock(&ctx->uring_lock);
3103 io_cqring_overflow_kill(ctx);
3104 mutex_unlock(&ctx->uring_lock);
3105 }
3106
3107 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3108 io_move_task_work_from_local(ctx);
3109
3110 while (io_uring_try_cancel_requests(ctx, NULL, true))
3111 cond_resched();
3112
3113 if (ctx->sq_data) {
3114 struct io_sq_data *sqd = ctx->sq_data;
3115 struct task_struct *tsk;
3116
3117 io_sq_thread_park(sqd);
3118 tsk = sqd->thread;
3119 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
3120 io_wq_cancel_cb(tsk->io_uring->io_wq,
3121 io_cancel_ctx_cb, ctx, true);
3122 io_sq_thread_unpark(sqd);
3123 }
3124
3125 io_req_caches_free(ctx);
3126
3127 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
3128 /* there is little hope left, don't run it too often */
3129 interval = HZ * 60;
3130 }
3131 /*
3132 * This is really an uninterruptible wait, as it has to be
3133 * complete. But it's also run from a kworker, which doesn't
3134 * take signals, so it's fine to make it interruptible. This
3135 * avoids scenarios where we knowingly can wait much longer
3136 * on completions, for example if someone does a SIGSTOP on
3137 * a task that needs to finish task_work to make this loop
3138 * complete. That's a synthetic situation that should not
3139 * cause a stuck task backtrace, and hence a potential panic
3140 * on stuck tasks if that is enabled.
3141 */
3142 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
3143
3144 init_completion(&exit.completion);
3145 init_task_work(&exit.task_work, io_tctx_exit_cb);
3146 exit.ctx = ctx;
3147
3148 mutex_lock(&ctx->uring_lock);
3149 while (!list_empty(&ctx->tctx_list)) {
3150 WARN_ON_ONCE(time_after(jiffies, timeout));
3151
3152 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
3153 ctx_node);
3154 /* don't spin on a single task if cancellation failed */
3155 list_rotate_left(&ctx->tctx_list);
3156 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
3157 if (WARN_ON_ONCE(ret))
3158 continue;
3159
3160 mutex_unlock(&ctx->uring_lock);
3161 /*
3162 * See comment above for
3163 * wait_for_completion_interruptible_timeout() on why this
3164 * wait is marked as interruptible.
3165 */
3166 wait_for_completion_interruptible(&exit.completion);
3167 mutex_lock(&ctx->uring_lock);
3168 }
3169 mutex_unlock(&ctx->uring_lock);
3170 spin_lock(&ctx->completion_lock);
3171 spin_unlock(&ctx->completion_lock);
3172
3173 /* pairs with RCU read section in io_req_local_work_add() */
3174 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3175 synchronize_rcu();
3176
3177 io_ring_ctx_free(ctx);
3178 }
3179
io_ring_ctx_wait_and_kill(struct io_ring_ctx * ctx)3180 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3181 {
3182 unsigned long index;
3183 struct creds *creds;
3184
3185 mutex_lock(&ctx->uring_lock);
3186 percpu_ref_kill(&ctx->refs);
3187 xa_for_each(&ctx->personalities, index, creds)
3188 io_unregister_personality(ctx, index);
3189 if (ctx->rings)
3190 io_poll_remove_all(ctx, NULL, true);
3191 mutex_unlock(&ctx->uring_lock);
3192
3193 /*
3194 * If we failed setting up the ctx, we might not have any rings
3195 * and therefore did not submit any requests
3196 */
3197 if (ctx->rings)
3198 io_kill_timeouts(ctx, NULL, true);
3199
3200 flush_delayed_work(&ctx->fallback_work);
3201
3202 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
3203 /*
3204 * Use system_unbound_wq to avoid spawning tons of event kworkers
3205 * if we're exiting a ton of rings at the same time. It just adds
3206 * noise and overhead, there's no discernable change in runtime
3207 * over using system_wq.
3208 */
3209 queue_work(iou_wq, &ctx->exit_work);
3210 }
3211
io_uring_release(struct inode * inode,struct file * file)3212 static int io_uring_release(struct inode *inode, struct file *file)
3213 {
3214 struct io_ring_ctx *ctx = file->private_data;
3215
3216 file->private_data = NULL;
3217 io_ring_ctx_wait_and_kill(ctx);
3218 return 0;
3219 }
3220
3221 struct io_task_cancel {
3222 struct task_struct *task;
3223 bool all;
3224 };
3225
io_cancel_task_cb(struct io_wq_work * work,void * data)3226 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3227 {
3228 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3229 struct io_task_cancel *cancel = data;
3230
3231 return io_match_task_safe(req, cancel->task, cancel->all);
3232 }
3233
io_cancel_defer_files(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)3234 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3235 struct task_struct *task,
3236 bool cancel_all)
3237 {
3238 struct io_defer_entry *de;
3239 LIST_HEAD(list);
3240
3241 spin_lock(&ctx->completion_lock);
3242 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
3243 if (io_match_task_safe(de->req, task, cancel_all)) {
3244 list_cut_position(&list, &ctx->defer_list, &de->list);
3245 break;
3246 }
3247 }
3248 spin_unlock(&ctx->completion_lock);
3249 if (list_empty(&list))
3250 return false;
3251
3252 while (!list_empty(&list)) {
3253 de = list_first_entry(&list, struct io_defer_entry, list);
3254 list_del_init(&de->list);
3255 io_req_task_queue_fail(de->req, -ECANCELED);
3256 kfree(de);
3257 }
3258 return true;
3259 }
3260
io_uring_try_cancel_iowq(struct io_ring_ctx * ctx)3261 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3262 {
3263 struct io_tctx_node *node;
3264 enum io_wq_cancel cret;
3265 bool ret = false;
3266
3267 mutex_lock(&ctx->uring_lock);
3268 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3269 struct io_uring_task *tctx = node->task->io_uring;
3270
3271 /*
3272 * io_wq will stay alive while we hold uring_lock, because it's
3273 * killed after ctx nodes, which requires to take the lock.
3274 */
3275 if (!tctx || !tctx->io_wq)
3276 continue;
3277 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3278 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3279 }
3280 mutex_unlock(&ctx->uring_lock);
3281
3282 return ret;
3283 }
3284
io_uring_try_cancel_requests(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)3285 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3286 struct task_struct *task,
3287 bool cancel_all)
3288 {
3289 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
3290 struct io_uring_task *tctx = task ? task->io_uring : NULL;
3291 enum io_wq_cancel cret;
3292 bool ret = false;
3293
3294 /* set it so io_req_local_work_add() would wake us up */
3295 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3296 atomic_set(&ctx->cq_wait_nr, 1);
3297 smp_mb();
3298 }
3299
3300 /* failed during ring init, it couldn't have issued any requests */
3301 if (!ctx->rings)
3302 return false;
3303
3304 if (!task) {
3305 ret |= io_uring_try_cancel_iowq(ctx);
3306 } else if (tctx && tctx->io_wq) {
3307 /*
3308 * Cancels requests of all rings, not only @ctx, but
3309 * it's fine as the task is in exit/exec.
3310 */
3311 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3312 &cancel, true);
3313 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3314 }
3315
3316 /* SQPOLL thread does its own polling */
3317 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3318 (ctx->sq_data && ctx->sq_data->thread == current)) {
3319 while (!wq_list_empty(&ctx->iopoll_list)) {
3320 io_iopoll_try_reap_events(ctx);
3321 ret = true;
3322 cond_resched();
3323 }
3324 }
3325
3326 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3327 io_allowed_defer_tw_run(ctx))
3328 ret |= io_run_local_work(ctx, INT_MAX) > 0;
3329 ret |= io_cancel_defer_files(ctx, task, cancel_all);
3330 mutex_lock(&ctx->uring_lock);
3331 ret |= io_poll_remove_all(ctx, task, cancel_all);
3332 mutex_unlock(&ctx->uring_lock);
3333 ret |= io_kill_timeouts(ctx, task, cancel_all);
3334 if (task)
3335 ret |= io_run_task_work() > 0;
3336 return ret;
3337 }
3338
tctx_inflight(struct io_uring_task * tctx,bool tracked)3339 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3340 {
3341 if (tracked)
3342 return atomic_read(&tctx->inflight_tracked);
3343 return percpu_counter_sum(&tctx->inflight);
3344 }
3345
3346 /*
3347 * Find any io_uring ctx that this task has registered or done IO on, and cancel
3348 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3349 */
io_uring_cancel_generic(bool cancel_all,struct io_sq_data * sqd)3350 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3351 {
3352 struct io_uring_task *tctx = current->io_uring;
3353 struct io_ring_ctx *ctx;
3354 struct io_tctx_node *node;
3355 unsigned long index;
3356 s64 inflight;
3357 DEFINE_WAIT(wait);
3358
3359 WARN_ON_ONCE(sqd && sqd->thread != current);
3360
3361 if (!current->io_uring)
3362 return;
3363 if (tctx->io_wq)
3364 io_wq_exit_start(tctx->io_wq);
3365
3366 atomic_inc(&tctx->in_cancel);
3367 do {
3368 bool loop = false;
3369
3370 io_uring_drop_tctx_refs(current);
3371 if (!tctx_inflight(tctx, !cancel_all))
3372 break;
3373
3374 /* read completions before cancelations */
3375 inflight = tctx_inflight(tctx, false);
3376 if (!inflight)
3377 break;
3378
3379 if (!sqd) {
3380 xa_for_each(&tctx->xa, index, node) {
3381 /* sqpoll task will cancel all its requests */
3382 if (node->ctx->sq_data)
3383 continue;
3384 loop |= io_uring_try_cancel_requests(node->ctx,
3385 current, cancel_all);
3386 }
3387 } else {
3388 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3389 loop |= io_uring_try_cancel_requests(ctx,
3390 current,
3391 cancel_all);
3392 }
3393
3394 if (loop) {
3395 cond_resched();
3396 continue;
3397 }
3398
3399 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3400 io_run_task_work();
3401 io_uring_drop_tctx_refs(current);
3402 xa_for_each(&tctx->xa, index, node) {
3403 if (!llist_empty(&node->ctx->work_llist)) {
3404 WARN_ON_ONCE(node->ctx->submitter_task &&
3405 node->ctx->submitter_task != current);
3406 goto end_wait;
3407 }
3408 }
3409 /*
3410 * If we've seen completions, retry without waiting. This
3411 * avoids a race where a completion comes in before we did
3412 * prepare_to_wait().
3413 */
3414 if (inflight == tctx_inflight(tctx, !cancel_all))
3415 schedule();
3416 end_wait:
3417 finish_wait(&tctx->wait, &wait);
3418 } while (1);
3419
3420 io_uring_clean_tctx(tctx);
3421 if (cancel_all) {
3422 /*
3423 * We shouldn't run task_works after cancel, so just leave
3424 * ->in_cancel set for normal exit.
3425 */
3426 atomic_dec(&tctx->in_cancel);
3427 /* for exec all current's requests should be gone, kill tctx */
3428 __io_uring_free(current);
3429 }
3430 }
3431
__io_uring_cancel(bool cancel_all)3432 void __io_uring_cancel(bool cancel_all)
3433 {
3434 io_uring_cancel_generic(cancel_all, NULL);
3435 }
3436
io_uring_validate_mmap_request(struct file * file,loff_t pgoff,size_t sz)3437 static void *io_uring_validate_mmap_request(struct file *file,
3438 loff_t pgoff, size_t sz)
3439 {
3440 struct io_ring_ctx *ctx = file->private_data;
3441 loff_t offset = pgoff << PAGE_SHIFT;
3442 struct page *page;
3443 void *ptr;
3444
3445 switch (offset & IORING_OFF_MMAP_MASK) {
3446 case IORING_OFF_SQ_RING:
3447 case IORING_OFF_CQ_RING:
3448 /* Don't allow mmap if the ring was setup without it */
3449 if (ctx->flags & IORING_SETUP_NO_MMAP)
3450 return ERR_PTR(-EINVAL);
3451 ptr = ctx->rings;
3452 break;
3453 case IORING_OFF_SQES:
3454 /* Don't allow mmap if the ring was setup without it */
3455 if (ctx->flags & IORING_SETUP_NO_MMAP)
3456 return ERR_PTR(-EINVAL);
3457 ptr = ctx->sq_sqes;
3458 break;
3459 case IORING_OFF_PBUF_RING: {
3460 struct io_buffer_list *bl;
3461 unsigned int bgid;
3462
3463 bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT;
3464 bl = io_pbuf_get_bl(ctx, bgid);
3465 if (IS_ERR(bl))
3466 return bl;
3467 ptr = bl->buf_ring;
3468 io_put_bl(ctx, bl);
3469 break;
3470 }
3471 default:
3472 return ERR_PTR(-EINVAL);
3473 }
3474
3475 page = virt_to_head_page(ptr);
3476 if (sz > page_size(page))
3477 return ERR_PTR(-EINVAL);
3478
3479 return ptr;
3480 }
3481
3482 #ifdef CONFIG_MMU
3483
io_uring_mmap(struct file * file,struct vm_area_struct * vma)3484 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3485 {
3486 size_t sz = vma->vm_end - vma->vm_start;
3487 unsigned long pfn;
3488 void *ptr;
3489
3490 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
3491 if (IS_ERR(ptr))
3492 return PTR_ERR(ptr);
3493
3494 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3495 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3496 }
3497
io_uring_mmu_get_unmapped_area(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)3498 static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp,
3499 unsigned long addr, unsigned long len,
3500 unsigned long pgoff, unsigned long flags)
3501 {
3502 void *ptr;
3503
3504 /*
3505 * Do not allow to map to user-provided address to avoid breaking the
3506 * aliasing rules. Userspace is not able to guess the offset address of
3507 * kernel kmalloc()ed memory area.
3508 */
3509 if (addr)
3510 return -EINVAL;
3511
3512 ptr = io_uring_validate_mmap_request(filp, pgoff, len);
3513 if (IS_ERR(ptr))
3514 return -ENOMEM;
3515
3516 /*
3517 * Some architectures have strong cache aliasing requirements.
3518 * For such architectures we need a coherent mapping which aliases
3519 * kernel memory *and* userspace memory. To achieve that:
3520 * - use a NULL file pointer to reference physical memory, and
3521 * - use the kernel virtual address of the shared io_uring context
3522 * (instead of the userspace-provided address, which has to be 0UL
3523 * anyway).
3524 * - use the same pgoff which the get_unmapped_area() uses to
3525 * calculate the page colouring.
3526 * For architectures without such aliasing requirements, the
3527 * architecture will return any suitable mapping because addr is 0.
3528 */
3529 filp = NULL;
3530 flags |= MAP_SHARED;
3531 pgoff = 0; /* has been translated to ptr above */
3532 #ifdef SHM_COLOUR
3533 addr = (uintptr_t) ptr;
3534 pgoff = addr >> PAGE_SHIFT;
3535 #else
3536 addr = 0UL;
3537 #endif
3538 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
3539 }
3540
3541 #else /* !CONFIG_MMU */
3542
io_uring_mmap(struct file * file,struct vm_area_struct * vma)3543 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3544 {
3545 return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL;
3546 }
3547
io_uring_nommu_mmap_capabilities(struct file * file)3548 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
3549 {
3550 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
3551 }
3552
io_uring_nommu_get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)3553 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3554 unsigned long addr, unsigned long len,
3555 unsigned long pgoff, unsigned long flags)
3556 {
3557 void *ptr;
3558
3559 ptr = io_uring_validate_mmap_request(file, pgoff, len);
3560 if (IS_ERR(ptr))
3561 return PTR_ERR(ptr);
3562
3563 return (unsigned long) ptr;
3564 }
3565
3566 #endif /* !CONFIG_MMU */
3567
io_validate_ext_arg(unsigned flags,const void __user * argp,size_t argsz)3568 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3569 {
3570 if (flags & IORING_ENTER_EXT_ARG) {
3571 struct io_uring_getevents_arg arg;
3572
3573 if (argsz != sizeof(arg))
3574 return -EINVAL;
3575 if (copy_from_user(&arg, argp, sizeof(arg)))
3576 return -EFAULT;
3577 }
3578 return 0;
3579 }
3580
io_get_ext_arg(unsigned flags,const void __user * argp,size_t * argsz,struct __kernel_timespec __user ** ts,const sigset_t __user ** sig)3581 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3582 struct __kernel_timespec __user **ts,
3583 const sigset_t __user **sig)
3584 {
3585 struct io_uring_getevents_arg arg;
3586
3587 /*
3588 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3589 * is just a pointer to the sigset_t.
3590 */
3591 if (!(flags & IORING_ENTER_EXT_ARG)) {
3592 *sig = (const sigset_t __user *) argp;
3593 *ts = NULL;
3594 return 0;
3595 }
3596
3597 /*
3598 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3599 * timespec and sigset_t pointers if good.
3600 */
3601 if (*argsz != sizeof(arg))
3602 return -EINVAL;
3603 if (copy_from_user(&arg, argp, sizeof(arg)))
3604 return -EFAULT;
3605 if (arg.pad)
3606 return -EINVAL;
3607 *sig = u64_to_user_ptr(arg.sigmask);
3608 *argsz = arg.sigmask_sz;
3609 *ts = u64_to_user_ptr(arg.ts);
3610 return 0;
3611 }
3612
SYSCALL_DEFINE6(io_uring_enter,unsigned int,fd,u32,to_submit,u32,min_complete,u32,flags,const void __user *,argp,size_t,argsz)3613 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3614 u32, min_complete, u32, flags, const void __user *, argp,
3615 size_t, argsz)
3616 {
3617 struct io_ring_ctx *ctx;
3618 struct file *file;
3619 long ret;
3620
3621 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3622 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3623 IORING_ENTER_REGISTERED_RING)))
3624 return -EINVAL;
3625
3626 /*
3627 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3628 * need only dereference our task private array to find it.
3629 */
3630 if (flags & IORING_ENTER_REGISTERED_RING) {
3631 struct io_uring_task *tctx = current->io_uring;
3632
3633 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3634 return -EINVAL;
3635 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3636 file = tctx->registered_rings[fd];
3637 if (unlikely(!file))
3638 return -EBADF;
3639 } else {
3640 file = fget(fd);
3641 if (unlikely(!file))
3642 return -EBADF;
3643 ret = -EOPNOTSUPP;
3644 if (unlikely(!io_is_uring_fops(file)))
3645 goto out;
3646 }
3647
3648 ctx = file->private_data;
3649 ret = -EBADFD;
3650 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3651 goto out;
3652
3653 /*
3654 * For SQ polling, the thread will do all submissions and completions.
3655 * Just return the requested submit count, and wake the thread if
3656 * we were asked to.
3657 */
3658 ret = 0;
3659 if (ctx->flags & IORING_SETUP_SQPOLL) {
3660 io_cqring_overflow_flush(ctx);
3661
3662 if (unlikely(ctx->sq_data->thread == NULL)) {
3663 ret = -EOWNERDEAD;
3664 goto out;
3665 }
3666 if (flags & IORING_ENTER_SQ_WAKEUP)
3667 wake_up(&ctx->sq_data->wait);
3668 if (flags & IORING_ENTER_SQ_WAIT)
3669 io_sqpoll_wait_sq(ctx);
3670
3671 ret = to_submit;
3672 } else if (to_submit) {
3673 ret = io_uring_add_tctx_node(ctx);
3674 if (unlikely(ret))
3675 goto out;
3676
3677 mutex_lock(&ctx->uring_lock);
3678 ret = io_submit_sqes(ctx, to_submit);
3679 if (ret != to_submit) {
3680 mutex_unlock(&ctx->uring_lock);
3681 goto out;
3682 }
3683 if (flags & IORING_ENTER_GETEVENTS) {
3684 if (ctx->syscall_iopoll)
3685 goto iopoll_locked;
3686 /*
3687 * Ignore errors, we'll soon call io_cqring_wait() and
3688 * it should handle ownership problems if any.
3689 */
3690 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3691 (void)io_run_local_work_locked(ctx, min_complete);
3692 }
3693 mutex_unlock(&ctx->uring_lock);
3694 }
3695
3696 if (flags & IORING_ENTER_GETEVENTS) {
3697 int ret2;
3698
3699 if (ctx->syscall_iopoll) {
3700 /*
3701 * We disallow the app entering submit/complete with
3702 * polling, but we still need to lock the ring to
3703 * prevent racing with polled issue that got punted to
3704 * a workqueue.
3705 */
3706 mutex_lock(&ctx->uring_lock);
3707 iopoll_locked:
3708 ret2 = io_validate_ext_arg(flags, argp, argsz);
3709 if (likely(!ret2)) {
3710 min_complete = min(min_complete,
3711 ctx->cq_entries);
3712 ret2 = io_iopoll_check(ctx, min_complete);
3713 }
3714 mutex_unlock(&ctx->uring_lock);
3715 } else {
3716 const sigset_t __user *sig;
3717 struct __kernel_timespec __user *ts;
3718
3719 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3720 if (likely(!ret2)) {
3721 min_complete = min(min_complete,
3722 ctx->cq_entries);
3723 ret2 = io_cqring_wait(ctx, min_complete, sig,
3724 argsz, ts);
3725 }
3726 }
3727
3728 if (!ret) {
3729 ret = ret2;
3730
3731 /*
3732 * EBADR indicates that one or more CQE were dropped.
3733 * Once the user has been informed we can clear the bit
3734 * as they are obviously ok with those drops.
3735 */
3736 if (unlikely(ret2 == -EBADR))
3737 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3738 &ctx->check_cq);
3739 }
3740 }
3741 out:
3742 if (!(flags & IORING_ENTER_REGISTERED_RING))
3743 fput(file);
3744 return ret;
3745 }
3746
3747 static const struct file_operations io_uring_fops = {
3748 .release = io_uring_release,
3749 .mmap = io_uring_mmap,
3750 #ifndef CONFIG_MMU
3751 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3752 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3753 #else
3754 .get_unmapped_area = io_uring_mmu_get_unmapped_area,
3755 #endif
3756 .poll = io_uring_poll,
3757 #ifdef CONFIG_PROC_FS
3758 .show_fdinfo = io_uring_show_fdinfo,
3759 #endif
3760 };
3761
io_is_uring_fops(struct file * file)3762 bool io_is_uring_fops(struct file *file)
3763 {
3764 return file->f_op == &io_uring_fops;
3765 }
3766
io_allocate_scq_urings(struct io_ring_ctx * ctx,struct io_uring_params * p)3767 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3768 struct io_uring_params *p)
3769 {
3770 struct io_rings *rings;
3771 size_t size, sq_array_offset;
3772 void *ptr;
3773
3774 /* make sure these are sane, as we already accounted them */
3775 ctx->sq_entries = p->sq_entries;
3776 ctx->cq_entries = p->cq_entries;
3777
3778 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3779 if (size == SIZE_MAX)
3780 return -EOVERFLOW;
3781
3782 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3783 rings = io_mem_alloc(size);
3784 else
3785 rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3786
3787 if (IS_ERR(rings))
3788 return PTR_ERR(rings);
3789
3790 ctx->rings = rings;
3791 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3792 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3793 rings->sq_ring_mask = p->sq_entries - 1;
3794 rings->cq_ring_mask = p->cq_entries - 1;
3795 rings->sq_ring_entries = p->sq_entries;
3796 rings->cq_ring_entries = p->cq_entries;
3797
3798 if (p->flags & IORING_SETUP_SQE128)
3799 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3800 else
3801 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3802 if (size == SIZE_MAX) {
3803 io_rings_free(ctx);
3804 return -EOVERFLOW;
3805 }
3806
3807 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3808 ptr = io_mem_alloc(size);
3809 else
3810 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3811
3812 if (IS_ERR(ptr)) {
3813 io_rings_free(ctx);
3814 return PTR_ERR(ptr);
3815 }
3816
3817 ctx->sq_sqes = ptr;
3818 return 0;
3819 }
3820
io_uring_install_fd(struct file * file)3821 static int io_uring_install_fd(struct file *file)
3822 {
3823 int fd;
3824
3825 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3826 if (fd < 0)
3827 return fd;
3828 fd_install(fd, file);
3829 return fd;
3830 }
3831
3832 /*
3833 * Allocate an anonymous fd, this is what constitutes the application
3834 * visible backing of an io_uring instance. The application mmaps this
3835 * fd to gain access to the SQ/CQ ring details.
3836 */
io_uring_get_file(struct io_ring_ctx * ctx)3837 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3838 {
3839 return anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
3840 O_RDWR | O_CLOEXEC, NULL);
3841 }
3842
io_uring_create(unsigned entries,struct io_uring_params * p,struct io_uring_params __user * params)3843 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3844 struct io_uring_params __user *params)
3845 {
3846 struct io_ring_ctx *ctx;
3847 struct io_uring_task *tctx;
3848 struct file *file;
3849 int ret;
3850
3851 if (!entries)
3852 return -EINVAL;
3853 if (entries > IORING_MAX_ENTRIES) {
3854 if (!(p->flags & IORING_SETUP_CLAMP))
3855 return -EINVAL;
3856 entries = IORING_MAX_ENTRIES;
3857 }
3858
3859 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3860 && !(p->flags & IORING_SETUP_NO_MMAP))
3861 return -EINVAL;
3862
3863 /*
3864 * Use twice as many entries for the CQ ring. It's possible for the
3865 * application to drive a higher depth than the size of the SQ ring,
3866 * since the sqes are only used at submission time. This allows for
3867 * some flexibility in overcommitting a bit. If the application has
3868 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3869 * of CQ ring entries manually.
3870 */
3871 p->sq_entries = roundup_pow_of_two(entries);
3872 if (p->flags & IORING_SETUP_CQSIZE) {
3873 /*
3874 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3875 * to a power-of-two, if it isn't already. We do NOT impose
3876 * any cq vs sq ring sizing.
3877 */
3878 if (!p->cq_entries)
3879 return -EINVAL;
3880 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3881 if (!(p->flags & IORING_SETUP_CLAMP))
3882 return -EINVAL;
3883 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3884 }
3885 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3886 if (p->cq_entries < p->sq_entries)
3887 return -EINVAL;
3888 } else {
3889 p->cq_entries = 2 * p->sq_entries;
3890 }
3891
3892 ctx = io_ring_ctx_alloc(p);
3893 if (!ctx)
3894 return -ENOMEM;
3895
3896 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3897 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3898 !(ctx->flags & IORING_SETUP_SQPOLL))
3899 ctx->task_complete = true;
3900
3901 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3902 ctx->lockless_cq = true;
3903
3904 /*
3905 * lazy poll_wq activation relies on ->task_complete for synchronisation
3906 * purposes, see io_activate_pollwq()
3907 */
3908 if (!ctx->task_complete)
3909 ctx->poll_activated = true;
3910
3911 /*
3912 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3913 * space applications don't need to do io completion events
3914 * polling again, they can rely on io_sq_thread to do polling
3915 * work, which can reduce cpu usage and uring_lock contention.
3916 */
3917 if (ctx->flags & IORING_SETUP_IOPOLL &&
3918 !(ctx->flags & IORING_SETUP_SQPOLL))
3919 ctx->syscall_iopoll = 1;
3920
3921 ctx->compat = in_compat_syscall();
3922 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3923 ctx->user = get_uid(current_user());
3924
3925 /*
3926 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3927 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3928 */
3929 ret = -EINVAL;
3930 if (ctx->flags & IORING_SETUP_SQPOLL) {
3931 /* IPI related flags don't make sense with SQPOLL */
3932 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3933 IORING_SETUP_TASKRUN_FLAG |
3934 IORING_SETUP_DEFER_TASKRUN))
3935 goto err;
3936 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3937 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3938 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3939 } else {
3940 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
3941 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
3942 goto err;
3943 ctx->notify_method = TWA_SIGNAL;
3944 }
3945
3946 /*
3947 * For DEFER_TASKRUN we require the completion task to be the same as the
3948 * submission task. This implies that there is only one submitter, so enforce
3949 * that.
3950 */
3951 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
3952 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
3953 goto err;
3954 }
3955
3956 /*
3957 * This is just grabbed for accounting purposes. When a process exits,
3958 * the mm is exited and dropped before the files, hence we need to hang
3959 * on to this mm purely for the purposes of being able to unaccount
3960 * memory (locked/pinned vm). It's not used for anything else.
3961 */
3962 mmgrab(current->mm);
3963 ctx->mm_account = current->mm;
3964
3965 ret = io_allocate_scq_urings(ctx, p);
3966 if (ret)
3967 goto err;
3968
3969 ret = io_sq_offload_create(ctx, p);
3970 if (ret)
3971 goto err;
3972
3973 ret = io_rsrc_init(ctx);
3974 if (ret)
3975 goto err;
3976
3977 p->sq_off.head = offsetof(struct io_rings, sq.head);
3978 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3979 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3980 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3981 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3982 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3983 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3984 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3985 p->sq_off.resv1 = 0;
3986 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3987 p->sq_off.user_addr = 0;
3988
3989 p->cq_off.head = offsetof(struct io_rings, cq.head);
3990 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3991 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3992 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3993 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3994 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3995 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3996 p->cq_off.resv1 = 0;
3997 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3998 p->cq_off.user_addr = 0;
3999
4000 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
4001 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
4002 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
4003 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
4004 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
4005 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
4006 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING;
4007
4008 if (copy_to_user(params, p, sizeof(*p))) {
4009 ret = -EFAULT;
4010 goto err;
4011 }
4012
4013 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
4014 && !(ctx->flags & IORING_SETUP_R_DISABLED))
4015 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4016
4017 file = io_uring_get_file(ctx);
4018 if (IS_ERR(file)) {
4019 ret = PTR_ERR(file);
4020 goto err;
4021 }
4022
4023 ret = __io_uring_add_tctx_node(ctx);
4024 if (ret)
4025 goto err_fput;
4026 tctx = current->io_uring;
4027
4028 /*
4029 * Install ring fd as the very last thing, so we don't risk someone
4030 * having closed it before we finish setup
4031 */
4032 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
4033 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
4034 else
4035 ret = io_uring_install_fd(file);
4036 if (ret < 0)
4037 goto err_fput;
4038
4039 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4040 return ret;
4041 err:
4042 io_ring_ctx_wait_and_kill(ctx);
4043 return ret;
4044 err_fput:
4045 fput(file);
4046 return ret;
4047 }
4048
4049 /*
4050 * Sets up an aio uring context, and returns the fd. Applications asks for a
4051 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4052 * params structure passed in.
4053 */
io_uring_setup(u32 entries,struct io_uring_params __user * params)4054 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4055 {
4056 struct io_uring_params p;
4057 int i;
4058
4059 if (copy_from_user(&p, params, sizeof(p)))
4060 return -EFAULT;
4061 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4062 if (p.resv[i])
4063 return -EINVAL;
4064 }
4065
4066 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4067 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
4068 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
4069 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
4070 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
4071 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
4072 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
4073 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
4074 IORING_SETUP_NO_SQARRAY))
4075 return -EINVAL;
4076
4077 return io_uring_create(entries, &p, params);
4078 }
4079
io_uring_allowed(void)4080 static inline bool io_uring_allowed(void)
4081 {
4082 int disabled = READ_ONCE(sysctl_io_uring_disabled);
4083 kgid_t io_uring_group;
4084
4085 if (disabled == 2)
4086 return false;
4087
4088 if (disabled == 0 || capable(CAP_SYS_ADMIN))
4089 return true;
4090
4091 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
4092 if (!gid_valid(io_uring_group))
4093 return false;
4094
4095 return in_group_p(io_uring_group);
4096 }
4097
SYSCALL_DEFINE2(io_uring_setup,u32,entries,struct io_uring_params __user *,params)4098 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4099 struct io_uring_params __user *, params)
4100 {
4101 if (!io_uring_allowed())
4102 return -EPERM;
4103
4104 return io_uring_setup(entries, params);
4105 }
4106
io_probe(struct io_ring_ctx * ctx,void __user * arg,unsigned nr_args)4107 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
4108 unsigned nr_args)
4109 {
4110 struct io_uring_probe *p;
4111 size_t size;
4112 int i, ret;
4113
4114 size = struct_size(p, ops, nr_args);
4115 if (size == SIZE_MAX)
4116 return -EOVERFLOW;
4117 p = kzalloc(size, GFP_KERNEL);
4118 if (!p)
4119 return -ENOMEM;
4120
4121 ret = -EFAULT;
4122 if (copy_from_user(p, arg, size))
4123 goto out;
4124 ret = -EINVAL;
4125 if (memchr_inv(p, 0, size))
4126 goto out;
4127
4128 p->last_op = IORING_OP_LAST - 1;
4129 if (nr_args > IORING_OP_LAST)
4130 nr_args = IORING_OP_LAST;
4131
4132 for (i = 0; i < nr_args; i++) {
4133 p->ops[i].op = i;
4134 if (!io_issue_defs[i].not_supported)
4135 p->ops[i].flags = IO_URING_OP_SUPPORTED;
4136 }
4137 p->ops_len = i;
4138
4139 ret = 0;
4140 if (copy_to_user(arg, p, size))
4141 ret = -EFAULT;
4142 out:
4143 kfree(p);
4144 return ret;
4145 }
4146
io_register_personality(struct io_ring_ctx * ctx)4147 static int io_register_personality(struct io_ring_ctx *ctx)
4148 {
4149 const struct cred *creds;
4150 u32 id;
4151 int ret;
4152
4153 creds = get_current_cred();
4154
4155 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
4156 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
4157 if (ret < 0) {
4158 put_cred(creds);
4159 return ret;
4160 }
4161 return id;
4162 }
4163
io_register_restrictions(struct io_ring_ctx * ctx,void __user * arg,unsigned int nr_args)4164 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
4165 void __user *arg, unsigned int nr_args)
4166 {
4167 struct io_uring_restriction *res;
4168 size_t size;
4169 int i, ret;
4170
4171 /* Restrictions allowed only if rings started disabled */
4172 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
4173 return -EBADFD;
4174
4175 /* We allow only a single restrictions registration */
4176 if (ctx->restrictions.registered)
4177 return -EBUSY;
4178
4179 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
4180 return -EINVAL;
4181
4182 size = array_size(nr_args, sizeof(*res));
4183 if (size == SIZE_MAX)
4184 return -EOVERFLOW;
4185
4186 res = memdup_user(arg, size);
4187 if (IS_ERR(res))
4188 return PTR_ERR(res);
4189
4190 ret = 0;
4191
4192 for (i = 0; i < nr_args; i++) {
4193 switch (res[i].opcode) {
4194 case IORING_RESTRICTION_REGISTER_OP:
4195 if (res[i].register_op >= IORING_REGISTER_LAST) {
4196 ret = -EINVAL;
4197 goto out;
4198 }
4199
4200 __set_bit(res[i].register_op,
4201 ctx->restrictions.register_op);
4202 break;
4203 case IORING_RESTRICTION_SQE_OP:
4204 if (res[i].sqe_op >= IORING_OP_LAST) {
4205 ret = -EINVAL;
4206 goto out;
4207 }
4208
4209 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
4210 break;
4211 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
4212 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
4213 break;
4214 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
4215 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
4216 break;
4217 default:
4218 ret = -EINVAL;
4219 goto out;
4220 }
4221 }
4222
4223 out:
4224 /* Reset all restrictions if an error happened */
4225 if (ret != 0)
4226 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
4227 else
4228 ctx->restrictions.registered = true;
4229
4230 kfree(res);
4231 return ret;
4232 }
4233
io_register_enable_rings(struct io_ring_ctx * ctx)4234 static int io_register_enable_rings(struct io_ring_ctx *ctx)
4235 {
4236 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
4237 return -EBADFD;
4238
4239 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER && !ctx->submitter_task) {
4240 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4241 /*
4242 * Lazy activation attempts would fail if it was polled before
4243 * submitter_task is set.
4244 */
4245 if (wq_has_sleeper(&ctx->poll_wq))
4246 io_activate_pollwq(ctx);
4247 }
4248
4249 if (ctx->restrictions.registered)
4250 ctx->restricted = 1;
4251
4252 ctx->flags &= ~IORING_SETUP_R_DISABLED;
4253 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
4254 wake_up(&ctx->sq_data->wait);
4255 return 0;
4256 }
4257
__io_register_iowq_aff(struct io_ring_ctx * ctx,cpumask_var_t new_mask)4258 static __cold int __io_register_iowq_aff(struct io_ring_ctx *ctx,
4259 cpumask_var_t new_mask)
4260 {
4261 int ret;
4262
4263 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
4264 ret = io_wq_cpu_affinity(current->io_uring, new_mask);
4265 } else {
4266 mutex_unlock(&ctx->uring_lock);
4267 ret = io_sqpoll_wq_cpu_affinity(ctx, new_mask);
4268 mutex_lock(&ctx->uring_lock);
4269 }
4270
4271 return ret;
4272 }
4273
io_register_iowq_aff(struct io_ring_ctx * ctx,void __user * arg,unsigned len)4274 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
4275 void __user *arg, unsigned len)
4276 {
4277 cpumask_var_t new_mask;
4278 int ret;
4279
4280 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4281 return -ENOMEM;
4282
4283 cpumask_clear(new_mask);
4284 if (len > cpumask_size())
4285 len = cpumask_size();
4286
4287 if (in_compat_syscall()) {
4288 ret = compat_get_bitmap(cpumask_bits(new_mask),
4289 (const compat_ulong_t __user *)arg,
4290 len * 8 /* CHAR_BIT */);
4291 } else {
4292 ret = copy_from_user(new_mask, arg, len);
4293 }
4294
4295 if (ret) {
4296 free_cpumask_var(new_mask);
4297 return -EFAULT;
4298 }
4299
4300 ret = __io_register_iowq_aff(ctx, new_mask);
4301 free_cpumask_var(new_mask);
4302 return ret;
4303 }
4304
io_unregister_iowq_aff(struct io_ring_ctx * ctx)4305 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
4306 {
4307 return __io_register_iowq_aff(ctx, NULL);
4308 }
4309
io_register_iowq_max_workers(struct io_ring_ctx * ctx,void __user * arg)4310 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
4311 void __user *arg)
4312 __must_hold(&ctx->uring_lock)
4313 {
4314 struct io_tctx_node *node;
4315 struct io_uring_task *tctx = NULL;
4316 struct io_sq_data *sqd = NULL;
4317 __u32 new_count[2];
4318 int i, ret;
4319
4320 if (copy_from_user(new_count, arg, sizeof(new_count)))
4321 return -EFAULT;
4322 for (i = 0; i < ARRAY_SIZE(new_count); i++)
4323 if (new_count[i] > INT_MAX)
4324 return -EINVAL;
4325
4326 if (ctx->flags & IORING_SETUP_SQPOLL) {
4327 sqd = ctx->sq_data;
4328 if (sqd) {
4329 /*
4330 * Observe the correct sqd->lock -> ctx->uring_lock
4331 * ordering. Fine to drop uring_lock here, we hold
4332 * a ref to the ctx.
4333 */
4334 refcount_inc(&sqd->refs);
4335 mutex_unlock(&ctx->uring_lock);
4336 mutex_lock(&sqd->lock);
4337 mutex_lock(&ctx->uring_lock);
4338 if (sqd->thread)
4339 tctx = sqd->thread->io_uring;
4340 }
4341 } else {
4342 tctx = current->io_uring;
4343 }
4344
4345 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
4346
4347 for (i = 0; i < ARRAY_SIZE(new_count); i++)
4348 if (new_count[i])
4349 ctx->iowq_limits[i] = new_count[i];
4350 ctx->iowq_limits_set = true;
4351
4352 if (tctx && tctx->io_wq) {
4353 ret = io_wq_max_workers(tctx->io_wq, new_count);
4354 if (ret)
4355 goto err;
4356 } else {
4357 memset(new_count, 0, sizeof(new_count));
4358 }
4359
4360 if (sqd) {
4361 mutex_unlock(&ctx->uring_lock);
4362 mutex_unlock(&sqd->lock);
4363 io_put_sq_data(sqd);
4364 mutex_lock(&ctx->uring_lock);
4365 }
4366
4367 if (copy_to_user(arg, new_count, sizeof(new_count)))
4368 return -EFAULT;
4369
4370 /* that's it for SQPOLL, only the SQPOLL task creates requests */
4371 if (sqd)
4372 return 0;
4373
4374 /* now propagate the restriction to all registered users */
4375 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
4376 struct io_uring_task *tctx = node->task->io_uring;
4377
4378 if (WARN_ON_ONCE(!tctx->io_wq))
4379 continue;
4380
4381 for (i = 0; i < ARRAY_SIZE(new_count); i++)
4382 new_count[i] = ctx->iowq_limits[i];
4383 /* ignore errors, it always returns zero anyway */
4384 (void)io_wq_max_workers(tctx->io_wq, new_count);
4385 }
4386 return 0;
4387 err:
4388 if (sqd) {
4389 mutex_unlock(&ctx->uring_lock);
4390 mutex_unlock(&sqd->lock);
4391 io_put_sq_data(sqd);
4392 mutex_lock(&ctx->uring_lock);
4393
4394 }
4395 return ret;
4396 }
4397
__io_uring_register(struct io_ring_ctx * ctx,unsigned opcode,void __user * arg,unsigned nr_args)4398 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4399 void __user *arg, unsigned nr_args)
4400 __releases(ctx->uring_lock)
4401 __acquires(ctx->uring_lock)
4402 {
4403 int ret;
4404
4405 /*
4406 * We don't quiesce the refs for register anymore and so it can't be
4407 * dying as we're holding a file ref here.
4408 */
4409 if (WARN_ON_ONCE(percpu_ref_is_dying(&ctx->refs)))
4410 return -ENXIO;
4411
4412 if (ctx->submitter_task && ctx->submitter_task != current)
4413 return -EEXIST;
4414
4415 if (ctx->restricted) {
4416 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
4417 if (!test_bit(opcode, ctx->restrictions.register_op))
4418 return -EACCES;
4419 }
4420
4421 switch (opcode) {
4422 case IORING_REGISTER_BUFFERS:
4423 ret = -EFAULT;
4424 if (!arg)
4425 break;
4426 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
4427 break;
4428 case IORING_UNREGISTER_BUFFERS:
4429 ret = -EINVAL;
4430 if (arg || nr_args)
4431 break;
4432 ret = io_sqe_buffers_unregister(ctx);
4433 break;
4434 case IORING_REGISTER_FILES:
4435 ret = -EFAULT;
4436 if (!arg)
4437 break;
4438 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
4439 break;
4440 case IORING_UNREGISTER_FILES:
4441 ret = -EINVAL;
4442 if (arg || nr_args)
4443 break;
4444 ret = io_sqe_files_unregister(ctx);
4445 break;
4446 case IORING_REGISTER_FILES_UPDATE:
4447 ret = io_register_files_update(ctx, arg, nr_args);
4448 break;
4449 case IORING_REGISTER_EVENTFD:
4450 ret = -EINVAL;
4451 if (nr_args != 1)
4452 break;
4453 ret = io_eventfd_register(ctx, arg, 0);
4454 break;
4455 case IORING_REGISTER_EVENTFD_ASYNC:
4456 ret = -EINVAL;
4457 if (nr_args != 1)
4458 break;
4459 ret = io_eventfd_register(ctx, arg, 1);
4460 break;
4461 case IORING_UNREGISTER_EVENTFD:
4462 ret = -EINVAL;
4463 if (arg || nr_args)
4464 break;
4465 ret = io_eventfd_unregister(ctx);
4466 break;
4467 case IORING_REGISTER_PROBE:
4468 ret = -EINVAL;
4469 if (!arg || nr_args > 256)
4470 break;
4471 ret = io_probe(ctx, arg, nr_args);
4472 break;
4473 case IORING_REGISTER_PERSONALITY:
4474 ret = -EINVAL;
4475 if (arg || nr_args)
4476 break;
4477 ret = io_register_personality(ctx);
4478 break;
4479 case IORING_UNREGISTER_PERSONALITY:
4480 ret = -EINVAL;
4481 if (arg)
4482 break;
4483 ret = io_unregister_personality(ctx, nr_args);
4484 break;
4485 case IORING_REGISTER_ENABLE_RINGS:
4486 ret = -EINVAL;
4487 if (arg || nr_args)
4488 break;
4489 ret = io_register_enable_rings(ctx);
4490 break;
4491 case IORING_REGISTER_RESTRICTIONS:
4492 ret = io_register_restrictions(ctx, arg, nr_args);
4493 break;
4494 case IORING_REGISTER_FILES2:
4495 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
4496 break;
4497 case IORING_REGISTER_FILES_UPDATE2:
4498 ret = io_register_rsrc_update(ctx, arg, nr_args,
4499 IORING_RSRC_FILE);
4500 break;
4501 case IORING_REGISTER_BUFFERS2:
4502 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
4503 break;
4504 case IORING_REGISTER_BUFFERS_UPDATE:
4505 ret = io_register_rsrc_update(ctx, arg, nr_args,
4506 IORING_RSRC_BUFFER);
4507 break;
4508 case IORING_REGISTER_IOWQ_AFF:
4509 ret = -EINVAL;
4510 if (!arg || !nr_args)
4511 break;
4512 ret = io_register_iowq_aff(ctx, arg, nr_args);
4513 break;
4514 case IORING_UNREGISTER_IOWQ_AFF:
4515 ret = -EINVAL;
4516 if (arg || nr_args)
4517 break;
4518 ret = io_unregister_iowq_aff(ctx);
4519 break;
4520 case IORING_REGISTER_IOWQ_MAX_WORKERS:
4521 ret = -EINVAL;
4522 if (!arg || nr_args != 2)
4523 break;
4524 ret = io_register_iowq_max_workers(ctx, arg);
4525 break;
4526 case IORING_REGISTER_RING_FDS:
4527 ret = io_ringfd_register(ctx, arg, nr_args);
4528 break;
4529 case IORING_UNREGISTER_RING_FDS:
4530 ret = io_ringfd_unregister(ctx, arg, nr_args);
4531 break;
4532 case IORING_REGISTER_PBUF_RING:
4533 ret = -EINVAL;
4534 if (!arg || nr_args != 1)
4535 break;
4536 ret = io_register_pbuf_ring(ctx, arg);
4537 break;
4538 case IORING_UNREGISTER_PBUF_RING:
4539 ret = -EINVAL;
4540 if (!arg || nr_args != 1)
4541 break;
4542 ret = io_unregister_pbuf_ring(ctx, arg);
4543 break;
4544 case IORING_REGISTER_SYNC_CANCEL:
4545 ret = -EINVAL;
4546 if (!arg || nr_args != 1)
4547 break;
4548 ret = io_sync_cancel(ctx, arg);
4549 break;
4550 case IORING_REGISTER_FILE_ALLOC_RANGE:
4551 ret = -EINVAL;
4552 if (!arg || nr_args)
4553 break;
4554 ret = io_register_file_alloc_range(ctx, arg);
4555 break;
4556 default:
4557 ret = -EINVAL;
4558 break;
4559 }
4560
4561 return ret;
4562 }
4563
SYSCALL_DEFINE4(io_uring_register,unsigned int,fd,unsigned int,opcode,void __user *,arg,unsigned int,nr_args)4564 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4565 void __user *, arg, unsigned int, nr_args)
4566 {
4567 struct io_ring_ctx *ctx;
4568 long ret = -EBADF;
4569 struct file *file;
4570 bool use_registered_ring;
4571
4572 use_registered_ring = !!(opcode & IORING_REGISTER_USE_REGISTERED_RING);
4573 opcode &= ~IORING_REGISTER_USE_REGISTERED_RING;
4574
4575 if (opcode >= IORING_REGISTER_LAST)
4576 return -EINVAL;
4577
4578 if (use_registered_ring) {
4579 /*
4580 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
4581 * need only dereference our task private array to find it.
4582 */
4583 struct io_uring_task *tctx = current->io_uring;
4584
4585 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
4586 return -EINVAL;
4587 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
4588 file = tctx->registered_rings[fd];
4589 if (unlikely(!file))
4590 return -EBADF;
4591 } else {
4592 file = fget(fd);
4593 if (unlikely(!file))
4594 return -EBADF;
4595 ret = -EOPNOTSUPP;
4596 if (!io_is_uring_fops(file))
4597 goto out_fput;
4598 }
4599
4600 ctx = file->private_data;
4601
4602 mutex_lock(&ctx->uring_lock);
4603 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4604 mutex_unlock(&ctx->uring_lock);
4605 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
4606 out_fput:
4607 if (!use_registered_ring)
4608 fput(file);
4609 return ret;
4610 }
4611
io_uring_init(void)4612 static int __init io_uring_init(void)
4613 {
4614 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
4615 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
4616 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
4617 } while (0)
4618
4619 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
4620 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
4621 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
4622 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
4623 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
4624 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
4625 BUILD_BUG_SQE_ELEM(1, __u8, flags);
4626 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
4627 BUILD_BUG_SQE_ELEM(4, __s32, fd);
4628 BUILD_BUG_SQE_ELEM(8, __u64, off);
4629 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
4630 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
4631 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
4632 BUILD_BUG_SQE_ELEM(16, __u64, addr);
4633 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
4634 BUILD_BUG_SQE_ELEM(24, __u32, len);
4635 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
4636 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
4637 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
4638 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
4639 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
4640 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
4641 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
4642 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
4643 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
4644 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
4645 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
4646 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
4647 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
4648 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
4649 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
4650 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
4651 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
4652 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
4653 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
4654 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
4655 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
4656 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
4657 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
4658 BUILD_BUG_SQE_ELEM(42, __u16, personality);
4659 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
4660 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
4661 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
4662 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
4663 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
4664 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
4665 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
4666
4667 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
4668 sizeof(struct io_uring_rsrc_update));
4669 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
4670 sizeof(struct io_uring_rsrc_update2));
4671
4672 /* ->buf_index is u16 */
4673 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
4674 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
4675 offsetof(struct io_uring_buf_ring, tail));
4676
4677 /* should fit into one byte */
4678 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
4679 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4680 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4681
4682 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
4683
4684 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4685
4686 io_uring_optable_init();
4687
4688 /*
4689 * Allow user copy in the per-command field, which starts after the
4690 * file in io_kiocb and until the opcode field. The openat2 handling
4691 * requires copying in user memory into the io_kiocb object in that
4692 * range, and HARDENED_USERCOPY will complain if we haven't
4693 * correctly annotated this range.
4694 */
4695 req_cachep = kmem_cache_create_usercopy("io_kiocb",
4696 sizeof(struct io_kiocb), 0,
4697 SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4698 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU,
4699 offsetof(struct io_kiocb, cmd.data),
4700 sizeof_field(struct io_kiocb, cmd.data), NULL);
4701
4702 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
4703
4704 #ifdef CONFIG_SYSCTL
4705 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
4706 #endif
4707
4708 return 0;
4709 };
4710 __initcall(io_uring_init);
4711