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 <net/af_unix.h>
63 #include <linux/anon_inodes.h>
64 #include <linux/sched/mm.h>
65 #include <linux/uaccess.h>
66 #include <linux/nospec.h>
67 #include <linux/highmem.h>
68 #include <linux/fsnotify.h>
69 #include <linux/fadvise.h>
70 #include <linux/task_work.h>
71 #include <linux/io_uring.h>
72 #include <linux/io_uring/cmd.h>
73 #include <linux/audit.h>
74 #include <linux/security.h>
75 #include <asm/shmparam.h>
77 #define CREATE_TRACE_POINTS
78 #include <trace/events/io_uring.h>
80 #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
126 IO_CHECK_CQ_OVERFLOW_BIT,
127 IO_CHECK_CQ_DROPPED_BIT,
130 struct io_defer_entry {
131 struct list_head list;
132 struct io_kiocb *req;
136 /* requests with any of those set should undergo io_disarm_next() */
137 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
138 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
141 * No waiters. It's larger than any valid value of the tw counter
142 * so that tests against ->cq_wait_nr would fail and skip wake_up().
144 #define IO_CQ_WAKE_INIT (-1U)
145 /* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
146 #define IO_CQ_WAKE_FORCE (IO_CQ_WAKE_INIT >> 1)
148 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
149 struct task_struct *task,
152 static void io_queue_sqe(struct io_kiocb *req);
154 struct kmem_cache *req_cachep;
155 static struct workqueue_struct *iou_wq __ro_after_init;
157 static int __read_mostly sysctl_io_uring_disabled;
158 static int __read_mostly sysctl_io_uring_group = -1;
161 static struct ctl_table kernel_io_uring_disabled_table[] = {
163 .procname = "io_uring_disabled",
164 .data = &sysctl_io_uring_disabled,
165 .maxlen = sizeof(sysctl_io_uring_disabled),
167 .proc_handler = proc_dointvec_minmax,
168 .extra1 = SYSCTL_ZERO,
169 .extra2 = SYSCTL_TWO,
172 .procname = "io_uring_group",
173 .data = &sysctl_io_uring_group,
174 .maxlen = sizeof(gid_t),
176 .proc_handler = proc_dointvec,
182 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
184 if (!wq_list_empty(&ctx->submit_state.compl_reqs) ||
185 ctx->submit_state.cqes_count)
186 __io_submit_flush_completions(ctx);
189 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
191 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
194 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
196 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
199 static bool io_match_linked(struct io_kiocb *head)
201 struct io_kiocb *req;
203 io_for_each_link(req, head) {
204 if (req->flags & REQ_F_INFLIGHT)
211 * As io_match_task() but protected against racing with linked timeouts.
212 * User must not hold timeout_lock.
214 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
219 if (task && head->task != task)
224 if (head->flags & REQ_F_LINK_TIMEOUT) {
225 struct io_ring_ctx *ctx = head->ctx;
227 /* protect against races with linked timeouts */
228 spin_lock_irq(&ctx->timeout_lock);
229 matched = io_match_linked(head);
230 spin_unlock_irq(&ctx->timeout_lock);
232 matched = io_match_linked(head);
237 static inline void req_fail_link_node(struct io_kiocb *req, int res)
240 io_req_set_res(req, res, 0);
243 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
245 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
248 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
250 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
252 complete(&ctx->ref_comp);
255 static __cold void io_fallback_req_func(struct work_struct *work)
257 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
259 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
260 struct io_kiocb *req, *tmp;
261 struct io_tw_state ts = { .locked = true, };
263 percpu_ref_get(&ctx->refs);
264 mutex_lock(&ctx->uring_lock);
265 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
266 req->io_task_work.func(req, &ts);
267 if (WARN_ON_ONCE(!ts.locked))
269 io_submit_flush_completions(ctx);
270 mutex_unlock(&ctx->uring_lock);
271 percpu_ref_put(&ctx->refs);
274 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
276 unsigned hash_buckets = 1U << bits;
277 size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
279 table->hbs = kmalloc(hash_size, GFP_KERNEL);
283 table->hash_bits = bits;
284 init_hash_table(table, hash_buckets);
288 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
290 struct io_ring_ctx *ctx;
293 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
297 xa_init(&ctx->io_bl_xa);
300 * Use 5 bits less than the max cq entries, that should give us around
301 * 32 entries per hash list if totally full and uniformly spread, but
302 * don't keep too many buckets to not overconsume memory.
304 hash_bits = ilog2(p->cq_entries) - 5;
305 hash_bits = clamp(hash_bits, 1, 8);
306 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
308 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
310 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
314 ctx->flags = p->flags;
315 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
316 init_waitqueue_head(&ctx->sqo_sq_wait);
317 INIT_LIST_HEAD(&ctx->sqd_list);
318 INIT_LIST_HEAD(&ctx->cq_overflow_list);
319 INIT_LIST_HEAD(&ctx->io_buffers_cache);
320 INIT_HLIST_HEAD(&ctx->io_buf_list);
321 io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
322 sizeof(struct io_rsrc_node));
323 io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX,
324 sizeof(struct async_poll));
325 io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
326 sizeof(struct io_async_msghdr));
327 io_futex_cache_init(ctx);
328 init_completion(&ctx->ref_comp);
329 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
330 mutex_init(&ctx->uring_lock);
331 init_waitqueue_head(&ctx->cq_wait);
332 init_waitqueue_head(&ctx->poll_wq);
333 init_waitqueue_head(&ctx->rsrc_quiesce_wq);
334 spin_lock_init(&ctx->completion_lock);
335 spin_lock_init(&ctx->timeout_lock);
336 INIT_WQ_LIST(&ctx->iopoll_list);
337 INIT_LIST_HEAD(&ctx->io_buffers_comp);
338 INIT_LIST_HEAD(&ctx->defer_list);
339 INIT_LIST_HEAD(&ctx->timeout_list);
340 INIT_LIST_HEAD(&ctx->ltimeout_list);
341 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
342 init_llist_head(&ctx->work_llist);
343 INIT_LIST_HEAD(&ctx->tctx_list);
344 ctx->submit_state.free_list.next = NULL;
345 INIT_WQ_LIST(&ctx->locked_free_list);
346 INIT_HLIST_HEAD(&ctx->waitid_list);
348 INIT_HLIST_HEAD(&ctx->futex_list);
350 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
351 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
352 INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
355 kfree(ctx->cancel_table.hbs);
356 kfree(ctx->cancel_table_locked.hbs);
357 xa_destroy(&ctx->io_bl_xa);
362 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
364 struct io_rings *r = ctx->rings;
366 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
370 static bool req_need_defer(struct io_kiocb *req, u32 seq)
372 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
373 struct io_ring_ctx *ctx = req->ctx;
375 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
381 static void io_clean_op(struct io_kiocb *req)
383 if (req->flags & REQ_F_BUFFER_SELECTED) {
384 spin_lock(&req->ctx->completion_lock);
385 io_put_kbuf_comp(req);
386 spin_unlock(&req->ctx->completion_lock);
389 if (req->flags & REQ_F_NEED_CLEANUP) {
390 const struct io_cold_def *def = &io_cold_defs[req->opcode];
395 if ((req->flags & REQ_F_POLLED) && req->apoll) {
396 kfree(req->apoll->double_poll);
400 if (req->flags & REQ_F_INFLIGHT) {
401 struct io_uring_task *tctx = req->task->io_uring;
403 atomic_dec(&tctx->inflight_tracked);
405 if (req->flags & REQ_F_CREDS)
406 put_cred(req->creds);
407 if (req->flags & REQ_F_ASYNC_DATA) {
408 kfree(req->async_data);
409 req->async_data = NULL;
411 req->flags &= ~IO_REQ_CLEAN_FLAGS;
414 static inline void io_req_track_inflight(struct io_kiocb *req)
416 if (!(req->flags & REQ_F_INFLIGHT)) {
417 req->flags |= REQ_F_INFLIGHT;
418 atomic_inc(&req->task->io_uring->inflight_tracked);
422 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
424 if (WARN_ON_ONCE(!req->link))
427 req->flags &= ~REQ_F_ARM_LTIMEOUT;
428 req->flags |= REQ_F_LINK_TIMEOUT;
430 /* linked timeouts should have two refs once prep'ed */
431 io_req_set_refcount(req);
432 __io_req_set_refcount(req->link, 2);
436 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
438 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
440 return __io_prep_linked_timeout(req);
443 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
445 io_queue_linked_timeout(__io_prep_linked_timeout(req));
448 static inline void io_arm_ltimeout(struct io_kiocb *req)
450 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
451 __io_arm_ltimeout(req);
454 static void io_prep_async_work(struct io_kiocb *req)
456 const struct io_issue_def *def = &io_issue_defs[req->opcode];
457 struct io_ring_ctx *ctx = req->ctx;
459 if (!(req->flags & REQ_F_CREDS)) {
460 req->flags |= REQ_F_CREDS;
461 req->creds = get_current_cred();
464 req->work.list.next = NULL;
466 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
467 if (req->flags & REQ_F_FORCE_ASYNC)
468 req->work.flags |= IO_WQ_WORK_CONCURRENT;
470 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
471 req->flags |= io_file_get_flags(req->file);
473 if (req->file && (req->flags & REQ_F_ISREG)) {
474 bool should_hash = def->hash_reg_file;
476 /* don't serialize this request if the fs doesn't need it */
477 if (should_hash && (req->file->f_flags & O_DIRECT) &&
478 (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE))
480 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
481 io_wq_hash_work(&req->work, file_inode(req->file));
482 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
483 if (def->unbound_nonreg_file)
484 req->work.flags |= IO_WQ_WORK_UNBOUND;
488 static void io_prep_async_link(struct io_kiocb *req)
490 struct io_kiocb *cur;
492 if (req->flags & REQ_F_LINK_TIMEOUT) {
493 struct io_ring_ctx *ctx = req->ctx;
495 spin_lock_irq(&ctx->timeout_lock);
496 io_for_each_link(cur, req)
497 io_prep_async_work(cur);
498 spin_unlock_irq(&ctx->timeout_lock);
500 io_for_each_link(cur, req)
501 io_prep_async_work(cur);
505 void io_queue_iowq(struct io_kiocb *req, struct io_tw_state *ts_dont_use)
507 struct io_kiocb *link = io_prep_linked_timeout(req);
508 struct io_uring_task *tctx = req->task->io_uring;
511 BUG_ON(!tctx->io_wq);
513 /* init ->work of the whole link before punting */
514 io_prep_async_link(req);
517 * Not expected to happen, but if we do have a bug where this _can_
518 * happen, catch it here and ensure the request is marked as
519 * canceled. That will make io-wq go through the usual work cancel
520 * procedure rather than attempt to run this request (or create a new
523 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
524 req->work.flags |= IO_WQ_WORK_CANCEL;
526 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
527 io_wq_enqueue(tctx->io_wq, &req->work);
529 io_queue_linked_timeout(link);
532 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
534 while (!list_empty(&ctx->defer_list)) {
535 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
536 struct io_defer_entry, list);
538 if (req_need_defer(de->req, de->seq))
540 list_del_init(&de->list);
541 io_req_task_queue(de->req);
546 void io_eventfd_ops(struct rcu_head *rcu)
548 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
549 int ops = atomic_xchg(&ev_fd->ops, 0);
551 if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT))
552 eventfd_signal_mask(ev_fd->cq_ev_fd, EPOLL_URING_WAKE);
554 /* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback
555 * ordering in a race but if references are 0 we know we have to free
558 if (atomic_dec_and_test(&ev_fd->refs)) {
559 eventfd_ctx_put(ev_fd->cq_ev_fd);
564 static void io_eventfd_signal(struct io_ring_ctx *ctx)
566 struct io_ev_fd *ev_fd = NULL;
570 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
573 ev_fd = rcu_dereference(ctx->io_ev_fd);
576 * Check again if ev_fd exists incase an io_eventfd_unregister call
577 * completed between the NULL check of ctx->io_ev_fd at the start of
578 * the function and rcu_read_lock.
580 if (unlikely(!ev_fd))
582 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
584 if (ev_fd->eventfd_async && !io_wq_current_is_worker())
587 if (likely(eventfd_signal_allowed())) {
588 eventfd_signal_mask(ev_fd->cq_ev_fd, EPOLL_URING_WAKE);
590 atomic_inc(&ev_fd->refs);
591 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops))
592 call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops);
594 atomic_dec(&ev_fd->refs);
601 static void io_eventfd_flush_signal(struct io_ring_ctx *ctx)
605 spin_lock(&ctx->completion_lock);
608 * Eventfd should only get triggered when at least one event has been
609 * posted. Some applications rely on the eventfd notification count
610 * only changing IFF a new CQE has been added to the CQ ring. There's
611 * no depedency on 1:1 relationship between how many times this
612 * function is called (and hence the eventfd count) and number of CQEs
613 * posted to the CQ ring.
615 skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail;
616 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
617 spin_unlock(&ctx->completion_lock);
621 io_eventfd_signal(ctx);
624 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
626 if (ctx->poll_activated)
627 io_poll_wq_wake(ctx);
628 if (ctx->off_timeout_used)
629 io_flush_timeouts(ctx);
630 if (ctx->drain_active) {
631 spin_lock(&ctx->completion_lock);
632 io_queue_deferred(ctx);
633 spin_unlock(&ctx->completion_lock);
636 io_eventfd_flush_signal(ctx);
639 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
641 if (!ctx->lockless_cq)
642 spin_lock(&ctx->completion_lock);
645 static inline void io_cq_lock(struct io_ring_ctx *ctx)
646 __acquires(ctx->completion_lock)
648 spin_lock(&ctx->completion_lock);
651 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
653 io_commit_cqring(ctx);
654 if (!ctx->task_complete) {
655 if (!ctx->lockless_cq)
656 spin_unlock(&ctx->completion_lock);
657 /* IOPOLL rings only need to wake up if it's also SQPOLL */
658 if (!ctx->syscall_iopoll)
661 io_commit_cqring_flush(ctx);
664 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
665 __releases(ctx->completion_lock)
667 io_commit_cqring(ctx);
668 spin_unlock(&ctx->completion_lock);
670 io_commit_cqring_flush(ctx);
673 /* Returns true if there are no backlogged entries after the flush */
674 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
676 struct io_overflow_cqe *ocqe;
679 spin_lock(&ctx->completion_lock);
680 list_splice_init(&ctx->cq_overflow_list, &list);
681 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
682 spin_unlock(&ctx->completion_lock);
684 while (!list_empty(&list)) {
685 ocqe = list_first_entry(&list, struct io_overflow_cqe, list);
686 list_del(&ocqe->list);
691 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx)
693 size_t cqe_size = sizeof(struct io_uring_cqe);
695 if (__io_cqring_events(ctx) == ctx->cq_entries)
698 if (ctx->flags & IORING_SETUP_CQE32)
702 while (!list_empty(&ctx->cq_overflow_list)) {
703 struct io_uring_cqe *cqe;
704 struct io_overflow_cqe *ocqe;
706 if (!io_get_cqe_overflow(ctx, &cqe, true))
708 ocqe = list_first_entry(&ctx->cq_overflow_list,
709 struct io_overflow_cqe, list);
710 memcpy(cqe, &ocqe->cqe, cqe_size);
711 list_del(&ocqe->list);
715 if (list_empty(&ctx->cq_overflow_list)) {
716 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
717 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
719 io_cq_unlock_post(ctx);
722 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
724 /* iopoll syncs against uring_lock, not completion_lock */
725 if (ctx->flags & IORING_SETUP_IOPOLL)
726 mutex_lock(&ctx->uring_lock);
727 __io_cqring_overflow_flush(ctx);
728 if (ctx->flags & IORING_SETUP_IOPOLL)
729 mutex_unlock(&ctx->uring_lock);
732 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx)
734 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
735 io_cqring_do_overflow_flush(ctx);
738 /* can be called by any task */
739 static void io_put_task_remote(struct task_struct *task)
741 struct io_uring_task *tctx = task->io_uring;
743 percpu_counter_sub(&tctx->inflight, 1);
744 if (unlikely(atomic_read(&tctx->in_cancel)))
745 wake_up(&tctx->wait);
746 put_task_struct(task);
749 /* used by a task to put its own references */
750 static void io_put_task_local(struct task_struct *task)
752 task->io_uring->cached_refs++;
755 /* must to be called somewhat shortly after putting a request */
756 static inline void io_put_task(struct task_struct *task)
758 if (likely(task == current))
759 io_put_task_local(task);
761 io_put_task_remote(task);
764 void io_task_refs_refill(struct io_uring_task *tctx)
766 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
768 percpu_counter_add(&tctx->inflight, refill);
769 refcount_add(refill, ¤t->usage);
770 tctx->cached_refs += refill;
773 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
775 struct io_uring_task *tctx = task->io_uring;
776 unsigned int refs = tctx->cached_refs;
779 tctx->cached_refs = 0;
780 percpu_counter_sub(&tctx->inflight, refs);
781 put_task_struct_many(task, refs);
785 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
786 s32 res, u32 cflags, u64 extra1, u64 extra2)
788 struct io_overflow_cqe *ocqe;
789 size_t ocq_size = sizeof(struct io_overflow_cqe);
790 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
792 lockdep_assert_held(&ctx->completion_lock);
795 ocq_size += sizeof(struct io_uring_cqe);
797 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
798 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
801 * If we're in ring overflow flush mode, or in task cancel mode,
802 * or cannot allocate an overflow entry, then we need to drop it
805 io_account_cq_overflow(ctx);
806 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
809 if (list_empty(&ctx->cq_overflow_list)) {
810 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
811 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
814 ocqe->cqe.user_data = user_data;
816 ocqe->cqe.flags = cflags;
818 ocqe->cqe.big_cqe[0] = extra1;
819 ocqe->cqe.big_cqe[1] = extra2;
821 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
825 void io_req_cqe_overflow(struct io_kiocb *req)
827 io_cqring_event_overflow(req->ctx, req->cqe.user_data,
828 req->cqe.res, req->cqe.flags,
829 req->big_cqe.extra1, req->big_cqe.extra2);
830 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
834 * writes to the cq entry need to come after reading head; the
835 * control dependency is enough as we're using WRITE_ONCE to
838 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
840 struct io_rings *rings = ctx->rings;
841 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
842 unsigned int free, queued, len;
845 * Posting into the CQ when there are pending overflowed CQEs may break
846 * ordering guarantees, which will affect links, F_MORE users and more.
847 * Force overflow the completion.
849 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
852 /* userspace may cheat modifying the tail, be safe and do min */
853 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
854 free = ctx->cq_entries - queued;
855 /* we need a contiguous range, limit based on the current array offset */
856 len = min(free, ctx->cq_entries - off);
860 if (ctx->flags & IORING_SETUP_CQE32) {
865 ctx->cqe_cached = &rings->cqes[off];
866 ctx->cqe_sentinel = ctx->cqe_cached + len;
870 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
873 struct io_uring_cqe *cqe;
878 * If we can't get a cq entry, userspace overflowed the
879 * submission (by quite a lot). Increment the overflow count in
882 if (likely(io_get_cqe(ctx, &cqe))) {
883 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
885 WRITE_ONCE(cqe->user_data, user_data);
886 WRITE_ONCE(cqe->res, res);
887 WRITE_ONCE(cqe->flags, cflags);
889 if (ctx->flags & IORING_SETUP_CQE32) {
890 WRITE_ONCE(cqe->big_cqe[0], 0);
891 WRITE_ONCE(cqe->big_cqe[1], 0);
898 static void __io_flush_post_cqes(struct io_ring_ctx *ctx)
899 __must_hold(&ctx->uring_lock)
901 struct io_submit_state *state = &ctx->submit_state;
904 lockdep_assert_held(&ctx->uring_lock);
905 for (i = 0; i < state->cqes_count; i++) {
906 struct io_uring_cqe *cqe = &ctx->completion_cqes[i];
908 if (!io_fill_cqe_aux(ctx, cqe->user_data, cqe->res, cqe->flags)) {
909 if (ctx->lockless_cq) {
910 spin_lock(&ctx->completion_lock);
911 io_cqring_event_overflow(ctx, cqe->user_data,
912 cqe->res, cqe->flags, 0, 0);
913 spin_unlock(&ctx->completion_lock);
915 io_cqring_event_overflow(ctx, cqe->user_data,
916 cqe->res, cqe->flags, 0, 0);
920 state->cqes_count = 0;
923 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags,
929 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
930 if (!filled && allow_overflow)
931 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
933 io_cq_unlock_post(ctx);
937 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
939 return __io_post_aux_cqe(ctx, user_data, res, cflags, true);
943 * A helper for multishot requests posting additional CQEs.
944 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
946 bool io_fill_cqe_req_aux(struct io_kiocb *req, bool defer, s32 res, u32 cflags)
948 struct io_ring_ctx *ctx = req->ctx;
949 u64 user_data = req->cqe.user_data;
950 struct io_uring_cqe *cqe;
952 lockdep_assert(!io_wq_current_is_worker());
955 return __io_post_aux_cqe(ctx, user_data, res, cflags, false);
957 lockdep_assert_held(&ctx->uring_lock);
959 if (ctx->submit_state.cqes_count == ARRAY_SIZE(ctx->completion_cqes)) {
961 __io_flush_post_cqes(ctx);
962 /* no need to flush - flush is deferred */
963 __io_cq_unlock_post(ctx);
966 /* For defered completions this is not as strict as it is otherwise,
967 * however it's main job is to prevent unbounded posted completions,
968 * and in that it works just as well.
970 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
973 cqe = &ctx->completion_cqes[ctx->submit_state.cqes_count++];
974 cqe->user_data = user_data;
980 static void __io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
982 struct io_ring_ctx *ctx = req->ctx;
983 struct io_rsrc_node *rsrc_node = NULL;
986 if (!(req->flags & REQ_F_CQE_SKIP)) {
987 if (!io_fill_cqe_req(ctx, req))
988 io_req_cqe_overflow(req);
992 * If we're the last reference to this request, add to our locked
995 if (req_ref_put_and_test(req)) {
996 if (req->flags & IO_REQ_LINK_FLAGS) {
997 if (req->flags & IO_DISARM_MASK)
1000 io_req_task_queue(req->link);
1004 io_put_kbuf_comp(req);
1005 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1009 rsrc_node = req->rsrc_node;
1011 * Selected buffer deallocation in io_clean_op() assumes that
1012 * we don't hold ->completion_lock. Clean them here to avoid
1015 io_put_task_remote(req->task);
1016 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1017 ctx->locked_free_nr++;
1019 io_cq_unlock_post(ctx);
1022 io_ring_submit_lock(ctx, issue_flags);
1023 io_put_rsrc_node(ctx, rsrc_node);
1024 io_ring_submit_unlock(ctx, issue_flags);
1028 void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
1030 if (req->ctx->task_complete && req->ctx->submitter_task != current) {
1031 req->io_task_work.func = io_req_task_complete;
1032 io_req_task_work_add(req);
1033 } else if (!(issue_flags & IO_URING_F_UNLOCKED) ||
1034 !(req->ctx->flags & IORING_SETUP_IOPOLL)) {
1035 __io_req_complete_post(req, issue_flags);
1037 struct io_ring_ctx *ctx = req->ctx;
1039 mutex_lock(&ctx->uring_lock);
1040 __io_req_complete_post(req, issue_flags & ~IO_URING_F_UNLOCKED);
1041 mutex_unlock(&ctx->uring_lock);
1045 void io_req_defer_failed(struct io_kiocb *req, s32 res)
1046 __must_hold(&ctx->uring_lock)
1048 const struct io_cold_def *def = &io_cold_defs[req->opcode];
1050 lockdep_assert_held(&req->ctx->uring_lock);
1053 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1056 io_req_complete_defer(req);
1060 * Don't initialise the fields below on every allocation, but do that in
1061 * advance and keep them valid across allocations.
1063 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1067 req->async_data = NULL;
1068 /* not necessary, but safer to zero */
1069 memset(&req->cqe, 0, sizeof(req->cqe));
1070 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
1073 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1074 struct io_submit_state *state)
1076 spin_lock(&ctx->completion_lock);
1077 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1078 ctx->locked_free_nr = 0;
1079 spin_unlock(&ctx->completion_lock);
1083 * A request might get retired back into the request caches even before opcode
1084 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1085 * Because of that, io_alloc_req() should be called only under ->uring_lock
1086 * and with extra caution to not get a request that is still worked on.
1088 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1089 __must_hold(&ctx->uring_lock)
1091 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1092 void *reqs[IO_REQ_ALLOC_BATCH];
1096 * If we have more than a batch's worth of requests in our IRQ side
1097 * locked cache, grab the lock and move them over to our submission
1100 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1101 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1102 if (!io_req_cache_empty(ctx))
1106 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1109 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1110 * retry single alloc to be on the safe side.
1112 if (unlikely(ret <= 0)) {
1113 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1119 percpu_ref_get_many(&ctx->refs, ret);
1120 for (i = 0; i < ret; i++) {
1121 struct io_kiocb *req = reqs[i];
1123 io_preinit_req(req, ctx);
1124 io_req_add_to_cache(req, ctx);
1129 __cold void io_free_req(struct io_kiocb *req)
1131 /* refs were already put, restore them for io_req_task_complete() */
1132 req->flags &= ~REQ_F_REFCOUNT;
1133 /* we only want to free it, don't post CQEs */
1134 req->flags |= REQ_F_CQE_SKIP;
1135 req->io_task_work.func = io_req_task_complete;
1136 io_req_task_work_add(req);
1139 static void __io_req_find_next_prep(struct io_kiocb *req)
1141 struct io_ring_ctx *ctx = req->ctx;
1143 spin_lock(&ctx->completion_lock);
1144 io_disarm_next(req);
1145 spin_unlock(&ctx->completion_lock);
1148 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1150 struct io_kiocb *nxt;
1153 * If LINK is set, we have dependent requests in this chain. If we
1154 * didn't fail this request, queue the first one up, moving any other
1155 * dependencies to the next request. In case of failure, fail the rest
1158 if (unlikely(req->flags & IO_DISARM_MASK))
1159 __io_req_find_next_prep(req);
1165 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
1169 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1170 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1172 io_submit_flush_completions(ctx);
1173 mutex_unlock(&ctx->uring_lock);
1176 percpu_ref_put(&ctx->refs);
1179 static unsigned int handle_tw_list(struct llist_node *node,
1180 struct io_ring_ctx **ctx,
1181 struct io_tw_state *ts)
1183 unsigned int count = 0;
1186 struct llist_node *next = node->next;
1187 struct io_kiocb *req = container_of(node, struct io_kiocb,
1190 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1192 if (req->ctx != *ctx) {
1193 ctx_flush_and_put(*ctx, ts);
1195 /* if not contended, grab and improve batching */
1196 ts->locked = mutex_trylock(&(*ctx)->uring_lock);
1197 percpu_ref_get(&(*ctx)->refs);
1199 INDIRECT_CALL_2(req->io_task_work.func,
1200 io_poll_task_func, io_req_rw_complete,
1204 if (unlikely(need_resched())) {
1205 ctx_flush_and_put(*ctx, ts);
1215 * io_llist_xchg - swap all entries in a lock-less list
1216 * @head: the head of lock-less list to delete all entries
1217 * @new: new entry as the head of the list
1219 * If list is empty, return NULL, otherwise, return the pointer to the first entry.
1220 * The order of entries returned is from the newest to the oldest added one.
1222 static inline struct llist_node *io_llist_xchg(struct llist_head *head,
1223 struct llist_node *new)
1225 return xchg(&head->first, new);
1228 static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1230 struct llist_node *node = llist_del_all(&tctx->task_list);
1231 struct io_ring_ctx *last_ctx = NULL;
1232 struct io_kiocb *req;
1235 req = container_of(node, struct io_kiocb, io_task_work.node);
1237 if (sync && last_ctx != req->ctx) {
1239 flush_delayed_work(&last_ctx->fallback_work);
1240 percpu_ref_put(&last_ctx->refs);
1242 last_ctx = req->ctx;
1243 percpu_ref_get(&last_ctx->refs);
1245 if (llist_add(&req->io_task_work.node,
1246 &req->ctx->fallback_llist))
1247 schedule_delayed_work(&req->ctx->fallback_work, 1);
1251 flush_delayed_work(&last_ctx->fallback_work);
1252 percpu_ref_put(&last_ctx->refs);
1256 void tctx_task_work(struct callback_head *cb)
1258 struct io_tw_state ts = {};
1259 struct io_ring_ctx *ctx = NULL;
1260 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1262 struct llist_node *node;
1263 unsigned int count = 0;
1265 if (unlikely(current->flags & PF_EXITING)) {
1266 io_fallback_tw(tctx, true);
1270 node = llist_del_all(&tctx->task_list);
1272 count = handle_tw_list(node, &ctx, &ts);
1274 ctx_flush_and_put(ctx, &ts);
1276 /* relaxed read is enough as only the task itself sets ->in_cancel */
1277 if (unlikely(atomic_read(&tctx->in_cancel)))
1278 io_uring_drop_tctx_refs(current);
1280 trace_io_uring_task_work_run(tctx, count, 1);
1283 static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1285 struct io_ring_ctx *ctx = req->ctx;
1286 unsigned nr_wait, nr_tw, nr_tw_prev;
1287 struct llist_node *head;
1289 /* See comment above IO_CQ_WAKE_INIT */
1290 BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
1293 * We don't know how many reuqests is there in the link and whether
1294 * they can even be queued lazily, fall back to non-lazy.
1296 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1297 flags &= ~IOU_F_TWQ_LAZY_WAKE;
1299 head = READ_ONCE(ctx->work_llist.first);
1303 struct io_kiocb *first_req = container_of(head,
1307 * Might be executed at any moment, rely on
1308 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1310 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1314 * Theoretically, it can overflow, but that's fine as one of
1315 * previous adds should've tried to wake the task.
1317 nr_tw = nr_tw_prev + 1;
1318 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1319 nr_tw = IO_CQ_WAKE_FORCE;
1322 req->io_task_work.node.next = head;
1323 } while (!try_cmpxchg(&ctx->work_llist.first, &head,
1324 &req->io_task_work.node));
1327 * cmpxchg implies a full barrier, which pairs with the barrier
1328 * in set_current_state() on the io_cqring_wait() side. It's used
1329 * to ensure that either we see updated ->cq_wait_nr, or waiters
1330 * going to sleep will observe the work added to the list, which
1331 * is similar to the wait/wawke task state sync.
1335 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1336 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1338 io_eventfd_signal(ctx);
1341 nr_wait = atomic_read(&ctx->cq_wait_nr);
1342 /* not enough or no one is waiting */
1343 if (nr_tw < nr_wait)
1345 /* the previous add has already woken it up */
1346 if (nr_tw_prev >= nr_wait)
1348 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1351 static void io_req_normal_work_add(struct io_kiocb *req)
1353 struct io_uring_task *tctx = req->task->io_uring;
1354 struct io_ring_ctx *ctx = req->ctx;
1356 /* task_work already pending, we're done */
1357 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1360 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1361 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1363 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1366 io_fallback_tw(tctx, false);
1369 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1371 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
1373 io_req_local_work_add(req, flags);
1376 io_req_normal_work_add(req);
1380 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1382 struct llist_node *node;
1384 node = llist_del_all(&ctx->work_llist);
1386 struct io_kiocb *req = container_of(node, struct io_kiocb,
1390 io_req_normal_work_add(req);
1394 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1397 if (llist_empty(&ctx->work_llist))
1399 if (events < min_events)
1401 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1402 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1406 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1409 struct llist_node *node;
1410 unsigned int loops = 0;
1413 if (WARN_ON_ONCE(ctx->submitter_task != current))
1415 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1416 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1419 * llists are in reverse order, flip it back the right way before
1420 * running the pending items.
1422 node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
1424 struct llist_node *next = node->next;
1425 struct io_kiocb *req = container_of(node, struct io_kiocb,
1427 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1428 INDIRECT_CALL_2(req->io_task_work.func,
1429 io_poll_task_func, io_req_rw_complete,
1436 if (io_run_local_work_continue(ctx, ret, min_events))
1439 io_submit_flush_completions(ctx);
1440 if (io_run_local_work_continue(ctx, ret, min_events))
1444 trace_io_uring_local_work_run(ctx, ret, loops);
1448 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1451 struct io_tw_state ts = { .locked = true, };
1454 if (llist_empty(&ctx->work_llist))
1457 ret = __io_run_local_work(ctx, &ts, min_events);
1458 /* shouldn't happen! */
1459 if (WARN_ON_ONCE(!ts.locked))
1460 mutex_lock(&ctx->uring_lock);
1464 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
1466 struct io_tw_state ts = {};
1469 ts.locked = mutex_trylock(&ctx->uring_lock);
1470 ret = __io_run_local_work(ctx, &ts, min_events);
1472 mutex_unlock(&ctx->uring_lock);
1477 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
1479 io_tw_lock(req->ctx, ts);
1480 io_req_defer_failed(req, req->cqe.res);
1483 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
1485 io_tw_lock(req->ctx, ts);
1486 /* req->task == current here, checking PF_EXITING is safe */
1487 if (unlikely(req->task->flags & PF_EXITING))
1488 io_req_defer_failed(req, -EFAULT);
1489 else if (req->flags & REQ_F_FORCE_ASYNC)
1490 io_queue_iowq(req, ts);
1495 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1497 io_req_set_res(req, ret, 0);
1498 req->io_task_work.func = io_req_task_cancel;
1499 io_req_task_work_add(req);
1502 void io_req_task_queue(struct io_kiocb *req)
1504 req->io_task_work.func = io_req_task_submit;
1505 io_req_task_work_add(req);
1508 void io_queue_next(struct io_kiocb *req)
1510 struct io_kiocb *nxt = io_req_find_next(req);
1513 io_req_task_queue(nxt);
1516 static void io_free_batch_list(struct io_ring_ctx *ctx,
1517 struct io_wq_work_node *node)
1518 __must_hold(&ctx->uring_lock)
1521 struct io_kiocb *req = container_of(node, struct io_kiocb,
1524 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1525 if (req->flags & REQ_F_REFCOUNT) {
1526 node = req->comp_list.next;
1527 if (!req_ref_put_and_test(req))
1530 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1531 struct async_poll *apoll = req->apoll;
1533 if (apoll->double_poll)
1534 kfree(apoll->double_poll);
1535 if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache))
1537 req->flags &= ~REQ_F_POLLED;
1539 if (req->flags & IO_REQ_LINK_FLAGS)
1541 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1546 io_req_put_rsrc_locked(req, ctx);
1548 io_put_task(req->task);
1549 node = req->comp_list.next;
1550 io_req_add_to_cache(req, ctx);
1554 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1555 __must_hold(&ctx->uring_lock)
1557 struct io_submit_state *state = &ctx->submit_state;
1558 struct io_wq_work_node *node;
1561 /* must come first to preserve CQE ordering in failure cases */
1562 if (state->cqes_count)
1563 __io_flush_post_cqes(ctx);
1564 __wq_list_for_each(node, &state->compl_reqs) {
1565 struct io_kiocb *req = container_of(node, struct io_kiocb,
1568 if (!(req->flags & REQ_F_CQE_SKIP) &&
1569 unlikely(!io_fill_cqe_req(ctx, req))) {
1570 if (ctx->lockless_cq) {
1571 spin_lock(&ctx->completion_lock);
1572 io_req_cqe_overflow(req);
1573 spin_unlock(&ctx->completion_lock);
1575 io_req_cqe_overflow(req);
1579 __io_cq_unlock_post(ctx);
1581 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) {
1582 io_free_batch_list(ctx, state->compl_reqs.first);
1583 INIT_WQ_LIST(&state->compl_reqs);
1587 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1589 /* See comment at the top of this file */
1591 return __io_cqring_events(ctx);
1595 * We can't just wait for polled events to come to us, we have to actively
1596 * find and complete them.
1598 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1600 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1603 mutex_lock(&ctx->uring_lock);
1604 while (!wq_list_empty(&ctx->iopoll_list)) {
1605 /* let it sleep and repeat later if can't complete a request */
1606 if (io_do_iopoll(ctx, true) == 0)
1609 * Ensure we allow local-to-the-cpu processing to take place,
1610 * in this case we need to ensure that we reap all events.
1611 * Also let task_work, etc. to progress by releasing the mutex
1613 if (need_resched()) {
1614 mutex_unlock(&ctx->uring_lock);
1616 mutex_lock(&ctx->uring_lock);
1619 mutex_unlock(&ctx->uring_lock);
1622 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1624 unsigned int nr_events = 0;
1625 unsigned long check_cq;
1627 if (!io_allowed_run_tw(ctx))
1630 check_cq = READ_ONCE(ctx->check_cq);
1631 if (unlikely(check_cq)) {
1632 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1633 __io_cqring_overflow_flush(ctx);
1635 * Similarly do not spin if we have not informed the user of any
1638 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1642 * Don't enter poll loop if we already have events pending.
1643 * If we do, we can potentially be spinning for commands that
1644 * already triggered a CQE (eg in error).
1646 if (io_cqring_events(ctx))
1653 * If a submit got punted to a workqueue, we can have the
1654 * application entering polling for a command before it gets
1655 * issued. That app will hold the uring_lock for the duration
1656 * of the poll right here, so we need to take a breather every
1657 * now and then to ensure that the issue has a chance to add
1658 * the poll to the issued list. Otherwise we can spin here
1659 * forever, while the workqueue is stuck trying to acquire the
1662 if (wq_list_empty(&ctx->iopoll_list) ||
1663 io_task_work_pending(ctx)) {
1664 u32 tail = ctx->cached_cq_tail;
1666 (void) io_run_local_work_locked(ctx, min);
1668 if (task_work_pending(current) ||
1669 wq_list_empty(&ctx->iopoll_list)) {
1670 mutex_unlock(&ctx->uring_lock);
1672 mutex_lock(&ctx->uring_lock);
1674 /* some requests don't go through iopoll_list */
1675 if (tail != ctx->cached_cq_tail ||
1676 wq_list_empty(&ctx->iopoll_list))
1679 ret = io_do_iopoll(ctx, !min);
1680 if (unlikely(ret < 0))
1683 if (task_sigpending(current))
1689 } while (nr_events < min);
1694 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
1697 io_req_complete_defer(req);
1699 io_req_complete_post(req, IO_URING_F_UNLOCKED);
1703 * After the iocb has been issued, it's safe to be found on the poll list.
1704 * Adding the kiocb to the list AFTER submission ensures that we don't
1705 * find it from a io_do_iopoll() thread before the issuer is done
1706 * accessing the kiocb cookie.
1708 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1710 struct io_ring_ctx *ctx = req->ctx;
1711 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1713 /* workqueue context doesn't hold uring_lock, grab it now */
1714 if (unlikely(needs_lock))
1715 mutex_lock(&ctx->uring_lock);
1718 * Track whether we have multiple files in our lists. This will impact
1719 * how we do polling eventually, not spinning if we're on potentially
1720 * different devices.
1722 if (wq_list_empty(&ctx->iopoll_list)) {
1723 ctx->poll_multi_queue = false;
1724 } else if (!ctx->poll_multi_queue) {
1725 struct io_kiocb *list_req;
1727 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1729 if (list_req->file != req->file)
1730 ctx->poll_multi_queue = true;
1734 * For fast devices, IO may have already completed. If it has, add
1735 * it to the front so we find it first.
1737 if (READ_ONCE(req->iopoll_completed))
1738 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1740 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1742 if (unlikely(needs_lock)) {
1744 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1745 * in sq thread task context or in io worker task context. If
1746 * current task context is sq thread, we don't need to check
1747 * whether should wake up sq thread.
1749 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1750 wq_has_sleeper(&ctx->sq_data->wait))
1751 wake_up(&ctx->sq_data->wait);
1753 mutex_unlock(&ctx->uring_lock);
1757 unsigned int io_file_get_flags(struct file *file)
1759 unsigned int res = 0;
1761 if (S_ISREG(file_inode(file)->i_mode))
1763 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1764 res |= REQ_F_SUPPORT_NOWAIT;
1768 bool io_alloc_async_data(struct io_kiocb *req)
1770 WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size);
1771 req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL);
1772 if (req->async_data) {
1773 req->flags |= REQ_F_ASYNC_DATA;
1779 int io_req_prep_async(struct io_kiocb *req)
1781 const struct io_cold_def *cdef = &io_cold_defs[req->opcode];
1782 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1784 /* assign early for deferred execution for non-fixed file */
1785 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file)
1786 req->file = io_file_get_normal(req, req->cqe.fd);
1787 if (!cdef->prep_async)
1789 if (WARN_ON_ONCE(req_has_async_data(req)))
1791 if (!def->manual_alloc) {
1792 if (io_alloc_async_data(req))
1795 return cdef->prep_async(req);
1798 static u32 io_get_sequence(struct io_kiocb *req)
1800 u32 seq = req->ctx->cached_sq_head;
1801 struct io_kiocb *cur;
1803 /* need original cached_sq_head, but it was increased for each req */
1804 io_for_each_link(cur, req)
1809 static __cold void io_drain_req(struct io_kiocb *req)
1810 __must_hold(&ctx->uring_lock)
1812 struct io_ring_ctx *ctx = req->ctx;
1813 struct io_defer_entry *de;
1815 u32 seq = io_get_sequence(req);
1817 /* Still need defer if there is pending req in defer list. */
1818 spin_lock(&ctx->completion_lock);
1819 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1820 spin_unlock(&ctx->completion_lock);
1822 ctx->drain_active = false;
1823 io_req_task_queue(req);
1826 spin_unlock(&ctx->completion_lock);
1828 io_prep_async_link(req);
1829 de = kmalloc(sizeof(*de), GFP_KERNEL);
1832 io_req_defer_failed(req, ret);
1836 spin_lock(&ctx->completion_lock);
1837 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1838 spin_unlock(&ctx->completion_lock);
1843 trace_io_uring_defer(req);
1846 list_add_tail(&de->list, &ctx->defer_list);
1847 spin_unlock(&ctx->completion_lock);
1850 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1851 unsigned int issue_flags)
1853 if (req->file || !def->needs_file)
1856 if (req->flags & REQ_F_FIXED_FILE)
1857 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1859 req->file = io_file_get_normal(req, req->cqe.fd);
1864 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1866 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1867 const struct cred *creds = NULL;
1870 if (unlikely(!io_assign_file(req, def, issue_flags)))
1873 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1874 creds = override_creds(req->creds);
1876 if (!def->audit_skip)
1877 audit_uring_entry(req->opcode);
1879 ret = def->issue(req, issue_flags);
1881 if (!def->audit_skip)
1882 audit_uring_exit(!ret, ret);
1885 revert_creds(creds);
1887 if (ret == IOU_OK) {
1888 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1889 io_req_complete_defer(req);
1891 io_req_complete_post(req, issue_flags);
1896 if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1898 io_arm_ltimeout(req);
1900 /* If the op doesn't have a file, we're not polling for it */
1901 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1902 io_iopoll_req_issued(req, issue_flags);
1907 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
1909 io_tw_lock(req->ctx, ts);
1910 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1911 IO_URING_F_COMPLETE_DEFER);
1914 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1916 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1917 struct io_kiocb *nxt = NULL;
1919 if (req_ref_put_and_test(req)) {
1920 if (req->flags & IO_REQ_LINK_FLAGS)
1921 nxt = io_req_find_next(req);
1924 return nxt ? &nxt->work : NULL;
1927 void io_wq_submit_work(struct io_wq_work *work)
1929 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1930 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1931 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1932 bool needs_poll = false;
1933 int ret = 0, err = -ECANCELED;
1935 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1936 if (!(req->flags & REQ_F_REFCOUNT))
1937 __io_req_set_refcount(req, 2);
1941 io_arm_ltimeout(req);
1943 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1944 if (work->flags & IO_WQ_WORK_CANCEL) {
1946 io_req_task_queue_fail(req, err);
1949 if (!io_assign_file(req, def, issue_flags)) {
1951 work->flags |= IO_WQ_WORK_CANCEL;
1956 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1957 * submitter task context. Final request completions are handed to the
1958 * right context, however this is not the case of auxiliary CQEs,
1959 * which is the main mean of operation for multishot requests.
1960 * Don't allow any multishot execution from io-wq. It's more restrictive
1961 * than necessary and also cleaner.
1963 if (req->flags & REQ_F_APOLL_MULTISHOT) {
1965 if (!file_can_poll(req->file))
1967 if (req->file->f_flags & O_NONBLOCK ||
1968 req->file->f_mode & FMODE_NOWAIT) {
1970 if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1974 req->flags &= ~REQ_F_APOLL_MULTISHOT;
1978 if (req->flags & REQ_F_FORCE_ASYNC) {
1979 bool opcode_poll = def->pollin || def->pollout;
1981 if (opcode_poll && file_can_poll(req->file)) {
1983 issue_flags |= IO_URING_F_NONBLOCK;
1988 ret = io_issue_sqe(req, issue_flags);
1993 * If REQ_F_NOWAIT is set, then don't wait or retry with
1994 * poll. -EAGAIN is final for that case.
1996 if (req->flags & REQ_F_NOWAIT)
2000 * We can get EAGAIN for iopolled IO even though we're
2001 * forcing a sync submission from here, since we can't
2002 * wait for request slots on the block side.
2005 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
2007 if (io_wq_worker_stopped())
2013 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
2015 /* aborted or ready, in either case retry blocking */
2017 issue_flags &= ~IO_URING_F_NONBLOCK;
2020 /* avoid locking problems by failing it from a clean context */
2022 io_req_task_queue_fail(req, ret);
2025 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
2026 unsigned int issue_flags)
2028 struct io_ring_ctx *ctx = req->ctx;
2029 struct io_fixed_file *slot;
2030 struct file *file = NULL;
2032 io_ring_submit_lock(ctx, issue_flags);
2034 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
2036 fd = array_index_nospec(fd, ctx->nr_user_files);
2037 slot = io_fixed_file_slot(&ctx->file_table, fd);
2038 if (!req->rsrc_node)
2039 __io_req_set_rsrc_node(req, ctx);
2040 req->flags |= io_slot_flags(slot);
2041 file = io_slot_file(slot);
2043 io_ring_submit_unlock(ctx, issue_flags);
2047 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
2049 struct file *file = fget(fd);
2051 trace_io_uring_file_get(req, fd);
2053 /* we don't allow fixed io_uring files */
2054 if (file && io_is_uring_fops(file))
2055 io_req_track_inflight(req);
2059 static void io_queue_async(struct io_kiocb *req, int ret)
2060 __must_hold(&req->ctx->uring_lock)
2062 struct io_kiocb *linked_timeout;
2064 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
2065 io_req_defer_failed(req, ret);
2069 linked_timeout = io_prep_linked_timeout(req);
2071 switch (io_arm_poll_handler(req, 0)) {
2072 case IO_APOLL_READY:
2073 io_kbuf_recycle(req, 0);
2074 io_req_task_queue(req);
2076 case IO_APOLL_ABORTED:
2077 io_kbuf_recycle(req, 0);
2078 io_queue_iowq(req, NULL);
2085 io_queue_linked_timeout(linked_timeout);
2088 static inline void io_queue_sqe(struct io_kiocb *req)
2089 __must_hold(&req->ctx->uring_lock)
2093 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
2096 * We async punt it if the file wasn't marked NOWAIT, or if the file
2097 * doesn't support non-blocking read/write attempts
2100 io_queue_async(req, ret);
2103 static void io_queue_sqe_fallback(struct io_kiocb *req)
2104 __must_hold(&req->ctx->uring_lock)
2106 if (unlikely(req->flags & REQ_F_FAIL)) {
2108 * We don't submit, fail them all, for that replace hardlinks
2109 * with normal links. Extra REQ_F_LINK is tolerated.
2111 req->flags &= ~REQ_F_HARDLINK;
2112 req->flags |= REQ_F_LINK;
2113 io_req_defer_failed(req, req->cqe.res);
2115 int ret = io_req_prep_async(req);
2117 if (unlikely(ret)) {
2118 io_req_defer_failed(req, ret);
2122 if (unlikely(req->ctx->drain_active))
2125 io_queue_iowq(req, NULL);
2130 * Check SQE restrictions (opcode and flags).
2132 * Returns 'true' if SQE is allowed, 'false' otherwise.
2134 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2135 struct io_kiocb *req,
2136 unsigned int sqe_flags)
2138 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2141 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2142 ctx->restrictions.sqe_flags_required)
2145 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2146 ctx->restrictions.sqe_flags_required))
2152 static void io_init_req_drain(struct io_kiocb *req)
2154 struct io_ring_ctx *ctx = req->ctx;
2155 struct io_kiocb *head = ctx->submit_state.link.head;
2157 ctx->drain_active = true;
2160 * If we need to drain a request in the middle of a link, drain
2161 * the head request and the next request/link after the current
2162 * link. Considering sequential execution of links,
2163 * REQ_F_IO_DRAIN will be maintained for every request of our
2166 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2167 ctx->drain_next = true;
2171 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2173 /* ensure per-opcode data is cleared if we fail before prep */
2174 memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2178 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2179 const struct io_uring_sqe *sqe)
2180 __must_hold(&ctx->uring_lock)
2182 const struct io_issue_def *def;
2183 unsigned int sqe_flags;
2187 /* req is partially pre-initialised, see io_preinit_req() */
2188 req->opcode = opcode = READ_ONCE(sqe->opcode);
2189 /* same numerical values with corresponding REQ_F_*, safe to copy */
2190 req->flags = sqe_flags = READ_ONCE(sqe->flags);
2191 req->cqe.user_data = READ_ONCE(sqe->user_data);
2193 req->rsrc_node = NULL;
2194 req->task = current;
2196 if (unlikely(opcode >= IORING_OP_LAST)) {
2198 return io_init_fail_req(req, -EINVAL);
2200 def = &io_issue_defs[opcode];
2201 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2202 /* enforce forwards compatibility on users */
2203 if (sqe_flags & ~SQE_VALID_FLAGS)
2204 return io_init_fail_req(req, -EINVAL);
2205 if (sqe_flags & IOSQE_BUFFER_SELECT) {
2206 if (!def->buffer_select)
2207 return io_init_fail_req(req, -EOPNOTSUPP);
2208 req->buf_index = READ_ONCE(sqe->buf_group);
2210 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2211 ctx->drain_disabled = true;
2212 if (sqe_flags & IOSQE_IO_DRAIN) {
2213 if (ctx->drain_disabled)
2214 return io_init_fail_req(req, -EOPNOTSUPP);
2215 io_init_req_drain(req);
2218 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2219 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2220 return io_init_fail_req(req, -EACCES);
2221 /* knock it to the slow queue path, will be drained there */
2222 if (ctx->drain_active)
2223 req->flags |= REQ_F_FORCE_ASYNC;
2224 /* if there is no link, we're at "next" request and need to drain */
2225 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2226 ctx->drain_next = false;
2227 ctx->drain_active = true;
2228 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2232 if (!def->ioprio && sqe->ioprio)
2233 return io_init_fail_req(req, -EINVAL);
2234 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2235 return io_init_fail_req(req, -EINVAL);
2237 if (def->needs_file) {
2238 struct io_submit_state *state = &ctx->submit_state;
2240 req->cqe.fd = READ_ONCE(sqe->fd);
2243 * Plug now if we have more than 2 IO left after this, and the
2244 * target is potentially a read/write to block based storage.
2246 if (state->need_plug && def->plug) {
2247 state->plug_started = true;
2248 state->need_plug = false;
2249 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2253 personality = READ_ONCE(sqe->personality);
2257 req->creds = xa_load(&ctx->personalities, personality);
2259 return io_init_fail_req(req, -EINVAL);
2260 get_cred(req->creds);
2261 ret = security_uring_override_creds(req->creds);
2263 put_cred(req->creds);
2264 return io_init_fail_req(req, ret);
2266 req->flags |= REQ_F_CREDS;
2269 return def->prep(req, sqe);
2272 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2273 struct io_kiocb *req, int ret)
2275 struct io_ring_ctx *ctx = req->ctx;
2276 struct io_submit_link *link = &ctx->submit_state.link;
2277 struct io_kiocb *head = link->head;
2279 trace_io_uring_req_failed(sqe, req, ret);
2282 * Avoid breaking links in the middle as it renders links with SQPOLL
2283 * unusable. Instead of failing eagerly, continue assembling the link if
2284 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2285 * should find the flag and handle the rest.
2287 req_fail_link_node(req, ret);
2288 if (head && !(head->flags & REQ_F_FAIL))
2289 req_fail_link_node(head, -ECANCELED);
2291 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2293 link->last->link = req;
2297 io_queue_sqe_fallback(req);
2302 link->last->link = req;
2309 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2310 const struct io_uring_sqe *sqe)
2311 __must_hold(&ctx->uring_lock)
2313 struct io_submit_link *link = &ctx->submit_state.link;
2316 ret = io_init_req(ctx, req, sqe);
2318 return io_submit_fail_init(sqe, req, ret);
2320 trace_io_uring_submit_req(req);
2323 * If we already have a head request, queue this one for async
2324 * submittal once the head completes. If we don't have a head but
2325 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2326 * submitted sync once the chain is complete. If none of those
2327 * conditions are true (normal request), then just queue it.
2329 if (unlikely(link->head)) {
2330 ret = io_req_prep_async(req);
2332 return io_submit_fail_init(sqe, req, ret);
2334 trace_io_uring_link(req, link->head);
2335 link->last->link = req;
2338 if (req->flags & IO_REQ_LINK_FLAGS)
2340 /* last request of the link, flush it */
2343 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2346 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2347 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2348 if (req->flags & IO_REQ_LINK_FLAGS) {
2353 io_queue_sqe_fallback(req);
2363 * Batched submission is done, ensure local IO is flushed out.
2365 static void io_submit_state_end(struct io_ring_ctx *ctx)
2367 struct io_submit_state *state = &ctx->submit_state;
2369 if (unlikely(state->link.head))
2370 io_queue_sqe_fallback(state->link.head);
2371 /* flush only after queuing links as they can generate completions */
2372 io_submit_flush_completions(ctx);
2373 if (state->plug_started)
2374 blk_finish_plug(&state->plug);
2378 * Start submission side cache.
2380 static void io_submit_state_start(struct io_submit_state *state,
2381 unsigned int max_ios)
2383 state->plug_started = false;
2384 state->need_plug = max_ios > 2;
2385 state->submit_nr = max_ios;
2386 /* set only head, no need to init link_last in advance */
2387 state->link.head = NULL;
2390 static void io_commit_sqring(struct io_ring_ctx *ctx)
2392 struct io_rings *rings = ctx->rings;
2395 * Ensure any loads from the SQEs are done at this point,
2396 * since once we write the new head, the application could
2397 * write new data to them.
2399 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2403 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2404 * that is mapped by userspace. This means that care needs to be taken to
2405 * ensure that reads are stable, as we cannot rely on userspace always
2406 * being a good citizen. If members of the sqe are validated and then later
2407 * used, it's important that those reads are done through READ_ONCE() to
2408 * prevent a re-load down the line.
2410 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2412 unsigned mask = ctx->sq_entries - 1;
2413 unsigned head = ctx->cached_sq_head++ & mask;
2415 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
2416 head = READ_ONCE(ctx->sq_array[head]);
2417 if (unlikely(head >= ctx->sq_entries)) {
2418 /* drop invalid entries */
2419 spin_lock(&ctx->completion_lock);
2421 spin_unlock(&ctx->completion_lock);
2422 WRITE_ONCE(ctx->rings->sq_dropped,
2423 READ_ONCE(ctx->rings->sq_dropped) + 1);
2429 * The cached sq head (or cq tail) serves two purposes:
2431 * 1) allows us to batch the cost of updating the user visible
2433 * 2) allows the kernel side to track the head on its own, even
2434 * though the application is the one updating it.
2437 /* double index for 128-byte SQEs, twice as long */
2438 if (ctx->flags & IORING_SETUP_SQE128)
2440 *sqe = &ctx->sq_sqes[head];
2444 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2445 __must_hold(&ctx->uring_lock)
2447 unsigned int entries = io_sqring_entries(ctx);
2451 if (unlikely(!entries))
2453 /* make sure SQ entry isn't read before tail */
2454 ret = left = min(nr, entries);
2455 io_get_task_refs(left);
2456 io_submit_state_start(&ctx->submit_state, left);
2459 const struct io_uring_sqe *sqe;
2460 struct io_kiocb *req;
2462 if (unlikely(!io_alloc_req(ctx, &req)))
2464 if (unlikely(!io_get_sqe(ctx, &sqe))) {
2465 io_req_add_to_cache(req, ctx);
2470 * Continue submitting even for sqe failure if the
2471 * ring was setup with IORING_SETUP_SUBMIT_ALL
2473 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2474 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2480 if (unlikely(left)) {
2482 /* try again if it submitted nothing and can't allocate a req */
2483 if (!ret && io_req_cache_empty(ctx))
2485 current->io_uring->cached_refs += left;
2488 io_submit_state_end(ctx);
2489 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2490 io_commit_sqring(ctx);
2494 struct io_wait_queue {
2495 struct wait_queue_entry wq;
2496 struct io_ring_ctx *ctx;
2498 unsigned nr_timeouts;
2502 static inline bool io_has_work(struct io_ring_ctx *ctx)
2504 return test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq) ||
2505 !llist_empty(&ctx->work_llist);
2508 static inline bool io_should_wake(struct io_wait_queue *iowq)
2510 struct io_ring_ctx *ctx = iowq->ctx;
2511 int dist = READ_ONCE(ctx->rings->cq.tail) - (int) iowq->cq_tail;
2514 * Wake up if we have enough events, or if a timeout occurred since we
2515 * started waiting. For timeouts, we always want to return to userspace,
2516 * regardless of event count.
2518 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2521 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2522 int wake_flags, void *key)
2524 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2527 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2528 * the task, and the next invocation will do it.
2530 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2531 return autoremove_wake_function(curr, mode, wake_flags, key);
2535 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2537 if (!llist_empty(&ctx->work_llist)) {
2538 __set_current_state(TASK_RUNNING);
2539 if (io_run_local_work(ctx, INT_MAX) > 0)
2542 if (io_run_task_work() > 0)
2544 if (task_sigpending(current))
2549 static bool current_pending_io(void)
2551 struct io_uring_task *tctx = current->io_uring;
2555 return percpu_counter_read_positive(&tctx->inflight);
2558 /* when returns >0, the caller should retry */
2559 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2560 struct io_wait_queue *iowq)
2564 if (unlikely(READ_ONCE(ctx->check_cq)))
2566 if (unlikely(!llist_empty(&ctx->work_llist)))
2568 if (unlikely(test_thread_flag(TIF_NOTIFY_SIGNAL)))
2570 if (unlikely(task_sigpending(current)))
2572 if (unlikely(io_should_wake(iowq)))
2576 * Mark us as being in io_wait if we have pending requests, so cpufreq
2577 * can take into account that the task is waiting for IO - turns out
2578 * to be important for low QD IO.
2580 if (current_pending_io())
2581 current->in_iowait = 1;
2583 if (iowq->timeout == KTIME_MAX)
2585 else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS))
2587 current->in_iowait = 0;
2592 * Wait until events become available, if we don't already have some. The
2593 * application must reap them itself, as they reside on the shared cq ring.
2595 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2596 const sigset_t __user *sig, size_t sigsz,
2597 struct __kernel_timespec __user *uts)
2599 struct io_wait_queue iowq;
2600 struct io_rings *rings = ctx->rings;
2603 if (!io_allowed_run_tw(ctx))
2605 if (!llist_empty(&ctx->work_llist))
2606 io_run_local_work(ctx, min_events);
2608 io_cqring_overflow_flush(ctx);
2609 /* if user messes with these they will just get an early return */
2610 if (__io_cqring_events_user(ctx) >= min_events)
2614 #ifdef CONFIG_COMPAT
2615 if (in_compat_syscall())
2616 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2620 ret = set_user_sigmask(sig, sigsz);
2626 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2627 iowq.wq.private = current;
2628 INIT_LIST_HEAD(&iowq.wq.entry);
2630 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2631 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2632 iowq.timeout = KTIME_MAX;
2635 struct timespec64 ts;
2637 if (get_timespec64(&ts, uts))
2639 iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2642 trace_io_uring_cqring_wait(ctx, min_events);
2644 int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail);
2645 unsigned long check_cq;
2647 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2648 atomic_set(&ctx->cq_wait_nr, nr_wait);
2649 set_current_state(TASK_INTERRUPTIBLE);
2651 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2652 TASK_INTERRUPTIBLE);
2655 ret = io_cqring_wait_schedule(ctx, &iowq);
2656 __set_current_state(TASK_RUNNING);
2657 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
2660 * Run task_work after scheduling and before io_should_wake().
2661 * If we got woken because of task_work being processed, run it
2662 * now rather than let the caller do another wait loop.
2665 if (!llist_empty(&ctx->work_llist))
2666 io_run_local_work(ctx, nr_wait);
2669 * Non-local task_work will be run on exit to userspace, but
2670 * if we're using DEFER_TASKRUN, then we could have waited
2671 * with a timeout for a number of requests. If the timeout
2672 * hits, we could have some requests ready to process. Ensure
2673 * this break is _after_ we have run task_work, to avoid
2674 * deferring running potentially pending requests until the
2675 * next time we wait for events.
2680 check_cq = READ_ONCE(ctx->check_cq);
2681 if (unlikely(check_cq)) {
2682 /* let the caller flush overflows, retry */
2683 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2684 io_cqring_do_overflow_flush(ctx);
2685 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2691 if (io_should_wake(&iowq)) {
2698 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2699 finish_wait(&ctx->cq_wait, &iowq.wq);
2700 restore_saved_sigmask_unless(ret == -EINTR);
2702 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2705 void io_mem_free(void *ptr)
2710 folio_put(virt_to_folio(ptr));
2713 static void io_pages_free(struct page ***pages, int npages)
2715 struct page **page_array;
2721 page_array = *pages;
2725 for (i = 0; i < npages; i++)
2726 unpin_user_page(page_array[i]);
2731 static void *__io_uaddr_map(struct page ***pages, unsigned short *npages,
2732 unsigned long uaddr, size_t size)
2734 struct page **page_array;
2735 unsigned int nr_pages;
2741 if (uaddr & (PAGE_SIZE - 1) || !size)
2742 return ERR_PTR(-EINVAL);
2744 nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2745 if (nr_pages > USHRT_MAX)
2746 return ERR_PTR(-EINVAL);
2747 page_array = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
2749 return ERR_PTR(-ENOMEM);
2752 pinned = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
2754 if (pinned != nr_pages) {
2755 ret = (pinned < 0) ? pinned : -EFAULT;
2759 page_addr = page_address(page_array[0]);
2760 for (i = 0; i < nr_pages; i++) {
2764 * Can't support mapping user allocated ring memory on 32-bit
2765 * archs where it could potentially reside in highmem. Just
2766 * fail those with -EINVAL, just like we did on kernels that
2767 * didn't support this feature.
2769 if (PageHighMem(page_array[i]))
2773 * No support for discontig pages for now, should either be a
2774 * single normal page, or a huge page. Later on we can add
2775 * support for remapping discontig pages, for now we will
2776 * just fail them with EINVAL.
2778 if (page_address(page_array[i]) != page_addr)
2780 page_addr += PAGE_SIZE;
2783 *pages = page_array;
2785 return page_to_virt(page_array[0]);
2788 io_pages_free(&page_array, pinned > 0 ? pinned : 0);
2789 return ERR_PTR(ret);
2792 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2795 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2799 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2802 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2806 static void io_rings_free(struct io_ring_ctx *ctx)
2808 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2809 io_mem_free(ctx->rings);
2810 io_mem_free(ctx->sq_sqes);
2812 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
2813 ctx->n_ring_pages = 0;
2814 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
2815 ctx->n_sqe_pages = 0;
2819 ctx->sq_sqes = NULL;
2822 void *io_mem_alloc(size_t size)
2824 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2827 ret = (void *) __get_free_pages(gfp, get_order(size));
2830 return ERR_PTR(-ENOMEM);
2833 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2834 unsigned int cq_entries, size_t *sq_offset)
2836 struct io_rings *rings;
2837 size_t off, sq_array_size;
2839 off = struct_size(rings, cqes, cq_entries);
2840 if (off == SIZE_MAX)
2842 if (ctx->flags & IORING_SETUP_CQE32) {
2843 if (check_shl_overflow(off, 1, &off))
2848 off = ALIGN(off, SMP_CACHE_BYTES);
2853 if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
2855 *sq_offset = SIZE_MAX;
2862 sq_array_size = array_size(sizeof(u32), sq_entries);
2863 if (sq_array_size == SIZE_MAX)
2866 if (check_add_overflow(off, sq_array_size, &off))
2872 static void io_req_caches_free(struct io_ring_ctx *ctx)
2874 struct io_kiocb *req;
2877 mutex_lock(&ctx->uring_lock);
2878 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2880 while (!io_req_cache_empty(ctx)) {
2881 req = io_extract_req(ctx);
2882 kmem_cache_free(req_cachep, req);
2886 percpu_ref_put_many(&ctx->refs, nr);
2887 mutex_unlock(&ctx->uring_lock);
2890 static void io_rsrc_node_cache_free(struct io_cache_entry *entry)
2892 kfree(container_of(entry, struct io_rsrc_node, cache));
2895 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2897 io_sq_thread_finish(ctx);
2898 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
2899 if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
2902 mutex_lock(&ctx->uring_lock);
2904 __io_sqe_buffers_unregister(ctx);
2906 __io_sqe_files_unregister(ctx);
2907 io_cqring_overflow_kill(ctx);
2908 io_eventfd_unregister(ctx);
2909 io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free);
2910 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
2911 io_futex_cache_free(ctx);
2912 io_destroy_buffers(ctx);
2913 mutex_unlock(&ctx->uring_lock);
2915 put_cred(ctx->sq_creds);
2916 if (ctx->submitter_task)
2917 put_task_struct(ctx->submitter_task);
2919 /* there are no registered resources left, nobody uses it */
2921 io_rsrc_node_destroy(ctx, ctx->rsrc_node);
2923 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
2924 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2926 io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free);
2927 if (ctx->mm_account) {
2928 mmdrop(ctx->mm_account);
2929 ctx->mm_account = NULL;
2932 io_kbuf_mmap_list_free(ctx);
2934 percpu_ref_exit(&ctx->refs);
2935 free_uid(ctx->user);
2936 io_req_caches_free(ctx);
2938 io_wq_put_hash(ctx->hash_map);
2939 kfree(ctx->cancel_table.hbs);
2940 kfree(ctx->cancel_table_locked.hbs);
2941 xa_destroy(&ctx->io_bl_xa);
2945 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2947 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2950 mutex_lock(&ctx->uring_lock);
2951 ctx->poll_activated = true;
2952 mutex_unlock(&ctx->uring_lock);
2955 * Wake ups for some events between start of polling and activation
2956 * might've been lost due to loose synchronisation.
2958 wake_up_all(&ctx->poll_wq);
2959 percpu_ref_put(&ctx->refs);
2962 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2964 spin_lock(&ctx->completion_lock);
2965 /* already activated or in progress */
2966 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2968 if (WARN_ON_ONCE(!ctx->task_complete))
2970 if (!ctx->submitter_task)
2973 * with ->submitter_task only the submitter task completes requests, we
2974 * only need to sync with it, which is done by injecting a tw
2976 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2977 percpu_ref_get(&ctx->refs);
2978 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2979 percpu_ref_put(&ctx->refs);
2981 spin_unlock(&ctx->completion_lock);
2984 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2986 struct io_ring_ctx *ctx = file->private_data;
2989 if (unlikely(!ctx->poll_activated))
2990 io_activate_pollwq(ctx);
2992 poll_wait(file, &ctx->poll_wq, wait);
2994 * synchronizes with barrier from wq_has_sleeper call in
2998 if (!io_sqring_full(ctx))
2999 mask |= EPOLLOUT | EPOLLWRNORM;
3002 * Don't flush cqring overflow list here, just do a simple check.
3003 * Otherwise there could possible be ABBA deadlock:
3006 * lock(&ctx->uring_lock);
3008 * lock(&ctx->uring_lock);
3011 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
3012 * pushes them to do the flush.
3015 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
3016 mask |= EPOLLIN | EPOLLRDNORM;
3021 struct io_tctx_exit {
3022 struct callback_head task_work;
3023 struct completion completion;
3024 struct io_ring_ctx *ctx;
3027 static __cold void io_tctx_exit_cb(struct callback_head *cb)
3029 struct io_uring_task *tctx = current->io_uring;
3030 struct io_tctx_exit *work;
3032 work = container_of(cb, struct io_tctx_exit, task_work);
3034 * When @in_cancel, we're in cancellation and it's racy to remove the
3035 * node. It'll be removed by the end of cancellation, just ignore it.
3036 * tctx can be NULL if the queueing of this task_work raced with
3037 * work cancelation off the exec path.
3039 if (tctx && !atomic_read(&tctx->in_cancel))
3040 io_uring_del_tctx_node((unsigned long)work->ctx);
3041 complete(&work->completion);
3044 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
3046 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3048 return req->ctx == data;
3051 static __cold void io_ring_exit_work(struct work_struct *work)
3053 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
3054 unsigned long timeout = jiffies + HZ * 60 * 5;
3055 unsigned long interval = HZ / 20;
3056 struct io_tctx_exit exit;
3057 struct io_tctx_node *node;
3061 * If we're doing polled IO and end up having requests being
3062 * submitted async (out-of-line), then completions can come in while
3063 * we're waiting for refs to drop. We need to reap these manually,
3064 * as nobody else will be looking for them.
3067 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
3068 mutex_lock(&ctx->uring_lock);
3069 io_cqring_overflow_kill(ctx);
3070 mutex_unlock(&ctx->uring_lock);
3073 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3074 io_move_task_work_from_local(ctx);
3076 while (io_uring_try_cancel_requests(ctx, NULL, true))
3080 struct io_sq_data *sqd = ctx->sq_data;
3081 struct task_struct *tsk;
3083 io_sq_thread_park(sqd);
3085 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
3086 io_wq_cancel_cb(tsk->io_uring->io_wq,
3087 io_cancel_ctx_cb, ctx, true);
3088 io_sq_thread_unpark(sqd);
3091 io_req_caches_free(ctx);
3093 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
3094 /* there is little hope left, don't run it too often */
3098 * This is really an uninterruptible wait, as it has to be
3099 * complete. But it's also run from a kworker, which doesn't
3100 * take signals, so it's fine to make it interruptible. This
3101 * avoids scenarios where we knowingly can wait much longer
3102 * on completions, for example if someone does a SIGSTOP on
3103 * a task that needs to finish task_work to make this loop
3104 * complete. That's a synthetic situation that should not
3105 * cause a stuck task backtrace, and hence a potential panic
3106 * on stuck tasks if that is enabled.
3108 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
3110 init_completion(&exit.completion);
3111 init_task_work(&exit.task_work, io_tctx_exit_cb);
3114 mutex_lock(&ctx->uring_lock);
3115 while (!list_empty(&ctx->tctx_list)) {
3116 WARN_ON_ONCE(time_after(jiffies, timeout));
3118 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
3120 /* don't spin on a single task if cancellation failed */
3121 list_rotate_left(&ctx->tctx_list);
3122 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
3123 if (WARN_ON_ONCE(ret))
3126 mutex_unlock(&ctx->uring_lock);
3128 * See comment above for
3129 * wait_for_completion_interruptible_timeout() on why this
3130 * wait is marked as interruptible.
3132 wait_for_completion_interruptible(&exit.completion);
3133 mutex_lock(&ctx->uring_lock);
3135 mutex_unlock(&ctx->uring_lock);
3136 spin_lock(&ctx->completion_lock);
3137 spin_unlock(&ctx->completion_lock);
3139 /* pairs with RCU read section in io_req_local_work_add() */
3140 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3143 io_ring_ctx_free(ctx);
3146 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3148 unsigned long index;
3149 struct creds *creds;
3151 mutex_lock(&ctx->uring_lock);
3152 percpu_ref_kill(&ctx->refs);
3153 xa_for_each(&ctx->personalities, index, creds)
3154 io_unregister_personality(ctx, index);
3156 io_poll_remove_all(ctx, NULL, true);
3157 mutex_unlock(&ctx->uring_lock);
3160 * If we failed setting up the ctx, we might not have any rings
3161 * and therefore did not submit any requests
3164 io_kill_timeouts(ctx, NULL, true);
3166 flush_delayed_work(&ctx->fallback_work);
3168 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
3170 * Use system_unbound_wq to avoid spawning tons of event kworkers
3171 * if we're exiting a ton of rings at the same time. It just adds
3172 * noise and overhead, there's no discernable change in runtime
3173 * over using system_wq.
3175 queue_work(iou_wq, &ctx->exit_work);
3178 static int io_uring_release(struct inode *inode, struct file *file)
3180 struct io_ring_ctx *ctx = file->private_data;
3182 file->private_data = NULL;
3183 io_ring_ctx_wait_and_kill(ctx);
3187 struct io_task_cancel {
3188 struct task_struct *task;
3192 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3194 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3195 struct io_task_cancel *cancel = data;
3197 return io_match_task_safe(req, cancel->task, cancel->all);
3200 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3201 struct task_struct *task,
3204 struct io_defer_entry *de;
3207 spin_lock(&ctx->completion_lock);
3208 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
3209 if (io_match_task_safe(de->req, task, cancel_all)) {
3210 list_cut_position(&list, &ctx->defer_list, &de->list);
3214 spin_unlock(&ctx->completion_lock);
3215 if (list_empty(&list))
3218 while (!list_empty(&list)) {
3219 de = list_first_entry(&list, struct io_defer_entry, list);
3220 list_del_init(&de->list);
3221 io_req_task_queue_fail(de->req, -ECANCELED);
3227 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3229 struct io_tctx_node *node;
3230 enum io_wq_cancel cret;
3233 mutex_lock(&ctx->uring_lock);
3234 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3235 struct io_uring_task *tctx = node->task->io_uring;
3238 * io_wq will stay alive while we hold uring_lock, because it's
3239 * killed after ctx nodes, which requires to take the lock.
3241 if (!tctx || !tctx->io_wq)
3243 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3244 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3246 mutex_unlock(&ctx->uring_lock);
3251 static bool io_uring_try_cancel_uring_cmd(struct io_ring_ctx *ctx,
3252 struct task_struct *task, bool cancel_all)
3254 struct hlist_node *tmp;
3255 struct io_kiocb *req;
3258 lockdep_assert_held(&ctx->uring_lock);
3260 hlist_for_each_entry_safe(req, tmp, &ctx->cancelable_uring_cmd,
3262 struct io_uring_cmd *cmd = io_kiocb_to_cmd(req,
3263 struct io_uring_cmd);
3264 struct file *file = req->file;
3266 if (!cancel_all && req->task != task)
3269 if (cmd->flags & IORING_URING_CMD_CANCELABLE) {
3270 /* ->sqe isn't available if no async data */
3271 if (!req_has_async_data(req))
3273 file->f_op->uring_cmd(cmd, IO_URING_F_CANCEL);
3277 io_submit_flush_completions(ctx);
3282 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3283 struct task_struct *task,
3286 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
3287 struct io_uring_task *tctx = task ? task->io_uring : NULL;
3288 enum io_wq_cancel cret;
3291 /* set it so io_req_local_work_add() would wake us up */
3292 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3293 atomic_set(&ctx->cq_wait_nr, 1);
3297 /* failed during ring init, it couldn't have issued any requests */
3302 ret |= io_uring_try_cancel_iowq(ctx);
3303 } else if (tctx && tctx->io_wq) {
3305 * Cancels requests of all rings, not only @ctx, but
3306 * it's fine as the task is in exit/exec.
3308 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3310 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3313 /* SQPOLL thread does its own polling */
3314 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3315 (ctx->sq_data && ctx->sq_data->thread == current)) {
3316 while (!wq_list_empty(&ctx->iopoll_list)) {
3317 io_iopoll_try_reap_events(ctx);
3323 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3324 io_allowed_defer_tw_run(ctx))
3325 ret |= io_run_local_work(ctx, INT_MAX) > 0;
3326 ret |= io_cancel_defer_files(ctx, task, cancel_all);
3327 mutex_lock(&ctx->uring_lock);
3328 ret |= io_poll_remove_all(ctx, task, cancel_all);
3329 ret |= io_waitid_remove_all(ctx, task, cancel_all);
3330 ret |= io_futex_remove_all(ctx, task, cancel_all);
3331 ret |= io_uring_try_cancel_uring_cmd(ctx, task, cancel_all);
3332 mutex_unlock(&ctx->uring_lock);
3333 ret |= io_kill_timeouts(ctx, task, cancel_all);
3335 ret |= io_run_task_work() > 0;
3339 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3342 return atomic_read(&tctx->inflight_tracked);
3343 return percpu_counter_sum(&tctx->inflight);
3347 * Find any io_uring ctx that this task has registered or done IO on, and cancel
3348 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3350 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3352 struct io_uring_task *tctx = current->io_uring;
3353 struct io_ring_ctx *ctx;
3354 struct io_tctx_node *node;
3355 unsigned long index;
3359 WARN_ON_ONCE(sqd && sqd->thread != current);
3361 if (!current->io_uring)
3364 io_wq_exit_start(tctx->io_wq);
3366 atomic_inc(&tctx->in_cancel);
3370 io_uring_drop_tctx_refs(current);
3371 /* read completions before cancelations */
3372 inflight = tctx_inflight(tctx, !cancel_all);
3377 xa_for_each(&tctx->xa, index, node) {
3378 /* sqpoll task will cancel all its requests */
3379 if (node->ctx->sq_data)
3381 loop |= io_uring_try_cancel_requests(node->ctx,
3382 current, cancel_all);
3385 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3386 loop |= io_uring_try_cancel_requests(ctx,
3396 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3398 io_uring_drop_tctx_refs(current);
3399 xa_for_each(&tctx->xa, index, node) {
3400 if (!llist_empty(&node->ctx->work_llist)) {
3401 WARN_ON_ONCE(node->ctx->submitter_task &&
3402 node->ctx->submitter_task != current);
3407 * If we've seen completions, retry without waiting. This
3408 * avoids a race where a completion comes in before we did
3409 * prepare_to_wait().
3411 if (inflight == tctx_inflight(tctx, !cancel_all))
3414 finish_wait(&tctx->wait, &wait);
3417 io_uring_clean_tctx(tctx);
3420 * We shouldn't run task_works after cancel, so just leave
3421 * ->in_cancel set for normal exit.
3423 atomic_dec(&tctx->in_cancel);
3424 /* for exec all current's requests should be gone, kill tctx */
3425 __io_uring_free(current);
3429 void __io_uring_cancel(bool cancel_all)
3431 io_uring_cancel_generic(cancel_all, NULL);
3434 static void *io_uring_validate_mmap_request(struct file *file,
3435 loff_t pgoff, size_t sz)
3437 struct io_ring_ctx *ctx = file->private_data;
3438 loff_t offset = pgoff << PAGE_SHIFT;
3442 switch (offset & IORING_OFF_MMAP_MASK) {
3443 case IORING_OFF_SQ_RING:
3444 case IORING_OFF_CQ_RING:
3445 /* Don't allow mmap if the ring was setup without it */
3446 if (ctx->flags & IORING_SETUP_NO_MMAP)
3447 return ERR_PTR(-EINVAL);
3450 case IORING_OFF_SQES:
3451 /* Don't allow mmap if the ring was setup without it */
3452 if (ctx->flags & IORING_SETUP_NO_MMAP)
3453 return ERR_PTR(-EINVAL);
3456 case IORING_OFF_PBUF_RING: {
3457 struct io_buffer_list *bl;
3460 bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT;
3461 bl = io_pbuf_get_bl(ctx, bgid);
3469 return ERR_PTR(-EINVAL);
3472 page = virt_to_head_page(ptr);
3473 if (sz > page_size(page))
3474 return ERR_PTR(-EINVAL);
3481 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3483 size_t sz = vma->vm_end - vma->vm_start;
3487 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
3489 return PTR_ERR(ptr);
3491 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3492 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3495 static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp,
3496 unsigned long addr, unsigned long len,
3497 unsigned long pgoff, unsigned long flags)
3502 * Do not allow to map to user-provided address to avoid breaking the
3503 * aliasing rules. Userspace is not able to guess the offset address of
3504 * kernel kmalloc()ed memory area.
3509 ptr = io_uring_validate_mmap_request(filp, pgoff, len);
3514 * Some architectures have strong cache aliasing requirements.
3515 * For such architectures we need a coherent mapping which aliases
3516 * kernel memory *and* userspace memory. To achieve that:
3517 * - use a NULL file pointer to reference physical memory, and
3518 * - use the kernel virtual address of the shared io_uring context
3519 * (instead of the userspace-provided address, which has to be 0UL
3521 * - use the same pgoff which the get_unmapped_area() uses to
3522 * calculate the page colouring.
3523 * For architectures without such aliasing requirements, the
3524 * architecture will return any suitable mapping because addr is 0.
3527 flags |= MAP_SHARED;
3528 pgoff = 0; /* has been translated to ptr above */
3530 addr = (uintptr_t) ptr;
3531 pgoff = addr >> PAGE_SHIFT;
3535 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
3538 #else /* !CONFIG_MMU */
3540 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3542 return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL;
3545 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
3547 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
3550 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3551 unsigned long addr, unsigned long len,
3552 unsigned long pgoff, unsigned long flags)
3556 ptr = io_uring_validate_mmap_request(file, pgoff, len);
3558 return PTR_ERR(ptr);
3560 return (unsigned long) ptr;
3563 #endif /* !CONFIG_MMU */
3565 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3567 if (flags & IORING_ENTER_EXT_ARG) {
3568 struct io_uring_getevents_arg arg;
3570 if (argsz != sizeof(arg))
3572 if (copy_from_user(&arg, argp, sizeof(arg)))
3578 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3579 struct __kernel_timespec __user **ts,
3580 const sigset_t __user **sig)
3582 struct io_uring_getevents_arg arg;
3585 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3586 * is just a pointer to the sigset_t.
3588 if (!(flags & IORING_ENTER_EXT_ARG)) {
3589 *sig = (const sigset_t __user *) argp;
3595 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3596 * timespec and sigset_t pointers if good.
3598 if (*argsz != sizeof(arg))
3600 if (copy_from_user(&arg, argp, sizeof(arg)))
3604 *sig = u64_to_user_ptr(arg.sigmask);
3605 *argsz = arg.sigmask_sz;
3606 *ts = u64_to_user_ptr(arg.ts);
3610 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3611 u32, min_complete, u32, flags, const void __user *, argp,
3614 struct io_ring_ctx *ctx;
3618 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3619 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3620 IORING_ENTER_REGISTERED_RING)))
3624 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3625 * need only dereference our task private array to find it.
3627 if (flags & IORING_ENTER_REGISTERED_RING) {
3628 struct io_uring_task *tctx = current->io_uring;
3630 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3632 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3633 file = tctx->registered_rings[fd];
3634 if (unlikely(!file))
3638 if (unlikely(!file))
3641 if (unlikely(!io_is_uring_fops(file)))
3645 ctx = file->private_data;
3647 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3651 * For SQ polling, the thread will do all submissions and completions.
3652 * Just return the requested submit count, and wake the thread if
3656 if (ctx->flags & IORING_SETUP_SQPOLL) {
3657 io_cqring_overflow_flush(ctx);
3659 if (unlikely(ctx->sq_data->thread == NULL)) {
3663 if (flags & IORING_ENTER_SQ_WAKEUP)
3664 wake_up(&ctx->sq_data->wait);
3665 if (flags & IORING_ENTER_SQ_WAIT)
3666 io_sqpoll_wait_sq(ctx);
3669 } else if (to_submit) {
3670 ret = io_uring_add_tctx_node(ctx);
3674 mutex_lock(&ctx->uring_lock);
3675 ret = io_submit_sqes(ctx, to_submit);
3676 if (ret != to_submit) {
3677 mutex_unlock(&ctx->uring_lock);
3680 if (flags & IORING_ENTER_GETEVENTS) {
3681 if (ctx->syscall_iopoll)
3684 * Ignore errors, we'll soon call io_cqring_wait() and
3685 * it should handle ownership problems if any.
3687 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3688 (void)io_run_local_work_locked(ctx, min_complete);
3690 mutex_unlock(&ctx->uring_lock);
3693 if (flags & IORING_ENTER_GETEVENTS) {
3696 if (ctx->syscall_iopoll) {
3698 * We disallow the app entering submit/complete with
3699 * polling, but we still need to lock the ring to
3700 * prevent racing with polled issue that got punted to
3703 mutex_lock(&ctx->uring_lock);
3705 ret2 = io_validate_ext_arg(flags, argp, argsz);
3706 if (likely(!ret2)) {
3707 min_complete = min(min_complete,
3709 ret2 = io_iopoll_check(ctx, min_complete);
3711 mutex_unlock(&ctx->uring_lock);
3713 const sigset_t __user *sig;
3714 struct __kernel_timespec __user *ts;
3716 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3717 if (likely(!ret2)) {
3718 min_complete = min(min_complete,
3720 ret2 = io_cqring_wait(ctx, min_complete, sig,
3729 * EBADR indicates that one or more CQE were dropped.
3730 * Once the user has been informed we can clear the bit
3731 * as they are obviously ok with those drops.
3733 if (unlikely(ret2 == -EBADR))
3734 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3739 if (!(flags & IORING_ENTER_REGISTERED_RING))
3744 static const struct file_operations io_uring_fops = {
3745 .release = io_uring_release,
3746 .mmap = io_uring_mmap,
3748 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3749 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3751 .get_unmapped_area = io_uring_mmu_get_unmapped_area,
3753 .poll = io_uring_poll,
3754 #ifdef CONFIG_PROC_FS
3755 .show_fdinfo = io_uring_show_fdinfo,
3759 bool io_is_uring_fops(struct file *file)
3761 return file->f_op == &io_uring_fops;
3764 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3765 struct io_uring_params *p)
3767 struct io_rings *rings;
3768 size_t size, sq_array_offset;
3771 /* make sure these are sane, as we already accounted them */
3772 ctx->sq_entries = p->sq_entries;
3773 ctx->cq_entries = p->cq_entries;
3775 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3776 if (size == SIZE_MAX)
3779 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3780 rings = io_mem_alloc(size);
3782 rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3785 return PTR_ERR(rings);
3788 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3789 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3790 rings->sq_ring_mask = p->sq_entries - 1;
3791 rings->cq_ring_mask = p->cq_entries - 1;
3792 rings->sq_ring_entries = p->sq_entries;
3793 rings->cq_ring_entries = p->cq_entries;
3795 if (p->flags & IORING_SETUP_SQE128)
3796 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3798 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3799 if (size == SIZE_MAX) {
3804 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3805 ptr = io_mem_alloc(size);
3807 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3811 return PTR_ERR(ptr);
3818 static int io_uring_install_fd(struct file *file)
3822 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3825 fd_install(fd, file);
3830 * Allocate an anonymous fd, this is what constitutes the application
3831 * visible backing of an io_uring instance. The application mmaps this
3832 * fd to gain access to the SQ/CQ ring details.
3834 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3836 /* Create a new inode so that the LSM can block the creation. */
3837 return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
3838 O_RDWR | O_CLOEXEC, NULL);
3841 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3842 struct io_uring_params __user *params)
3844 struct io_ring_ctx *ctx;
3845 struct io_uring_task *tctx;
3851 if (entries > IORING_MAX_ENTRIES) {
3852 if (!(p->flags & IORING_SETUP_CLAMP))
3854 entries = IORING_MAX_ENTRIES;
3857 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3858 && !(p->flags & IORING_SETUP_NO_MMAP))
3862 * Use twice as many entries for the CQ ring. It's possible for the
3863 * application to drive a higher depth than the size of the SQ ring,
3864 * since the sqes are only used at submission time. This allows for
3865 * some flexibility in overcommitting a bit. If the application has
3866 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3867 * of CQ ring entries manually.
3869 p->sq_entries = roundup_pow_of_two(entries);
3870 if (p->flags & IORING_SETUP_CQSIZE) {
3872 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3873 * to a power-of-two, if it isn't already. We do NOT impose
3874 * any cq vs sq ring sizing.
3878 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3879 if (!(p->flags & IORING_SETUP_CLAMP))
3881 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3883 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3884 if (p->cq_entries < p->sq_entries)
3887 p->cq_entries = 2 * p->sq_entries;
3890 ctx = io_ring_ctx_alloc(p);
3894 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3895 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3896 !(ctx->flags & IORING_SETUP_SQPOLL))
3897 ctx->task_complete = true;
3899 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3900 ctx->lockless_cq = true;
3903 * lazy poll_wq activation relies on ->task_complete for synchronisation
3904 * purposes, see io_activate_pollwq()
3906 if (!ctx->task_complete)
3907 ctx->poll_activated = true;
3910 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3911 * space applications don't need to do io completion events
3912 * polling again, they can rely on io_sq_thread to do polling
3913 * work, which can reduce cpu usage and uring_lock contention.
3915 if (ctx->flags & IORING_SETUP_IOPOLL &&
3916 !(ctx->flags & IORING_SETUP_SQPOLL))
3917 ctx->syscall_iopoll = 1;
3919 ctx->compat = in_compat_syscall();
3920 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3921 ctx->user = get_uid(current_user());
3924 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3925 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3928 if (ctx->flags & IORING_SETUP_SQPOLL) {
3929 /* IPI related flags don't make sense with SQPOLL */
3930 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3931 IORING_SETUP_TASKRUN_FLAG |
3932 IORING_SETUP_DEFER_TASKRUN))
3934 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3935 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3936 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3938 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
3939 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
3941 ctx->notify_method = TWA_SIGNAL;
3945 * For DEFER_TASKRUN we require the completion task to be the same as the
3946 * submission task. This implies that there is only one submitter, so enforce
3949 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
3950 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
3955 * This is just grabbed for accounting purposes. When a process exits,
3956 * the mm is exited and dropped before the files, hence we need to hang
3957 * on to this mm purely for the purposes of being able to unaccount
3958 * memory (locked/pinned vm). It's not used for anything else.
3960 mmgrab(current->mm);
3961 ctx->mm_account = current->mm;
3963 ret = io_allocate_scq_urings(ctx, p);
3967 ret = io_sq_offload_create(ctx, p);
3971 ret = io_rsrc_init(ctx);
3975 p->sq_off.head = offsetof(struct io_rings, sq.head);
3976 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3977 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3978 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3979 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3980 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3981 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3982 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3983 p->sq_off.resv1 = 0;
3984 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3985 p->sq_off.user_addr = 0;
3987 p->cq_off.head = offsetof(struct io_rings, cq.head);
3988 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3989 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3990 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3991 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3992 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3993 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3994 p->cq_off.resv1 = 0;
3995 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3996 p->cq_off.user_addr = 0;
3998 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3999 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
4000 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
4001 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
4002 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
4003 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
4004 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING;
4006 if (copy_to_user(params, p, sizeof(*p))) {
4011 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
4012 && !(ctx->flags & IORING_SETUP_R_DISABLED))
4013 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4015 file = io_uring_get_file(ctx);
4017 ret = PTR_ERR(file);
4021 ret = __io_uring_add_tctx_node(ctx);
4024 tctx = current->io_uring;
4027 * Install ring fd as the very last thing, so we don't risk someone
4028 * having closed it before we finish setup
4030 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
4031 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
4033 ret = io_uring_install_fd(file);
4037 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4040 io_ring_ctx_wait_and_kill(ctx);
4048 * Sets up an aio uring context, and returns the fd. Applications asks for a
4049 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4050 * params structure passed in.
4052 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4054 struct io_uring_params p;
4057 if (copy_from_user(&p, params, sizeof(p)))
4059 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4064 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4065 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
4066 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
4067 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
4068 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
4069 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
4070 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
4071 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
4072 IORING_SETUP_NO_SQARRAY))
4075 return io_uring_create(entries, &p, params);
4078 static inline bool io_uring_allowed(void)
4080 int disabled = READ_ONCE(sysctl_io_uring_disabled);
4081 kgid_t io_uring_group;
4086 if (disabled == 0 || capable(CAP_SYS_ADMIN))
4089 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
4090 if (!gid_valid(io_uring_group))
4093 return in_group_p(io_uring_group);
4096 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4097 struct io_uring_params __user *, params)
4099 if (!io_uring_allowed())
4102 return io_uring_setup(entries, params);
4105 static int __init io_uring_init(void)
4107 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
4108 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
4109 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
4112 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
4113 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
4114 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
4115 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
4116 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
4117 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
4118 BUILD_BUG_SQE_ELEM(1, __u8, flags);
4119 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
4120 BUILD_BUG_SQE_ELEM(4, __s32, fd);
4121 BUILD_BUG_SQE_ELEM(8, __u64, off);
4122 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
4123 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
4124 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
4125 BUILD_BUG_SQE_ELEM(16, __u64, addr);
4126 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
4127 BUILD_BUG_SQE_ELEM(24, __u32, len);
4128 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
4129 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
4130 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
4131 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
4132 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
4133 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
4134 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
4135 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
4136 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
4137 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
4138 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
4139 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
4140 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
4141 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
4142 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
4143 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
4144 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
4145 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
4146 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
4147 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
4148 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
4149 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
4150 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
4151 BUILD_BUG_SQE_ELEM(42, __u16, personality);
4152 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
4153 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
4154 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
4155 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
4156 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
4157 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
4158 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
4160 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
4161 sizeof(struct io_uring_rsrc_update));
4162 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
4163 sizeof(struct io_uring_rsrc_update2));
4165 /* ->buf_index is u16 */
4166 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
4167 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
4168 offsetof(struct io_uring_buf_ring, tail));
4170 /* should fit into one byte */
4171 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
4172 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4173 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4175 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
4177 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4179 /* top 8bits are for internal use */
4180 BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
4182 io_uring_optable_init();
4185 * Allow user copy in the per-command field, which starts after the
4186 * file in io_kiocb and until the opcode field. The openat2 handling
4187 * requires copying in user memory into the io_kiocb object in that
4188 * range, and HARDENED_USERCOPY will complain if we haven't
4189 * correctly annotated this range.
4191 req_cachep = kmem_cache_create_usercopy("io_kiocb",
4192 sizeof(struct io_kiocb), 0,
4193 SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4194 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU,
4195 offsetof(struct io_kiocb, cmd.data),
4196 sizeof_field(struct io_kiocb, cmd.data), NULL);
4197 io_buf_cachep = kmem_cache_create("io_buffer", sizeof(struct io_buffer), 0,
4198 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT,
4201 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
4203 #ifdef CONFIG_SYSCTL
4204 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
4209 __initcall(io_uring_init);