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>
64 #include <linux/anon_inodes.h>
65 #include <linux/sched/mm.h>
66 #include <linux/uaccess.h>
67 #include <linux/nospec.h>
68 #include <linux/highmem.h>
69 #include <linux/fsnotify.h>
70 #include <linux/fadvise.h>
71 #include <linux/task_work.h>
72 #include <linux/io_uring.h>
73 #include <linux/audit.h>
74 #include <linux/security.h>
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
79 #include <uapi/linux/io_uring.h>
96 #define IORING_MAX_ENTRIES 32768
97 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
102 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
103 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
105 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
106 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
108 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
109 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
112 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
115 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
117 #define IO_COMPL_BATCH 32
118 #define IO_REQ_ALLOC_BATCH 8
121 IO_CHECK_CQ_OVERFLOW_BIT,
122 IO_CHECK_CQ_DROPPED_BIT,
125 struct io_defer_entry {
126 struct list_head list;
127 struct io_kiocb *req;
131 /* requests with any of those set should undergo io_disarm_next() */
132 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
133 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
135 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
136 struct task_struct *task,
139 static void io_dismantle_req(struct io_kiocb *req);
140 static void io_clean_op(struct io_kiocb *req);
141 static void io_queue_sqe(struct io_kiocb *req);
143 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
145 static void io_eventfd_signal(struct io_ring_ctx *ctx);
147 static struct kmem_cache *req_cachep;
149 struct sock *io_uring_get_socket(struct file *file)
151 #if defined(CONFIG_UNIX)
152 if (io_is_uring_fops(file)) {
153 struct io_ring_ctx *ctx = file->private_data;
155 return ctx->ring_sock->sk;
160 EXPORT_SYMBOL(io_uring_get_socket);
162 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
164 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
165 __io_submit_flush_completions(ctx);
168 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
170 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
173 static bool io_match_linked(struct io_kiocb *head)
175 struct io_kiocb *req;
177 io_for_each_link(req, head) {
178 if (req->flags & REQ_F_INFLIGHT)
185 * As io_match_task() but protected against racing with linked timeouts.
186 * User must not hold timeout_lock.
188 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
193 if (task && head->task != task)
198 if (head->flags & REQ_F_LINK_TIMEOUT) {
199 struct io_ring_ctx *ctx = head->ctx;
201 /* protect against races with linked timeouts */
202 spin_lock_irq(&ctx->timeout_lock);
203 matched = io_match_linked(head);
204 spin_unlock_irq(&ctx->timeout_lock);
206 matched = io_match_linked(head);
211 static inline void req_fail_link_node(struct io_kiocb *req, int res)
214 io_req_set_res(req, res, 0);
217 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
219 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
222 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
224 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
226 complete(&ctx->ref_comp);
229 static __cold void io_fallback_req_func(struct work_struct *work)
231 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
233 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
234 struct io_kiocb *req, *tmp;
237 percpu_ref_get(&ctx->refs);
238 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
239 req->io_task_work.func(req, &locked);
242 io_submit_flush_completions(ctx);
243 mutex_unlock(&ctx->uring_lock);
245 percpu_ref_put(&ctx->refs);
248 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
250 unsigned hash_buckets = 1U << bits;
251 size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
253 table->hbs = kmalloc(hash_size, GFP_KERNEL);
257 table->hash_bits = bits;
258 init_hash_table(table, hash_buckets);
262 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
264 struct io_ring_ctx *ctx;
267 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
271 xa_init(&ctx->io_bl_xa);
274 * Use 5 bits less than the max cq entries, that should give us around
275 * 32 entries per hash list if totally full and uniformly spread, but
276 * don't keep too many buckets to not overconsume memory.
278 hash_bits = ilog2(p->cq_entries) - 5;
279 hash_bits = clamp(hash_bits, 1, 8);
280 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
282 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
285 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
286 if (!ctx->dummy_ubuf)
288 /* set invalid range, so io_import_fixed() fails meeting it */
289 ctx->dummy_ubuf->ubuf = -1UL;
291 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
292 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
295 ctx->flags = p->flags;
296 init_waitqueue_head(&ctx->sqo_sq_wait);
297 INIT_LIST_HEAD(&ctx->sqd_list);
298 INIT_LIST_HEAD(&ctx->cq_overflow_list);
299 INIT_LIST_HEAD(&ctx->io_buffers_cache);
300 INIT_LIST_HEAD(&ctx->apoll_cache);
301 init_completion(&ctx->ref_comp);
302 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
303 mutex_init(&ctx->uring_lock);
304 init_waitqueue_head(&ctx->cq_wait);
305 spin_lock_init(&ctx->completion_lock);
306 spin_lock_init(&ctx->timeout_lock);
307 INIT_WQ_LIST(&ctx->iopoll_list);
308 INIT_LIST_HEAD(&ctx->io_buffers_pages);
309 INIT_LIST_HEAD(&ctx->io_buffers_comp);
310 INIT_LIST_HEAD(&ctx->defer_list);
311 INIT_LIST_HEAD(&ctx->timeout_list);
312 INIT_LIST_HEAD(&ctx->ltimeout_list);
313 spin_lock_init(&ctx->rsrc_ref_lock);
314 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
315 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
316 init_llist_head(&ctx->rsrc_put_llist);
317 INIT_LIST_HEAD(&ctx->tctx_list);
318 ctx->submit_state.free_list.next = NULL;
319 INIT_WQ_LIST(&ctx->locked_free_list);
320 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
321 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
324 kfree(ctx->dummy_ubuf);
325 kfree(ctx->cancel_table.hbs);
326 kfree(ctx->cancel_table_locked.hbs);
328 xa_destroy(&ctx->io_bl_xa);
333 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
335 struct io_rings *r = ctx->rings;
337 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
341 static bool req_need_defer(struct io_kiocb *req, u32 seq)
343 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
344 struct io_ring_ctx *ctx = req->ctx;
346 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
352 static inline void io_req_track_inflight(struct io_kiocb *req)
354 if (!(req->flags & REQ_F_INFLIGHT)) {
355 req->flags |= REQ_F_INFLIGHT;
356 atomic_inc(&req->task->io_uring->inflight_tracked);
360 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
362 if (WARN_ON_ONCE(!req->link))
365 req->flags &= ~REQ_F_ARM_LTIMEOUT;
366 req->flags |= REQ_F_LINK_TIMEOUT;
368 /* linked timeouts should have two refs once prep'ed */
369 io_req_set_refcount(req);
370 __io_req_set_refcount(req->link, 2);
374 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
376 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
378 return __io_prep_linked_timeout(req);
381 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
383 io_queue_linked_timeout(__io_prep_linked_timeout(req));
386 static inline void io_arm_ltimeout(struct io_kiocb *req)
388 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
389 __io_arm_ltimeout(req);
392 static void io_prep_async_work(struct io_kiocb *req)
394 const struct io_op_def *def = &io_op_defs[req->opcode];
395 struct io_ring_ctx *ctx = req->ctx;
397 if (!(req->flags & REQ_F_CREDS)) {
398 req->flags |= REQ_F_CREDS;
399 req->creds = get_current_cred();
402 req->work.list.next = NULL;
404 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
405 if (req->flags & REQ_F_FORCE_ASYNC)
406 req->work.flags |= IO_WQ_WORK_CONCURRENT;
408 if (req->flags & REQ_F_ISREG) {
409 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
410 io_wq_hash_work(&req->work, file_inode(req->file));
411 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
412 if (def->unbound_nonreg_file)
413 req->work.flags |= IO_WQ_WORK_UNBOUND;
417 static void io_prep_async_link(struct io_kiocb *req)
419 struct io_kiocb *cur;
421 if (req->flags & REQ_F_LINK_TIMEOUT) {
422 struct io_ring_ctx *ctx = req->ctx;
424 spin_lock_irq(&ctx->timeout_lock);
425 io_for_each_link(cur, req)
426 io_prep_async_work(cur);
427 spin_unlock_irq(&ctx->timeout_lock);
429 io_for_each_link(cur, req)
430 io_prep_async_work(cur);
434 void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
436 struct io_kiocb *link = io_prep_linked_timeout(req);
437 struct io_uring_task *tctx = req->task->io_uring;
440 BUG_ON(!tctx->io_wq);
442 /* init ->work of the whole link before punting */
443 io_prep_async_link(req);
446 * Not expected to happen, but if we do have a bug where this _can_
447 * happen, catch it here and ensure the request is marked as
448 * canceled. That will make io-wq go through the usual work cancel
449 * procedure rather than attempt to run this request (or create a new
452 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
453 req->work.flags |= IO_WQ_WORK_CANCEL;
455 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
456 io_wq_enqueue(tctx->io_wq, &req->work);
458 io_queue_linked_timeout(link);
461 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
463 while (!list_empty(&ctx->defer_list)) {
464 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
465 struct io_defer_entry, list);
467 if (req_need_defer(de->req, de->seq))
469 list_del_init(&de->list);
470 io_req_task_queue(de->req);
475 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
477 if (ctx->off_timeout_used || ctx->drain_active) {
478 spin_lock(&ctx->completion_lock);
479 if (ctx->off_timeout_used)
480 io_flush_timeouts(ctx);
481 if (ctx->drain_active)
482 io_queue_deferred(ctx);
483 spin_unlock(&ctx->completion_lock);
486 io_eventfd_signal(ctx);
489 static void io_eventfd_signal(struct io_ring_ctx *ctx)
491 struct io_ev_fd *ev_fd;
495 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
498 ev_fd = rcu_dereference(ctx->io_ev_fd);
501 * Check again if ev_fd exists incase an io_eventfd_unregister call
502 * completed between the NULL check of ctx->io_ev_fd at the start of
503 * the function and rcu_read_lock.
505 if (unlikely(!ev_fd))
507 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
510 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
511 eventfd_signal(ev_fd->cq_ev_fd, 1);
517 * This should only get called when at least one event has been posted.
518 * Some applications rely on the eventfd notification count only changing
519 * IFF a new CQE has been added to the CQ ring. There's no depedency on
520 * 1:1 relationship between how many times this function is called (and
521 * hence the eventfd count) and number of CQEs posted to the CQ ring.
523 void io_cqring_ev_posted(struct io_ring_ctx *ctx)
525 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
527 __io_commit_cqring_flush(ctx);
532 /* Returns true if there are no backlogged entries after the flush */
533 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
535 bool all_flushed, posted;
536 size_t cqe_size = sizeof(struct io_uring_cqe);
538 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
541 if (ctx->flags & IORING_SETUP_CQE32)
545 spin_lock(&ctx->completion_lock);
546 while (!list_empty(&ctx->cq_overflow_list)) {
547 struct io_uring_cqe *cqe = io_get_cqe(ctx);
548 struct io_overflow_cqe *ocqe;
552 ocqe = list_first_entry(&ctx->cq_overflow_list,
553 struct io_overflow_cqe, list);
555 memcpy(cqe, &ocqe->cqe, cqe_size);
557 io_account_cq_overflow(ctx);
560 list_del(&ocqe->list);
564 all_flushed = list_empty(&ctx->cq_overflow_list);
566 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
567 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
570 io_commit_cqring(ctx);
571 spin_unlock(&ctx->completion_lock);
573 io_cqring_ev_posted(ctx);
577 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
581 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
582 /* iopoll syncs against uring_lock, not completion_lock */
583 if (ctx->flags & IORING_SETUP_IOPOLL)
584 mutex_lock(&ctx->uring_lock);
585 ret = __io_cqring_overflow_flush(ctx, false);
586 if (ctx->flags & IORING_SETUP_IOPOLL)
587 mutex_unlock(&ctx->uring_lock);
593 static void __io_put_task(struct task_struct *task, int nr)
595 struct io_uring_task *tctx = task->io_uring;
597 percpu_counter_sub(&tctx->inflight, nr);
598 if (unlikely(atomic_read(&tctx->in_idle)))
599 wake_up(&tctx->wait);
600 put_task_struct_many(task, nr);
603 /* must to be called somewhat shortly after putting a request */
604 static inline void io_put_task(struct task_struct *task, int nr)
606 if (likely(task == current))
607 task->io_uring->cached_refs += nr;
609 __io_put_task(task, nr);
612 static void io_task_refs_refill(struct io_uring_task *tctx)
614 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
616 percpu_counter_add(&tctx->inflight, refill);
617 refcount_add(refill, ¤t->usage);
618 tctx->cached_refs += refill;
621 static inline void io_get_task_refs(int nr)
623 struct io_uring_task *tctx = current->io_uring;
625 tctx->cached_refs -= nr;
626 if (unlikely(tctx->cached_refs < 0))
627 io_task_refs_refill(tctx);
630 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
632 struct io_uring_task *tctx = task->io_uring;
633 unsigned int refs = tctx->cached_refs;
636 tctx->cached_refs = 0;
637 percpu_counter_sub(&tctx->inflight, refs);
638 put_task_struct_many(task, refs);
642 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
643 s32 res, u32 cflags, u64 extra1, u64 extra2)
645 struct io_overflow_cqe *ocqe;
646 size_t ocq_size = sizeof(struct io_overflow_cqe);
647 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
650 ocq_size += sizeof(struct io_uring_cqe);
652 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
653 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
656 * If we're in ring overflow flush mode, or in task cancel mode,
657 * or cannot allocate an overflow entry, then we need to drop it
660 io_account_cq_overflow(ctx);
661 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
664 if (list_empty(&ctx->cq_overflow_list)) {
665 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
666 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
669 ocqe->cqe.user_data = user_data;
671 ocqe->cqe.flags = cflags;
673 ocqe->cqe.big_cqe[0] = extra1;
674 ocqe->cqe.big_cqe[1] = extra2;
676 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
680 bool io_req_cqe_overflow(struct io_kiocb *req)
682 if (!(req->flags & REQ_F_CQE32_INIT)) {
686 return io_cqring_event_overflow(req->ctx, req->cqe.user_data,
687 req->cqe.res, req->cqe.flags,
688 req->extra1, req->extra2);
692 * writes to the cq entry need to come after reading head; the
693 * control dependency is enough as we're using WRITE_ONCE to
696 struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
698 struct io_rings *rings = ctx->rings;
699 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
700 unsigned int free, queued, len;
703 /* userspace may cheat modifying the tail, be safe and do min */
704 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
705 free = ctx->cq_entries - queued;
706 /* we need a contiguous range, limit based on the current array offset */
707 len = min(free, ctx->cq_entries - off);
711 if (ctx->flags & IORING_SETUP_CQE32) {
716 ctx->cqe_cached = &rings->cqes[off];
717 ctx->cqe_sentinel = ctx->cqe_cached + len;
719 ctx->cached_cq_tail++;
721 if (ctx->flags & IORING_SETUP_CQE32)
723 return &rings->cqes[off];
726 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx,
727 u64 user_data, s32 res, u32 cflags)
729 struct io_uring_cqe *cqe;
732 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
735 * If we can't get a cq entry, userspace overflowed the
736 * submission (by quite a lot). Increment the overflow count in
739 cqe = io_get_cqe(ctx);
741 WRITE_ONCE(cqe->user_data, user_data);
742 WRITE_ONCE(cqe->res, res);
743 WRITE_ONCE(cqe->flags, cflags);
745 if (ctx->flags & IORING_SETUP_CQE32) {
746 WRITE_ONCE(cqe->big_cqe[0], 0);
747 WRITE_ONCE(cqe->big_cqe[1], 0);
751 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
754 bool io_post_aux_cqe(struct io_ring_ctx *ctx,
755 u64 user_data, s32 res, u32 cflags)
759 spin_lock(&ctx->completion_lock);
760 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
761 io_commit_cqring(ctx);
762 spin_unlock(&ctx->completion_lock);
764 io_cqring_ev_posted(ctx);
768 static void __io_req_complete_put(struct io_kiocb *req)
771 * If we're the last reference to this request, add to our locked
774 if (req_ref_put_and_test(req)) {
775 struct io_ring_ctx *ctx = req->ctx;
777 if (req->flags & IO_REQ_LINK_FLAGS) {
778 if (req->flags & IO_DISARM_MASK)
781 io_req_task_queue(req->link);
785 io_req_put_rsrc(req);
787 * Selected buffer deallocation in io_clean_op() assumes that
788 * we don't hold ->completion_lock. Clean them here to avoid
791 io_put_kbuf_comp(req);
792 io_dismantle_req(req);
793 io_put_task(req->task, 1);
794 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
795 ctx->locked_free_nr++;
799 void __io_req_complete_post(struct io_kiocb *req)
801 if (!(req->flags & REQ_F_CQE_SKIP))
802 __io_fill_cqe_req(req->ctx, req);
803 __io_req_complete_put(req);
806 void io_req_complete_post(struct io_kiocb *req)
808 struct io_ring_ctx *ctx = req->ctx;
810 spin_lock(&ctx->completion_lock);
811 __io_req_complete_post(req);
812 io_commit_cqring(ctx);
813 spin_unlock(&ctx->completion_lock);
814 io_cqring_ev_posted(ctx);
817 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
819 io_req_complete_post(req);
822 void io_req_complete_failed(struct io_kiocb *req, s32 res)
825 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
826 io_req_complete_post(req);
830 * Don't initialise the fields below on every allocation, but do that in
831 * advance and keep them valid across allocations.
833 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
837 req->async_data = NULL;
838 /* not necessary, but safer to zero */
842 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
843 struct io_submit_state *state)
845 spin_lock(&ctx->completion_lock);
846 wq_list_splice(&ctx->locked_free_list, &state->free_list);
847 ctx->locked_free_nr = 0;
848 spin_unlock(&ctx->completion_lock);
851 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
853 return !ctx->submit_state.free_list.next;
857 * A request might get retired back into the request caches even before opcode
858 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
859 * Because of that, io_alloc_req() should be called only under ->uring_lock
860 * and with extra caution to not get a request that is still worked on.
862 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
863 __must_hold(&ctx->uring_lock)
865 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
866 void *reqs[IO_REQ_ALLOC_BATCH];
870 * If we have more than a batch's worth of requests in our IRQ side
871 * locked cache, grab the lock and move them over to our submission
874 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
875 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
876 if (!io_req_cache_empty(ctx))
880 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
883 * Bulk alloc is all-or-nothing. If we fail to get a batch,
884 * retry single alloc to be on the safe side.
886 if (unlikely(ret <= 0)) {
887 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
893 percpu_ref_get_many(&ctx->refs, ret);
894 for (i = 0; i < ret; i++) {
895 struct io_kiocb *req = reqs[i];
897 io_preinit_req(req, ctx);
898 io_req_add_to_cache(req, ctx);
903 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
905 if (unlikely(io_req_cache_empty(ctx)))
906 return __io_alloc_req_refill(ctx);
910 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
912 struct io_wq_work_node *node;
914 node = wq_stack_extract(&ctx->submit_state.free_list);
915 return container_of(node, struct io_kiocb, comp_list);
918 static inline void io_dismantle_req(struct io_kiocb *req)
920 unsigned int flags = req->flags;
922 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
924 if (!(flags & REQ_F_FIXED_FILE))
925 io_put_file(req->file);
928 __cold void io_free_req(struct io_kiocb *req)
930 struct io_ring_ctx *ctx = req->ctx;
932 io_req_put_rsrc(req);
933 io_dismantle_req(req);
934 io_put_task(req->task, 1);
936 spin_lock(&ctx->completion_lock);
937 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
938 ctx->locked_free_nr++;
939 spin_unlock(&ctx->completion_lock);
942 static void __io_req_find_next_prep(struct io_kiocb *req)
944 struct io_ring_ctx *ctx = req->ctx;
947 spin_lock(&ctx->completion_lock);
948 posted = io_disarm_next(req);
949 io_commit_cqring(ctx);
950 spin_unlock(&ctx->completion_lock);
952 io_cqring_ev_posted(ctx);
955 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
957 struct io_kiocb *nxt;
960 * If LINK is set, we have dependent requests in this chain. If we
961 * didn't fail this request, queue the first one up, moving any other
962 * dependencies to the next request. In case of failure, fail the rest
965 if (unlikely(req->flags & IO_DISARM_MASK))
966 __io_req_find_next_prep(req);
972 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
976 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
977 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
979 io_submit_flush_completions(ctx);
980 mutex_unlock(&ctx->uring_lock);
983 percpu_ref_put(&ctx->refs);
986 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
988 io_commit_cqring(ctx);
989 spin_unlock(&ctx->completion_lock);
990 io_cqring_ev_posted(ctx);
993 static void handle_prev_tw_list(struct io_wq_work_node *node,
994 struct io_ring_ctx **ctx, bool *uring_locked)
996 if (*ctx && !*uring_locked)
997 spin_lock(&(*ctx)->completion_lock);
1000 struct io_wq_work_node *next = node->next;
1001 struct io_kiocb *req = container_of(node, struct io_kiocb,
1004 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1006 if (req->ctx != *ctx) {
1007 if (unlikely(!*uring_locked && *ctx))
1008 ctx_commit_and_unlock(*ctx);
1010 ctx_flush_and_put(*ctx, uring_locked);
1012 /* if not contended, grab and improve batching */
1013 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
1014 percpu_ref_get(&(*ctx)->refs);
1015 if (unlikely(!*uring_locked))
1016 spin_lock(&(*ctx)->completion_lock);
1018 if (likely(*uring_locked)) {
1019 req->io_task_work.func(req, uring_locked);
1021 req->cqe.flags = io_put_kbuf_comp(req);
1022 __io_req_complete_post(req);
1027 if (unlikely(!*uring_locked))
1028 ctx_commit_and_unlock(*ctx);
1031 static void handle_tw_list(struct io_wq_work_node *node,
1032 struct io_ring_ctx **ctx, bool *locked)
1035 struct io_wq_work_node *next = node->next;
1036 struct io_kiocb *req = container_of(node, struct io_kiocb,
1039 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1041 if (req->ctx != *ctx) {
1042 ctx_flush_and_put(*ctx, locked);
1044 /* if not contended, grab and improve batching */
1045 *locked = mutex_trylock(&(*ctx)->uring_lock);
1046 percpu_ref_get(&(*ctx)->refs);
1048 req->io_task_work.func(req, locked);
1053 void tctx_task_work(struct callback_head *cb)
1055 bool uring_locked = false;
1056 struct io_ring_ctx *ctx = NULL;
1057 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1061 struct io_wq_work_node *node1, *node2;
1063 spin_lock_irq(&tctx->task_lock);
1064 node1 = tctx->prio_task_list.first;
1065 node2 = tctx->task_list.first;
1066 INIT_WQ_LIST(&tctx->task_list);
1067 INIT_WQ_LIST(&tctx->prio_task_list);
1068 if (!node2 && !node1)
1069 tctx->task_running = false;
1070 spin_unlock_irq(&tctx->task_lock);
1071 if (!node2 && !node1)
1075 handle_prev_tw_list(node1, &ctx, &uring_locked);
1077 handle_tw_list(node2, &ctx, &uring_locked);
1080 if (data_race(!tctx->task_list.first) &&
1081 data_race(!tctx->prio_task_list.first) && uring_locked)
1082 io_submit_flush_completions(ctx);
1085 ctx_flush_and_put(ctx, &uring_locked);
1087 /* relaxed read is enough as only the task itself sets ->in_idle */
1088 if (unlikely(atomic_read(&tctx->in_idle)))
1089 io_uring_drop_tctx_refs(current);
1092 static void __io_req_task_work_add(struct io_kiocb *req,
1093 struct io_uring_task *tctx,
1094 struct io_wq_work_list *list)
1096 struct io_ring_ctx *ctx = req->ctx;
1097 struct io_wq_work_node *node;
1098 unsigned long flags;
1101 spin_lock_irqsave(&tctx->task_lock, flags);
1102 wq_list_add_tail(&req->io_task_work.node, list);
1103 running = tctx->task_running;
1105 tctx->task_running = true;
1106 spin_unlock_irqrestore(&tctx->task_lock, flags);
1108 /* task_work already pending, we're done */
1112 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1113 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1115 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1118 spin_lock_irqsave(&tctx->task_lock, flags);
1119 tctx->task_running = false;
1120 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
1121 spin_unlock_irqrestore(&tctx->task_lock, flags);
1124 req = container_of(node, struct io_kiocb, io_task_work.node);
1126 if (llist_add(&req->io_task_work.fallback_node,
1127 &req->ctx->fallback_llist))
1128 schedule_delayed_work(&req->ctx->fallback_work, 1);
1132 void io_req_task_work_add(struct io_kiocb *req)
1134 struct io_uring_task *tctx = req->task->io_uring;
1136 __io_req_task_work_add(req, tctx, &tctx->task_list);
1139 void io_req_task_prio_work_add(struct io_kiocb *req)
1141 struct io_uring_task *tctx = req->task->io_uring;
1143 if (req->ctx->flags & IORING_SETUP_SQPOLL)
1144 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
1146 __io_req_task_work_add(req, tctx, &tctx->task_list);
1149 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
1151 io_req_complete_post(req);
1154 void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
1156 io_req_set_res(req, res, cflags);
1157 req->io_task_work.func = io_req_tw_post;
1158 io_req_task_work_add(req);
1161 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
1163 /* not needed for normal modes, but SQPOLL depends on it */
1164 io_tw_lock(req->ctx, locked);
1165 io_req_complete_failed(req, req->cqe.res);
1168 void io_req_task_submit(struct io_kiocb *req, bool *locked)
1170 io_tw_lock(req->ctx, locked);
1171 /* req->task == current here, checking PF_EXITING is safe */
1172 if (likely(!(req->task->flags & PF_EXITING)))
1175 io_req_complete_failed(req, -EFAULT);
1178 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1180 io_req_set_res(req, ret, 0);
1181 req->io_task_work.func = io_req_task_cancel;
1182 io_req_task_work_add(req);
1185 void io_req_task_queue(struct io_kiocb *req)
1187 req->io_task_work.func = io_req_task_submit;
1188 io_req_task_work_add(req);
1191 void io_queue_next(struct io_kiocb *req)
1193 struct io_kiocb *nxt = io_req_find_next(req);
1196 io_req_task_queue(nxt);
1199 void io_free_batch_list(struct io_ring_ctx *ctx, struct io_wq_work_node *node)
1200 __must_hold(&ctx->uring_lock)
1202 struct task_struct *task = NULL;
1206 struct io_kiocb *req = container_of(node, struct io_kiocb,
1209 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1210 if (req->flags & REQ_F_REFCOUNT) {
1211 node = req->comp_list.next;
1212 if (!req_ref_put_and_test(req))
1215 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1216 struct async_poll *apoll = req->apoll;
1218 if (apoll->double_poll)
1219 kfree(apoll->double_poll);
1220 list_add(&apoll->poll.wait.entry,
1222 req->flags &= ~REQ_F_POLLED;
1224 if (req->flags & IO_REQ_LINK_FLAGS)
1226 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1229 if (!(req->flags & REQ_F_FIXED_FILE))
1230 io_put_file(req->file);
1232 io_req_put_rsrc_locked(req, ctx);
1234 if (req->task != task) {
1236 io_put_task(task, task_refs);
1241 node = req->comp_list.next;
1242 io_req_add_to_cache(req, ctx);
1246 io_put_task(task, task_refs);
1249 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1250 __must_hold(&ctx->uring_lock)
1252 struct io_wq_work_node *node, *prev;
1253 struct io_submit_state *state = &ctx->submit_state;
1255 if (state->flush_cqes) {
1256 spin_lock(&ctx->completion_lock);
1257 wq_list_for_each(node, prev, &state->compl_reqs) {
1258 struct io_kiocb *req = container_of(node, struct io_kiocb,
1261 if (!(req->flags & REQ_F_CQE_SKIP))
1262 __io_fill_cqe_req(ctx, req);
1265 io_commit_cqring(ctx);
1266 spin_unlock(&ctx->completion_lock);
1267 io_cqring_ev_posted(ctx);
1268 state->flush_cqes = false;
1271 io_free_batch_list(ctx, state->compl_reqs.first);
1272 INIT_WQ_LIST(&state->compl_reqs);
1276 * Drop reference to request, return next in chain (if there is one) if this
1277 * was the last reference to this request.
1279 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1281 struct io_kiocb *nxt = NULL;
1283 if (req_ref_put_and_test(req)) {
1284 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
1285 nxt = io_req_find_next(req);
1291 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1293 /* See comment at the top of this file */
1295 return __io_cqring_events(ctx);
1299 * We can't just wait for polled events to come to us, we have to actively
1300 * find and complete them.
1302 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1304 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1307 mutex_lock(&ctx->uring_lock);
1308 while (!wq_list_empty(&ctx->iopoll_list)) {
1309 /* let it sleep and repeat later if can't complete a request */
1310 if (io_do_iopoll(ctx, true) == 0)
1313 * Ensure we allow local-to-the-cpu processing to take place,
1314 * in this case we need to ensure that we reap all events.
1315 * Also let task_work, etc. to progress by releasing the mutex
1317 if (need_resched()) {
1318 mutex_unlock(&ctx->uring_lock);
1320 mutex_lock(&ctx->uring_lock);
1323 mutex_unlock(&ctx->uring_lock);
1326 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1328 unsigned int nr_events = 0;
1330 unsigned long check_cq;
1332 check_cq = READ_ONCE(ctx->check_cq);
1333 if (unlikely(check_cq)) {
1334 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1335 __io_cqring_overflow_flush(ctx, false);
1337 * Similarly do not spin if we have not informed the user of any
1340 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1344 * Don't enter poll loop if we already have events pending.
1345 * If we do, we can potentially be spinning for commands that
1346 * already triggered a CQE (eg in error).
1348 if (io_cqring_events(ctx))
1353 * If a submit got punted to a workqueue, we can have the
1354 * application entering polling for a command before it gets
1355 * issued. That app will hold the uring_lock for the duration
1356 * of the poll right here, so we need to take a breather every
1357 * now and then to ensure that the issue has a chance to add
1358 * the poll to the issued list. Otherwise we can spin here
1359 * forever, while the workqueue is stuck trying to acquire the
1362 if (wq_list_empty(&ctx->iopoll_list)) {
1363 u32 tail = ctx->cached_cq_tail;
1365 mutex_unlock(&ctx->uring_lock);
1367 mutex_lock(&ctx->uring_lock);
1369 /* some requests don't go through iopoll_list */
1370 if (tail != ctx->cached_cq_tail ||
1371 wq_list_empty(&ctx->iopoll_list))
1374 ret = io_do_iopoll(ctx, !min);
1379 } while (nr_events < min && !need_resched());
1384 void io_req_task_complete(struct io_kiocb *req, bool *locked)
1386 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
1387 unsigned issue_flags = *locked ? 0 : IO_URING_F_UNLOCKED;
1389 req->cqe.flags |= io_put_kbuf(req, issue_flags);
1393 io_req_add_compl_list(req);
1395 io_req_complete_post(req);
1399 * After the iocb has been issued, it's safe to be found on the poll list.
1400 * Adding the kiocb to the list AFTER submission ensures that we don't
1401 * find it from a io_do_iopoll() thread before the issuer is done
1402 * accessing the kiocb cookie.
1404 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1406 struct io_ring_ctx *ctx = req->ctx;
1407 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1409 /* workqueue context doesn't hold uring_lock, grab it now */
1410 if (unlikely(needs_lock))
1411 mutex_lock(&ctx->uring_lock);
1414 * Track whether we have multiple files in our lists. This will impact
1415 * how we do polling eventually, not spinning if we're on potentially
1416 * different devices.
1418 if (wq_list_empty(&ctx->iopoll_list)) {
1419 ctx->poll_multi_queue = false;
1420 } else if (!ctx->poll_multi_queue) {
1421 struct io_kiocb *list_req;
1423 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1425 if (list_req->file != req->file)
1426 ctx->poll_multi_queue = true;
1430 * For fast devices, IO may have already completed. If it has, add
1431 * it to the front so we find it first.
1433 if (READ_ONCE(req->iopoll_completed))
1434 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1436 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1438 if (unlikely(needs_lock)) {
1440 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1441 * in sq thread task context or in io worker task context. If
1442 * current task context is sq thread, we don't need to check
1443 * whether should wake up sq thread.
1445 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1446 wq_has_sleeper(&ctx->sq_data->wait))
1447 wake_up(&ctx->sq_data->wait);
1449 mutex_unlock(&ctx->uring_lock);
1453 static bool io_bdev_nowait(struct block_device *bdev)
1455 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
1459 * If we tracked the file through the SCM inflight mechanism, we could support
1460 * any file. For now, just ensure that anything potentially problematic is done
1463 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
1465 if (S_ISBLK(mode)) {
1466 if (IS_ENABLED(CONFIG_BLOCK) &&
1467 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
1473 if (S_ISREG(mode)) {
1474 if (IS_ENABLED(CONFIG_BLOCK) &&
1475 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
1476 !io_is_uring_fops(file))
1481 /* any ->read/write should understand O_NONBLOCK */
1482 if (file->f_flags & O_NONBLOCK)
1484 return file->f_mode & FMODE_NOWAIT;
1488 * If we tracked the file through the SCM inflight mechanism, we could support
1489 * any file. For now, just ensure that anything potentially problematic is done
1492 unsigned int io_file_get_flags(struct file *file)
1494 umode_t mode = file_inode(file)->i_mode;
1495 unsigned int res = 0;
1499 if (__io_file_supports_nowait(file, mode))
1501 if (io_file_need_scm(file))
1506 bool io_alloc_async_data(struct io_kiocb *req)
1508 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
1509 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
1510 if (req->async_data) {
1511 req->flags |= REQ_F_ASYNC_DATA;
1517 int io_req_prep_async(struct io_kiocb *req)
1519 const struct io_op_def *def = &io_op_defs[req->opcode];
1521 /* assign early for deferred execution for non-fixed file */
1522 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
1523 req->file = io_file_get_normal(req, req->cqe.fd);
1524 if (!def->prep_async)
1526 if (WARN_ON_ONCE(req_has_async_data(req)))
1528 if (io_alloc_async_data(req))
1531 return def->prep_async(req);
1534 static u32 io_get_sequence(struct io_kiocb *req)
1536 u32 seq = req->ctx->cached_sq_head;
1537 struct io_kiocb *cur;
1539 /* need original cached_sq_head, but it was increased for each req */
1540 io_for_each_link(cur, req)
1545 static __cold void io_drain_req(struct io_kiocb *req)
1547 struct io_ring_ctx *ctx = req->ctx;
1548 struct io_defer_entry *de;
1550 u32 seq = io_get_sequence(req);
1552 /* Still need defer if there is pending req in defer list. */
1553 spin_lock(&ctx->completion_lock);
1554 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1555 spin_unlock(&ctx->completion_lock);
1557 ctx->drain_active = false;
1558 io_req_task_queue(req);
1561 spin_unlock(&ctx->completion_lock);
1563 ret = io_req_prep_async(req);
1566 io_req_complete_failed(req, ret);
1569 io_prep_async_link(req);
1570 de = kmalloc(sizeof(*de), GFP_KERNEL);
1576 spin_lock(&ctx->completion_lock);
1577 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1578 spin_unlock(&ctx->completion_lock);
1583 trace_io_uring_defer(req);
1586 list_add_tail(&de->list, &ctx->defer_list);
1587 spin_unlock(&ctx->completion_lock);
1590 static void io_clean_op(struct io_kiocb *req)
1592 if (req->flags & REQ_F_BUFFER_SELECTED) {
1593 spin_lock(&req->ctx->completion_lock);
1594 io_put_kbuf_comp(req);
1595 spin_unlock(&req->ctx->completion_lock);
1598 if (req->flags & REQ_F_NEED_CLEANUP) {
1599 const struct io_op_def *def = &io_op_defs[req->opcode];
1604 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1605 kfree(req->apoll->double_poll);
1609 if (req->flags & REQ_F_INFLIGHT) {
1610 struct io_uring_task *tctx = req->task->io_uring;
1612 atomic_dec(&tctx->inflight_tracked);
1614 if (req->flags & REQ_F_CREDS)
1615 put_cred(req->creds);
1616 if (req->flags & REQ_F_ASYNC_DATA) {
1617 kfree(req->async_data);
1618 req->async_data = NULL;
1620 req->flags &= ~IO_REQ_CLEAN_FLAGS;
1623 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
1625 if (req->file || !io_op_defs[req->opcode].needs_file)
1628 if (req->flags & REQ_F_FIXED_FILE)
1629 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1631 req->file = io_file_get_normal(req, req->cqe.fd);
1636 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1638 const struct io_op_def *def = &io_op_defs[req->opcode];
1639 const struct cred *creds = NULL;
1642 if (unlikely(!io_assign_file(req, issue_flags)))
1645 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1646 creds = override_creds(req->creds);
1648 if (!def->audit_skip)
1649 audit_uring_entry(req->opcode);
1651 ret = def->issue(req, issue_flags);
1653 if (!def->audit_skip)
1654 audit_uring_exit(!ret, ret);
1657 revert_creds(creds);
1659 if (ret == IOU_OK) {
1660 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1661 io_req_add_compl_list(req);
1663 io_req_complete_post(req);
1664 } else if (ret != IOU_ISSUE_SKIP_COMPLETE)
1667 /* If the op doesn't have a file, we're not polling for it */
1668 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
1669 io_iopoll_req_issued(req, issue_flags);
1674 int io_poll_issue(struct io_kiocb *req, bool *locked)
1676 io_tw_lock(req->ctx, locked);
1677 if (unlikely(req->task->flags & PF_EXITING))
1679 return io_issue_sqe(req, IO_URING_F_NONBLOCK);
1682 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1684 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1686 req = io_put_req_find_next(req);
1687 return req ? &req->work : NULL;
1690 void io_wq_submit_work(struct io_wq_work *work)
1692 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1693 const struct io_op_def *def = &io_op_defs[req->opcode];
1694 unsigned int issue_flags = IO_URING_F_UNLOCKED;
1695 bool needs_poll = false;
1696 int ret = 0, err = -ECANCELED;
1698 /* one will be dropped by ->io_free_work() after returning to io-wq */
1699 if (!(req->flags & REQ_F_REFCOUNT))
1700 __io_req_set_refcount(req, 2);
1704 io_arm_ltimeout(req);
1706 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1707 if (work->flags & IO_WQ_WORK_CANCEL) {
1709 io_req_task_queue_fail(req, err);
1712 if (!io_assign_file(req, issue_flags)) {
1714 work->flags |= IO_WQ_WORK_CANCEL;
1718 if (req->flags & REQ_F_FORCE_ASYNC) {
1719 bool opcode_poll = def->pollin || def->pollout;
1721 if (opcode_poll && file_can_poll(req->file)) {
1723 issue_flags |= IO_URING_F_NONBLOCK;
1728 ret = io_issue_sqe(req, issue_flags);
1732 * We can get EAGAIN for iopolled IO even though we're
1733 * forcing a sync submission from here, since we can't
1734 * wait for request slots on the block side.
1737 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1743 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1745 /* aborted or ready, in either case retry blocking */
1747 issue_flags &= ~IO_URING_F_NONBLOCK;
1750 /* avoid locking problems by failing it from a clean context */
1752 io_req_task_queue_fail(req, ret);
1755 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1756 unsigned int issue_flags)
1758 struct io_ring_ctx *ctx = req->ctx;
1759 struct file *file = NULL;
1760 unsigned long file_ptr;
1762 io_ring_submit_lock(ctx, issue_flags);
1764 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
1766 fd = array_index_nospec(fd, ctx->nr_user_files);
1767 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
1768 file = (struct file *) (file_ptr & FFS_MASK);
1769 file_ptr &= ~FFS_MASK;
1770 /* mask in overlapping REQ_F and FFS bits */
1771 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
1772 io_req_set_rsrc_node(req, ctx, 0);
1773 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
1775 io_ring_submit_unlock(ctx, issue_flags);
1779 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1781 struct file *file = fget(fd);
1783 trace_io_uring_file_get(req, fd);
1785 /* we don't allow fixed io_uring files */
1786 if (file && io_is_uring_fops(file))
1787 io_req_track_inflight(req);
1791 static void io_queue_async(struct io_kiocb *req, int ret)
1792 __must_hold(&req->ctx->uring_lock)
1794 struct io_kiocb *linked_timeout;
1796 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1797 io_req_complete_failed(req, ret);
1801 linked_timeout = io_prep_linked_timeout(req);
1803 switch (io_arm_poll_handler(req, 0)) {
1804 case IO_APOLL_READY:
1805 io_req_task_queue(req);
1807 case IO_APOLL_ABORTED:
1809 * Queued up for async execution, worker will release
1810 * submit reference when the iocb is actually submitted.
1812 io_kbuf_recycle(req, 0);
1813 io_queue_iowq(req, NULL);
1820 io_queue_linked_timeout(linked_timeout);
1823 static inline void io_queue_sqe(struct io_kiocb *req)
1824 __must_hold(&req->ctx->uring_lock)
1828 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
1831 * We async punt it if the file wasn't marked NOWAIT, or if the file
1832 * doesn't support non-blocking read/write attempts
1835 io_arm_ltimeout(req);
1837 io_queue_async(req, ret);
1840 static void io_queue_sqe_fallback(struct io_kiocb *req)
1841 __must_hold(&req->ctx->uring_lock)
1843 if (unlikely(req->flags & REQ_F_FAIL)) {
1845 * We don't submit, fail them all, for that replace hardlinks
1846 * with normal links. Extra REQ_F_LINK is tolerated.
1848 req->flags &= ~REQ_F_HARDLINK;
1849 req->flags |= REQ_F_LINK;
1850 io_req_complete_failed(req, req->cqe.res);
1851 } else if (unlikely(req->ctx->drain_active)) {
1854 int ret = io_req_prep_async(req);
1857 io_req_complete_failed(req, ret);
1859 io_queue_iowq(req, NULL);
1864 * Check SQE restrictions (opcode and flags).
1866 * Returns 'true' if SQE is allowed, 'false' otherwise.
1868 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
1869 struct io_kiocb *req,
1870 unsigned int sqe_flags)
1872 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
1875 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
1876 ctx->restrictions.sqe_flags_required)
1879 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
1880 ctx->restrictions.sqe_flags_required))
1886 static void io_init_req_drain(struct io_kiocb *req)
1888 struct io_ring_ctx *ctx = req->ctx;
1889 struct io_kiocb *head = ctx->submit_state.link.head;
1891 ctx->drain_active = true;
1894 * If we need to drain a request in the middle of a link, drain
1895 * the head request and the next request/link after the current
1896 * link. Considering sequential execution of links,
1897 * REQ_F_IO_DRAIN will be maintained for every request of our
1900 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1901 ctx->drain_next = true;
1905 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
1906 const struct io_uring_sqe *sqe)
1907 __must_hold(&ctx->uring_lock)
1909 const struct io_op_def *def;
1910 unsigned int sqe_flags;
1914 /* req is partially pre-initialised, see io_preinit_req() */
1915 req->opcode = opcode = READ_ONCE(sqe->opcode);
1916 /* same numerical values with corresponding REQ_F_*, safe to copy */
1917 req->flags = sqe_flags = READ_ONCE(sqe->flags);
1918 req->cqe.user_data = READ_ONCE(sqe->user_data);
1920 req->rsrc_node = NULL;
1921 req->task = current;
1923 if (unlikely(opcode >= IORING_OP_LAST)) {
1927 def = &io_op_defs[opcode];
1928 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
1929 /* enforce forwards compatibility on users */
1930 if (sqe_flags & ~SQE_VALID_FLAGS)
1932 if (sqe_flags & IOSQE_BUFFER_SELECT) {
1933 if (!def->buffer_select)
1935 req->buf_index = READ_ONCE(sqe->buf_group);
1937 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
1938 ctx->drain_disabled = true;
1939 if (sqe_flags & IOSQE_IO_DRAIN) {
1940 if (ctx->drain_disabled)
1942 io_init_req_drain(req);
1945 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
1946 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
1948 /* knock it to the slow queue path, will be drained there */
1949 if (ctx->drain_active)
1950 req->flags |= REQ_F_FORCE_ASYNC;
1951 /* if there is no link, we're at "next" request and need to drain */
1952 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
1953 ctx->drain_next = false;
1954 ctx->drain_active = true;
1955 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1959 if (!def->ioprio && sqe->ioprio)
1961 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
1964 if (def->needs_file) {
1965 struct io_submit_state *state = &ctx->submit_state;
1967 req->cqe.fd = READ_ONCE(sqe->fd);
1970 * Plug now if we have more than 2 IO left after this, and the
1971 * target is potentially a read/write to block based storage.
1973 if (state->need_plug && def->plug) {
1974 state->plug_started = true;
1975 state->need_plug = false;
1976 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
1980 personality = READ_ONCE(sqe->personality);
1984 req->creds = xa_load(&ctx->personalities, personality);
1987 get_cred(req->creds);
1988 ret = security_uring_override_creds(req->creds);
1990 put_cred(req->creds);
1993 req->flags |= REQ_F_CREDS;
1996 return def->prep(req, sqe);
1999 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2000 struct io_kiocb *req, int ret)
2002 struct io_ring_ctx *ctx = req->ctx;
2003 struct io_submit_link *link = &ctx->submit_state.link;
2004 struct io_kiocb *head = link->head;
2006 trace_io_uring_req_failed(sqe, req, ret);
2009 * Avoid breaking links in the middle as it renders links with SQPOLL
2010 * unusable. Instead of failing eagerly, continue assembling the link if
2011 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2012 * should find the flag and handle the rest.
2014 req_fail_link_node(req, ret);
2015 if (head && !(head->flags & REQ_F_FAIL))
2016 req_fail_link_node(head, -ECANCELED);
2018 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2020 link->last->link = req;
2024 io_queue_sqe_fallback(req);
2029 link->last->link = req;
2036 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2037 const struct io_uring_sqe *sqe)
2038 __must_hold(&ctx->uring_lock)
2040 struct io_submit_link *link = &ctx->submit_state.link;
2043 ret = io_init_req(ctx, req, sqe);
2045 return io_submit_fail_init(sqe, req, ret);
2047 /* don't need @sqe from now on */
2048 trace_io_uring_submit_sqe(req, true);
2051 * If we already have a head request, queue this one for async
2052 * submittal once the head completes. If we don't have a head but
2053 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2054 * submitted sync once the chain is complete. If none of those
2055 * conditions are true (normal request), then just queue it.
2057 if (unlikely(link->head)) {
2058 ret = io_req_prep_async(req);
2060 return io_submit_fail_init(sqe, req, ret);
2062 trace_io_uring_link(req, link->head);
2063 link->last->link = req;
2066 if (req->flags & IO_REQ_LINK_FLAGS)
2068 /* last request of the link, flush it */
2071 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2074 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2075 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2076 if (req->flags & IO_REQ_LINK_FLAGS) {
2081 io_queue_sqe_fallback(req);
2091 * Batched submission is done, ensure local IO is flushed out.
2093 static void io_submit_state_end(struct io_ring_ctx *ctx)
2095 struct io_submit_state *state = &ctx->submit_state;
2097 if (unlikely(state->link.head))
2098 io_queue_sqe_fallback(state->link.head);
2099 /* flush only after queuing links as they can generate completions */
2100 io_submit_flush_completions(ctx);
2101 if (state->plug_started)
2102 blk_finish_plug(&state->plug);
2106 * Start submission side cache.
2108 static void io_submit_state_start(struct io_submit_state *state,
2109 unsigned int max_ios)
2111 state->plug_started = false;
2112 state->need_plug = max_ios > 2;
2113 state->submit_nr = max_ios;
2114 /* set only head, no need to init link_last in advance */
2115 state->link.head = NULL;
2118 static void io_commit_sqring(struct io_ring_ctx *ctx)
2120 struct io_rings *rings = ctx->rings;
2123 * Ensure any loads from the SQEs are done at this point,
2124 * since once we write the new head, the application could
2125 * write new data to them.
2127 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2131 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2132 * that is mapped by userspace. This means that care needs to be taken to
2133 * ensure that reads are stable, as we cannot rely on userspace always
2134 * being a good citizen. If members of the sqe are validated and then later
2135 * used, it's important that those reads are done through READ_ONCE() to
2136 * prevent a re-load down the line.
2138 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
2140 unsigned head, mask = ctx->sq_entries - 1;
2141 unsigned sq_idx = ctx->cached_sq_head++ & mask;
2144 * The cached sq head (or cq tail) serves two purposes:
2146 * 1) allows us to batch the cost of updating the user visible
2148 * 2) allows the kernel side to track the head on its own, even
2149 * though the application is the one updating it.
2151 head = READ_ONCE(ctx->sq_array[sq_idx]);
2152 if (likely(head < ctx->sq_entries)) {
2153 /* double index for 128-byte SQEs, twice as long */
2154 if (ctx->flags & IORING_SETUP_SQE128)
2156 return &ctx->sq_sqes[head];
2159 /* drop invalid entries */
2161 WRITE_ONCE(ctx->rings->sq_dropped,
2162 READ_ONCE(ctx->rings->sq_dropped) + 1);
2166 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2167 __must_hold(&ctx->uring_lock)
2169 unsigned int entries = io_sqring_entries(ctx);
2173 if (unlikely(!entries))
2175 /* make sure SQ entry isn't read before tail */
2176 ret = left = min3(nr, ctx->sq_entries, entries);
2177 io_get_task_refs(left);
2178 io_submit_state_start(&ctx->submit_state, left);
2181 const struct io_uring_sqe *sqe;
2182 struct io_kiocb *req;
2184 if (unlikely(!io_alloc_req_refill(ctx)))
2186 req = io_alloc_req(ctx);
2187 sqe = io_get_sqe(ctx);
2188 if (unlikely(!sqe)) {
2189 io_req_add_to_cache(req, ctx);
2194 * Continue submitting even for sqe failure if the
2195 * ring was setup with IORING_SETUP_SUBMIT_ALL
2197 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2198 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2204 if (unlikely(left)) {
2206 /* try again if it submitted nothing and can't allocate a req */
2207 if (!ret && io_req_cache_empty(ctx))
2209 current->io_uring->cached_refs += left;
2212 io_submit_state_end(ctx);
2213 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2214 io_commit_sqring(ctx);
2218 struct io_wait_queue {
2219 struct wait_queue_entry wq;
2220 struct io_ring_ctx *ctx;
2222 unsigned nr_timeouts;
2225 static inline bool io_should_wake(struct io_wait_queue *iowq)
2227 struct io_ring_ctx *ctx = iowq->ctx;
2228 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
2231 * Wake up if we have enough events, or if a timeout occurred since we
2232 * started waiting. For timeouts, we always want to return to userspace,
2233 * regardless of event count.
2235 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2238 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2239 int wake_flags, void *key)
2241 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
2245 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2246 * the task, and the next invocation will do it.
2248 if (io_should_wake(iowq) ||
2249 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
2250 return autoremove_wake_function(curr, mode, wake_flags, key);
2254 int io_run_task_work_sig(void)
2256 if (io_run_task_work())
2258 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
2259 return -ERESTARTSYS;
2260 if (task_sigpending(current))
2265 /* when returns >0, the caller should retry */
2266 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2267 struct io_wait_queue *iowq,
2271 unsigned long check_cq;
2273 /* make sure we run task_work before checking for signals */
2274 ret = io_run_task_work_sig();
2275 if (ret || io_should_wake(iowq))
2278 check_cq = READ_ONCE(ctx->check_cq);
2279 if (unlikely(check_cq)) {
2280 /* let the caller flush overflows, retry */
2281 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2283 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
2286 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
2292 * Wait until events become available, if we don't already have some. The
2293 * application must reap them itself, as they reside on the shared cq ring.
2295 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2296 const sigset_t __user *sig, size_t sigsz,
2297 struct __kernel_timespec __user *uts)
2299 struct io_wait_queue iowq;
2300 struct io_rings *rings = ctx->rings;
2301 ktime_t timeout = KTIME_MAX;
2305 io_cqring_overflow_flush(ctx);
2306 if (io_cqring_events(ctx) >= min_events)
2308 if (!io_run_task_work())
2313 #ifdef CONFIG_COMPAT
2314 if (in_compat_syscall())
2315 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2319 ret = set_user_sigmask(sig, sigsz);
2326 struct timespec64 ts;
2328 if (get_timespec64(&ts, uts))
2330 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2333 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2334 iowq.wq.private = current;
2335 INIT_LIST_HEAD(&iowq.wq.entry);
2337 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2338 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2340 trace_io_uring_cqring_wait(ctx, min_events);
2342 /* if we can't even flush overflow, don't wait for more */
2343 if (!io_cqring_overflow_flush(ctx)) {
2347 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2348 TASK_INTERRUPTIBLE);
2349 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
2353 finish_wait(&ctx->cq_wait, &iowq.wq);
2354 restore_saved_sigmask_unless(ret == -EINTR);
2356 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2359 static void io_mem_free(void *ptr)
2366 page = virt_to_head_page(ptr);
2367 if (put_page_testzero(page))
2368 free_compound_page(page);
2371 static void *io_mem_alloc(size_t size)
2373 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2375 return (void *) __get_free_pages(gfp, get_order(size));
2378 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2379 unsigned int cq_entries, size_t *sq_offset)
2381 struct io_rings *rings;
2382 size_t off, sq_array_size;
2384 off = struct_size(rings, cqes, cq_entries);
2385 if (off == SIZE_MAX)
2387 if (ctx->flags & IORING_SETUP_CQE32) {
2388 if (check_shl_overflow(off, 1, &off))
2393 off = ALIGN(off, SMP_CACHE_BYTES);
2401 sq_array_size = array_size(sizeof(u32), sq_entries);
2402 if (sq_array_size == SIZE_MAX)
2405 if (check_add_overflow(off, sq_array_size, &off))
2411 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
2412 unsigned int eventfd_async)
2414 struct io_ev_fd *ev_fd;
2415 __s32 __user *fds = arg;
2418 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2419 lockdep_is_held(&ctx->uring_lock));
2423 if (copy_from_user(&fd, fds, sizeof(*fds)))
2426 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
2430 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
2431 if (IS_ERR(ev_fd->cq_ev_fd)) {
2432 int ret = PTR_ERR(ev_fd->cq_ev_fd);
2436 ev_fd->eventfd_async = eventfd_async;
2437 ctx->has_evfd = true;
2438 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
2442 static void io_eventfd_put(struct rcu_head *rcu)
2444 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
2446 eventfd_ctx_put(ev_fd->cq_ev_fd);
2450 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2452 struct io_ev_fd *ev_fd;
2454 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2455 lockdep_is_held(&ctx->uring_lock));
2457 ctx->has_evfd = false;
2458 rcu_assign_pointer(ctx->io_ev_fd, NULL);
2459 call_rcu(&ev_fd->rcu, io_eventfd_put);
2466 static void io_req_caches_free(struct io_ring_ctx *ctx)
2468 struct io_submit_state *state = &ctx->submit_state;
2471 mutex_lock(&ctx->uring_lock);
2472 io_flush_cached_locked_reqs(ctx, state);
2474 while (!io_req_cache_empty(ctx)) {
2475 struct io_wq_work_node *node;
2476 struct io_kiocb *req;
2478 node = wq_stack_extract(&state->free_list);
2479 req = container_of(node, struct io_kiocb, comp_list);
2480 kmem_cache_free(req_cachep, req);
2484 percpu_ref_put_many(&ctx->refs, nr);
2485 mutex_unlock(&ctx->uring_lock);
2488 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
2490 struct async_poll *apoll;
2492 while (!list_empty(&ctx->apoll_cache)) {
2493 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
2495 list_del(&apoll->poll.wait.entry);
2500 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2502 io_sq_thread_finish(ctx);
2504 if (ctx->mm_account) {
2505 mmdrop(ctx->mm_account);
2506 ctx->mm_account = NULL;
2509 io_rsrc_refs_drop(ctx);
2510 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
2511 io_wait_rsrc_data(ctx->buf_data);
2512 io_wait_rsrc_data(ctx->file_data);
2514 mutex_lock(&ctx->uring_lock);
2516 __io_sqe_buffers_unregister(ctx);
2518 __io_sqe_files_unregister(ctx);
2520 __io_cqring_overflow_flush(ctx, true);
2521 io_eventfd_unregister(ctx);
2522 io_flush_apoll_cache(ctx);
2523 mutex_unlock(&ctx->uring_lock);
2524 io_destroy_buffers(ctx);
2526 put_cred(ctx->sq_creds);
2527 if (ctx->submitter_task)
2528 put_task_struct(ctx->submitter_task);
2530 /* there are no registered resources left, nobody uses it */
2532 io_rsrc_node_destroy(ctx->rsrc_node);
2533 if (ctx->rsrc_backup_node)
2534 io_rsrc_node_destroy(ctx->rsrc_backup_node);
2535 flush_delayed_work(&ctx->rsrc_put_work);
2536 flush_delayed_work(&ctx->fallback_work);
2538 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
2539 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
2541 #if defined(CONFIG_UNIX)
2542 if (ctx->ring_sock) {
2543 ctx->ring_sock->file = NULL; /* so that iput() is called */
2544 sock_release(ctx->ring_sock);
2547 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2549 io_mem_free(ctx->rings);
2550 io_mem_free(ctx->sq_sqes);
2552 percpu_ref_exit(&ctx->refs);
2553 free_uid(ctx->user);
2554 io_req_caches_free(ctx);
2556 io_wq_put_hash(ctx->hash_map);
2557 kfree(ctx->cancel_table.hbs);
2558 kfree(ctx->cancel_table_locked.hbs);
2559 kfree(ctx->dummy_ubuf);
2561 xa_destroy(&ctx->io_bl_xa);
2565 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2567 struct io_ring_ctx *ctx = file->private_data;
2570 poll_wait(file, &ctx->cq_wait, wait);
2572 * synchronizes with barrier from wq_has_sleeper call in
2576 if (!io_sqring_full(ctx))
2577 mask |= EPOLLOUT | EPOLLWRNORM;
2580 * Don't flush cqring overflow list here, just do a simple check.
2581 * Otherwise there could possible be ABBA deadlock:
2584 * lock(&ctx->uring_lock);
2586 * lock(&ctx->uring_lock);
2589 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2590 * pushs them to do the flush.
2592 if (io_cqring_events(ctx) ||
2593 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
2594 mask |= EPOLLIN | EPOLLRDNORM;
2599 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
2601 const struct cred *creds;
2603 creds = xa_erase(&ctx->personalities, id);
2612 struct io_tctx_exit {
2613 struct callback_head task_work;
2614 struct completion completion;
2615 struct io_ring_ctx *ctx;
2618 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2620 struct io_uring_task *tctx = current->io_uring;
2621 struct io_tctx_exit *work;
2623 work = container_of(cb, struct io_tctx_exit, task_work);
2625 * When @in_idle, we're in cancellation and it's racy to remove the
2626 * node. It'll be removed by the end of cancellation, just ignore it.
2628 if (!atomic_read(&tctx->in_idle))
2629 io_uring_del_tctx_node((unsigned long)work->ctx);
2630 complete(&work->completion);
2633 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
2635 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2637 return req->ctx == data;
2640 static __cold void io_ring_exit_work(struct work_struct *work)
2642 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2643 unsigned long timeout = jiffies + HZ * 60 * 5;
2644 unsigned long interval = HZ / 20;
2645 struct io_tctx_exit exit;
2646 struct io_tctx_node *node;
2650 * If we're doing polled IO and end up having requests being
2651 * submitted async (out-of-line), then completions can come in while
2652 * we're waiting for refs to drop. We need to reap these manually,
2653 * as nobody else will be looking for them.
2656 io_uring_try_cancel_requests(ctx, NULL, true);
2658 struct io_sq_data *sqd = ctx->sq_data;
2659 struct task_struct *tsk;
2661 io_sq_thread_park(sqd);
2663 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2664 io_wq_cancel_cb(tsk->io_uring->io_wq,
2665 io_cancel_ctx_cb, ctx, true);
2666 io_sq_thread_unpark(sqd);
2669 io_req_caches_free(ctx);
2671 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2672 /* there is little hope left, don't run it too often */
2675 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
2677 init_completion(&exit.completion);
2678 init_task_work(&exit.task_work, io_tctx_exit_cb);
2681 * Some may use context even when all refs and requests have been put,
2682 * and they are free to do so while still holding uring_lock or
2683 * completion_lock, see io_req_task_submit(). Apart from other work,
2684 * this lock/unlock section also waits them to finish.
2686 mutex_lock(&ctx->uring_lock);
2687 while (!list_empty(&ctx->tctx_list)) {
2688 WARN_ON_ONCE(time_after(jiffies, timeout));
2690 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2692 /* don't spin on a single task if cancellation failed */
2693 list_rotate_left(&ctx->tctx_list);
2694 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2695 if (WARN_ON_ONCE(ret))
2698 mutex_unlock(&ctx->uring_lock);
2699 wait_for_completion(&exit.completion);
2700 mutex_lock(&ctx->uring_lock);
2702 mutex_unlock(&ctx->uring_lock);
2703 spin_lock(&ctx->completion_lock);
2704 spin_unlock(&ctx->completion_lock);
2706 io_ring_ctx_free(ctx);
2709 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2711 unsigned long index;
2712 struct creds *creds;
2714 mutex_lock(&ctx->uring_lock);
2715 percpu_ref_kill(&ctx->refs);
2717 __io_cqring_overflow_flush(ctx, true);
2718 xa_for_each(&ctx->personalities, index, creds)
2719 io_unregister_personality(ctx, index);
2721 io_poll_remove_all(ctx, NULL, true);
2722 mutex_unlock(&ctx->uring_lock);
2724 /* failed during ring init, it couldn't have issued any requests */
2726 io_kill_timeouts(ctx, NULL, true);
2727 /* if we failed setting up the ctx, we might not have any rings */
2728 io_iopoll_try_reap_events(ctx);
2731 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2733 * Use system_unbound_wq to avoid spawning tons of event kworkers
2734 * if we're exiting a ton of rings at the same time. It just adds
2735 * noise and overhead, there's no discernable change in runtime
2736 * over using system_wq.
2738 queue_work(system_unbound_wq, &ctx->exit_work);
2741 static int io_uring_release(struct inode *inode, struct file *file)
2743 struct io_ring_ctx *ctx = file->private_data;
2745 file->private_data = NULL;
2746 io_ring_ctx_wait_and_kill(ctx);
2750 struct io_task_cancel {
2751 struct task_struct *task;
2755 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
2757 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2758 struct io_task_cancel *cancel = data;
2760 return io_match_task_safe(req, cancel->task, cancel->all);
2763 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
2764 struct task_struct *task,
2767 struct io_defer_entry *de;
2770 spin_lock(&ctx->completion_lock);
2771 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
2772 if (io_match_task_safe(de->req, task, cancel_all)) {
2773 list_cut_position(&list, &ctx->defer_list, &de->list);
2777 spin_unlock(&ctx->completion_lock);
2778 if (list_empty(&list))
2781 while (!list_empty(&list)) {
2782 de = list_first_entry(&list, struct io_defer_entry, list);
2783 list_del_init(&de->list);
2784 io_req_complete_failed(de->req, -ECANCELED);
2790 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
2792 struct io_tctx_node *node;
2793 enum io_wq_cancel cret;
2796 mutex_lock(&ctx->uring_lock);
2797 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
2798 struct io_uring_task *tctx = node->task->io_uring;
2801 * io_wq will stay alive while we hold uring_lock, because it's
2802 * killed after ctx nodes, which requires to take the lock.
2804 if (!tctx || !tctx->io_wq)
2806 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
2807 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
2809 mutex_unlock(&ctx->uring_lock);
2814 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
2815 struct task_struct *task,
2818 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
2819 struct io_uring_task *tctx = task ? task->io_uring : NULL;
2821 /* failed during ring init, it couldn't have issued any requests */
2826 enum io_wq_cancel cret;
2830 ret |= io_uring_try_cancel_iowq(ctx);
2831 } else if (tctx && tctx->io_wq) {
2833 * Cancels requests of all rings, not only @ctx, but
2834 * it's fine as the task is in exit/exec.
2836 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
2838 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
2841 /* SQPOLL thread does its own polling */
2842 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
2843 (ctx->sq_data && ctx->sq_data->thread == current)) {
2844 while (!wq_list_empty(&ctx->iopoll_list)) {
2845 io_iopoll_try_reap_events(ctx);
2850 ret |= io_cancel_defer_files(ctx, task, cancel_all);
2851 mutex_lock(&ctx->uring_lock);
2852 ret |= io_poll_remove_all(ctx, task, cancel_all);
2853 mutex_unlock(&ctx->uring_lock);
2854 ret |= io_kill_timeouts(ctx, task, cancel_all);
2856 ret |= io_run_task_work();
2863 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
2866 return atomic_read(&tctx->inflight_tracked);
2867 return percpu_counter_sum(&tctx->inflight);
2871 * Find any io_uring ctx that this task has registered or done IO on, and cancel
2872 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
2874 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
2876 struct io_uring_task *tctx = current->io_uring;
2877 struct io_ring_ctx *ctx;
2881 WARN_ON_ONCE(sqd && sqd->thread != current);
2883 if (!current->io_uring)
2886 io_wq_exit_start(tctx->io_wq);
2888 atomic_inc(&tctx->in_idle);
2890 io_uring_drop_tctx_refs(current);
2891 /* read completions before cancelations */
2892 inflight = tctx_inflight(tctx, !cancel_all);
2897 struct io_tctx_node *node;
2898 unsigned long index;
2900 xa_for_each(&tctx->xa, index, node) {
2901 /* sqpoll task will cancel all its requests */
2902 if (node->ctx->sq_data)
2904 io_uring_try_cancel_requests(node->ctx, current,
2908 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
2909 io_uring_try_cancel_requests(ctx, current,
2913 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
2915 io_uring_drop_tctx_refs(current);
2918 * If we've seen completions, retry without waiting. This
2919 * avoids a race where a completion comes in before we did
2920 * prepare_to_wait().
2922 if (inflight == tctx_inflight(tctx, !cancel_all))
2924 finish_wait(&tctx->wait, &wait);
2927 io_uring_clean_tctx(tctx);
2930 * We shouldn't run task_works after cancel, so just leave
2931 * ->in_idle set for normal exit.
2933 atomic_dec(&tctx->in_idle);
2934 /* for exec all current's requests should be gone, kill tctx */
2935 __io_uring_free(current);
2939 void __io_uring_cancel(bool cancel_all)
2941 io_uring_cancel_generic(cancel_all, NULL);
2944 static void *io_uring_validate_mmap_request(struct file *file,
2945 loff_t pgoff, size_t sz)
2947 struct io_ring_ctx *ctx = file->private_data;
2948 loff_t offset = pgoff << PAGE_SHIFT;
2953 case IORING_OFF_SQ_RING:
2954 case IORING_OFF_CQ_RING:
2957 case IORING_OFF_SQES:
2961 return ERR_PTR(-EINVAL);
2964 page = virt_to_head_page(ptr);
2965 if (sz > page_size(page))
2966 return ERR_PTR(-EINVAL);
2973 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2975 size_t sz = vma->vm_end - vma->vm_start;
2979 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
2981 return PTR_ERR(ptr);
2983 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2984 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2987 #else /* !CONFIG_MMU */
2989 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2991 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
2994 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
2996 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
2999 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3000 unsigned long addr, unsigned long len,
3001 unsigned long pgoff, unsigned long flags)
3005 ptr = io_uring_validate_mmap_request(file, pgoff, len);
3007 return PTR_ERR(ptr);
3009 return (unsigned long) ptr;
3012 #endif /* !CONFIG_MMU */
3014 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3016 if (flags & IORING_ENTER_EXT_ARG) {
3017 struct io_uring_getevents_arg arg;
3019 if (argsz != sizeof(arg))
3021 if (copy_from_user(&arg, argp, sizeof(arg)))
3027 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3028 struct __kernel_timespec __user **ts,
3029 const sigset_t __user **sig)
3031 struct io_uring_getevents_arg arg;
3034 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3035 * is just a pointer to the sigset_t.
3037 if (!(flags & IORING_ENTER_EXT_ARG)) {
3038 *sig = (const sigset_t __user *) argp;
3044 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3045 * timespec and sigset_t pointers if good.
3047 if (*argsz != sizeof(arg))
3049 if (copy_from_user(&arg, argp, sizeof(arg)))
3053 *sig = u64_to_user_ptr(arg.sigmask);
3054 *argsz = arg.sigmask_sz;
3055 *ts = u64_to_user_ptr(arg.ts);
3059 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3060 u32, min_complete, u32, flags, const void __user *, argp,
3063 struct io_ring_ctx *ctx;
3069 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3070 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3071 IORING_ENTER_REGISTERED_RING)))
3075 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3076 * need only dereference our task private array to find it.
3078 if (flags & IORING_ENTER_REGISTERED_RING) {
3079 struct io_uring_task *tctx = current->io_uring;
3081 if (!tctx || fd >= IO_RINGFD_REG_MAX)
3083 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3084 f.file = tctx->registered_rings[fd];
3090 if (unlikely(!f.file))
3094 if (unlikely(!io_is_uring_fops(f.file)))
3098 ctx = f.file->private_data;
3099 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
3103 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3107 * For SQ polling, the thread will do all submissions and completions.
3108 * Just return the requested submit count, and wake the thread if
3112 if (ctx->flags & IORING_SETUP_SQPOLL) {
3113 io_cqring_overflow_flush(ctx);
3115 if (unlikely(ctx->sq_data->thread == NULL)) {
3119 if (flags & IORING_ENTER_SQ_WAKEUP)
3120 wake_up(&ctx->sq_data->wait);
3121 if (flags & IORING_ENTER_SQ_WAIT) {
3122 ret = io_sqpoll_wait_sq(ctx);
3127 } else if (to_submit) {
3128 ret = io_uring_add_tctx_node(ctx);
3132 mutex_lock(&ctx->uring_lock);
3133 ret = io_submit_sqes(ctx, to_submit);
3134 if (ret != to_submit) {
3135 mutex_unlock(&ctx->uring_lock);
3138 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
3140 mutex_unlock(&ctx->uring_lock);
3142 if (flags & IORING_ENTER_GETEVENTS) {
3144 if (ctx->syscall_iopoll) {
3146 * We disallow the app entering submit/complete with
3147 * polling, but we still need to lock the ring to
3148 * prevent racing with polled issue that got punted to
3151 mutex_lock(&ctx->uring_lock);
3153 ret2 = io_validate_ext_arg(flags, argp, argsz);
3154 if (likely(!ret2)) {
3155 min_complete = min(min_complete,
3157 ret2 = io_iopoll_check(ctx, min_complete);
3159 mutex_unlock(&ctx->uring_lock);
3161 const sigset_t __user *sig;
3162 struct __kernel_timespec __user *ts;
3164 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3165 if (likely(!ret2)) {
3166 min_complete = min(min_complete,
3168 ret2 = io_cqring_wait(ctx, min_complete, sig,
3177 * EBADR indicates that one or more CQE were dropped.
3178 * Once the user has been informed we can clear the bit
3179 * as they are obviously ok with those drops.
3181 if (unlikely(ret2 == -EBADR))
3182 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3188 percpu_ref_put(&ctx->refs);
3194 static const struct file_operations io_uring_fops = {
3195 .release = io_uring_release,
3196 .mmap = io_uring_mmap,
3198 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3199 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3201 .poll = io_uring_poll,
3202 #ifdef CONFIG_PROC_FS
3203 .show_fdinfo = io_uring_show_fdinfo,
3207 bool io_is_uring_fops(struct file *file)
3209 return file->f_op == &io_uring_fops;
3212 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3213 struct io_uring_params *p)
3215 struct io_rings *rings;
3216 size_t size, sq_array_offset;
3218 /* make sure these are sane, as we already accounted them */
3219 ctx->sq_entries = p->sq_entries;
3220 ctx->cq_entries = p->cq_entries;
3222 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3223 if (size == SIZE_MAX)
3226 rings = io_mem_alloc(size);
3231 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3232 rings->sq_ring_mask = p->sq_entries - 1;
3233 rings->cq_ring_mask = p->cq_entries - 1;
3234 rings->sq_ring_entries = p->sq_entries;
3235 rings->cq_ring_entries = p->cq_entries;
3237 if (p->flags & IORING_SETUP_SQE128)
3238 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3240 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3241 if (size == SIZE_MAX) {
3242 io_mem_free(ctx->rings);
3247 ctx->sq_sqes = io_mem_alloc(size);
3248 if (!ctx->sq_sqes) {
3249 io_mem_free(ctx->rings);
3257 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
3261 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3265 ret = __io_uring_add_tctx_node(ctx, false);
3270 fd_install(fd, file);
3275 * Allocate an anonymous fd, this is what constitutes the application
3276 * visible backing of an io_uring instance. The application mmaps this
3277 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3278 * we have to tie this fd to a socket for file garbage collection purposes.
3280 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3283 #if defined(CONFIG_UNIX)
3286 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3289 return ERR_PTR(ret);
3292 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
3293 O_RDWR | O_CLOEXEC, NULL);
3294 #if defined(CONFIG_UNIX)
3296 sock_release(ctx->ring_sock);
3297 ctx->ring_sock = NULL;
3299 ctx->ring_sock->file = file;
3305 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3306 struct io_uring_params __user *params)
3308 struct io_ring_ctx *ctx;
3314 if (entries > IORING_MAX_ENTRIES) {
3315 if (!(p->flags & IORING_SETUP_CLAMP))
3317 entries = IORING_MAX_ENTRIES;
3321 * Use twice as many entries for the CQ ring. It's possible for the
3322 * application to drive a higher depth than the size of the SQ ring,
3323 * since the sqes are only used at submission time. This allows for
3324 * some flexibility in overcommitting a bit. If the application has
3325 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3326 * of CQ ring entries manually.
3328 p->sq_entries = roundup_pow_of_two(entries);
3329 if (p->flags & IORING_SETUP_CQSIZE) {
3331 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3332 * to a power-of-two, if it isn't already. We do NOT impose
3333 * any cq vs sq ring sizing.
3337 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3338 if (!(p->flags & IORING_SETUP_CLAMP))
3340 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3342 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3343 if (p->cq_entries < p->sq_entries)
3346 p->cq_entries = 2 * p->sq_entries;
3349 ctx = io_ring_ctx_alloc(p);
3354 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3355 * space applications don't need to do io completion events
3356 * polling again, they can rely on io_sq_thread to do polling
3357 * work, which can reduce cpu usage and uring_lock contention.
3359 if (ctx->flags & IORING_SETUP_IOPOLL &&
3360 !(ctx->flags & IORING_SETUP_SQPOLL))
3361 ctx->syscall_iopoll = 1;
3363 ctx->compat = in_compat_syscall();
3364 if (!capable(CAP_IPC_LOCK))
3365 ctx->user = get_uid(current_user());
3368 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3369 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3372 if (ctx->flags & IORING_SETUP_SQPOLL) {
3373 /* IPI related flags don't make sense with SQPOLL */
3374 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3375 IORING_SETUP_TASKRUN_FLAG))
3377 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3378 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3379 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3381 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
3383 ctx->notify_method = TWA_SIGNAL;
3387 * This is just grabbed for accounting purposes. When a process exits,
3388 * the mm is exited and dropped before the files, hence we need to hang
3389 * on to this mm purely for the purposes of being able to unaccount
3390 * memory (locked/pinned vm). It's not used for anything else.
3392 mmgrab(current->mm);
3393 ctx->mm_account = current->mm;
3395 ret = io_allocate_scq_urings(ctx, p);
3399 ret = io_sq_offload_create(ctx, p);
3402 /* always set a rsrc node */
3403 ret = io_rsrc_node_switch_start(ctx);
3406 io_rsrc_node_switch(ctx, NULL);
3408 memset(&p->sq_off, 0, sizeof(p->sq_off));
3409 p->sq_off.head = offsetof(struct io_rings, sq.head);
3410 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3411 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3412 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3413 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3414 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3415 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3417 memset(&p->cq_off, 0, sizeof(p->cq_off));
3418 p->cq_off.head = offsetof(struct io_rings, cq.head);
3419 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3420 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3421 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3422 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3423 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3424 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3426 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3427 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
3428 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
3429 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
3430 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
3431 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
3432 IORING_FEAT_LINKED_FILE;
3434 if (copy_to_user(params, p, sizeof(*p))) {
3439 file = io_uring_get_file(ctx);
3441 ret = PTR_ERR(file);
3446 * Install ring fd as the very last thing, so we don't risk someone
3447 * having closed it before we finish setup
3449 ret = io_uring_install_fd(ctx, file);
3451 /* fput will clean it up */
3456 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3459 io_ring_ctx_wait_and_kill(ctx);
3464 * Sets up an aio uring context, and returns the fd. Applications asks for a
3465 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3466 * params structure passed in.
3468 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3470 struct io_uring_params p;
3473 if (copy_from_user(&p, params, sizeof(p)))
3475 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3480 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3481 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
3482 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
3483 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
3484 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
3485 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
3486 IORING_SETUP_SINGLE_ISSUER))
3489 return io_uring_create(entries, &p, params);
3492 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3493 struct io_uring_params __user *, params)
3495 return io_uring_setup(entries, params);
3498 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
3501 struct io_uring_probe *p;
3505 size = struct_size(p, ops, nr_args);
3506 if (size == SIZE_MAX)
3508 p = kzalloc(size, GFP_KERNEL);
3513 if (copy_from_user(p, arg, size))
3516 if (memchr_inv(p, 0, size))
3519 p->last_op = IORING_OP_LAST - 1;
3520 if (nr_args > IORING_OP_LAST)
3521 nr_args = IORING_OP_LAST;
3523 for (i = 0; i < nr_args; i++) {
3525 if (!io_op_defs[i].not_supported)
3526 p->ops[i].flags = IO_URING_OP_SUPPORTED;
3531 if (copy_to_user(arg, p, size))
3538 static int io_register_personality(struct io_ring_ctx *ctx)
3540 const struct cred *creds;
3544 creds = get_current_cred();
3546 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
3547 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
3555 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
3556 void __user *arg, unsigned int nr_args)
3558 struct io_uring_restriction *res;
3562 /* Restrictions allowed only if rings started disabled */
3563 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
3566 /* We allow only a single restrictions registration */
3567 if (ctx->restrictions.registered)
3570 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
3573 size = array_size(nr_args, sizeof(*res));
3574 if (size == SIZE_MAX)
3577 res = memdup_user(arg, size);
3579 return PTR_ERR(res);
3583 for (i = 0; i < nr_args; i++) {
3584 switch (res[i].opcode) {
3585 case IORING_RESTRICTION_REGISTER_OP:
3586 if (res[i].register_op >= IORING_REGISTER_LAST) {
3591 __set_bit(res[i].register_op,
3592 ctx->restrictions.register_op);
3594 case IORING_RESTRICTION_SQE_OP:
3595 if (res[i].sqe_op >= IORING_OP_LAST) {
3600 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
3602 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
3603 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
3605 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
3606 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
3615 /* Reset all restrictions if an error happened */
3617 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
3619 ctx->restrictions.registered = true;
3625 static int io_register_enable_rings(struct io_ring_ctx *ctx)
3627 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
3630 if (ctx->restrictions.registered)
3631 ctx->restricted = 1;
3633 ctx->flags &= ~IORING_SETUP_R_DISABLED;
3634 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
3635 wake_up(&ctx->sq_data->wait);
3639 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
3640 void __user *arg, unsigned len)
3642 struct io_uring_task *tctx = current->io_uring;
3643 cpumask_var_t new_mask;
3646 if (!tctx || !tctx->io_wq)
3649 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
3652 cpumask_clear(new_mask);
3653 if (len > cpumask_size())
3654 len = cpumask_size();
3656 if (in_compat_syscall()) {
3657 ret = compat_get_bitmap(cpumask_bits(new_mask),
3658 (const compat_ulong_t __user *)arg,
3659 len * 8 /* CHAR_BIT */);
3661 ret = copy_from_user(new_mask, arg, len);
3665 free_cpumask_var(new_mask);
3669 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
3670 free_cpumask_var(new_mask);
3674 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
3676 struct io_uring_task *tctx = current->io_uring;
3678 if (!tctx || !tctx->io_wq)
3681 return io_wq_cpu_affinity(tctx->io_wq, NULL);
3684 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
3686 __must_hold(&ctx->uring_lock)
3688 struct io_tctx_node *node;
3689 struct io_uring_task *tctx = NULL;
3690 struct io_sq_data *sqd = NULL;
3694 if (copy_from_user(new_count, arg, sizeof(new_count)))
3696 for (i = 0; i < ARRAY_SIZE(new_count); i++)
3697 if (new_count[i] > INT_MAX)
3700 if (ctx->flags & IORING_SETUP_SQPOLL) {
3704 * Observe the correct sqd->lock -> ctx->uring_lock
3705 * ordering. Fine to drop uring_lock here, we hold
3708 refcount_inc(&sqd->refs);
3709 mutex_unlock(&ctx->uring_lock);
3710 mutex_lock(&sqd->lock);
3711 mutex_lock(&ctx->uring_lock);
3713 tctx = sqd->thread->io_uring;
3716 tctx = current->io_uring;
3719 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
3721 for (i = 0; i < ARRAY_SIZE(new_count); i++)
3723 ctx->iowq_limits[i] = new_count[i];
3724 ctx->iowq_limits_set = true;
3726 if (tctx && tctx->io_wq) {
3727 ret = io_wq_max_workers(tctx->io_wq, new_count);
3731 memset(new_count, 0, sizeof(new_count));
3735 mutex_unlock(&sqd->lock);
3736 io_put_sq_data(sqd);
3739 if (copy_to_user(arg, new_count, sizeof(new_count)))
3742 /* that's it for SQPOLL, only the SQPOLL task creates requests */
3746 /* now propagate the restriction to all registered users */
3747 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3748 struct io_uring_task *tctx = node->task->io_uring;
3750 if (WARN_ON_ONCE(!tctx->io_wq))
3753 for (i = 0; i < ARRAY_SIZE(new_count); i++)
3754 new_count[i] = ctx->iowq_limits[i];
3755 /* ignore errors, it always returns zero anyway */
3756 (void)io_wq_max_workers(tctx->io_wq, new_count);
3761 mutex_unlock(&sqd->lock);
3762 io_put_sq_data(sqd);
3767 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3768 void __user *arg, unsigned nr_args)
3769 __releases(ctx->uring_lock)
3770 __acquires(ctx->uring_lock)
3775 * We're inside the ring mutex, if the ref is already dying, then
3776 * someone else killed the ctx or is already going through
3777 * io_uring_register().
3779 if (percpu_ref_is_dying(&ctx->refs))
3782 if (ctx->restricted) {
3783 if (opcode >= IORING_REGISTER_LAST)
3785 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
3786 if (!test_bit(opcode, ctx->restrictions.register_op))
3791 case IORING_REGISTER_BUFFERS:
3795 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
3797 case IORING_UNREGISTER_BUFFERS:
3801 ret = io_sqe_buffers_unregister(ctx);
3803 case IORING_REGISTER_FILES:
3807 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
3809 case IORING_UNREGISTER_FILES:
3813 ret = io_sqe_files_unregister(ctx);
3815 case IORING_REGISTER_FILES_UPDATE:
3816 ret = io_register_files_update(ctx, arg, nr_args);
3818 case IORING_REGISTER_EVENTFD:
3822 ret = io_eventfd_register(ctx, arg, 0);
3824 case IORING_REGISTER_EVENTFD_ASYNC:
3828 ret = io_eventfd_register(ctx, arg, 1);
3830 case IORING_UNREGISTER_EVENTFD:
3834 ret = io_eventfd_unregister(ctx);
3836 case IORING_REGISTER_PROBE:
3838 if (!arg || nr_args > 256)
3840 ret = io_probe(ctx, arg, nr_args);
3842 case IORING_REGISTER_PERSONALITY:
3846 ret = io_register_personality(ctx);
3848 case IORING_UNREGISTER_PERSONALITY:
3852 ret = io_unregister_personality(ctx, nr_args);
3854 case IORING_REGISTER_ENABLE_RINGS:
3858 ret = io_register_enable_rings(ctx);
3860 case IORING_REGISTER_RESTRICTIONS:
3861 ret = io_register_restrictions(ctx, arg, nr_args);
3863 case IORING_REGISTER_FILES2:
3864 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
3866 case IORING_REGISTER_FILES_UPDATE2:
3867 ret = io_register_rsrc_update(ctx, arg, nr_args,
3870 case IORING_REGISTER_BUFFERS2:
3871 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
3873 case IORING_REGISTER_BUFFERS_UPDATE:
3874 ret = io_register_rsrc_update(ctx, arg, nr_args,
3875 IORING_RSRC_BUFFER);
3877 case IORING_REGISTER_IOWQ_AFF:
3879 if (!arg || !nr_args)
3881 ret = io_register_iowq_aff(ctx, arg, nr_args);
3883 case IORING_UNREGISTER_IOWQ_AFF:
3887 ret = io_unregister_iowq_aff(ctx);
3889 case IORING_REGISTER_IOWQ_MAX_WORKERS:
3891 if (!arg || nr_args != 2)
3893 ret = io_register_iowq_max_workers(ctx, arg);
3895 case IORING_REGISTER_RING_FDS:
3896 ret = io_ringfd_register(ctx, arg, nr_args);
3898 case IORING_UNREGISTER_RING_FDS:
3899 ret = io_ringfd_unregister(ctx, arg, nr_args);
3901 case IORING_REGISTER_PBUF_RING:
3903 if (!arg || nr_args != 1)
3905 ret = io_register_pbuf_ring(ctx, arg);
3907 case IORING_UNREGISTER_PBUF_RING:
3909 if (!arg || nr_args != 1)
3911 ret = io_unregister_pbuf_ring(ctx, arg);
3921 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3922 void __user *, arg, unsigned int, nr_args)
3924 struct io_ring_ctx *ctx;
3933 if (!io_is_uring_fops(f.file))
3936 ctx = f.file->private_data;
3940 mutex_lock(&ctx->uring_lock);
3941 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3942 mutex_unlock(&ctx->uring_lock);
3943 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
3949 static int __init io_uring_init(void)
3951 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
3952 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
3953 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
3956 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
3957 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
3958 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
3959 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
3960 BUILD_BUG_SQE_ELEM(1, __u8, flags);
3961 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
3962 BUILD_BUG_SQE_ELEM(4, __s32, fd);
3963 BUILD_BUG_SQE_ELEM(8, __u64, off);
3964 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
3965 BUILD_BUG_SQE_ELEM(16, __u64, addr);
3966 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
3967 BUILD_BUG_SQE_ELEM(24, __u32, len);
3968 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
3969 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
3970 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
3971 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
3972 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
3973 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
3974 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
3975 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
3976 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
3977 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
3978 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
3979 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
3980 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
3981 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
3982 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
3983 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
3984 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
3985 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
3986 BUILD_BUG_SQE_ELEM(42, __u16, personality);
3987 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
3988 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
3989 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
3991 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3992 sizeof(struct io_uring_rsrc_update));
3993 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3994 sizeof(struct io_uring_rsrc_update2));
3996 /* ->buf_index is u16 */
3997 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3998 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3999 offsetof(struct io_uring_buf_ring, tail));
4001 /* should fit into one byte */
4002 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
4003 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4004 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4006 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
4008 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4010 io_uring_optable_init();
4012 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4016 __initcall(io_uring_init);