1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
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
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
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
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
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.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
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>
51 #include <linux/sched/signal.h>
53 #include <linux/file.h>
54 #include <linux/fdtable.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>
62 #include <linux/anon_inodes.h>
63 #include <linux/sched/mm.h>
64 #include <linux/uaccess.h>
65 #include <linux/nospec.h>
66 #include <linux/highmem.h>
67 #include <linux/fsnotify.h>
68 #include <linux/fadvise.h>
69 #include <linux/task_work.h>
70 #include <linux/io_uring.h>
71 #include <linux/io_uring/cmd.h>
72 #include <linux/audit.h>
73 #include <linux/security.h>
74 #include <asm/shmparam.h>
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
79 #include <uapi/linux/io_uring.h>
102 #include "alloc_cache.h"
104 #define IORING_MAX_ENTRIES 32768
105 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
117 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
120 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
122 #define IO_COMPL_BATCH 32
123 #define IO_REQ_ALLOC_BATCH 8
125 struct io_defer_entry {
126 struct list_head list;
127 struct io_kiocb *req;
131 /* requests with any of those set should undergo io_disarm_next() */
132 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
133 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
136 * No waiters. It's larger than any valid value of the tw counter
137 * so that tests against ->cq_wait_nr would fail and skip wake_up().
139 #define IO_CQ_WAKE_INIT (-1U)
140 /* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
141 #define IO_CQ_WAKE_FORCE (IO_CQ_WAKE_INIT >> 1)
143 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
144 struct task_struct *task,
147 static void io_queue_sqe(struct io_kiocb *req);
149 struct kmem_cache *req_cachep;
151 static int __read_mostly sysctl_io_uring_disabled;
152 static int __read_mostly sysctl_io_uring_group = -1;
155 static struct ctl_table kernel_io_uring_disabled_table[] = {
157 .procname = "io_uring_disabled",
158 .data = &sysctl_io_uring_disabled,
159 .maxlen = sizeof(sysctl_io_uring_disabled),
161 .proc_handler = proc_dointvec_minmax,
162 .extra1 = SYSCTL_ZERO,
163 .extra2 = SYSCTL_TWO,
166 .procname = "io_uring_group",
167 .data = &sysctl_io_uring_group,
168 .maxlen = sizeof(gid_t),
170 .proc_handler = proc_dointvec,
176 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
178 if (!wq_list_empty(&ctx->submit_state.compl_reqs) ||
179 ctx->submit_state.cqes_count)
180 __io_submit_flush_completions(ctx);
183 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
185 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
188 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
190 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
193 static bool io_match_linked(struct io_kiocb *head)
195 struct io_kiocb *req;
197 io_for_each_link(req, head) {
198 if (req->flags & REQ_F_INFLIGHT)
205 * As io_match_task() but protected against racing with linked timeouts.
206 * User must not hold timeout_lock.
208 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
213 if (task && head->task != task)
218 if (head->flags & REQ_F_LINK_TIMEOUT) {
219 struct io_ring_ctx *ctx = head->ctx;
221 /* protect against races with linked timeouts */
222 spin_lock_irq(&ctx->timeout_lock);
223 matched = io_match_linked(head);
224 spin_unlock_irq(&ctx->timeout_lock);
226 matched = io_match_linked(head);
231 static inline void req_fail_link_node(struct io_kiocb *req, int res)
234 io_req_set_res(req, res, 0);
237 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
239 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
242 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
244 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
246 complete(&ctx->ref_comp);
249 static __cold void io_fallback_req_func(struct work_struct *work)
251 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
253 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
254 struct io_kiocb *req, *tmp;
255 struct io_tw_state ts = { .locked = true, };
257 percpu_ref_get(&ctx->refs);
258 mutex_lock(&ctx->uring_lock);
259 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
260 req->io_task_work.func(req, &ts);
261 if (WARN_ON_ONCE(!ts.locked))
263 io_submit_flush_completions(ctx);
264 mutex_unlock(&ctx->uring_lock);
265 percpu_ref_put(&ctx->refs);
268 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
270 unsigned hash_buckets = 1U << bits;
271 size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
273 table->hbs = kmalloc(hash_size, GFP_KERNEL);
277 table->hash_bits = bits;
278 init_hash_table(table, hash_buckets);
282 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
284 struct io_ring_ctx *ctx;
287 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
291 xa_init(&ctx->io_bl_xa);
294 * Use 5 bits less than the max cq entries, that should give us around
295 * 32 entries per hash list if totally full and uniformly spread, but
296 * don't keep too many buckets to not overconsume memory.
298 hash_bits = ilog2(p->cq_entries) - 5;
299 hash_bits = clamp(hash_bits, 1, 8);
300 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
302 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
304 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
308 ctx->flags = p->flags;
309 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
310 init_waitqueue_head(&ctx->sqo_sq_wait);
311 INIT_LIST_HEAD(&ctx->sqd_list);
312 INIT_LIST_HEAD(&ctx->cq_overflow_list);
313 INIT_LIST_HEAD(&ctx->io_buffers_cache);
314 INIT_HLIST_HEAD(&ctx->io_buf_list);
315 io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
316 sizeof(struct io_rsrc_node));
317 io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX,
318 sizeof(struct async_poll));
319 io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
320 sizeof(struct io_async_msghdr));
321 io_futex_cache_init(ctx);
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_comp);
332 INIT_LIST_HEAD(&ctx->defer_list);
333 INIT_LIST_HEAD(&ctx->timeout_list);
334 INIT_LIST_HEAD(&ctx->ltimeout_list);
335 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
336 init_llist_head(&ctx->work_llist);
337 INIT_LIST_HEAD(&ctx->tctx_list);
338 ctx->submit_state.free_list.next = NULL;
339 INIT_WQ_LIST(&ctx->locked_free_list);
340 INIT_HLIST_HEAD(&ctx->waitid_list);
342 INIT_HLIST_HEAD(&ctx->futex_list);
344 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
345 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
346 INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
351 kfree(ctx->cancel_table.hbs);
352 kfree(ctx->cancel_table_locked.hbs);
354 xa_destroy(&ctx->io_bl_xa);
359 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
361 struct io_rings *r = ctx->rings;
363 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
367 static bool req_need_defer(struct io_kiocb *req, u32 seq)
369 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
370 struct io_ring_ctx *ctx = req->ctx;
372 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
378 static void io_clean_op(struct io_kiocb *req)
380 if (req->flags & REQ_F_BUFFER_SELECTED) {
381 spin_lock(&req->ctx->completion_lock);
382 io_put_kbuf_comp(req);
383 spin_unlock(&req->ctx->completion_lock);
386 if (req->flags & REQ_F_NEED_CLEANUP) {
387 const struct io_cold_def *def = &io_cold_defs[req->opcode];
392 if ((req->flags & REQ_F_POLLED) && req->apoll) {
393 kfree(req->apoll->double_poll);
397 if (req->flags & REQ_F_INFLIGHT) {
398 struct io_uring_task *tctx = req->task->io_uring;
400 atomic_dec(&tctx->inflight_tracked);
402 if (req->flags & REQ_F_CREDS)
403 put_cred(req->creds);
404 if (req->flags & REQ_F_ASYNC_DATA) {
405 kfree(req->async_data);
406 req->async_data = NULL;
408 req->flags &= ~IO_REQ_CLEAN_FLAGS;
411 static inline void io_req_track_inflight(struct io_kiocb *req)
413 if (!(req->flags & REQ_F_INFLIGHT)) {
414 req->flags |= REQ_F_INFLIGHT;
415 atomic_inc(&req->task->io_uring->inflight_tracked);
419 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
421 if (WARN_ON_ONCE(!req->link))
424 req->flags &= ~REQ_F_ARM_LTIMEOUT;
425 req->flags |= REQ_F_LINK_TIMEOUT;
427 /* linked timeouts should have two refs once prep'ed */
428 io_req_set_refcount(req);
429 __io_req_set_refcount(req->link, 2);
433 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
435 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
437 return __io_prep_linked_timeout(req);
440 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
442 io_queue_linked_timeout(__io_prep_linked_timeout(req));
445 static inline void io_arm_ltimeout(struct io_kiocb *req)
447 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
448 __io_arm_ltimeout(req);
451 static void io_prep_async_work(struct io_kiocb *req)
453 const struct io_issue_def *def = &io_issue_defs[req->opcode];
454 struct io_ring_ctx *ctx = req->ctx;
456 if (!(req->flags & REQ_F_CREDS)) {
457 req->flags |= REQ_F_CREDS;
458 req->creds = get_current_cred();
461 req->work.list.next = NULL;
463 if (req->flags & REQ_F_FORCE_ASYNC)
464 req->work.flags |= IO_WQ_WORK_CONCURRENT;
466 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
467 req->flags |= io_file_get_flags(req->file);
469 if (req->file && (req->flags & REQ_F_ISREG)) {
470 bool should_hash = def->hash_reg_file;
472 /* don't serialize this request if the fs doesn't need it */
473 if (should_hash && (req->file->f_flags & O_DIRECT) &&
474 (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE))
476 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
477 io_wq_hash_work(&req->work, file_inode(req->file));
478 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
479 if (def->unbound_nonreg_file)
480 req->work.flags |= IO_WQ_WORK_UNBOUND;
484 static void io_prep_async_link(struct io_kiocb *req)
486 struct io_kiocb *cur;
488 if (req->flags & REQ_F_LINK_TIMEOUT) {
489 struct io_ring_ctx *ctx = req->ctx;
491 spin_lock_irq(&ctx->timeout_lock);
492 io_for_each_link(cur, req)
493 io_prep_async_work(cur);
494 spin_unlock_irq(&ctx->timeout_lock);
496 io_for_each_link(cur, req)
497 io_prep_async_work(cur);
501 void io_queue_iowq(struct io_kiocb *req, struct io_tw_state *ts_dont_use)
503 struct io_kiocb *link = io_prep_linked_timeout(req);
504 struct io_uring_task *tctx = req->task->io_uring;
507 BUG_ON(!tctx->io_wq);
509 /* init ->work of the whole link before punting */
510 io_prep_async_link(req);
513 * Not expected to happen, but if we do have a bug where this _can_
514 * happen, catch it here and ensure the request is marked as
515 * canceled. That will make io-wq go through the usual work cancel
516 * procedure rather than attempt to run this request (or create a new
519 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
520 req->work.flags |= IO_WQ_WORK_CANCEL;
522 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
523 io_wq_enqueue(tctx->io_wq, &req->work);
525 io_queue_linked_timeout(link);
528 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
530 while (!list_empty(&ctx->defer_list)) {
531 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
532 struct io_defer_entry, list);
534 if (req_need_defer(de->req, de->seq))
536 list_del_init(&de->list);
537 io_req_task_queue(de->req);
542 void io_eventfd_ops(struct rcu_head *rcu)
544 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
545 int ops = atomic_xchg(&ev_fd->ops, 0);
547 if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT))
548 eventfd_signal_mask(ev_fd->cq_ev_fd, EPOLL_URING_WAKE);
550 /* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback
551 * ordering in a race but if references are 0 we know we have to free
554 if (atomic_dec_and_test(&ev_fd->refs)) {
555 eventfd_ctx_put(ev_fd->cq_ev_fd);
560 static void io_eventfd_signal(struct io_ring_ctx *ctx)
562 struct io_ev_fd *ev_fd = NULL;
566 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
569 ev_fd = rcu_dereference(ctx->io_ev_fd);
572 * Check again if ev_fd exists incase an io_eventfd_unregister call
573 * completed between the NULL check of ctx->io_ev_fd at the start of
574 * the function and rcu_read_lock.
576 if (unlikely(!ev_fd))
578 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
580 if (ev_fd->eventfd_async && !io_wq_current_is_worker())
583 if (likely(eventfd_signal_allowed())) {
584 eventfd_signal_mask(ev_fd->cq_ev_fd, EPOLL_URING_WAKE);
586 atomic_inc(&ev_fd->refs);
587 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops))
588 call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops);
590 atomic_dec(&ev_fd->refs);
597 static void io_eventfd_flush_signal(struct io_ring_ctx *ctx)
601 spin_lock(&ctx->completion_lock);
604 * Eventfd should only get triggered when at least one event has been
605 * posted. Some applications rely on the eventfd notification count
606 * only changing IFF a new CQE has been added to the CQ ring. There's
607 * no depedency on 1:1 relationship between how many times this
608 * function is called (and hence the eventfd count) and number of CQEs
609 * posted to the CQ ring.
611 skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail;
612 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
613 spin_unlock(&ctx->completion_lock);
617 io_eventfd_signal(ctx);
620 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
622 if (ctx->poll_activated)
623 io_poll_wq_wake(ctx);
624 if (ctx->off_timeout_used)
625 io_flush_timeouts(ctx);
626 if (ctx->drain_active) {
627 spin_lock(&ctx->completion_lock);
628 io_queue_deferred(ctx);
629 spin_unlock(&ctx->completion_lock);
632 io_eventfd_flush_signal(ctx);
635 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
637 if (!ctx->lockless_cq)
638 spin_lock(&ctx->completion_lock);
641 static inline void io_cq_lock(struct io_ring_ctx *ctx)
642 __acquires(ctx->completion_lock)
644 spin_lock(&ctx->completion_lock);
647 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
649 io_commit_cqring(ctx);
650 if (!ctx->task_complete) {
651 if (!ctx->lockless_cq)
652 spin_unlock(&ctx->completion_lock);
653 /* IOPOLL rings only need to wake up if it's also SQPOLL */
654 if (!ctx->syscall_iopoll)
657 io_commit_cqring_flush(ctx);
660 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
661 __releases(ctx->completion_lock)
663 io_commit_cqring(ctx);
664 spin_unlock(&ctx->completion_lock);
666 io_commit_cqring_flush(ctx);
669 /* Returns true if there are no backlogged entries after the flush */
670 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
672 struct io_overflow_cqe *ocqe;
675 spin_lock(&ctx->completion_lock);
676 list_splice_init(&ctx->cq_overflow_list, &list);
677 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
678 spin_unlock(&ctx->completion_lock);
680 while (!list_empty(&list)) {
681 ocqe = list_first_entry(&list, struct io_overflow_cqe, list);
682 list_del(&ocqe->list);
687 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx)
689 size_t cqe_size = sizeof(struct io_uring_cqe);
691 if (__io_cqring_events(ctx) == ctx->cq_entries)
694 if (ctx->flags & IORING_SETUP_CQE32)
698 while (!list_empty(&ctx->cq_overflow_list)) {
699 struct io_uring_cqe *cqe;
700 struct io_overflow_cqe *ocqe;
702 if (!io_get_cqe_overflow(ctx, &cqe, true))
704 ocqe = list_first_entry(&ctx->cq_overflow_list,
705 struct io_overflow_cqe, list);
706 memcpy(cqe, &ocqe->cqe, cqe_size);
707 list_del(&ocqe->list);
711 if (list_empty(&ctx->cq_overflow_list)) {
712 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
713 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
715 io_cq_unlock_post(ctx);
718 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
720 /* iopoll syncs against uring_lock, not completion_lock */
721 if (ctx->flags & IORING_SETUP_IOPOLL)
722 mutex_lock(&ctx->uring_lock);
723 __io_cqring_overflow_flush(ctx);
724 if (ctx->flags & IORING_SETUP_IOPOLL)
725 mutex_unlock(&ctx->uring_lock);
728 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx)
730 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
731 io_cqring_do_overflow_flush(ctx);
734 /* can be called by any task */
735 static void io_put_task_remote(struct task_struct *task)
737 struct io_uring_task *tctx = task->io_uring;
739 percpu_counter_sub(&tctx->inflight, 1);
740 if (unlikely(atomic_read(&tctx->in_cancel)))
741 wake_up(&tctx->wait);
742 put_task_struct(task);
745 /* used by a task to put its own references */
746 static void io_put_task_local(struct task_struct *task)
748 task->io_uring->cached_refs++;
751 /* must to be called somewhat shortly after putting a request */
752 static inline void io_put_task(struct task_struct *task)
754 if (likely(task == current))
755 io_put_task_local(task);
757 io_put_task_remote(task);
760 void io_task_refs_refill(struct io_uring_task *tctx)
762 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
764 percpu_counter_add(&tctx->inflight, refill);
765 refcount_add(refill, ¤t->usage);
766 tctx->cached_refs += refill;
769 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
771 struct io_uring_task *tctx = task->io_uring;
772 unsigned int refs = tctx->cached_refs;
775 tctx->cached_refs = 0;
776 percpu_counter_sub(&tctx->inflight, refs);
777 put_task_struct_many(task, refs);
781 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
782 s32 res, u32 cflags, u64 extra1, u64 extra2)
784 struct io_overflow_cqe *ocqe;
785 size_t ocq_size = sizeof(struct io_overflow_cqe);
786 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
788 lockdep_assert_held(&ctx->completion_lock);
791 ocq_size += sizeof(struct io_uring_cqe);
793 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
794 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
797 * If we're in ring overflow flush mode, or in task cancel mode,
798 * or cannot allocate an overflow entry, then we need to drop it
801 io_account_cq_overflow(ctx);
802 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
805 if (list_empty(&ctx->cq_overflow_list)) {
806 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
807 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
810 ocqe->cqe.user_data = user_data;
812 ocqe->cqe.flags = cflags;
814 ocqe->cqe.big_cqe[0] = extra1;
815 ocqe->cqe.big_cqe[1] = extra2;
817 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
821 void io_req_cqe_overflow(struct io_kiocb *req)
823 io_cqring_event_overflow(req->ctx, req->cqe.user_data,
824 req->cqe.res, req->cqe.flags,
825 req->big_cqe.extra1, req->big_cqe.extra2);
826 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
830 * writes to the cq entry need to come after reading head; the
831 * control dependency is enough as we're using WRITE_ONCE to
834 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
836 struct io_rings *rings = ctx->rings;
837 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
838 unsigned int free, queued, len;
841 * Posting into the CQ when there are pending overflowed CQEs may break
842 * ordering guarantees, which will affect links, F_MORE users and more.
843 * Force overflow the completion.
845 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
848 /* userspace may cheat modifying the tail, be safe and do min */
849 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
850 free = ctx->cq_entries - queued;
851 /* we need a contiguous range, limit based on the current array offset */
852 len = min(free, ctx->cq_entries - off);
856 if (ctx->flags & IORING_SETUP_CQE32) {
861 ctx->cqe_cached = &rings->cqes[off];
862 ctx->cqe_sentinel = ctx->cqe_cached + len;
866 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
869 struct io_uring_cqe *cqe;
874 * If we can't get a cq entry, userspace overflowed the
875 * submission (by quite a lot). Increment the overflow count in
878 if (likely(io_get_cqe(ctx, &cqe))) {
879 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
881 WRITE_ONCE(cqe->user_data, user_data);
882 WRITE_ONCE(cqe->res, res);
883 WRITE_ONCE(cqe->flags, cflags);
885 if (ctx->flags & IORING_SETUP_CQE32) {
886 WRITE_ONCE(cqe->big_cqe[0], 0);
887 WRITE_ONCE(cqe->big_cqe[1], 0);
894 static void __io_flush_post_cqes(struct io_ring_ctx *ctx)
895 __must_hold(&ctx->uring_lock)
897 struct io_submit_state *state = &ctx->submit_state;
900 lockdep_assert_held(&ctx->uring_lock);
901 for (i = 0; i < state->cqes_count; i++) {
902 struct io_uring_cqe *cqe = &ctx->completion_cqes[i];
904 if (!io_fill_cqe_aux(ctx, cqe->user_data, cqe->res, cqe->flags)) {
905 if (ctx->lockless_cq) {
906 spin_lock(&ctx->completion_lock);
907 io_cqring_event_overflow(ctx, cqe->user_data,
908 cqe->res, cqe->flags, 0, 0);
909 spin_unlock(&ctx->completion_lock);
911 io_cqring_event_overflow(ctx, cqe->user_data,
912 cqe->res, cqe->flags, 0, 0);
916 state->cqes_count = 0;
919 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags,
925 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
926 if (!filled && allow_overflow)
927 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
929 io_cq_unlock_post(ctx);
933 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
935 return __io_post_aux_cqe(ctx, user_data, res, cflags, true);
939 * A helper for multishot requests posting additional CQEs.
940 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
942 bool io_fill_cqe_req_aux(struct io_kiocb *req, bool defer, s32 res, u32 cflags)
944 struct io_ring_ctx *ctx = req->ctx;
945 u64 user_data = req->cqe.user_data;
946 struct io_uring_cqe *cqe;
949 return __io_post_aux_cqe(ctx, user_data, res, cflags, false);
951 lockdep_assert_held(&ctx->uring_lock);
953 if (ctx->submit_state.cqes_count == ARRAY_SIZE(ctx->completion_cqes)) {
955 __io_flush_post_cqes(ctx);
956 /* no need to flush - flush is deferred */
957 __io_cq_unlock_post(ctx);
960 /* For defered completions this is not as strict as it is otherwise,
961 * however it's main job is to prevent unbounded posted completions,
962 * and in that it works just as well.
964 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
967 cqe = &ctx->completion_cqes[ctx->submit_state.cqes_count++];
968 cqe->user_data = user_data;
974 static void __io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
976 struct io_ring_ctx *ctx = req->ctx;
977 struct io_rsrc_node *rsrc_node = NULL;
980 if (!(req->flags & REQ_F_CQE_SKIP)) {
981 if (!io_fill_cqe_req(ctx, req))
982 io_req_cqe_overflow(req);
986 * If we're the last reference to this request, add to our locked
989 if (req_ref_put_and_test(req)) {
990 if (req->flags & IO_REQ_LINK_FLAGS) {
991 if (req->flags & IO_DISARM_MASK)
994 io_req_task_queue(req->link);
998 io_put_kbuf_comp(req);
999 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1003 rsrc_node = req->rsrc_node;
1005 * Selected buffer deallocation in io_clean_op() assumes that
1006 * we don't hold ->completion_lock. Clean them here to avoid
1009 io_put_task_remote(req->task);
1010 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1011 ctx->locked_free_nr++;
1013 io_cq_unlock_post(ctx);
1016 io_ring_submit_lock(ctx, issue_flags);
1017 io_put_rsrc_node(ctx, rsrc_node);
1018 io_ring_submit_unlock(ctx, issue_flags);
1022 void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
1024 struct io_ring_ctx *ctx = req->ctx;
1026 if (ctx->task_complete && ctx->submitter_task != current) {
1027 req->io_task_work.func = io_req_task_complete;
1028 io_req_task_work_add(req);
1029 } else if (!(issue_flags & IO_URING_F_UNLOCKED) ||
1030 !(ctx->flags & IORING_SETUP_IOPOLL)) {
1031 __io_req_complete_post(req, issue_flags);
1033 mutex_lock(&ctx->uring_lock);
1034 __io_req_complete_post(req, issue_flags & ~IO_URING_F_UNLOCKED);
1035 mutex_unlock(&ctx->uring_lock);
1039 void io_req_defer_failed(struct io_kiocb *req, s32 res)
1040 __must_hold(&ctx->uring_lock)
1042 const struct io_cold_def *def = &io_cold_defs[req->opcode];
1044 lockdep_assert_held(&req->ctx->uring_lock);
1047 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1050 io_req_complete_defer(req);
1054 * Don't initialise the fields below on every allocation, but do that in
1055 * advance and keep them valid across allocations.
1057 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1061 req->async_data = NULL;
1062 /* not necessary, but safer to zero */
1063 memset(&req->cqe, 0, sizeof(req->cqe));
1064 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
1067 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1068 struct io_submit_state *state)
1070 spin_lock(&ctx->completion_lock);
1071 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1072 ctx->locked_free_nr = 0;
1073 spin_unlock(&ctx->completion_lock);
1077 * A request might get retired back into the request caches even before opcode
1078 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1079 * Because of that, io_alloc_req() should be called only under ->uring_lock
1080 * and with extra caution to not get a request that is still worked on.
1082 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1083 __must_hold(&ctx->uring_lock)
1085 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1086 void *reqs[IO_REQ_ALLOC_BATCH];
1090 * If we have more than a batch's worth of requests in our IRQ side
1091 * locked cache, grab the lock and move them over to our submission
1094 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1095 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1096 if (!io_req_cache_empty(ctx))
1100 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1103 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1104 * retry single alloc to be on the safe side.
1106 if (unlikely(ret <= 0)) {
1107 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1113 percpu_ref_get_many(&ctx->refs, ret);
1114 for (i = 0; i < ret; i++) {
1115 struct io_kiocb *req = reqs[i];
1117 io_preinit_req(req, ctx);
1118 io_req_add_to_cache(req, ctx);
1123 __cold void io_free_req(struct io_kiocb *req)
1125 /* refs were already put, restore them for io_req_task_complete() */
1126 req->flags &= ~REQ_F_REFCOUNT;
1127 /* we only want to free it, don't post CQEs */
1128 req->flags |= REQ_F_CQE_SKIP;
1129 req->io_task_work.func = io_req_task_complete;
1130 io_req_task_work_add(req);
1133 static void __io_req_find_next_prep(struct io_kiocb *req)
1135 struct io_ring_ctx *ctx = req->ctx;
1137 spin_lock(&ctx->completion_lock);
1138 io_disarm_next(req);
1139 spin_unlock(&ctx->completion_lock);
1142 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1144 struct io_kiocb *nxt;
1147 * If LINK is set, we have dependent requests in this chain. If we
1148 * didn't fail this request, queue the first one up, moving any other
1149 * dependencies to the next request. In case of failure, fail the rest
1152 if (unlikely(req->flags & IO_DISARM_MASK))
1153 __io_req_find_next_prep(req);
1159 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
1163 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1164 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1166 io_submit_flush_completions(ctx);
1167 mutex_unlock(&ctx->uring_lock);
1170 percpu_ref_put(&ctx->refs);
1174 * Run queued task_work, returning the number of entries processed in *count.
1175 * If more entries than max_entries are available, stop processing once this
1176 * is reached and return the rest of the list.
1178 struct llist_node *io_handle_tw_list(struct llist_node *node,
1179 unsigned int *count,
1180 unsigned int max_entries)
1182 struct io_ring_ctx *ctx = NULL;
1183 struct io_tw_state ts = { };
1186 struct llist_node *next = node->next;
1187 struct io_kiocb *req = container_of(node, struct io_kiocb,
1190 if (req->ctx != ctx) {
1191 ctx_flush_and_put(ctx, &ts);
1193 /* if not contended, grab and improve batching */
1194 ts.locked = mutex_trylock(&ctx->uring_lock);
1195 percpu_ref_get(&ctx->refs);
1197 INDIRECT_CALL_2(req->io_task_work.func,
1198 io_poll_task_func, io_req_rw_complete,
1202 if (unlikely(need_resched())) {
1203 ctx_flush_and_put(ctx, &ts);
1207 } while (node && *count < max_entries);
1209 ctx_flush_and_put(ctx, &ts);
1214 * io_llist_xchg - swap all entries in a lock-less list
1215 * @head: the head of lock-less list to delete all entries
1216 * @new: new entry as the head of the list
1218 * If list is empty, return NULL, otherwise, return the pointer to the first entry.
1219 * The order of entries returned is from the newest to the oldest added one.
1221 static inline struct llist_node *io_llist_xchg(struct llist_head *head,
1222 struct llist_node *new)
1224 return xchg(&head->first, new);
1227 static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1229 struct llist_node *node = llist_del_all(&tctx->task_list);
1230 struct io_ring_ctx *last_ctx = NULL;
1231 struct io_kiocb *req;
1234 req = container_of(node, struct io_kiocb, io_task_work.node);
1236 if (sync && last_ctx != req->ctx) {
1238 flush_delayed_work(&last_ctx->fallback_work);
1239 percpu_ref_put(&last_ctx->refs);
1241 last_ctx = req->ctx;
1242 percpu_ref_get(&last_ctx->refs);
1244 if (llist_add(&req->io_task_work.node,
1245 &req->ctx->fallback_llist))
1246 schedule_delayed_work(&req->ctx->fallback_work, 1);
1250 flush_delayed_work(&last_ctx->fallback_work);
1251 percpu_ref_put(&last_ctx->refs);
1255 struct llist_node *tctx_task_work_run(struct io_uring_task *tctx,
1256 unsigned int max_entries,
1257 unsigned int *count)
1259 struct llist_node *node;
1261 if (unlikely(current->flags & PF_EXITING)) {
1262 io_fallback_tw(tctx, true);
1266 node = llist_del_all(&tctx->task_list);
1268 node = llist_reverse_order(node);
1269 node = io_handle_tw_list(node, count, max_entries);
1272 /* relaxed read is enough as only the task itself sets ->in_cancel */
1273 if (unlikely(atomic_read(&tctx->in_cancel)))
1274 io_uring_drop_tctx_refs(current);
1276 trace_io_uring_task_work_run(tctx, *count);
1280 void tctx_task_work(struct callback_head *cb)
1282 struct io_uring_task *tctx;
1283 struct llist_node *ret;
1284 unsigned int count = 0;
1286 tctx = container_of(cb, struct io_uring_task, task_work);
1287 ret = tctx_task_work_run(tctx, UINT_MAX, &count);
1292 static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1294 struct io_ring_ctx *ctx = req->ctx;
1295 unsigned nr_wait, nr_tw, nr_tw_prev;
1296 struct llist_node *head;
1298 /* See comment above IO_CQ_WAKE_INIT */
1299 BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
1302 * We don't know how many reuqests is there in the link and whether
1303 * they can even be queued lazily, fall back to non-lazy.
1305 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1306 flags &= ~IOU_F_TWQ_LAZY_WAKE;
1308 head = READ_ONCE(ctx->work_llist.first);
1312 struct io_kiocb *first_req = container_of(head,
1316 * Might be executed at any moment, rely on
1317 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1319 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1323 * Theoretically, it can overflow, but that's fine as one of
1324 * previous adds should've tried to wake the task.
1326 nr_tw = nr_tw_prev + 1;
1327 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1328 nr_tw = IO_CQ_WAKE_FORCE;
1331 req->io_task_work.node.next = head;
1332 } while (!try_cmpxchg(&ctx->work_llist.first, &head,
1333 &req->io_task_work.node));
1336 * cmpxchg implies a full barrier, which pairs with the barrier
1337 * in set_current_state() on the io_cqring_wait() side. It's used
1338 * to ensure that either we see updated ->cq_wait_nr, or waiters
1339 * going to sleep will observe the work added to the list, which
1340 * is similar to the wait/wawke task state sync.
1344 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1345 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1347 io_eventfd_signal(ctx);
1350 nr_wait = atomic_read(&ctx->cq_wait_nr);
1351 /* not enough or no one is waiting */
1352 if (nr_tw < nr_wait)
1354 /* the previous add has already woken it up */
1355 if (nr_tw_prev >= nr_wait)
1357 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1360 static void io_req_normal_work_add(struct io_kiocb *req)
1362 struct io_uring_task *tctx = req->task->io_uring;
1363 struct io_ring_ctx *ctx = req->ctx;
1365 /* task_work already pending, we're done */
1366 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1369 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1370 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1372 /* SQPOLL doesn't need the task_work added, it'll run it itself */
1373 if (ctx->flags & IORING_SETUP_SQPOLL)
1376 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1379 io_fallback_tw(tctx, false);
1382 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1384 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
1386 io_req_local_work_add(req, flags);
1389 io_req_normal_work_add(req);
1393 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1395 struct llist_node *node;
1397 node = llist_del_all(&ctx->work_llist);
1399 struct io_kiocb *req = container_of(node, struct io_kiocb,
1403 io_req_normal_work_add(req);
1407 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1410 if (llist_empty(&ctx->work_llist))
1412 if (events < min_events)
1414 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1415 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1419 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1422 struct llist_node *node;
1423 unsigned int loops = 0;
1426 if (WARN_ON_ONCE(ctx->submitter_task != current))
1428 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1429 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1432 * llists are in reverse order, flip it back the right way before
1433 * running the pending items.
1435 node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
1437 struct llist_node *next = node->next;
1438 struct io_kiocb *req = container_of(node, struct io_kiocb,
1440 INDIRECT_CALL_2(req->io_task_work.func,
1441 io_poll_task_func, io_req_rw_complete,
1448 if (io_run_local_work_continue(ctx, ret, min_events))
1451 io_submit_flush_completions(ctx);
1452 if (io_run_local_work_continue(ctx, ret, min_events))
1456 trace_io_uring_local_work_run(ctx, ret, loops);
1460 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1463 struct io_tw_state ts = { .locked = true, };
1466 if (llist_empty(&ctx->work_llist))
1469 ret = __io_run_local_work(ctx, &ts, min_events);
1470 /* shouldn't happen! */
1471 if (WARN_ON_ONCE(!ts.locked))
1472 mutex_lock(&ctx->uring_lock);
1476 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
1478 struct io_tw_state ts = {};
1481 ts.locked = mutex_trylock(&ctx->uring_lock);
1482 ret = __io_run_local_work(ctx, &ts, min_events);
1484 mutex_unlock(&ctx->uring_lock);
1489 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
1491 io_tw_lock(req->ctx, ts);
1492 io_req_defer_failed(req, req->cqe.res);
1495 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
1497 io_tw_lock(req->ctx, ts);
1498 /* req->task == current here, checking PF_EXITING is safe */
1499 if (unlikely(req->task->flags & PF_EXITING))
1500 io_req_defer_failed(req, -EFAULT);
1501 else if (req->flags & REQ_F_FORCE_ASYNC)
1502 io_queue_iowq(req, ts);
1507 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1509 io_req_set_res(req, ret, 0);
1510 req->io_task_work.func = io_req_task_cancel;
1511 io_req_task_work_add(req);
1514 void io_req_task_queue(struct io_kiocb *req)
1516 req->io_task_work.func = io_req_task_submit;
1517 io_req_task_work_add(req);
1520 void io_queue_next(struct io_kiocb *req)
1522 struct io_kiocb *nxt = io_req_find_next(req);
1525 io_req_task_queue(nxt);
1528 static void io_free_batch_list(struct io_ring_ctx *ctx,
1529 struct io_wq_work_node *node)
1530 __must_hold(&ctx->uring_lock)
1533 struct io_kiocb *req = container_of(node, struct io_kiocb,
1536 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1537 if (req->flags & REQ_F_REFCOUNT) {
1538 node = req->comp_list.next;
1539 if (!req_ref_put_and_test(req))
1542 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1543 struct async_poll *apoll = req->apoll;
1545 if (apoll->double_poll)
1546 kfree(apoll->double_poll);
1547 if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache))
1549 req->flags &= ~REQ_F_POLLED;
1551 if (req->flags & IO_REQ_LINK_FLAGS)
1553 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1558 io_req_put_rsrc_locked(req, ctx);
1560 io_put_task(req->task);
1561 node = req->comp_list.next;
1562 io_req_add_to_cache(req, ctx);
1566 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1567 __must_hold(&ctx->uring_lock)
1569 struct io_submit_state *state = &ctx->submit_state;
1570 struct io_wq_work_node *node;
1573 /* must come first to preserve CQE ordering in failure cases */
1574 if (state->cqes_count)
1575 __io_flush_post_cqes(ctx);
1576 __wq_list_for_each(node, &state->compl_reqs) {
1577 struct io_kiocb *req = container_of(node, struct io_kiocb,
1580 if (!(req->flags & REQ_F_CQE_SKIP) &&
1581 unlikely(!io_fill_cqe_req(ctx, req))) {
1582 if (ctx->lockless_cq) {
1583 spin_lock(&ctx->completion_lock);
1584 io_req_cqe_overflow(req);
1585 spin_unlock(&ctx->completion_lock);
1587 io_req_cqe_overflow(req);
1591 __io_cq_unlock_post(ctx);
1593 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) {
1594 io_free_batch_list(ctx, state->compl_reqs.first);
1595 INIT_WQ_LIST(&state->compl_reqs);
1599 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1601 /* See comment at the top of this file */
1603 return __io_cqring_events(ctx);
1607 * We can't just wait for polled events to come to us, we have to actively
1608 * find and complete them.
1610 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1612 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1615 mutex_lock(&ctx->uring_lock);
1616 while (!wq_list_empty(&ctx->iopoll_list)) {
1617 /* let it sleep and repeat later if can't complete a request */
1618 if (io_do_iopoll(ctx, true) == 0)
1621 * Ensure we allow local-to-the-cpu processing to take place,
1622 * in this case we need to ensure that we reap all events.
1623 * Also let task_work, etc. to progress by releasing the mutex
1625 if (need_resched()) {
1626 mutex_unlock(&ctx->uring_lock);
1628 mutex_lock(&ctx->uring_lock);
1631 mutex_unlock(&ctx->uring_lock);
1634 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1636 unsigned int nr_events = 0;
1637 unsigned long check_cq;
1639 if (!io_allowed_run_tw(ctx))
1642 check_cq = READ_ONCE(ctx->check_cq);
1643 if (unlikely(check_cq)) {
1644 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1645 __io_cqring_overflow_flush(ctx);
1647 * Similarly do not spin if we have not informed the user of any
1650 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1654 * Don't enter poll loop if we already have events pending.
1655 * If we do, we can potentially be spinning for commands that
1656 * already triggered a CQE (eg in error).
1658 if (io_cqring_events(ctx))
1665 * If a submit got punted to a workqueue, we can have the
1666 * application entering polling for a command before it gets
1667 * issued. That app will hold the uring_lock for the duration
1668 * of the poll right here, so we need to take a breather every
1669 * now and then to ensure that the issue has a chance to add
1670 * the poll to the issued list. Otherwise we can spin here
1671 * forever, while the workqueue is stuck trying to acquire the
1674 if (wq_list_empty(&ctx->iopoll_list) ||
1675 io_task_work_pending(ctx)) {
1676 u32 tail = ctx->cached_cq_tail;
1678 (void) io_run_local_work_locked(ctx, min);
1680 if (task_work_pending(current) ||
1681 wq_list_empty(&ctx->iopoll_list)) {
1682 mutex_unlock(&ctx->uring_lock);
1684 mutex_lock(&ctx->uring_lock);
1686 /* some requests don't go through iopoll_list */
1687 if (tail != ctx->cached_cq_tail ||
1688 wq_list_empty(&ctx->iopoll_list))
1691 ret = io_do_iopoll(ctx, !min);
1692 if (unlikely(ret < 0))
1695 if (task_sigpending(current))
1701 } while (nr_events < min);
1706 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
1709 io_req_complete_defer(req);
1711 io_req_complete_post(req, IO_URING_F_UNLOCKED);
1715 * After the iocb has been issued, it's safe to be found on the poll list.
1716 * Adding the kiocb to the list AFTER submission ensures that we don't
1717 * find it from a io_do_iopoll() thread before the issuer is done
1718 * accessing the kiocb cookie.
1720 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1722 struct io_ring_ctx *ctx = req->ctx;
1723 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1725 /* workqueue context doesn't hold uring_lock, grab it now */
1726 if (unlikely(needs_lock))
1727 mutex_lock(&ctx->uring_lock);
1730 * Track whether we have multiple files in our lists. This will impact
1731 * how we do polling eventually, not spinning if we're on potentially
1732 * different devices.
1734 if (wq_list_empty(&ctx->iopoll_list)) {
1735 ctx->poll_multi_queue = false;
1736 } else if (!ctx->poll_multi_queue) {
1737 struct io_kiocb *list_req;
1739 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1741 if (list_req->file != req->file)
1742 ctx->poll_multi_queue = true;
1746 * For fast devices, IO may have already completed. If it has, add
1747 * it to the front so we find it first.
1749 if (READ_ONCE(req->iopoll_completed))
1750 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1752 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1754 if (unlikely(needs_lock)) {
1756 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1757 * in sq thread task context or in io worker task context. If
1758 * current task context is sq thread, we don't need to check
1759 * whether should wake up sq thread.
1761 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1762 wq_has_sleeper(&ctx->sq_data->wait))
1763 wake_up(&ctx->sq_data->wait);
1765 mutex_unlock(&ctx->uring_lock);
1769 io_req_flags_t io_file_get_flags(struct file *file)
1771 io_req_flags_t res = 0;
1773 if (S_ISREG(file_inode(file)->i_mode))
1775 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1776 res |= REQ_F_SUPPORT_NOWAIT;
1780 bool io_alloc_async_data(struct io_kiocb *req)
1782 WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size);
1783 req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL);
1784 if (req->async_data) {
1785 req->flags |= REQ_F_ASYNC_DATA;
1791 int io_req_prep_async(struct io_kiocb *req)
1793 const struct io_cold_def *cdef = &io_cold_defs[req->opcode];
1794 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1796 /* assign early for deferred execution for non-fixed file */
1797 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file)
1798 req->file = io_file_get_normal(req, req->cqe.fd);
1799 if (!cdef->prep_async)
1801 if (WARN_ON_ONCE(req_has_async_data(req)))
1803 if (!def->manual_alloc) {
1804 if (io_alloc_async_data(req))
1807 return cdef->prep_async(req);
1810 static u32 io_get_sequence(struct io_kiocb *req)
1812 u32 seq = req->ctx->cached_sq_head;
1813 struct io_kiocb *cur;
1815 /* need original cached_sq_head, but it was increased for each req */
1816 io_for_each_link(cur, req)
1821 static __cold void io_drain_req(struct io_kiocb *req)
1822 __must_hold(&ctx->uring_lock)
1824 struct io_ring_ctx *ctx = req->ctx;
1825 struct io_defer_entry *de;
1827 u32 seq = io_get_sequence(req);
1829 /* Still need defer if there is pending req in defer list. */
1830 spin_lock(&ctx->completion_lock);
1831 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1832 spin_unlock(&ctx->completion_lock);
1834 ctx->drain_active = false;
1835 io_req_task_queue(req);
1838 spin_unlock(&ctx->completion_lock);
1840 io_prep_async_link(req);
1841 de = kmalloc(sizeof(*de), GFP_KERNEL);
1844 io_req_defer_failed(req, ret);
1848 spin_lock(&ctx->completion_lock);
1849 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1850 spin_unlock(&ctx->completion_lock);
1855 trace_io_uring_defer(req);
1858 list_add_tail(&de->list, &ctx->defer_list);
1859 spin_unlock(&ctx->completion_lock);
1862 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1863 unsigned int issue_flags)
1865 if (req->file || !def->needs_file)
1868 if (req->flags & REQ_F_FIXED_FILE)
1869 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1871 req->file = io_file_get_normal(req, req->cqe.fd);
1876 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1878 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1879 const struct cred *creds = NULL;
1882 if (unlikely(!io_assign_file(req, def, issue_flags)))
1885 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1886 creds = override_creds(req->creds);
1888 if (!def->audit_skip)
1889 audit_uring_entry(req->opcode);
1891 ret = def->issue(req, issue_flags);
1893 if (!def->audit_skip)
1894 audit_uring_exit(!ret, ret);
1897 revert_creds(creds);
1899 if (ret == IOU_OK) {
1900 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1901 io_req_complete_defer(req);
1903 io_req_complete_post(req, issue_flags);
1908 if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1910 io_arm_ltimeout(req);
1912 /* If the op doesn't have a file, we're not polling for it */
1913 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1914 io_iopoll_req_issued(req, issue_flags);
1919 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
1921 io_tw_lock(req->ctx, ts);
1922 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1923 IO_URING_F_COMPLETE_DEFER);
1926 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1928 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1929 struct io_kiocb *nxt = NULL;
1931 if (req_ref_put_and_test(req)) {
1932 if (req->flags & IO_REQ_LINK_FLAGS)
1933 nxt = io_req_find_next(req);
1936 return nxt ? &nxt->work : NULL;
1939 void io_wq_submit_work(struct io_wq_work *work)
1941 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1942 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1943 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1944 bool needs_poll = false;
1945 int ret = 0, err = -ECANCELED;
1947 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1948 if (!(req->flags & REQ_F_REFCOUNT))
1949 __io_req_set_refcount(req, 2);
1953 io_arm_ltimeout(req);
1955 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1956 if (work->flags & IO_WQ_WORK_CANCEL) {
1958 io_req_task_queue_fail(req, err);
1961 if (!io_assign_file(req, def, issue_flags)) {
1963 work->flags |= IO_WQ_WORK_CANCEL;
1967 if (req->flags & REQ_F_FORCE_ASYNC) {
1968 bool opcode_poll = def->pollin || def->pollout;
1970 if (opcode_poll && io_file_can_poll(req)) {
1972 issue_flags |= IO_URING_F_NONBLOCK;
1977 ret = io_issue_sqe(req, issue_flags);
1982 * If REQ_F_NOWAIT is set, then don't wait or retry with
1983 * poll. -EAGAIN is final for that case.
1985 if (req->flags & REQ_F_NOWAIT)
1989 * We can get EAGAIN for iopolled IO even though we're
1990 * forcing a sync submission from here, since we can't
1991 * wait for request slots on the block side.
1994 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1996 if (io_wq_worker_stopped())
2002 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
2004 /* aborted or ready, in either case retry blocking */
2006 issue_flags &= ~IO_URING_F_NONBLOCK;
2009 /* avoid locking problems by failing it from a clean context */
2011 io_req_task_queue_fail(req, ret);
2014 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
2015 unsigned int issue_flags)
2017 struct io_ring_ctx *ctx = req->ctx;
2018 struct io_fixed_file *slot;
2019 struct file *file = NULL;
2021 io_ring_submit_lock(ctx, issue_flags);
2023 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
2025 fd = array_index_nospec(fd, ctx->nr_user_files);
2026 slot = io_fixed_file_slot(&ctx->file_table, fd);
2027 if (!req->rsrc_node)
2028 __io_req_set_rsrc_node(req, ctx);
2029 req->flags |= io_slot_flags(slot);
2030 file = io_slot_file(slot);
2032 io_ring_submit_unlock(ctx, issue_flags);
2036 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
2038 struct file *file = fget(fd);
2040 trace_io_uring_file_get(req, fd);
2042 /* we don't allow fixed io_uring files */
2043 if (file && io_is_uring_fops(file))
2044 io_req_track_inflight(req);
2048 static void io_queue_async(struct io_kiocb *req, int ret)
2049 __must_hold(&req->ctx->uring_lock)
2051 struct io_kiocb *linked_timeout;
2053 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
2054 io_req_defer_failed(req, ret);
2058 linked_timeout = io_prep_linked_timeout(req);
2060 switch (io_arm_poll_handler(req, 0)) {
2061 case IO_APOLL_READY:
2062 io_kbuf_recycle(req, 0);
2063 io_req_task_queue(req);
2065 case IO_APOLL_ABORTED:
2066 io_kbuf_recycle(req, 0);
2067 io_queue_iowq(req, NULL);
2074 io_queue_linked_timeout(linked_timeout);
2077 static inline void io_queue_sqe(struct io_kiocb *req)
2078 __must_hold(&req->ctx->uring_lock)
2082 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
2085 * We async punt it if the file wasn't marked NOWAIT, or if the file
2086 * doesn't support non-blocking read/write attempts
2089 io_queue_async(req, ret);
2092 static void io_queue_sqe_fallback(struct io_kiocb *req)
2093 __must_hold(&req->ctx->uring_lock)
2095 if (unlikely(req->flags & REQ_F_FAIL)) {
2097 * We don't submit, fail them all, for that replace hardlinks
2098 * with normal links. Extra REQ_F_LINK is tolerated.
2100 req->flags &= ~REQ_F_HARDLINK;
2101 req->flags |= REQ_F_LINK;
2102 io_req_defer_failed(req, req->cqe.res);
2104 int ret = io_req_prep_async(req);
2106 if (unlikely(ret)) {
2107 io_req_defer_failed(req, ret);
2111 if (unlikely(req->ctx->drain_active))
2114 io_queue_iowq(req, NULL);
2119 * Check SQE restrictions (opcode and flags).
2121 * Returns 'true' if SQE is allowed, 'false' otherwise.
2123 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2124 struct io_kiocb *req,
2125 unsigned int sqe_flags)
2127 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2130 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2131 ctx->restrictions.sqe_flags_required)
2134 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2135 ctx->restrictions.sqe_flags_required))
2141 static void io_init_req_drain(struct io_kiocb *req)
2143 struct io_ring_ctx *ctx = req->ctx;
2144 struct io_kiocb *head = ctx->submit_state.link.head;
2146 ctx->drain_active = true;
2149 * If we need to drain a request in the middle of a link, drain
2150 * the head request and the next request/link after the current
2151 * link. Considering sequential execution of links,
2152 * REQ_F_IO_DRAIN will be maintained for every request of our
2155 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2156 ctx->drain_next = true;
2160 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2161 const struct io_uring_sqe *sqe)
2162 __must_hold(&ctx->uring_lock)
2164 const struct io_issue_def *def;
2165 unsigned int sqe_flags;
2169 /* req is partially pre-initialised, see io_preinit_req() */
2170 req->opcode = opcode = READ_ONCE(sqe->opcode);
2171 /* same numerical values with corresponding REQ_F_*, safe to copy */
2172 sqe_flags = READ_ONCE(sqe->flags);
2173 req->flags = (io_req_flags_t) sqe_flags;
2174 req->cqe.user_data = READ_ONCE(sqe->user_data);
2176 req->rsrc_node = NULL;
2177 req->task = current;
2179 if (unlikely(opcode >= IORING_OP_LAST)) {
2183 def = &io_issue_defs[opcode];
2184 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2185 /* enforce forwards compatibility on users */
2186 if (sqe_flags & ~SQE_VALID_FLAGS)
2188 if (sqe_flags & IOSQE_BUFFER_SELECT) {
2189 if (!def->buffer_select)
2191 req->buf_index = READ_ONCE(sqe->buf_group);
2193 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2194 ctx->drain_disabled = true;
2195 if (sqe_flags & IOSQE_IO_DRAIN) {
2196 if (ctx->drain_disabled)
2198 io_init_req_drain(req);
2201 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2202 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2204 /* knock it to the slow queue path, will be drained there */
2205 if (ctx->drain_active)
2206 req->flags |= REQ_F_FORCE_ASYNC;
2207 /* if there is no link, we're at "next" request and need to drain */
2208 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2209 ctx->drain_next = false;
2210 ctx->drain_active = true;
2211 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2215 if (!def->ioprio && sqe->ioprio)
2217 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2220 if (def->needs_file) {
2221 struct io_submit_state *state = &ctx->submit_state;
2223 req->cqe.fd = READ_ONCE(sqe->fd);
2226 * Plug now if we have more than 2 IO left after this, and the
2227 * target is potentially a read/write to block based storage.
2229 if (state->need_plug && def->plug) {
2230 state->plug_started = true;
2231 state->need_plug = false;
2232 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2236 personality = READ_ONCE(sqe->personality);
2240 req->creds = xa_load(&ctx->personalities, personality);
2243 get_cred(req->creds);
2244 ret = security_uring_override_creds(req->creds);
2246 put_cred(req->creds);
2249 req->flags |= REQ_F_CREDS;
2252 return def->prep(req, sqe);
2255 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2256 struct io_kiocb *req, int ret)
2258 struct io_ring_ctx *ctx = req->ctx;
2259 struct io_submit_link *link = &ctx->submit_state.link;
2260 struct io_kiocb *head = link->head;
2262 trace_io_uring_req_failed(sqe, req, ret);
2265 * Avoid breaking links in the middle as it renders links with SQPOLL
2266 * unusable. Instead of failing eagerly, continue assembling the link if
2267 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2268 * should find the flag and handle the rest.
2270 req_fail_link_node(req, ret);
2271 if (head && !(head->flags & REQ_F_FAIL))
2272 req_fail_link_node(head, -ECANCELED);
2274 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2276 link->last->link = req;
2280 io_queue_sqe_fallback(req);
2285 link->last->link = req;
2292 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2293 const struct io_uring_sqe *sqe)
2294 __must_hold(&ctx->uring_lock)
2296 struct io_submit_link *link = &ctx->submit_state.link;
2299 ret = io_init_req(ctx, req, sqe);
2301 return io_submit_fail_init(sqe, req, ret);
2303 trace_io_uring_submit_req(req);
2306 * If we already have a head request, queue this one for async
2307 * submittal once the head completes. If we don't have a head but
2308 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2309 * submitted sync once the chain is complete. If none of those
2310 * conditions are true (normal request), then just queue it.
2312 if (unlikely(link->head)) {
2313 ret = io_req_prep_async(req);
2315 return io_submit_fail_init(sqe, req, ret);
2317 trace_io_uring_link(req, link->head);
2318 link->last->link = req;
2321 if (req->flags & IO_REQ_LINK_FLAGS)
2323 /* last request of the link, flush it */
2326 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2329 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2330 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2331 if (req->flags & IO_REQ_LINK_FLAGS) {
2336 io_queue_sqe_fallback(req);
2346 * Batched submission is done, ensure local IO is flushed out.
2348 static void io_submit_state_end(struct io_ring_ctx *ctx)
2350 struct io_submit_state *state = &ctx->submit_state;
2352 if (unlikely(state->link.head))
2353 io_queue_sqe_fallback(state->link.head);
2354 /* flush only after queuing links as they can generate completions */
2355 io_submit_flush_completions(ctx);
2356 if (state->plug_started)
2357 blk_finish_plug(&state->plug);
2361 * Start submission side cache.
2363 static void io_submit_state_start(struct io_submit_state *state,
2364 unsigned int max_ios)
2366 state->plug_started = false;
2367 state->need_plug = max_ios > 2;
2368 state->submit_nr = max_ios;
2369 /* set only head, no need to init link_last in advance */
2370 state->link.head = NULL;
2373 static void io_commit_sqring(struct io_ring_ctx *ctx)
2375 struct io_rings *rings = ctx->rings;
2378 * Ensure any loads from the SQEs are done at this point,
2379 * since once we write the new head, the application could
2380 * write new data to them.
2382 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2386 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2387 * that is mapped by userspace. This means that care needs to be taken to
2388 * ensure that reads are stable, as we cannot rely on userspace always
2389 * being a good citizen. If members of the sqe are validated and then later
2390 * used, it's important that those reads are done through READ_ONCE() to
2391 * prevent a re-load down the line.
2393 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2395 unsigned mask = ctx->sq_entries - 1;
2396 unsigned head = ctx->cached_sq_head++ & mask;
2398 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
2399 head = READ_ONCE(ctx->sq_array[head]);
2400 if (unlikely(head >= ctx->sq_entries)) {
2401 /* drop invalid entries */
2402 spin_lock(&ctx->completion_lock);
2404 spin_unlock(&ctx->completion_lock);
2405 WRITE_ONCE(ctx->rings->sq_dropped,
2406 READ_ONCE(ctx->rings->sq_dropped) + 1);
2412 * The cached sq head (or cq tail) serves two purposes:
2414 * 1) allows us to batch the cost of updating the user visible
2416 * 2) allows the kernel side to track the head on its own, even
2417 * though the application is the one updating it.
2420 /* double index for 128-byte SQEs, twice as long */
2421 if (ctx->flags & IORING_SETUP_SQE128)
2423 *sqe = &ctx->sq_sqes[head];
2427 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2428 __must_hold(&ctx->uring_lock)
2430 unsigned int entries = io_sqring_entries(ctx);
2434 if (unlikely(!entries))
2436 /* make sure SQ entry isn't read before tail */
2437 ret = left = min(nr, entries);
2438 io_get_task_refs(left);
2439 io_submit_state_start(&ctx->submit_state, left);
2442 const struct io_uring_sqe *sqe;
2443 struct io_kiocb *req;
2445 if (unlikely(!io_alloc_req(ctx, &req)))
2447 if (unlikely(!io_get_sqe(ctx, &sqe))) {
2448 io_req_add_to_cache(req, ctx);
2453 * Continue submitting even for sqe failure if the
2454 * ring was setup with IORING_SETUP_SUBMIT_ALL
2456 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2457 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2463 if (unlikely(left)) {
2465 /* try again if it submitted nothing and can't allocate a req */
2466 if (!ret && io_req_cache_empty(ctx))
2468 current->io_uring->cached_refs += left;
2471 io_submit_state_end(ctx);
2472 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2473 io_commit_sqring(ctx);
2477 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2478 int wake_flags, void *key)
2480 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2483 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2484 * the task, and the next invocation will do it.
2486 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2487 return autoremove_wake_function(curr, mode, wake_flags, key);
2491 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2493 if (!llist_empty(&ctx->work_llist)) {
2494 __set_current_state(TASK_RUNNING);
2495 if (io_run_local_work(ctx, INT_MAX) > 0)
2498 if (io_run_task_work() > 0)
2500 if (task_sigpending(current))
2505 static bool current_pending_io(void)
2507 struct io_uring_task *tctx = current->io_uring;
2511 return percpu_counter_read_positive(&tctx->inflight);
2514 /* when returns >0, the caller should retry */
2515 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2516 struct io_wait_queue *iowq)
2520 if (unlikely(READ_ONCE(ctx->check_cq)))
2522 if (unlikely(!llist_empty(&ctx->work_llist)))
2524 if (unlikely(test_thread_flag(TIF_NOTIFY_SIGNAL)))
2526 if (unlikely(task_sigpending(current)))
2528 if (unlikely(io_should_wake(iowq)))
2532 * Mark us as being in io_wait if we have pending requests, so cpufreq
2533 * can take into account that the task is waiting for IO - turns out
2534 * to be important for low QD IO.
2536 io_wait = current->in_iowait;
2537 if (current_pending_io())
2538 current->in_iowait = 1;
2540 if (iowq->timeout == KTIME_MAX)
2542 else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS))
2544 current->in_iowait = io_wait;
2549 * Wait until events become available, if we don't already have some. The
2550 * application must reap them itself, as they reside on the shared cq ring.
2552 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2553 const sigset_t __user *sig, size_t sigsz,
2554 struct __kernel_timespec __user *uts)
2556 struct io_wait_queue iowq;
2557 struct io_rings *rings = ctx->rings;
2560 if (!io_allowed_run_tw(ctx))
2562 if (!llist_empty(&ctx->work_llist))
2563 io_run_local_work(ctx, min_events);
2565 io_cqring_overflow_flush(ctx);
2566 /* if user messes with these they will just get an early return */
2567 if (__io_cqring_events_user(ctx) >= min_events)
2571 #ifdef CONFIG_COMPAT
2572 if (in_compat_syscall())
2573 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2577 ret = set_user_sigmask(sig, sigsz);
2583 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2584 iowq.wq.private = current;
2585 INIT_LIST_HEAD(&iowq.wq.entry);
2587 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2588 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2589 iowq.timeout = KTIME_MAX;
2592 struct timespec64 ts;
2594 if (get_timespec64(&ts, uts))
2597 iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2598 io_napi_adjust_timeout(ctx, &iowq, &ts);
2601 io_napi_busy_loop(ctx, &iowq);
2603 trace_io_uring_cqring_wait(ctx, min_events);
2605 int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail);
2606 unsigned long check_cq;
2608 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2609 atomic_set(&ctx->cq_wait_nr, nr_wait);
2610 set_current_state(TASK_INTERRUPTIBLE);
2612 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2613 TASK_INTERRUPTIBLE);
2616 ret = io_cqring_wait_schedule(ctx, &iowq);
2617 __set_current_state(TASK_RUNNING);
2618 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
2621 * Run task_work after scheduling and before io_should_wake().
2622 * If we got woken because of task_work being processed, run it
2623 * now rather than let the caller do another wait loop.
2626 if (!llist_empty(&ctx->work_llist))
2627 io_run_local_work(ctx, nr_wait);
2630 * Non-local task_work will be run on exit to userspace, but
2631 * if we're using DEFER_TASKRUN, then we could have waited
2632 * with a timeout for a number of requests. If the timeout
2633 * hits, we could have some requests ready to process. Ensure
2634 * this break is _after_ we have run task_work, to avoid
2635 * deferring running potentially pending requests until the
2636 * next time we wait for events.
2641 check_cq = READ_ONCE(ctx->check_cq);
2642 if (unlikely(check_cq)) {
2643 /* let the caller flush overflows, retry */
2644 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2645 io_cqring_do_overflow_flush(ctx);
2646 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2652 if (io_should_wake(&iowq)) {
2659 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2660 finish_wait(&ctx->cq_wait, &iowq.wq);
2661 restore_saved_sigmask_unless(ret == -EINTR);
2663 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2666 void io_mem_free(void *ptr)
2671 folio_put(virt_to_folio(ptr));
2674 static void io_pages_free(struct page ***pages, int npages)
2676 struct page **page_array;
2682 page_array = *pages;
2686 for (i = 0; i < npages; i++)
2687 unpin_user_page(page_array[i]);
2692 static void *__io_uaddr_map(struct page ***pages, unsigned short *npages,
2693 unsigned long uaddr, size_t size)
2695 struct page **page_array;
2696 unsigned int nr_pages;
2702 if (uaddr & (PAGE_SIZE - 1) || !size)
2703 return ERR_PTR(-EINVAL);
2705 nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2706 if (nr_pages > USHRT_MAX)
2707 return ERR_PTR(-EINVAL);
2708 page_array = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
2710 return ERR_PTR(-ENOMEM);
2712 ret = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
2714 if (ret != nr_pages) {
2716 io_pages_free(&page_array, ret > 0 ? ret : 0);
2717 return ret < 0 ? ERR_PTR(ret) : ERR_PTR(-EFAULT);
2720 page_addr = page_address(page_array[0]);
2721 for (i = 0; i < nr_pages; i++) {
2725 * Can't support mapping user allocated ring memory on 32-bit
2726 * archs where it could potentially reside in highmem. Just
2727 * fail those with -EINVAL, just like we did on kernels that
2728 * didn't support this feature.
2730 if (PageHighMem(page_array[i]))
2734 * No support for discontig pages for now, should either be a
2735 * single normal page, or a huge page. Later on we can add
2736 * support for remapping discontig pages, for now we will
2737 * just fail them with EINVAL.
2739 if (page_address(page_array[i]) != page_addr)
2741 page_addr += PAGE_SIZE;
2744 *pages = page_array;
2746 return page_to_virt(page_array[0]);
2749 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2752 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2756 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2759 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2763 static void io_rings_free(struct io_ring_ctx *ctx)
2765 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2766 io_mem_free(ctx->rings);
2767 io_mem_free(ctx->sq_sqes);
2769 ctx->sq_sqes = NULL;
2771 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
2772 ctx->n_ring_pages = 0;
2773 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
2774 ctx->n_sqe_pages = 0;
2778 void *io_mem_alloc(size_t size)
2780 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2783 ret = (void *) __get_free_pages(gfp, get_order(size));
2786 return ERR_PTR(-ENOMEM);
2789 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2790 unsigned int cq_entries, size_t *sq_offset)
2792 struct io_rings *rings;
2793 size_t off, sq_array_size;
2795 off = struct_size(rings, cqes, cq_entries);
2796 if (off == SIZE_MAX)
2798 if (ctx->flags & IORING_SETUP_CQE32) {
2799 if (check_shl_overflow(off, 1, &off))
2804 off = ALIGN(off, SMP_CACHE_BYTES);
2809 if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
2811 *sq_offset = SIZE_MAX;
2818 sq_array_size = array_size(sizeof(u32), sq_entries);
2819 if (sq_array_size == SIZE_MAX)
2822 if (check_add_overflow(off, sq_array_size, &off))
2828 static void io_req_caches_free(struct io_ring_ctx *ctx)
2830 struct io_kiocb *req;
2833 mutex_lock(&ctx->uring_lock);
2834 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2836 while (!io_req_cache_empty(ctx)) {
2837 req = io_extract_req(ctx);
2838 kmem_cache_free(req_cachep, req);
2842 percpu_ref_put_many(&ctx->refs, nr);
2843 mutex_unlock(&ctx->uring_lock);
2846 static void io_rsrc_node_cache_free(struct io_cache_entry *entry)
2848 kfree(container_of(entry, struct io_rsrc_node, cache));
2851 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2853 io_sq_thread_finish(ctx);
2854 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
2855 if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
2858 mutex_lock(&ctx->uring_lock);
2860 __io_sqe_buffers_unregister(ctx);
2862 __io_sqe_files_unregister(ctx);
2863 io_cqring_overflow_kill(ctx);
2864 io_eventfd_unregister(ctx);
2865 io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free);
2866 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
2867 io_futex_cache_free(ctx);
2868 io_destroy_buffers(ctx);
2869 mutex_unlock(&ctx->uring_lock);
2871 put_cred(ctx->sq_creds);
2872 if (ctx->submitter_task)
2873 put_task_struct(ctx->submitter_task);
2875 /* there are no registered resources left, nobody uses it */
2877 io_rsrc_node_destroy(ctx, ctx->rsrc_node);
2879 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
2880 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2882 io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free);
2883 if (ctx->mm_account) {
2884 mmdrop(ctx->mm_account);
2885 ctx->mm_account = NULL;
2888 io_kbuf_mmap_list_free(ctx);
2890 percpu_ref_exit(&ctx->refs);
2891 free_uid(ctx->user);
2892 io_req_caches_free(ctx);
2894 io_wq_put_hash(ctx->hash_map);
2896 kfree(ctx->cancel_table.hbs);
2897 kfree(ctx->cancel_table_locked.hbs);
2899 xa_destroy(&ctx->io_bl_xa);
2903 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2905 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2908 mutex_lock(&ctx->uring_lock);
2909 ctx->poll_activated = true;
2910 mutex_unlock(&ctx->uring_lock);
2913 * Wake ups for some events between start of polling and activation
2914 * might've been lost due to loose synchronisation.
2916 wake_up_all(&ctx->poll_wq);
2917 percpu_ref_put(&ctx->refs);
2920 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2922 spin_lock(&ctx->completion_lock);
2923 /* already activated or in progress */
2924 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2926 if (WARN_ON_ONCE(!ctx->task_complete))
2928 if (!ctx->submitter_task)
2931 * with ->submitter_task only the submitter task completes requests, we
2932 * only need to sync with it, which is done by injecting a tw
2934 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2935 percpu_ref_get(&ctx->refs);
2936 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2937 percpu_ref_put(&ctx->refs);
2939 spin_unlock(&ctx->completion_lock);
2942 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2944 struct io_ring_ctx *ctx = file->private_data;
2947 if (unlikely(!ctx->poll_activated))
2948 io_activate_pollwq(ctx);
2950 poll_wait(file, &ctx->poll_wq, wait);
2952 * synchronizes with barrier from wq_has_sleeper call in
2956 if (!io_sqring_full(ctx))
2957 mask |= EPOLLOUT | EPOLLWRNORM;
2960 * Don't flush cqring overflow list here, just do a simple check.
2961 * Otherwise there could possible be ABBA deadlock:
2964 * lock(&ctx->uring_lock);
2966 * lock(&ctx->uring_lock);
2969 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2970 * pushes them to do the flush.
2973 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2974 mask |= EPOLLIN | EPOLLRDNORM;
2979 struct io_tctx_exit {
2980 struct callback_head task_work;
2981 struct completion completion;
2982 struct io_ring_ctx *ctx;
2985 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2987 struct io_uring_task *tctx = current->io_uring;
2988 struct io_tctx_exit *work;
2990 work = container_of(cb, struct io_tctx_exit, task_work);
2992 * When @in_cancel, we're in cancellation and it's racy to remove the
2993 * node. It'll be removed by the end of cancellation, just ignore it.
2994 * tctx can be NULL if the queueing of this task_work raced with
2995 * work cancelation off the exec path.
2997 if (tctx && !atomic_read(&tctx->in_cancel))
2998 io_uring_del_tctx_node((unsigned long)work->ctx);
2999 complete(&work->completion);
3002 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
3004 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3006 return req->ctx == data;
3009 static __cold void io_ring_exit_work(struct work_struct *work)
3011 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
3012 unsigned long timeout = jiffies + HZ * 60 * 5;
3013 unsigned long interval = HZ / 20;
3014 struct io_tctx_exit exit;
3015 struct io_tctx_node *node;
3019 * If we're doing polled IO and end up having requests being
3020 * submitted async (out-of-line), then completions can come in while
3021 * we're waiting for refs to drop. We need to reap these manually,
3022 * as nobody else will be looking for them.
3025 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
3026 mutex_lock(&ctx->uring_lock);
3027 io_cqring_overflow_kill(ctx);
3028 mutex_unlock(&ctx->uring_lock);
3031 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3032 io_move_task_work_from_local(ctx);
3034 while (io_uring_try_cancel_requests(ctx, NULL, true))
3038 struct io_sq_data *sqd = ctx->sq_data;
3039 struct task_struct *tsk;
3041 io_sq_thread_park(sqd);
3043 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
3044 io_wq_cancel_cb(tsk->io_uring->io_wq,
3045 io_cancel_ctx_cb, ctx, true);
3046 io_sq_thread_unpark(sqd);
3049 io_req_caches_free(ctx);
3051 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
3052 /* there is little hope left, don't run it too often */
3056 * This is really an uninterruptible wait, as it has to be
3057 * complete. But it's also run from a kworker, which doesn't
3058 * take signals, so it's fine to make it interruptible. This
3059 * avoids scenarios where we knowingly can wait much longer
3060 * on completions, for example if someone does a SIGSTOP on
3061 * a task that needs to finish task_work to make this loop
3062 * complete. That's a synthetic situation that should not
3063 * cause a stuck task backtrace, and hence a potential panic
3064 * on stuck tasks if that is enabled.
3066 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
3068 init_completion(&exit.completion);
3069 init_task_work(&exit.task_work, io_tctx_exit_cb);
3072 mutex_lock(&ctx->uring_lock);
3073 while (!list_empty(&ctx->tctx_list)) {
3074 WARN_ON_ONCE(time_after(jiffies, timeout));
3076 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
3078 /* don't spin on a single task if cancellation failed */
3079 list_rotate_left(&ctx->tctx_list);
3080 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
3081 if (WARN_ON_ONCE(ret))
3084 mutex_unlock(&ctx->uring_lock);
3086 * See comment above for
3087 * wait_for_completion_interruptible_timeout() on why this
3088 * wait is marked as interruptible.
3090 wait_for_completion_interruptible(&exit.completion);
3091 mutex_lock(&ctx->uring_lock);
3093 mutex_unlock(&ctx->uring_lock);
3094 spin_lock(&ctx->completion_lock);
3095 spin_unlock(&ctx->completion_lock);
3097 /* pairs with RCU read section in io_req_local_work_add() */
3098 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3101 io_ring_ctx_free(ctx);
3104 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3106 unsigned long index;
3107 struct creds *creds;
3109 mutex_lock(&ctx->uring_lock);
3110 percpu_ref_kill(&ctx->refs);
3111 xa_for_each(&ctx->personalities, index, creds)
3112 io_unregister_personality(ctx, index);
3114 io_poll_remove_all(ctx, NULL, true);
3115 mutex_unlock(&ctx->uring_lock);
3118 * If we failed setting up the ctx, we might not have any rings
3119 * and therefore did not submit any requests
3122 io_kill_timeouts(ctx, NULL, true);
3124 flush_delayed_work(&ctx->fallback_work);
3126 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
3128 * Use system_unbound_wq to avoid spawning tons of event kworkers
3129 * if we're exiting a ton of rings at the same time. It just adds
3130 * noise and overhead, there's no discernable change in runtime
3131 * over using system_wq.
3133 queue_work(system_unbound_wq, &ctx->exit_work);
3136 static int io_uring_release(struct inode *inode, struct file *file)
3138 struct io_ring_ctx *ctx = file->private_data;
3140 file->private_data = NULL;
3141 io_ring_ctx_wait_and_kill(ctx);
3145 struct io_task_cancel {
3146 struct task_struct *task;
3150 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3152 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3153 struct io_task_cancel *cancel = data;
3155 return io_match_task_safe(req, cancel->task, cancel->all);
3158 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3159 struct task_struct *task,
3162 struct io_defer_entry *de;
3165 spin_lock(&ctx->completion_lock);
3166 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
3167 if (io_match_task_safe(de->req, task, cancel_all)) {
3168 list_cut_position(&list, &ctx->defer_list, &de->list);
3172 spin_unlock(&ctx->completion_lock);
3173 if (list_empty(&list))
3176 while (!list_empty(&list)) {
3177 de = list_first_entry(&list, struct io_defer_entry, list);
3178 list_del_init(&de->list);
3179 io_req_task_queue_fail(de->req, -ECANCELED);
3185 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3187 struct io_tctx_node *node;
3188 enum io_wq_cancel cret;
3191 mutex_lock(&ctx->uring_lock);
3192 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3193 struct io_uring_task *tctx = node->task->io_uring;
3196 * io_wq will stay alive while we hold uring_lock, because it's
3197 * killed after ctx nodes, which requires to take the lock.
3199 if (!tctx || !tctx->io_wq)
3201 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3202 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3204 mutex_unlock(&ctx->uring_lock);
3209 static bool io_uring_try_cancel_uring_cmd(struct io_ring_ctx *ctx,
3210 struct task_struct *task, bool cancel_all)
3212 struct hlist_node *tmp;
3213 struct io_kiocb *req;
3216 lockdep_assert_held(&ctx->uring_lock);
3218 hlist_for_each_entry_safe(req, tmp, &ctx->cancelable_uring_cmd,
3220 struct io_uring_cmd *cmd = io_kiocb_to_cmd(req,
3221 struct io_uring_cmd);
3222 struct file *file = req->file;
3224 if (!cancel_all && req->task != task)
3227 if (cmd->flags & IORING_URING_CMD_CANCELABLE) {
3228 /* ->sqe isn't available if no async data */
3229 if (!req_has_async_data(req))
3231 file->f_op->uring_cmd(cmd, IO_URING_F_CANCEL);
3235 io_submit_flush_completions(ctx);
3240 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3241 struct task_struct *task,
3244 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
3245 struct io_uring_task *tctx = task ? task->io_uring : NULL;
3246 enum io_wq_cancel cret;
3249 /* set it so io_req_local_work_add() would wake us up */
3250 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3251 atomic_set(&ctx->cq_wait_nr, 1);
3255 /* failed during ring init, it couldn't have issued any requests */
3260 ret |= io_uring_try_cancel_iowq(ctx);
3261 } else if (tctx && tctx->io_wq) {
3263 * Cancels requests of all rings, not only @ctx, but
3264 * it's fine as the task is in exit/exec.
3266 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3268 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3271 /* SQPOLL thread does its own polling */
3272 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3273 (ctx->sq_data && ctx->sq_data->thread == current)) {
3274 while (!wq_list_empty(&ctx->iopoll_list)) {
3275 io_iopoll_try_reap_events(ctx);
3281 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3282 io_allowed_defer_tw_run(ctx))
3283 ret |= io_run_local_work(ctx, INT_MAX) > 0;
3284 ret |= io_cancel_defer_files(ctx, task, cancel_all);
3285 mutex_lock(&ctx->uring_lock);
3286 ret |= io_poll_remove_all(ctx, task, cancel_all);
3287 ret |= io_waitid_remove_all(ctx, task, cancel_all);
3288 ret |= io_futex_remove_all(ctx, task, cancel_all);
3289 ret |= io_uring_try_cancel_uring_cmd(ctx, task, cancel_all);
3290 mutex_unlock(&ctx->uring_lock);
3291 ret |= io_kill_timeouts(ctx, task, cancel_all);
3293 ret |= io_run_task_work() > 0;
3297 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3300 return atomic_read(&tctx->inflight_tracked);
3301 return percpu_counter_sum(&tctx->inflight);
3305 * Find any io_uring ctx that this task has registered or done IO on, and cancel
3306 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3308 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3310 struct io_uring_task *tctx = current->io_uring;
3311 struct io_ring_ctx *ctx;
3312 struct io_tctx_node *node;
3313 unsigned long index;
3317 WARN_ON_ONCE(sqd && sqd->thread != current);
3319 if (!current->io_uring)
3322 io_wq_exit_start(tctx->io_wq);
3324 atomic_inc(&tctx->in_cancel);
3328 io_uring_drop_tctx_refs(current);
3329 /* read completions before cancelations */
3330 inflight = tctx_inflight(tctx, !cancel_all);
3335 xa_for_each(&tctx->xa, index, node) {
3336 /* sqpoll task will cancel all its requests */
3337 if (node->ctx->sq_data)
3339 loop |= io_uring_try_cancel_requests(node->ctx,
3340 current, cancel_all);
3343 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3344 loop |= io_uring_try_cancel_requests(ctx,
3354 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3356 io_uring_drop_tctx_refs(current);
3357 xa_for_each(&tctx->xa, index, node) {
3358 if (!llist_empty(&node->ctx->work_llist)) {
3359 WARN_ON_ONCE(node->ctx->submitter_task &&
3360 node->ctx->submitter_task != current);
3365 * If we've seen completions, retry without waiting. This
3366 * avoids a race where a completion comes in before we did
3367 * prepare_to_wait().
3369 if (inflight == tctx_inflight(tctx, !cancel_all))
3372 finish_wait(&tctx->wait, &wait);
3375 io_uring_clean_tctx(tctx);
3378 * We shouldn't run task_works after cancel, so just leave
3379 * ->in_cancel set for normal exit.
3381 atomic_dec(&tctx->in_cancel);
3382 /* for exec all current's requests should be gone, kill tctx */
3383 __io_uring_free(current);
3387 void __io_uring_cancel(bool cancel_all)
3389 io_uring_cancel_generic(cancel_all, NULL);
3392 static void *io_uring_validate_mmap_request(struct file *file,
3393 loff_t pgoff, size_t sz)
3395 struct io_ring_ctx *ctx = file->private_data;
3396 loff_t offset = pgoff << PAGE_SHIFT;
3400 switch (offset & IORING_OFF_MMAP_MASK) {
3401 case IORING_OFF_SQ_RING:
3402 case IORING_OFF_CQ_RING:
3403 /* Don't allow mmap if the ring was setup without it */
3404 if (ctx->flags & IORING_SETUP_NO_MMAP)
3405 return ERR_PTR(-EINVAL);
3408 case IORING_OFF_SQES:
3409 /* Don't allow mmap if the ring was setup without it */
3410 if (ctx->flags & IORING_SETUP_NO_MMAP)
3411 return ERR_PTR(-EINVAL);
3414 case IORING_OFF_PBUF_RING: {
3417 bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT;
3419 ptr = io_pbuf_get_address(ctx, bgid);
3422 return ERR_PTR(-EINVAL);
3426 return ERR_PTR(-EINVAL);
3429 page = virt_to_head_page(ptr);
3430 if (sz > page_size(page))
3431 return ERR_PTR(-EINVAL);
3438 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3440 size_t sz = vma->vm_end - vma->vm_start;
3444 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
3446 return PTR_ERR(ptr);
3448 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3449 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3452 static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp,
3453 unsigned long addr, unsigned long len,
3454 unsigned long pgoff, unsigned long flags)
3459 * Do not allow to map to user-provided address to avoid breaking the
3460 * aliasing rules. Userspace is not able to guess the offset address of
3461 * kernel kmalloc()ed memory area.
3466 ptr = io_uring_validate_mmap_request(filp, pgoff, len);
3471 * Some architectures have strong cache aliasing requirements.
3472 * For such architectures we need a coherent mapping which aliases
3473 * kernel memory *and* userspace memory. To achieve that:
3474 * - use a NULL file pointer to reference physical memory, and
3475 * - use the kernel virtual address of the shared io_uring context
3476 * (instead of the userspace-provided address, which has to be 0UL
3478 * - use the same pgoff which the get_unmapped_area() uses to
3479 * calculate the page colouring.
3480 * For architectures without such aliasing requirements, the
3481 * architecture will return any suitable mapping because addr is 0.
3484 flags |= MAP_SHARED;
3485 pgoff = 0; /* has been translated to ptr above */
3487 addr = (uintptr_t) ptr;
3488 pgoff = addr >> PAGE_SHIFT;
3492 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
3495 #else /* !CONFIG_MMU */
3497 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3499 return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL;
3502 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
3504 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
3507 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3508 unsigned long addr, unsigned long len,
3509 unsigned long pgoff, unsigned long flags)
3513 ptr = io_uring_validate_mmap_request(file, pgoff, len);
3515 return PTR_ERR(ptr);
3517 return (unsigned long) ptr;
3520 #endif /* !CONFIG_MMU */
3522 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3524 if (flags & IORING_ENTER_EXT_ARG) {
3525 struct io_uring_getevents_arg arg;
3527 if (argsz != sizeof(arg))
3529 if (copy_from_user(&arg, argp, sizeof(arg)))
3535 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3536 struct __kernel_timespec __user **ts,
3537 const sigset_t __user **sig)
3539 struct io_uring_getevents_arg arg;
3542 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3543 * is just a pointer to the sigset_t.
3545 if (!(flags & IORING_ENTER_EXT_ARG)) {
3546 *sig = (const sigset_t __user *) argp;
3552 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3553 * timespec and sigset_t pointers if good.
3555 if (*argsz != sizeof(arg))
3557 if (copy_from_user(&arg, argp, sizeof(arg)))
3561 *sig = u64_to_user_ptr(arg.sigmask);
3562 *argsz = arg.sigmask_sz;
3563 *ts = u64_to_user_ptr(arg.ts);
3567 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3568 u32, min_complete, u32, flags, const void __user *, argp,
3571 struct io_ring_ctx *ctx;
3575 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3576 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3577 IORING_ENTER_REGISTERED_RING)))
3581 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3582 * need only dereference our task private array to find it.
3584 if (flags & IORING_ENTER_REGISTERED_RING) {
3585 struct io_uring_task *tctx = current->io_uring;
3587 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3589 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3590 file = tctx->registered_rings[fd];
3591 if (unlikely(!file))
3595 if (unlikely(!file))
3598 if (unlikely(!io_is_uring_fops(file)))
3602 ctx = file->private_data;
3604 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3608 * For SQ polling, the thread will do all submissions and completions.
3609 * Just return the requested submit count, and wake the thread if
3613 if (ctx->flags & IORING_SETUP_SQPOLL) {
3614 io_cqring_overflow_flush(ctx);
3616 if (unlikely(ctx->sq_data->thread == NULL)) {
3620 if (flags & IORING_ENTER_SQ_WAKEUP)
3621 wake_up(&ctx->sq_data->wait);
3622 if (flags & IORING_ENTER_SQ_WAIT)
3623 io_sqpoll_wait_sq(ctx);
3626 } else if (to_submit) {
3627 ret = io_uring_add_tctx_node(ctx);
3631 mutex_lock(&ctx->uring_lock);
3632 ret = io_submit_sqes(ctx, to_submit);
3633 if (ret != to_submit) {
3634 mutex_unlock(&ctx->uring_lock);
3637 if (flags & IORING_ENTER_GETEVENTS) {
3638 if (ctx->syscall_iopoll)
3641 * Ignore errors, we'll soon call io_cqring_wait() and
3642 * it should handle ownership problems if any.
3644 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3645 (void)io_run_local_work_locked(ctx, min_complete);
3647 mutex_unlock(&ctx->uring_lock);
3650 if (flags & IORING_ENTER_GETEVENTS) {
3653 if (ctx->syscall_iopoll) {
3655 * We disallow the app entering submit/complete with
3656 * polling, but we still need to lock the ring to
3657 * prevent racing with polled issue that got punted to
3660 mutex_lock(&ctx->uring_lock);
3662 ret2 = io_validate_ext_arg(flags, argp, argsz);
3663 if (likely(!ret2)) {
3664 min_complete = min(min_complete,
3666 ret2 = io_iopoll_check(ctx, min_complete);
3668 mutex_unlock(&ctx->uring_lock);
3670 const sigset_t __user *sig;
3671 struct __kernel_timespec __user *ts;
3673 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3674 if (likely(!ret2)) {
3675 min_complete = min(min_complete,
3677 ret2 = io_cqring_wait(ctx, min_complete, sig,
3686 * EBADR indicates that one or more CQE were dropped.
3687 * Once the user has been informed we can clear the bit
3688 * as they are obviously ok with those drops.
3690 if (unlikely(ret2 == -EBADR))
3691 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3696 if (!(flags & IORING_ENTER_REGISTERED_RING))
3701 static const struct file_operations io_uring_fops = {
3702 .release = io_uring_release,
3703 .mmap = io_uring_mmap,
3705 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3706 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3708 .get_unmapped_area = io_uring_mmu_get_unmapped_area,
3710 .poll = io_uring_poll,
3711 #ifdef CONFIG_PROC_FS
3712 .show_fdinfo = io_uring_show_fdinfo,
3716 bool io_is_uring_fops(struct file *file)
3718 return file->f_op == &io_uring_fops;
3721 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3722 struct io_uring_params *p)
3724 struct io_rings *rings;
3725 size_t size, sq_array_offset;
3728 /* make sure these are sane, as we already accounted them */
3729 ctx->sq_entries = p->sq_entries;
3730 ctx->cq_entries = p->cq_entries;
3732 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3733 if (size == SIZE_MAX)
3736 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3737 rings = io_mem_alloc(size);
3739 rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3742 return PTR_ERR(rings);
3745 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3746 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3747 rings->sq_ring_mask = p->sq_entries - 1;
3748 rings->cq_ring_mask = p->cq_entries - 1;
3749 rings->sq_ring_entries = p->sq_entries;
3750 rings->cq_ring_entries = p->cq_entries;
3752 if (p->flags & IORING_SETUP_SQE128)
3753 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3755 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3756 if (size == SIZE_MAX) {
3761 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3762 ptr = io_mem_alloc(size);
3764 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3768 return PTR_ERR(ptr);
3775 static int io_uring_install_fd(struct file *file)
3779 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3782 fd_install(fd, file);
3787 * Allocate an anonymous fd, this is what constitutes the application
3788 * visible backing of an io_uring instance. The application mmaps this
3789 * fd to gain access to the SQ/CQ ring details.
3791 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3793 /* Create a new inode so that the LSM can block the creation. */
3794 return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
3795 O_RDWR | O_CLOEXEC, NULL);
3798 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3799 struct io_uring_params __user *params)
3801 struct io_ring_ctx *ctx;
3802 struct io_uring_task *tctx;
3808 if (entries > IORING_MAX_ENTRIES) {
3809 if (!(p->flags & IORING_SETUP_CLAMP))
3811 entries = IORING_MAX_ENTRIES;
3814 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3815 && !(p->flags & IORING_SETUP_NO_MMAP))
3819 * Use twice as many entries for the CQ ring. It's possible for the
3820 * application to drive a higher depth than the size of the SQ ring,
3821 * since the sqes are only used at submission time. This allows for
3822 * some flexibility in overcommitting a bit. If the application has
3823 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3824 * of CQ ring entries manually.
3826 p->sq_entries = roundup_pow_of_two(entries);
3827 if (p->flags & IORING_SETUP_CQSIZE) {
3829 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3830 * to a power-of-two, if it isn't already. We do NOT impose
3831 * any cq vs sq ring sizing.
3835 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3836 if (!(p->flags & IORING_SETUP_CLAMP))
3838 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3840 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3841 if (p->cq_entries < p->sq_entries)
3844 p->cq_entries = 2 * p->sq_entries;
3847 ctx = io_ring_ctx_alloc(p);
3851 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3852 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3853 !(ctx->flags & IORING_SETUP_SQPOLL))
3854 ctx->task_complete = true;
3856 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3857 ctx->lockless_cq = true;
3860 * lazy poll_wq activation relies on ->task_complete for synchronisation
3861 * purposes, see io_activate_pollwq()
3863 if (!ctx->task_complete)
3864 ctx->poll_activated = true;
3867 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3868 * space applications don't need to do io completion events
3869 * polling again, they can rely on io_sq_thread to do polling
3870 * work, which can reduce cpu usage and uring_lock contention.
3872 if (ctx->flags & IORING_SETUP_IOPOLL &&
3873 !(ctx->flags & IORING_SETUP_SQPOLL))
3874 ctx->syscall_iopoll = 1;
3876 ctx->compat = in_compat_syscall();
3877 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3878 ctx->user = get_uid(current_user());
3881 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3882 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3885 if (ctx->flags & IORING_SETUP_SQPOLL) {
3886 /* IPI related flags don't make sense with SQPOLL */
3887 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3888 IORING_SETUP_TASKRUN_FLAG |
3889 IORING_SETUP_DEFER_TASKRUN))
3891 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3892 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3893 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3895 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
3896 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
3898 ctx->notify_method = TWA_SIGNAL;
3902 * For DEFER_TASKRUN we require the completion task to be the same as the
3903 * submission task. This implies that there is only one submitter, so enforce
3906 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
3907 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
3912 * This is just grabbed for accounting purposes. When a process exits,
3913 * the mm is exited and dropped before the files, hence we need to hang
3914 * on to this mm purely for the purposes of being able to unaccount
3915 * memory (locked/pinned vm). It's not used for anything else.
3917 mmgrab(current->mm);
3918 ctx->mm_account = current->mm;
3920 ret = io_allocate_scq_urings(ctx, p);
3924 ret = io_sq_offload_create(ctx, p);
3928 ret = io_rsrc_init(ctx);
3932 p->sq_off.head = offsetof(struct io_rings, sq.head);
3933 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3934 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3935 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3936 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3937 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3938 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3939 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3940 p->sq_off.resv1 = 0;
3941 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3942 p->sq_off.user_addr = 0;
3944 p->cq_off.head = offsetof(struct io_rings, cq.head);
3945 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3946 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3947 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3948 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3949 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3950 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3951 p->cq_off.resv1 = 0;
3952 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3953 p->cq_off.user_addr = 0;
3955 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3956 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
3957 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
3958 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
3959 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
3960 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
3961 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING;
3963 if (copy_to_user(params, p, sizeof(*p))) {
3968 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
3969 && !(ctx->flags & IORING_SETUP_R_DISABLED))
3970 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
3972 file = io_uring_get_file(ctx);
3974 ret = PTR_ERR(file);
3978 ret = __io_uring_add_tctx_node(ctx);
3981 tctx = current->io_uring;
3984 * Install ring fd as the very last thing, so we don't risk someone
3985 * having closed it before we finish setup
3987 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3988 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
3990 ret = io_uring_install_fd(file);
3994 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3997 io_ring_ctx_wait_and_kill(ctx);
4005 * Sets up an aio uring context, and returns the fd. Applications asks for a
4006 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4007 * params structure passed in.
4009 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4011 struct io_uring_params p;
4014 if (copy_from_user(&p, params, sizeof(p)))
4016 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4021 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4022 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
4023 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
4024 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
4025 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
4026 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
4027 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
4028 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
4029 IORING_SETUP_NO_SQARRAY))
4032 return io_uring_create(entries, &p, params);
4035 static inline bool io_uring_allowed(void)
4037 int disabled = READ_ONCE(sysctl_io_uring_disabled);
4038 kgid_t io_uring_group;
4043 if (disabled == 0 || capable(CAP_SYS_ADMIN))
4046 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
4047 if (!gid_valid(io_uring_group))
4050 return in_group_p(io_uring_group);
4053 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4054 struct io_uring_params __user *, params)
4056 if (!io_uring_allowed())
4059 return io_uring_setup(entries, params);
4062 static int __init io_uring_init(void)
4064 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
4065 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
4066 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
4069 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
4070 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
4071 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
4072 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
4073 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
4074 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
4075 BUILD_BUG_SQE_ELEM(1, __u8, flags);
4076 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
4077 BUILD_BUG_SQE_ELEM(4, __s32, fd);
4078 BUILD_BUG_SQE_ELEM(8, __u64, off);
4079 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
4080 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
4081 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
4082 BUILD_BUG_SQE_ELEM(16, __u64, addr);
4083 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
4084 BUILD_BUG_SQE_ELEM(24, __u32, len);
4085 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
4086 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
4087 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
4088 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
4089 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
4090 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
4091 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
4092 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
4093 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
4094 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
4095 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
4096 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
4097 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
4098 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
4099 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
4100 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
4101 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
4102 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
4103 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
4104 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
4105 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
4106 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
4107 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
4108 BUILD_BUG_SQE_ELEM(42, __u16, personality);
4109 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
4110 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
4111 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
4112 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
4113 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
4114 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
4115 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
4117 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
4118 sizeof(struct io_uring_rsrc_update));
4119 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
4120 sizeof(struct io_uring_rsrc_update2));
4122 /* ->buf_index is u16 */
4123 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
4124 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
4125 offsetof(struct io_uring_buf_ring, tail));
4127 /* should fit into one byte */
4128 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
4129 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4130 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4132 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
4134 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4136 /* top 8bits are for internal use */
4137 BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
4139 io_uring_optable_init();
4142 * Allow user copy in the per-command field, which starts after the
4143 * file in io_kiocb and until the opcode field. The openat2 handling
4144 * requires copying in user memory into the io_kiocb object in that
4145 * range, and HARDENED_USERCOPY will complain if we haven't
4146 * correctly annotated this range.
4148 req_cachep = kmem_cache_create_usercopy("io_kiocb",
4149 sizeof(struct io_kiocb), 0,
4150 SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4151 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU,
4152 offsetof(struct io_kiocb, cmd.data),
4153 sizeof_field(struct io_kiocb, cmd.data), NULL);
4154 io_buf_cachep = KMEM_CACHE(io_buffer,
4155 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT);
4157 #ifdef CONFIG_SYSCTL
4158 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
4163 __initcall(io_uring_init);