printf: Remove unused 'bprintf'
[drm/drm-misc.git] / io_uring / io_uring.c
blob8012933998837ddcef45c14f1dfe543947a9eaec
1 // SPDX-License-Identifier: GPL-2.0
2 /*
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
16 * CQ entries.
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
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>
52 #include <linux/fs.h>
53 #include <linux/file.h>
54 #include <linux/mm.h>
55 #include <linux/mman.h>
56 #include <linux/percpu.h>
57 #include <linux/slab.h>
58 #include <linux/bvec.h>
59 #include <linux/net.h>
60 #include <net/sock.h>
61 #include <linux/anon_inodes.h>
62 #include <linux/sched/mm.h>
63 #include <linux/uaccess.h>
64 #include <linux/nospec.h>
65 #include <linux/fsnotify.h>
66 #include <linux/fadvise.h>
67 #include <linux/task_work.h>
68 #include <linux/io_uring.h>
69 #include <linux/io_uring/cmd.h>
70 #include <linux/audit.h>
71 #include <linux/security.h>
72 #include <linux/jump_label.h>
73 #include <asm/shmparam.h>
75 #define CREATE_TRACE_POINTS
76 #include <trace/events/io_uring.h>
78 #include <uapi/linux/io_uring.h>
80 #include "io-wq.h"
82 #include "io_uring.h"
83 #include "opdef.h"
84 #include "refs.h"
85 #include "tctx.h"
86 #include "register.h"
87 #include "sqpoll.h"
88 #include "fdinfo.h"
89 #include "kbuf.h"
90 #include "rsrc.h"
91 #include "cancel.h"
92 #include "net.h"
93 #include "notif.h"
94 #include "waitid.h"
95 #include "futex.h"
96 #include "napi.h"
97 #include "uring_cmd.h"
98 #include "msg_ring.h"
99 #include "memmap.h"
101 #include "timeout.h"
102 #include "poll.h"
103 #include "rw.h"
104 #include "alloc_cache.h"
105 #include "eventfd.h"
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
115 REQ_F_ASYNC_DATA)
117 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
118 IO_REQ_CLEAN_FLAGS)
120 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
122 #define IO_COMPL_BATCH 32
123 #define IO_REQ_ALLOC_BATCH 8
125 struct io_defer_entry {
126 struct list_head list;
127 struct io_kiocb *req;
128 u32 seq;
131 /* requests with any of those set should undergo io_disarm_next() */
132 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
133 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
136 * No waiters. It's larger than any valid value of the tw counter
137 * so that tests against ->cq_wait_nr would fail and skip wake_up().
139 #define IO_CQ_WAKE_INIT (-1U)
140 /* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
141 #define IO_CQ_WAKE_FORCE (IO_CQ_WAKE_INIT >> 1)
143 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
144 struct io_uring_task *tctx,
145 bool cancel_all);
147 static void io_queue_sqe(struct io_kiocb *req);
149 static __read_mostly DEFINE_STATIC_KEY_FALSE(io_key_has_sqarray);
151 struct kmem_cache *req_cachep;
152 static struct workqueue_struct *iou_wq __ro_after_init;
154 static int __read_mostly sysctl_io_uring_disabled;
155 static int __read_mostly sysctl_io_uring_group = -1;
157 #ifdef CONFIG_SYSCTL
158 static struct ctl_table kernel_io_uring_disabled_table[] = {
160 .procname = "io_uring_disabled",
161 .data = &sysctl_io_uring_disabled,
162 .maxlen = sizeof(sysctl_io_uring_disabled),
163 .mode = 0644,
164 .proc_handler = proc_dointvec_minmax,
165 .extra1 = SYSCTL_ZERO,
166 .extra2 = SYSCTL_TWO,
169 .procname = "io_uring_group",
170 .data = &sysctl_io_uring_group,
171 .maxlen = sizeof(gid_t),
172 .mode = 0644,
173 .proc_handler = proc_dointvec,
176 #endif
178 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
180 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
183 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
185 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
188 static bool io_match_linked(struct io_kiocb *head)
190 struct io_kiocb *req;
192 io_for_each_link(req, head) {
193 if (req->flags & REQ_F_INFLIGHT)
194 return true;
196 return false;
200 * As io_match_task() but protected against racing with linked timeouts.
201 * User must not hold timeout_lock.
203 bool io_match_task_safe(struct io_kiocb *head, struct io_uring_task *tctx,
204 bool cancel_all)
206 bool matched;
208 if (tctx && head->tctx != tctx)
209 return false;
210 if (cancel_all)
211 return true;
213 if (head->flags & REQ_F_LINK_TIMEOUT) {
214 struct io_ring_ctx *ctx = head->ctx;
216 /* protect against races with linked timeouts */
217 spin_lock_irq(&ctx->timeout_lock);
218 matched = io_match_linked(head);
219 spin_unlock_irq(&ctx->timeout_lock);
220 } else {
221 matched = io_match_linked(head);
223 return matched;
226 static inline void req_fail_link_node(struct io_kiocb *req, int res)
228 req_set_fail(req);
229 io_req_set_res(req, res, 0);
232 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
234 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
237 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
239 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
241 complete(&ctx->ref_comp);
244 static __cold void io_fallback_req_func(struct work_struct *work)
246 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
247 fallback_work.work);
248 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
249 struct io_kiocb *req, *tmp;
250 struct io_tw_state ts = {};
252 percpu_ref_get(&ctx->refs);
253 mutex_lock(&ctx->uring_lock);
254 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
255 req->io_task_work.func(req, &ts);
256 io_submit_flush_completions(ctx);
257 mutex_unlock(&ctx->uring_lock);
258 percpu_ref_put(&ctx->refs);
261 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
263 unsigned int hash_buckets;
264 int i;
266 do {
267 hash_buckets = 1U << bits;
268 table->hbs = kvmalloc_array(hash_buckets, sizeof(table->hbs[0]),
269 GFP_KERNEL_ACCOUNT);
270 if (table->hbs)
271 break;
272 if (bits == 1)
273 return -ENOMEM;
274 bits--;
275 } while (1);
277 table->hash_bits = bits;
278 for (i = 0; i < hash_buckets; i++)
279 INIT_HLIST_HEAD(&table->hbs[i].list);
280 return 0;
283 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
285 struct io_ring_ctx *ctx;
286 int hash_bits;
287 bool ret;
289 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
290 if (!ctx)
291 return NULL;
293 xa_init(&ctx->io_bl_xa);
296 * Use 5 bits less than the max cq entries, that should give us around
297 * 32 entries per hash list if totally full and uniformly spread, but
298 * don't keep too many buckets to not overconsume memory.
300 hash_bits = ilog2(p->cq_entries) - 5;
301 hash_bits = clamp(hash_bits, 1, 8);
302 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
303 goto err;
304 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
305 0, GFP_KERNEL))
306 goto err;
308 ctx->flags = p->flags;
309 ctx->hybrid_poll_time = LLONG_MAX;
310 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
311 init_waitqueue_head(&ctx->sqo_sq_wait);
312 INIT_LIST_HEAD(&ctx->sqd_list);
313 INIT_LIST_HEAD(&ctx->cq_overflow_list);
314 INIT_LIST_HEAD(&ctx->io_buffers_cache);
315 ret = io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX,
316 sizeof(struct async_poll));
317 ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
318 sizeof(struct io_async_msghdr));
319 ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX,
320 sizeof(struct io_async_rw));
321 ret |= io_alloc_cache_init(&ctx->uring_cache, IO_ALLOC_CACHE_MAX,
322 sizeof(struct uring_cache));
323 spin_lock_init(&ctx->msg_lock);
324 ret |= io_alloc_cache_init(&ctx->msg_cache, IO_ALLOC_CACHE_MAX,
325 sizeof(struct io_kiocb));
326 ret |= io_futex_cache_init(ctx);
327 if (ret)
328 goto free_ref;
329 init_completion(&ctx->ref_comp);
330 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
331 mutex_init(&ctx->uring_lock);
332 init_waitqueue_head(&ctx->cq_wait);
333 init_waitqueue_head(&ctx->poll_wq);
334 spin_lock_init(&ctx->completion_lock);
335 spin_lock_init(&ctx->timeout_lock);
336 INIT_WQ_LIST(&ctx->iopoll_list);
337 INIT_LIST_HEAD(&ctx->io_buffers_comp);
338 INIT_LIST_HEAD(&ctx->defer_list);
339 INIT_LIST_HEAD(&ctx->timeout_list);
340 INIT_LIST_HEAD(&ctx->ltimeout_list);
341 init_llist_head(&ctx->work_llist);
342 INIT_LIST_HEAD(&ctx->tctx_list);
343 ctx->submit_state.free_list.next = NULL;
344 INIT_HLIST_HEAD(&ctx->waitid_list);
345 #ifdef CONFIG_FUTEX
346 INIT_HLIST_HEAD(&ctx->futex_list);
347 #endif
348 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
349 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
350 INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
351 io_napi_init(ctx);
352 mutex_init(&ctx->resize_lock);
354 return ctx;
356 free_ref:
357 percpu_ref_exit(&ctx->refs);
358 err:
359 io_alloc_cache_free(&ctx->apoll_cache, kfree);
360 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
361 io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
362 io_alloc_cache_free(&ctx->uring_cache, kfree);
363 io_alloc_cache_free(&ctx->msg_cache, io_msg_cache_free);
364 io_futex_cache_free(ctx);
365 kvfree(ctx->cancel_table.hbs);
366 xa_destroy(&ctx->io_bl_xa);
367 kfree(ctx);
368 return NULL;
371 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
373 struct io_rings *r = ctx->rings;
375 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
376 ctx->cq_extra--;
379 static bool req_need_defer(struct io_kiocb *req, u32 seq)
381 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
382 struct io_ring_ctx *ctx = req->ctx;
384 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
387 return false;
390 static void io_clean_op(struct io_kiocb *req)
392 if (req->flags & REQ_F_BUFFER_SELECTED) {
393 spin_lock(&req->ctx->completion_lock);
394 io_kbuf_drop(req);
395 spin_unlock(&req->ctx->completion_lock);
398 if (req->flags & REQ_F_NEED_CLEANUP) {
399 const struct io_cold_def *def = &io_cold_defs[req->opcode];
401 if (def->cleanup)
402 def->cleanup(req);
404 if ((req->flags & REQ_F_POLLED) && req->apoll) {
405 kfree(req->apoll->double_poll);
406 kfree(req->apoll);
407 req->apoll = NULL;
409 if (req->flags & REQ_F_INFLIGHT)
410 atomic_dec(&req->tctx->inflight_tracked);
411 if (req->flags & REQ_F_CREDS)
412 put_cred(req->creds);
413 if (req->flags & REQ_F_ASYNC_DATA) {
414 kfree(req->async_data);
415 req->async_data = NULL;
417 req->flags &= ~IO_REQ_CLEAN_FLAGS;
420 static inline void io_req_track_inflight(struct io_kiocb *req)
422 if (!(req->flags & REQ_F_INFLIGHT)) {
423 req->flags |= REQ_F_INFLIGHT;
424 atomic_inc(&req->tctx->inflight_tracked);
428 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
430 if (WARN_ON_ONCE(!req->link))
431 return NULL;
433 req->flags &= ~REQ_F_ARM_LTIMEOUT;
434 req->flags |= REQ_F_LINK_TIMEOUT;
436 /* linked timeouts should have two refs once prep'ed */
437 io_req_set_refcount(req);
438 __io_req_set_refcount(req->link, 2);
439 return req->link;
442 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
444 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
445 return NULL;
446 return __io_prep_linked_timeout(req);
449 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
451 io_queue_linked_timeout(__io_prep_linked_timeout(req));
454 static inline void io_arm_ltimeout(struct io_kiocb *req)
456 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
457 __io_arm_ltimeout(req);
460 static void io_prep_async_work(struct io_kiocb *req)
462 const struct io_issue_def *def = &io_issue_defs[req->opcode];
463 struct io_ring_ctx *ctx = req->ctx;
465 if (!(req->flags & REQ_F_CREDS)) {
466 req->flags |= REQ_F_CREDS;
467 req->creds = get_current_cred();
470 req->work.list.next = NULL;
471 atomic_set(&req->work.flags, 0);
472 if (req->flags & REQ_F_FORCE_ASYNC)
473 atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
475 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
476 req->flags |= io_file_get_flags(req->file);
478 if (req->file && (req->flags & REQ_F_ISREG)) {
479 bool should_hash = def->hash_reg_file;
481 /* don't serialize this request if the fs doesn't need it */
482 if (should_hash && (req->file->f_flags & O_DIRECT) &&
483 (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
484 should_hash = false;
485 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
486 io_wq_hash_work(&req->work, file_inode(req->file));
487 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
488 if (def->unbound_nonreg_file)
489 atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
493 static void io_prep_async_link(struct io_kiocb *req)
495 struct io_kiocb *cur;
497 if (req->flags & REQ_F_LINK_TIMEOUT) {
498 struct io_ring_ctx *ctx = req->ctx;
500 spin_lock_irq(&ctx->timeout_lock);
501 io_for_each_link(cur, req)
502 io_prep_async_work(cur);
503 spin_unlock_irq(&ctx->timeout_lock);
504 } else {
505 io_for_each_link(cur, req)
506 io_prep_async_work(cur);
510 static void io_queue_iowq(struct io_kiocb *req)
512 struct io_kiocb *link = io_prep_linked_timeout(req);
513 struct io_uring_task *tctx = req->tctx;
515 BUG_ON(!tctx);
516 BUG_ON(!tctx->io_wq);
518 /* init ->work of the whole link before punting */
519 io_prep_async_link(req);
522 * Not expected to happen, but if we do have a bug where this _can_
523 * happen, catch it here and ensure the request is marked as
524 * canceled. That will make io-wq go through the usual work cancel
525 * procedure rather than attempt to run this request (or create a new
526 * worker for it).
528 if (WARN_ON_ONCE(!same_thread_group(tctx->task, current)))
529 atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
531 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
532 io_wq_enqueue(tctx->io_wq, &req->work);
533 if (link)
534 io_queue_linked_timeout(link);
537 static void io_req_queue_iowq_tw(struct io_kiocb *req, struct io_tw_state *ts)
539 io_queue_iowq(req);
542 void io_req_queue_iowq(struct io_kiocb *req)
544 req->io_task_work.func = io_req_queue_iowq_tw;
545 io_req_task_work_add(req);
548 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
550 while (!list_empty(&ctx->defer_list)) {
551 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
552 struct io_defer_entry, list);
554 if (req_need_defer(de->req, de->seq))
555 break;
556 list_del_init(&de->list);
557 io_req_task_queue(de->req);
558 kfree(de);
562 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
564 if (ctx->poll_activated)
565 io_poll_wq_wake(ctx);
566 if (ctx->off_timeout_used)
567 io_flush_timeouts(ctx);
568 if (ctx->drain_active) {
569 spin_lock(&ctx->completion_lock);
570 io_queue_deferred(ctx);
571 spin_unlock(&ctx->completion_lock);
573 if (ctx->has_evfd)
574 io_eventfd_flush_signal(ctx);
577 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
579 if (!ctx->lockless_cq)
580 spin_lock(&ctx->completion_lock);
583 static inline void io_cq_lock(struct io_ring_ctx *ctx)
584 __acquires(ctx->completion_lock)
586 spin_lock(&ctx->completion_lock);
589 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
591 io_commit_cqring(ctx);
592 if (!ctx->task_complete) {
593 if (!ctx->lockless_cq)
594 spin_unlock(&ctx->completion_lock);
595 /* IOPOLL rings only need to wake up if it's also SQPOLL */
596 if (!ctx->syscall_iopoll)
597 io_cqring_wake(ctx);
599 io_commit_cqring_flush(ctx);
602 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
603 __releases(ctx->completion_lock)
605 io_commit_cqring(ctx);
606 spin_unlock(&ctx->completion_lock);
607 io_cqring_wake(ctx);
608 io_commit_cqring_flush(ctx);
611 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
613 size_t cqe_size = sizeof(struct io_uring_cqe);
615 lockdep_assert_held(&ctx->uring_lock);
617 /* don't abort if we're dying, entries must get freed */
618 if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
619 return;
621 if (ctx->flags & IORING_SETUP_CQE32)
622 cqe_size <<= 1;
624 io_cq_lock(ctx);
625 while (!list_empty(&ctx->cq_overflow_list)) {
626 struct io_uring_cqe *cqe;
627 struct io_overflow_cqe *ocqe;
629 ocqe = list_first_entry(&ctx->cq_overflow_list,
630 struct io_overflow_cqe, list);
632 if (!dying) {
633 if (!io_get_cqe_overflow(ctx, &cqe, true))
634 break;
635 memcpy(cqe, &ocqe->cqe, cqe_size);
637 list_del(&ocqe->list);
638 kfree(ocqe);
641 * For silly syzbot cases that deliberately overflow by huge
642 * amounts, check if we need to resched and drop and
643 * reacquire the locks if so. Nothing real would ever hit this.
644 * Ideally we'd have a non-posting unlock for this, but hard
645 * to care for a non-real case.
647 if (need_resched()) {
648 io_cq_unlock_post(ctx);
649 mutex_unlock(&ctx->uring_lock);
650 cond_resched();
651 mutex_lock(&ctx->uring_lock);
652 io_cq_lock(ctx);
656 if (list_empty(&ctx->cq_overflow_list)) {
657 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
658 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
660 io_cq_unlock_post(ctx);
663 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
665 if (ctx->rings)
666 __io_cqring_overflow_flush(ctx, true);
669 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
671 mutex_lock(&ctx->uring_lock);
672 __io_cqring_overflow_flush(ctx, false);
673 mutex_unlock(&ctx->uring_lock);
676 /* must to be called somewhat shortly after putting a request */
677 static inline void io_put_task(struct io_kiocb *req)
679 struct io_uring_task *tctx = req->tctx;
681 if (likely(tctx->task == current)) {
682 tctx->cached_refs++;
683 } else {
684 percpu_counter_sub(&tctx->inflight, 1);
685 if (unlikely(atomic_read(&tctx->in_cancel)))
686 wake_up(&tctx->wait);
687 put_task_struct(tctx->task);
691 void io_task_refs_refill(struct io_uring_task *tctx)
693 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
695 percpu_counter_add(&tctx->inflight, refill);
696 refcount_add(refill, &current->usage);
697 tctx->cached_refs += refill;
700 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
702 struct io_uring_task *tctx = task->io_uring;
703 unsigned int refs = tctx->cached_refs;
705 if (refs) {
706 tctx->cached_refs = 0;
707 percpu_counter_sub(&tctx->inflight, refs);
708 put_task_struct_many(task, refs);
712 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
713 s32 res, u32 cflags, u64 extra1, u64 extra2)
715 struct io_overflow_cqe *ocqe;
716 size_t ocq_size = sizeof(struct io_overflow_cqe);
717 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
719 lockdep_assert_held(&ctx->completion_lock);
721 if (is_cqe32)
722 ocq_size += sizeof(struct io_uring_cqe);
724 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
725 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
726 if (!ocqe) {
728 * If we're in ring overflow flush mode, or in task cancel mode,
729 * or cannot allocate an overflow entry, then we need to drop it
730 * on the floor.
732 io_account_cq_overflow(ctx);
733 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
734 return false;
736 if (list_empty(&ctx->cq_overflow_list)) {
737 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
738 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
741 ocqe->cqe.user_data = user_data;
742 ocqe->cqe.res = res;
743 ocqe->cqe.flags = cflags;
744 if (is_cqe32) {
745 ocqe->cqe.big_cqe[0] = extra1;
746 ocqe->cqe.big_cqe[1] = extra2;
748 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
749 return true;
752 static void io_req_cqe_overflow(struct io_kiocb *req)
754 io_cqring_event_overflow(req->ctx, req->cqe.user_data,
755 req->cqe.res, req->cqe.flags,
756 req->big_cqe.extra1, req->big_cqe.extra2);
757 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
761 * writes to the cq entry need to come after reading head; the
762 * control dependency is enough as we're using WRITE_ONCE to
763 * fill the cq entry
765 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
767 struct io_rings *rings = ctx->rings;
768 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
769 unsigned int free, queued, len;
772 * Posting into the CQ when there are pending overflowed CQEs may break
773 * ordering guarantees, which will affect links, F_MORE users and more.
774 * Force overflow the completion.
776 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
777 return false;
779 /* userspace may cheat modifying the tail, be safe and do min */
780 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
781 free = ctx->cq_entries - queued;
782 /* we need a contiguous range, limit based on the current array offset */
783 len = min(free, ctx->cq_entries - off);
784 if (!len)
785 return false;
787 if (ctx->flags & IORING_SETUP_CQE32) {
788 off <<= 1;
789 len <<= 1;
792 ctx->cqe_cached = &rings->cqes[off];
793 ctx->cqe_sentinel = ctx->cqe_cached + len;
794 return true;
797 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
798 u32 cflags)
800 struct io_uring_cqe *cqe;
802 ctx->cq_extra++;
805 * If we can't get a cq entry, userspace overflowed the
806 * submission (by quite a lot). Increment the overflow count in
807 * the ring.
809 if (likely(io_get_cqe(ctx, &cqe))) {
810 WRITE_ONCE(cqe->user_data, user_data);
811 WRITE_ONCE(cqe->res, res);
812 WRITE_ONCE(cqe->flags, cflags);
814 if (ctx->flags & IORING_SETUP_CQE32) {
815 WRITE_ONCE(cqe->big_cqe[0], 0);
816 WRITE_ONCE(cqe->big_cqe[1], 0);
819 trace_io_uring_complete(ctx, NULL, cqe);
820 return true;
822 return false;
825 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res,
826 u32 cflags)
828 bool filled;
830 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
831 if (!filled)
832 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
834 return filled;
837 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
839 bool filled;
841 io_cq_lock(ctx);
842 filled = __io_post_aux_cqe(ctx, user_data, res, cflags);
843 io_cq_unlock_post(ctx);
844 return filled;
848 * Must be called from inline task_work so we now a flush will happen later,
849 * and obviously with ctx->uring_lock held (tw always has that).
851 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
853 if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
854 spin_lock(&ctx->completion_lock);
855 io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
856 spin_unlock(&ctx->completion_lock);
858 ctx->submit_state.cq_flush = true;
862 * A helper for multishot requests posting additional CQEs.
863 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
865 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
867 struct io_ring_ctx *ctx = req->ctx;
868 bool posted;
870 lockdep_assert(!io_wq_current_is_worker());
871 lockdep_assert_held(&ctx->uring_lock);
873 __io_cq_lock(ctx);
874 posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
875 ctx->submit_state.cq_flush = true;
876 __io_cq_unlock_post(ctx);
877 return posted;
880 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
882 struct io_ring_ctx *ctx = req->ctx;
885 * All execution paths but io-wq use the deferred completions by
886 * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
888 if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
889 return;
892 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
893 * the submitter task context, IOPOLL protects with uring_lock.
895 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL)) {
896 req->io_task_work.func = io_req_task_complete;
897 io_req_task_work_add(req);
898 return;
901 io_cq_lock(ctx);
902 if (!(req->flags & REQ_F_CQE_SKIP)) {
903 if (!io_fill_cqe_req(ctx, req))
904 io_req_cqe_overflow(req);
906 io_cq_unlock_post(ctx);
909 * We don't free the request here because we know it's called from
910 * io-wq only, which holds a reference, so it cannot be the last put.
912 req_ref_put(req);
915 void io_req_defer_failed(struct io_kiocb *req, s32 res)
916 __must_hold(&ctx->uring_lock)
918 const struct io_cold_def *def = &io_cold_defs[req->opcode];
920 lockdep_assert_held(&req->ctx->uring_lock);
922 req_set_fail(req);
923 io_req_set_res(req, res, io_put_kbuf(req, res, IO_URING_F_UNLOCKED));
924 if (def->fail)
925 def->fail(req);
926 io_req_complete_defer(req);
930 * Don't initialise the fields below on every allocation, but do that in
931 * advance and keep them valid across allocations.
933 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
935 req->ctx = ctx;
936 req->buf_node = NULL;
937 req->file_node = NULL;
938 req->link = NULL;
939 req->async_data = NULL;
940 /* not necessary, but safer to zero */
941 memset(&req->cqe, 0, sizeof(req->cqe));
942 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
946 * A request might get retired back into the request caches even before opcode
947 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
948 * Because of that, io_alloc_req() should be called only under ->uring_lock
949 * and with extra caution to not get a request that is still worked on.
951 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
952 __must_hold(&ctx->uring_lock)
954 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
955 void *reqs[IO_REQ_ALLOC_BATCH];
956 int ret;
958 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
961 * Bulk alloc is all-or-nothing. If we fail to get a batch,
962 * retry single alloc to be on the safe side.
964 if (unlikely(ret <= 0)) {
965 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
966 if (!reqs[0])
967 return false;
968 ret = 1;
971 percpu_ref_get_many(&ctx->refs, ret);
972 while (ret--) {
973 struct io_kiocb *req = reqs[ret];
975 io_preinit_req(req, ctx);
976 io_req_add_to_cache(req, ctx);
978 return true;
981 __cold void io_free_req(struct io_kiocb *req)
983 /* refs were already put, restore them for io_req_task_complete() */
984 req->flags &= ~REQ_F_REFCOUNT;
985 /* we only want to free it, don't post CQEs */
986 req->flags |= REQ_F_CQE_SKIP;
987 req->io_task_work.func = io_req_task_complete;
988 io_req_task_work_add(req);
991 static void __io_req_find_next_prep(struct io_kiocb *req)
993 struct io_ring_ctx *ctx = req->ctx;
995 spin_lock(&ctx->completion_lock);
996 io_disarm_next(req);
997 spin_unlock(&ctx->completion_lock);
1000 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1002 struct io_kiocb *nxt;
1005 * If LINK is set, we have dependent requests in this chain. If we
1006 * didn't fail this request, queue the first one up, moving any other
1007 * dependencies to the next request. In case of failure, fail the rest
1008 * of the chain.
1010 if (unlikely(req->flags & IO_DISARM_MASK))
1011 __io_req_find_next_prep(req);
1012 nxt = req->link;
1013 req->link = NULL;
1014 return nxt;
1017 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
1019 if (!ctx)
1020 return;
1021 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1022 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1024 io_submit_flush_completions(ctx);
1025 mutex_unlock(&ctx->uring_lock);
1026 percpu_ref_put(&ctx->refs);
1030 * Run queued task_work, returning the number of entries processed in *count.
1031 * If more entries than max_entries are available, stop processing once this
1032 * is reached and return the rest of the list.
1034 struct llist_node *io_handle_tw_list(struct llist_node *node,
1035 unsigned int *count,
1036 unsigned int max_entries)
1038 struct io_ring_ctx *ctx = NULL;
1039 struct io_tw_state ts = { };
1041 do {
1042 struct llist_node *next = node->next;
1043 struct io_kiocb *req = container_of(node, struct io_kiocb,
1044 io_task_work.node);
1046 if (req->ctx != ctx) {
1047 ctx_flush_and_put(ctx, &ts);
1048 ctx = req->ctx;
1049 mutex_lock(&ctx->uring_lock);
1050 percpu_ref_get(&ctx->refs);
1052 INDIRECT_CALL_2(req->io_task_work.func,
1053 io_poll_task_func, io_req_rw_complete,
1054 req, &ts);
1055 node = next;
1056 (*count)++;
1057 if (unlikely(need_resched())) {
1058 ctx_flush_and_put(ctx, &ts);
1059 ctx = NULL;
1060 cond_resched();
1062 } while (node && *count < max_entries);
1064 ctx_flush_and_put(ctx, &ts);
1065 return node;
1068 static __cold void __io_fallback_tw(struct llist_node *node, bool sync)
1070 struct io_ring_ctx *last_ctx = NULL;
1071 struct io_kiocb *req;
1073 while (node) {
1074 req = container_of(node, struct io_kiocb, io_task_work.node);
1075 node = node->next;
1076 if (sync && last_ctx != req->ctx) {
1077 if (last_ctx) {
1078 flush_delayed_work(&last_ctx->fallback_work);
1079 percpu_ref_put(&last_ctx->refs);
1081 last_ctx = req->ctx;
1082 percpu_ref_get(&last_ctx->refs);
1084 if (llist_add(&req->io_task_work.node,
1085 &req->ctx->fallback_llist))
1086 schedule_delayed_work(&req->ctx->fallback_work, 1);
1089 if (last_ctx) {
1090 flush_delayed_work(&last_ctx->fallback_work);
1091 percpu_ref_put(&last_ctx->refs);
1095 static void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1097 struct llist_node *node = llist_del_all(&tctx->task_list);
1099 __io_fallback_tw(node, sync);
1102 struct llist_node *tctx_task_work_run(struct io_uring_task *tctx,
1103 unsigned int max_entries,
1104 unsigned int *count)
1106 struct llist_node *node;
1108 if (unlikely(current->flags & PF_EXITING)) {
1109 io_fallback_tw(tctx, true);
1110 return NULL;
1113 node = llist_del_all(&tctx->task_list);
1114 if (node) {
1115 node = llist_reverse_order(node);
1116 node = io_handle_tw_list(node, count, max_entries);
1119 /* relaxed read is enough as only the task itself sets ->in_cancel */
1120 if (unlikely(atomic_read(&tctx->in_cancel)))
1121 io_uring_drop_tctx_refs(current);
1123 trace_io_uring_task_work_run(tctx, *count);
1124 return node;
1127 void tctx_task_work(struct callback_head *cb)
1129 struct io_uring_task *tctx;
1130 struct llist_node *ret;
1131 unsigned int count = 0;
1133 tctx = container_of(cb, struct io_uring_task, task_work);
1134 ret = tctx_task_work_run(tctx, UINT_MAX, &count);
1135 /* can't happen */
1136 WARN_ON_ONCE(ret);
1139 static inline void io_req_local_work_add(struct io_kiocb *req,
1140 struct io_ring_ctx *ctx,
1141 unsigned flags)
1143 unsigned nr_wait, nr_tw, nr_tw_prev;
1144 struct llist_node *head;
1146 /* See comment above IO_CQ_WAKE_INIT */
1147 BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
1150 * We don't know how many reuqests is there in the link and whether
1151 * they can even be queued lazily, fall back to non-lazy.
1153 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1154 flags &= ~IOU_F_TWQ_LAZY_WAKE;
1156 guard(rcu)();
1158 head = READ_ONCE(ctx->work_llist.first);
1159 do {
1160 nr_tw_prev = 0;
1161 if (head) {
1162 struct io_kiocb *first_req = container_of(head,
1163 struct io_kiocb,
1164 io_task_work.node);
1166 * Might be executed at any moment, rely on
1167 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1169 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1173 * Theoretically, it can overflow, but that's fine as one of
1174 * previous adds should've tried to wake the task.
1176 nr_tw = nr_tw_prev + 1;
1177 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1178 nr_tw = IO_CQ_WAKE_FORCE;
1180 req->nr_tw = nr_tw;
1181 req->io_task_work.node.next = head;
1182 } while (!try_cmpxchg(&ctx->work_llist.first, &head,
1183 &req->io_task_work.node));
1186 * cmpxchg implies a full barrier, which pairs with the barrier
1187 * in set_current_state() on the io_cqring_wait() side. It's used
1188 * to ensure that either we see updated ->cq_wait_nr, or waiters
1189 * going to sleep will observe the work added to the list, which
1190 * is similar to the wait/wawke task state sync.
1193 if (!head) {
1194 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1195 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1196 if (ctx->has_evfd)
1197 io_eventfd_signal(ctx);
1200 nr_wait = atomic_read(&ctx->cq_wait_nr);
1201 /* not enough or no one is waiting */
1202 if (nr_tw < nr_wait)
1203 return;
1204 /* the previous add has already woken it up */
1205 if (nr_tw_prev >= nr_wait)
1206 return;
1207 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1210 static void io_req_normal_work_add(struct io_kiocb *req)
1212 struct io_uring_task *tctx = req->tctx;
1213 struct io_ring_ctx *ctx = req->ctx;
1215 /* task_work already pending, we're done */
1216 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1217 return;
1219 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1220 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1222 /* SQPOLL doesn't need the task_work added, it'll run it itself */
1223 if (ctx->flags & IORING_SETUP_SQPOLL) {
1224 struct io_sq_data *sqd = ctx->sq_data;
1226 if (sqd->thread)
1227 __set_notify_signal(sqd->thread);
1228 return;
1231 if (likely(!task_work_add(tctx->task, &tctx->task_work, ctx->notify_method)))
1232 return;
1234 io_fallback_tw(tctx, false);
1237 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1239 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN)
1240 io_req_local_work_add(req, req->ctx, flags);
1241 else
1242 io_req_normal_work_add(req);
1245 void io_req_task_work_add_remote(struct io_kiocb *req, struct io_ring_ctx *ctx,
1246 unsigned flags)
1248 if (WARN_ON_ONCE(!(ctx->flags & IORING_SETUP_DEFER_TASKRUN)))
1249 return;
1250 io_req_local_work_add(req, ctx, flags);
1253 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1255 struct llist_node *node = llist_del_all(&ctx->work_llist);
1257 __io_fallback_tw(node, false);
1260 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1261 int min_events)
1263 if (llist_empty(&ctx->work_llist))
1264 return false;
1265 if (events < min_events)
1266 return true;
1267 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1268 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1269 return false;
1272 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1273 int min_events)
1275 struct llist_node *node;
1276 unsigned int loops = 0;
1277 int ret = 0;
1279 if (WARN_ON_ONCE(ctx->submitter_task != current))
1280 return -EEXIST;
1281 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1282 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1283 again:
1285 * llists are in reverse order, flip it back the right way before
1286 * running the pending items.
1288 node = llist_reverse_order(llist_del_all(&ctx->work_llist));
1289 while (node) {
1290 struct llist_node *next = node->next;
1291 struct io_kiocb *req = container_of(node, struct io_kiocb,
1292 io_task_work.node);
1293 INDIRECT_CALL_2(req->io_task_work.func,
1294 io_poll_task_func, io_req_rw_complete,
1295 req, ts);
1296 ret++;
1297 node = next;
1299 loops++;
1301 if (io_run_local_work_continue(ctx, ret, min_events))
1302 goto again;
1303 io_submit_flush_completions(ctx);
1304 if (io_run_local_work_continue(ctx, ret, min_events))
1305 goto again;
1307 trace_io_uring_local_work_run(ctx, ret, loops);
1308 return ret;
1311 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1312 int min_events)
1314 struct io_tw_state ts = {};
1316 if (llist_empty(&ctx->work_llist))
1317 return 0;
1318 return __io_run_local_work(ctx, &ts, min_events);
1321 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
1323 struct io_tw_state ts = {};
1324 int ret;
1326 mutex_lock(&ctx->uring_lock);
1327 ret = __io_run_local_work(ctx, &ts, min_events);
1328 mutex_unlock(&ctx->uring_lock);
1329 return ret;
1332 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
1334 io_tw_lock(req->ctx, ts);
1335 io_req_defer_failed(req, req->cqe.res);
1338 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
1340 io_tw_lock(req->ctx, ts);
1341 if (unlikely(io_should_terminate_tw()))
1342 io_req_defer_failed(req, -EFAULT);
1343 else if (req->flags & REQ_F_FORCE_ASYNC)
1344 io_queue_iowq(req);
1345 else
1346 io_queue_sqe(req);
1349 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1351 io_req_set_res(req, ret, 0);
1352 req->io_task_work.func = io_req_task_cancel;
1353 io_req_task_work_add(req);
1356 void io_req_task_queue(struct io_kiocb *req)
1358 req->io_task_work.func = io_req_task_submit;
1359 io_req_task_work_add(req);
1362 void io_queue_next(struct io_kiocb *req)
1364 struct io_kiocb *nxt = io_req_find_next(req);
1366 if (nxt)
1367 io_req_task_queue(nxt);
1370 static void io_free_batch_list(struct io_ring_ctx *ctx,
1371 struct io_wq_work_node *node)
1372 __must_hold(&ctx->uring_lock)
1374 do {
1375 struct io_kiocb *req = container_of(node, struct io_kiocb,
1376 comp_list);
1378 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1379 if (req->flags & REQ_F_REFCOUNT) {
1380 node = req->comp_list.next;
1381 if (!req_ref_put_and_test(req))
1382 continue;
1384 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1385 struct async_poll *apoll = req->apoll;
1387 if (apoll->double_poll)
1388 kfree(apoll->double_poll);
1389 if (!io_alloc_cache_put(&ctx->apoll_cache, apoll))
1390 kfree(apoll);
1391 req->flags &= ~REQ_F_POLLED;
1393 if (req->flags & IO_REQ_LINK_FLAGS)
1394 io_queue_next(req);
1395 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1396 io_clean_op(req);
1398 io_put_file(req);
1399 io_req_put_rsrc_nodes(req);
1400 io_put_task(req);
1402 node = req->comp_list.next;
1403 io_req_add_to_cache(req, ctx);
1404 } while (node);
1407 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1408 __must_hold(&ctx->uring_lock)
1410 struct io_submit_state *state = &ctx->submit_state;
1411 struct io_wq_work_node *node;
1413 __io_cq_lock(ctx);
1414 __wq_list_for_each(node, &state->compl_reqs) {
1415 struct io_kiocb *req = container_of(node, struct io_kiocb,
1416 comp_list);
1418 if (!(req->flags & REQ_F_CQE_SKIP) &&
1419 unlikely(!io_fill_cqe_req(ctx, req))) {
1420 if (ctx->lockless_cq) {
1421 spin_lock(&ctx->completion_lock);
1422 io_req_cqe_overflow(req);
1423 spin_unlock(&ctx->completion_lock);
1424 } else {
1425 io_req_cqe_overflow(req);
1429 __io_cq_unlock_post(ctx);
1431 if (!wq_list_empty(&state->compl_reqs)) {
1432 io_free_batch_list(ctx, state->compl_reqs.first);
1433 INIT_WQ_LIST(&state->compl_reqs);
1435 ctx->submit_state.cq_flush = false;
1438 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1440 /* See comment at the top of this file */
1441 smp_rmb();
1442 return __io_cqring_events(ctx);
1446 * We can't just wait for polled events to come to us, we have to actively
1447 * find and complete them.
1449 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1451 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1452 return;
1454 mutex_lock(&ctx->uring_lock);
1455 while (!wq_list_empty(&ctx->iopoll_list)) {
1456 /* let it sleep and repeat later if can't complete a request */
1457 if (io_do_iopoll(ctx, true) == 0)
1458 break;
1460 * Ensure we allow local-to-the-cpu processing to take place,
1461 * in this case we need to ensure that we reap all events.
1462 * Also let task_work, etc. to progress by releasing the mutex
1464 if (need_resched()) {
1465 mutex_unlock(&ctx->uring_lock);
1466 cond_resched();
1467 mutex_lock(&ctx->uring_lock);
1470 mutex_unlock(&ctx->uring_lock);
1473 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1475 unsigned int nr_events = 0;
1476 unsigned long check_cq;
1478 lockdep_assert_held(&ctx->uring_lock);
1480 if (!io_allowed_run_tw(ctx))
1481 return -EEXIST;
1483 check_cq = READ_ONCE(ctx->check_cq);
1484 if (unlikely(check_cq)) {
1485 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1486 __io_cqring_overflow_flush(ctx, false);
1488 * Similarly do not spin if we have not informed the user of any
1489 * dropped CQE.
1491 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1492 return -EBADR;
1495 * Don't enter poll loop if we already have events pending.
1496 * If we do, we can potentially be spinning for commands that
1497 * already triggered a CQE (eg in error).
1499 if (io_cqring_events(ctx))
1500 return 0;
1502 do {
1503 int ret = 0;
1506 * If a submit got punted to a workqueue, we can have the
1507 * application entering polling for a command before it gets
1508 * issued. That app will hold the uring_lock for the duration
1509 * of the poll right here, so we need to take a breather every
1510 * now and then to ensure that the issue has a chance to add
1511 * the poll to the issued list. Otherwise we can spin here
1512 * forever, while the workqueue is stuck trying to acquire the
1513 * very same mutex.
1515 if (wq_list_empty(&ctx->iopoll_list) ||
1516 io_task_work_pending(ctx)) {
1517 u32 tail = ctx->cached_cq_tail;
1519 (void) io_run_local_work_locked(ctx, min);
1521 if (task_work_pending(current) ||
1522 wq_list_empty(&ctx->iopoll_list)) {
1523 mutex_unlock(&ctx->uring_lock);
1524 io_run_task_work();
1525 mutex_lock(&ctx->uring_lock);
1527 /* some requests don't go through iopoll_list */
1528 if (tail != ctx->cached_cq_tail ||
1529 wq_list_empty(&ctx->iopoll_list))
1530 break;
1532 ret = io_do_iopoll(ctx, !min);
1533 if (unlikely(ret < 0))
1534 return ret;
1536 if (task_sigpending(current))
1537 return -EINTR;
1538 if (need_resched())
1539 break;
1541 nr_events += ret;
1542 } while (nr_events < min);
1544 return 0;
1547 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
1549 io_req_complete_defer(req);
1553 * After the iocb has been issued, it's safe to be found on the poll list.
1554 * Adding the kiocb to the list AFTER submission ensures that we don't
1555 * find it from a io_do_iopoll() thread before the issuer is done
1556 * accessing the kiocb cookie.
1558 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1560 struct io_ring_ctx *ctx = req->ctx;
1561 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1563 /* workqueue context doesn't hold uring_lock, grab it now */
1564 if (unlikely(needs_lock))
1565 mutex_lock(&ctx->uring_lock);
1568 * Track whether we have multiple files in our lists. This will impact
1569 * how we do polling eventually, not spinning if we're on potentially
1570 * different devices.
1572 if (wq_list_empty(&ctx->iopoll_list)) {
1573 ctx->poll_multi_queue = false;
1574 } else if (!ctx->poll_multi_queue) {
1575 struct io_kiocb *list_req;
1577 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1578 comp_list);
1579 if (list_req->file != req->file)
1580 ctx->poll_multi_queue = true;
1584 * For fast devices, IO may have already completed. If it has, add
1585 * it to the front so we find it first.
1587 if (READ_ONCE(req->iopoll_completed))
1588 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1589 else
1590 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1592 if (unlikely(needs_lock)) {
1594 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1595 * in sq thread task context or in io worker task context. If
1596 * current task context is sq thread, we don't need to check
1597 * whether should wake up sq thread.
1599 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1600 wq_has_sleeper(&ctx->sq_data->wait))
1601 wake_up(&ctx->sq_data->wait);
1603 mutex_unlock(&ctx->uring_lock);
1607 io_req_flags_t io_file_get_flags(struct file *file)
1609 io_req_flags_t res = 0;
1611 if (S_ISREG(file_inode(file)->i_mode))
1612 res |= REQ_F_ISREG;
1613 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1614 res |= REQ_F_SUPPORT_NOWAIT;
1615 return res;
1618 bool io_alloc_async_data(struct io_kiocb *req)
1620 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1622 WARN_ON_ONCE(!def->async_size);
1623 req->async_data = kmalloc(def->async_size, GFP_KERNEL);
1624 if (req->async_data) {
1625 req->flags |= REQ_F_ASYNC_DATA;
1626 return false;
1628 return true;
1631 static u32 io_get_sequence(struct io_kiocb *req)
1633 u32 seq = req->ctx->cached_sq_head;
1634 struct io_kiocb *cur;
1636 /* need original cached_sq_head, but it was increased for each req */
1637 io_for_each_link(cur, req)
1638 seq--;
1639 return seq;
1642 static __cold void io_drain_req(struct io_kiocb *req)
1643 __must_hold(&ctx->uring_lock)
1645 struct io_ring_ctx *ctx = req->ctx;
1646 struct io_defer_entry *de;
1647 int ret;
1648 u32 seq = io_get_sequence(req);
1650 /* Still need defer if there is pending req in defer list. */
1651 spin_lock(&ctx->completion_lock);
1652 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1653 spin_unlock(&ctx->completion_lock);
1654 queue:
1655 ctx->drain_active = false;
1656 io_req_task_queue(req);
1657 return;
1659 spin_unlock(&ctx->completion_lock);
1661 io_prep_async_link(req);
1662 de = kmalloc(sizeof(*de), GFP_KERNEL);
1663 if (!de) {
1664 ret = -ENOMEM;
1665 io_req_defer_failed(req, ret);
1666 return;
1669 spin_lock(&ctx->completion_lock);
1670 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1671 spin_unlock(&ctx->completion_lock);
1672 kfree(de);
1673 goto queue;
1676 trace_io_uring_defer(req);
1677 de->req = req;
1678 de->seq = seq;
1679 list_add_tail(&de->list, &ctx->defer_list);
1680 spin_unlock(&ctx->completion_lock);
1683 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1684 unsigned int issue_flags)
1686 if (req->file || !def->needs_file)
1687 return true;
1689 if (req->flags & REQ_F_FIXED_FILE)
1690 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1691 else
1692 req->file = io_file_get_normal(req, req->cqe.fd);
1694 return !!req->file;
1697 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1699 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1700 const struct cred *creds = NULL;
1701 int ret;
1703 if (unlikely(!io_assign_file(req, def, issue_flags)))
1704 return -EBADF;
1706 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1707 creds = override_creds(req->creds);
1709 if (!def->audit_skip)
1710 audit_uring_entry(req->opcode);
1712 ret = def->issue(req, issue_flags);
1714 if (!def->audit_skip)
1715 audit_uring_exit(!ret, ret);
1717 if (creds)
1718 revert_creds(creds);
1720 if (ret == IOU_OK) {
1721 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1722 io_req_complete_defer(req);
1723 else
1724 io_req_complete_post(req, issue_flags);
1726 return 0;
1729 if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1730 ret = 0;
1731 io_arm_ltimeout(req);
1733 /* If the op doesn't have a file, we're not polling for it */
1734 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1735 io_iopoll_req_issued(req, issue_flags);
1737 return ret;
1740 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
1742 io_tw_lock(req->ctx, ts);
1743 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1744 IO_URING_F_COMPLETE_DEFER);
1747 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1749 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1750 struct io_kiocb *nxt = NULL;
1752 if (req_ref_put_and_test(req)) {
1753 if (req->flags & IO_REQ_LINK_FLAGS)
1754 nxt = io_req_find_next(req);
1755 io_free_req(req);
1757 return nxt ? &nxt->work : NULL;
1760 void io_wq_submit_work(struct io_wq_work *work)
1762 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1763 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1764 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1765 bool needs_poll = false;
1766 int ret = 0, err = -ECANCELED;
1768 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1769 if (!(req->flags & REQ_F_REFCOUNT))
1770 __io_req_set_refcount(req, 2);
1771 else
1772 req_ref_get(req);
1774 io_arm_ltimeout(req);
1776 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1777 if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
1778 fail:
1779 io_req_task_queue_fail(req, err);
1780 return;
1782 if (!io_assign_file(req, def, issue_flags)) {
1783 err = -EBADF;
1784 atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1785 goto fail;
1789 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1790 * submitter task context. Final request completions are handed to the
1791 * right context, however this is not the case of auxiliary CQEs,
1792 * which is the main mean of operation for multishot requests.
1793 * Don't allow any multishot execution from io-wq. It's more restrictive
1794 * than necessary and also cleaner.
1796 if (req->flags & REQ_F_APOLL_MULTISHOT) {
1797 err = -EBADFD;
1798 if (!io_file_can_poll(req))
1799 goto fail;
1800 if (req->file->f_flags & O_NONBLOCK ||
1801 req->file->f_mode & FMODE_NOWAIT) {
1802 err = -ECANCELED;
1803 if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1804 goto fail;
1805 return;
1806 } else {
1807 req->flags &= ~REQ_F_APOLL_MULTISHOT;
1811 if (req->flags & REQ_F_FORCE_ASYNC) {
1812 bool opcode_poll = def->pollin || def->pollout;
1814 if (opcode_poll && io_file_can_poll(req)) {
1815 needs_poll = true;
1816 issue_flags |= IO_URING_F_NONBLOCK;
1820 do {
1821 ret = io_issue_sqe(req, issue_flags);
1822 if (ret != -EAGAIN)
1823 break;
1826 * If REQ_F_NOWAIT is set, then don't wait or retry with
1827 * poll. -EAGAIN is final for that case.
1829 if (req->flags & REQ_F_NOWAIT)
1830 break;
1833 * We can get EAGAIN for iopolled IO even though we're
1834 * forcing a sync submission from here, since we can't
1835 * wait for request slots on the block side.
1837 if (!needs_poll) {
1838 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1839 break;
1840 if (io_wq_worker_stopped())
1841 break;
1842 cond_resched();
1843 continue;
1846 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1847 return;
1848 /* aborted or ready, in either case retry blocking */
1849 needs_poll = false;
1850 issue_flags &= ~IO_URING_F_NONBLOCK;
1851 } while (1);
1853 /* avoid locking problems by failing it from a clean context */
1854 if (ret)
1855 io_req_task_queue_fail(req, ret);
1858 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1859 unsigned int issue_flags)
1861 struct io_ring_ctx *ctx = req->ctx;
1862 struct io_rsrc_node *node;
1863 struct file *file = NULL;
1865 io_ring_submit_lock(ctx, issue_flags);
1866 node = io_rsrc_node_lookup(&ctx->file_table.data, fd);
1867 if (node) {
1868 io_req_assign_rsrc_node(&req->file_node, node);
1869 req->flags |= io_slot_flags(node);
1870 file = io_slot_file(node);
1872 io_ring_submit_unlock(ctx, issue_flags);
1873 return file;
1876 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1878 struct file *file = fget(fd);
1880 trace_io_uring_file_get(req, fd);
1882 /* we don't allow fixed io_uring files */
1883 if (file && io_is_uring_fops(file))
1884 io_req_track_inflight(req);
1885 return file;
1888 static void io_queue_async(struct io_kiocb *req, int ret)
1889 __must_hold(&req->ctx->uring_lock)
1891 struct io_kiocb *linked_timeout;
1893 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1894 io_req_defer_failed(req, ret);
1895 return;
1898 linked_timeout = io_prep_linked_timeout(req);
1900 switch (io_arm_poll_handler(req, 0)) {
1901 case IO_APOLL_READY:
1902 io_kbuf_recycle(req, 0);
1903 io_req_task_queue(req);
1904 break;
1905 case IO_APOLL_ABORTED:
1906 io_kbuf_recycle(req, 0);
1907 io_queue_iowq(req);
1908 break;
1909 case IO_APOLL_OK:
1910 break;
1913 if (linked_timeout)
1914 io_queue_linked_timeout(linked_timeout);
1917 static inline void io_queue_sqe(struct io_kiocb *req)
1918 __must_hold(&req->ctx->uring_lock)
1920 int ret;
1922 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
1925 * We async punt it if the file wasn't marked NOWAIT, or if the file
1926 * doesn't support non-blocking read/write attempts
1928 if (unlikely(ret))
1929 io_queue_async(req, ret);
1932 static void io_queue_sqe_fallback(struct io_kiocb *req)
1933 __must_hold(&req->ctx->uring_lock)
1935 if (unlikely(req->flags & REQ_F_FAIL)) {
1937 * We don't submit, fail them all, for that replace hardlinks
1938 * with normal links. Extra REQ_F_LINK is tolerated.
1940 req->flags &= ~REQ_F_HARDLINK;
1941 req->flags |= REQ_F_LINK;
1942 io_req_defer_failed(req, req->cqe.res);
1943 } else {
1944 if (unlikely(req->ctx->drain_active))
1945 io_drain_req(req);
1946 else
1947 io_queue_iowq(req);
1952 * Check SQE restrictions (opcode and flags).
1954 * Returns 'true' if SQE is allowed, 'false' otherwise.
1956 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
1957 struct io_kiocb *req,
1958 unsigned int sqe_flags)
1960 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
1961 return false;
1963 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
1964 ctx->restrictions.sqe_flags_required)
1965 return false;
1967 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
1968 ctx->restrictions.sqe_flags_required))
1969 return false;
1971 return true;
1974 static void io_init_req_drain(struct io_kiocb *req)
1976 struct io_ring_ctx *ctx = req->ctx;
1977 struct io_kiocb *head = ctx->submit_state.link.head;
1979 ctx->drain_active = true;
1980 if (head) {
1982 * If we need to drain a request in the middle of a link, drain
1983 * the head request and the next request/link after the current
1984 * link. Considering sequential execution of links,
1985 * REQ_F_IO_DRAIN will be maintained for every request of our
1986 * link.
1988 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1989 ctx->drain_next = true;
1993 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
1995 /* ensure per-opcode data is cleared if we fail before prep */
1996 memset(&req->cmd.data, 0, sizeof(req->cmd.data));
1997 return err;
2000 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2001 const struct io_uring_sqe *sqe)
2002 __must_hold(&ctx->uring_lock)
2004 const struct io_issue_def *def;
2005 unsigned int sqe_flags;
2006 int personality;
2007 u8 opcode;
2009 /* req is partially pre-initialised, see io_preinit_req() */
2010 req->opcode = opcode = READ_ONCE(sqe->opcode);
2011 /* same numerical values with corresponding REQ_F_*, safe to copy */
2012 sqe_flags = READ_ONCE(sqe->flags);
2013 req->flags = (__force io_req_flags_t) sqe_flags;
2014 req->cqe.user_data = READ_ONCE(sqe->user_data);
2015 req->file = NULL;
2016 req->tctx = current->io_uring;
2017 req->cancel_seq_set = false;
2019 if (unlikely(opcode >= IORING_OP_LAST)) {
2020 req->opcode = 0;
2021 return io_init_fail_req(req, -EINVAL);
2023 def = &io_issue_defs[opcode];
2024 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2025 /* enforce forwards compatibility on users */
2026 if (sqe_flags & ~SQE_VALID_FLAGS)
2027 return io_init_fail_req(req, -EINVAL);
2028 if (sqe_flags & IOSQE_BUFFER_SELECT) {
2029 if (!def->buffer_select)
2030 return io_init_fail_req(req, -EOPNOTSUPP);
2031 req->buf_index = READ_ONCE(sqe->buf_group);
2033 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2034 ctx->drain_disabled = true;
2035 if (sqe_flags & IOSQE_IO_DRAIN) {
2036 if (ctx->drain_disabled)
2037 return io_init_fail_req(req, -EOPNOTSUPP);
2038 io_init_req_drain(req);
2041 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2042 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2043 return io_init_fail_req(req, -EACCES);
2044 /* knock it to the slow queue path, will be drained there */
2045 if (ctx->drain_active)
2046 req->flags |= REQ_F_FORCE_ASYNC;
2047 /* if there is no link, we're at "next" request and need to drain */
2048 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2049 ctx->drain_next = false;
2050 ctx->drain_active = true;
2051 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2055 if (!def->ioprio && sqe->ioprio)
2056 return io_init_fail_req(req, -EINVAL);
2057 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2058 return io_init_fail_req(req, -EINVAL);
2060 if (def->needs_file) {
2061 struct io_submit_state *state = &ctx->submit_state;
2063 req->cqe.fd = READ_ONCE(sqe->fd);
2066 * Plug now if we have more than 2 IO left after this, and the
2067 * target is potentially a read/write to block based storage.
2069 if (state->need_plug && def->plug) {
2070 state->plug_started = true;
2071 state->need_plug = false;
2072 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2076 personality = READ_ONCE(sqe->personality);
2077 if (personality) {
2078 int ret;
2080 req->creds = xa_load(&ctx->personalities, personality);
2081 if (!req->creds)
2082 return io_init_fail_req(req, -EINVAL);
2083 get_cred(req->creds);
2084 ret = security_uring_override_creds(req->creds);
2085 if (ret) {
2086 put_cred(req->creds);
2087 return io_init_fail_req(req, ret);
2089 req->flags |= REQ_F_CREDS;
2092 return def->prep(req, sqe);
2095 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2096 struct io_kiocb *req, int ret)
2098 struct io_ring_ctx *ctx = req->ctx;
2099 struct io_submit_link *link = &ctx->submit_state.link;
2100 struct io_kiocb *head = link->head;
2102 trace_io_uring_req_failed(sqe, req, ret);
2105 * Avoid breaking links in the middle as it renders links with SQPOLL
2106 * unusable. Instead of failing eagerly, continue assembling the link if
2107 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2108 * should find the flag and handle the rest.
2110 req_fail_link_node(req, ret);
2111 if (head && !(head->flags & REQ_F_FAIL))
2112 req_fail_link_node(head, -ECANCELED);
2114 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2115 if (head) {
2116 link->last->link = req;
2117 link->head = NULL;
2118 req = head;
2120 io_queue_sqe_fallback(req);
2121 return ret;
2124 if (head)
2125 link->last->link = req;
2126 else
2127 link->head = req;
2128 link->last = req;
2129 return 0;
2132 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2133 const struct io_uring_sqe *sqe)
2134 __must_hold(&ctx->uring_lock)
2136 struct io_submit_link *link = &ctx->submit_state.link;
2137 int ret;
2139 ret = io_init_req(ctx, req, sqe);
2140 if (unlikely(ret))
2141 return io_submit_fail_init(sqe, req, ret);
2143 trace_io_uring_submit_req(req);
2146 * If we already have a head request, queue this one for async
2147 * submittal once the head completes. If we don't have a head but
2148 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2149 * submitted sync once the chain is complete. If none of those
2150 * conditions are true (normal request), then just queue it.
2152 if (unlikely(link->head)) {
2153 trace_io_uring_link(req, link->last);
2154 link->last->link = req;
2155 link->last = req;
2157 if (req->flags & IO_REQ_LINK_FLAGS)
2158 return 0;
2159 /* last request of the link, flush it */
2160 req = link->head;
2161 link->head = NULL;
2162 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2163 goto fallback;
2165 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2166 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2167 if (req->flags & IO_REQ_LINK_FLAGS) {
2168 link->head = req;
2169 link->last = req;
2170 } else {
2171 fallback:
2172 io_queue_sqe_fallback(req);
2174 return 0;
2177 io_queue_sqe(req);
2178 return 0;
2182 * Batched submission is done, ensure local IO is flushed out.
2184 static void io_submit_state_end(struct io_ring_ctx *ctx)
2186 struct io_submit_state *state = &ctx->submit_state;
2188 if (unlikely(state->link.head))
2189 io_queue_sqe_fallback(state->link.head);
2190 /* flush only after queuing links as they can generate completions */
2191 io_submit_flush_completions(ctx);
2192 if (state->plug_started)
2193 blk_finish_plug(&state->plug);
2197 * Start submission side cache.
2199 static void io_submit_state_start(struct io_submit_state *state,
2200 unsigned int max_ios)
2202 state->plug_started = false;
2203 state->need_plug = max_ios > 2;
2204 state->submit_nr = max_ios;
2205 /* set only head, no need to init link_last in advance */
2206 state->link.head = NULL;
2209 static void io_commit_sqring(struct io_ring_ctx *ctx)
2211 struct io_rings *rings = ctx->rings;
2214 * Ensure any loads from the SQEs are done at this point,
2215 * since once we write the new head, the application could
2216 * write new data to them.
2218 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2222 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2223 * that is mapped by userspace. This means that care needs to be taken to
2224 * ensure that reads are stable, as we cannot rely on userspace always
2225 * being a good citizen. If members of the sqe are validated and then later
2226 * used, it's important that those reads are done through READ_ONCE() to
2227 * prevent a re-load down the line.
2229 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2231 unsigned mask = ctx->sq_entries - 1;
2232 unsigned head = ctx->cached_sq_head++ & mask;
2234 if (static_branch_unlikely(&io_key_has_sqarray) &&
2235 (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) {
2236 head = READ_ONCE(ctx->sq_array[head]);
2237 if (unlikely(head >= ctx->sq_entries)) {
2238 /* drop invalid entries */
2239 spin_lock(&ctx->completion_lock);
2240 ctx->cq_extra--;
2241 spin_unlock(&ctx->completion_lock);
2242 WRITE_ONCE(ctx->rings->sq_dropped,
2243 READ_ONCE(ctx->rings->sq_dropped) + 1);
2244 return false;
2246 head = array_index_nospec(head, ctx->sq_entries);
2250 * The cached sq head (or cq tail) serves two purposes:
2252 * 1) allows us to batch the cost of updating the user visible
2253 * head updates.
2254 * 2) allows the kernel side to track the head on its own, even
2255 * though the application is the one updating it.
2258 /* double index for 128-byte SQEs, twice as long */
2259 if (ctx->flags & IORING_SETUP_SQE128)
2260 head <<= 1;
2261 *sqe = &ctx->sq_sqes[head];
2262 return true;
2265 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2266 __must_hold(&ctx->uring_lock)
2268 unsigned int entries = io_sqring_entries(ctx);
2269 unsigned int left;
2270 int ret;
2272 if (unlikely(!entries))
2273 return 0;
2274 /* make sure SQ entry isn't read before tail */
2275 ret = left = min(nr, entries);
2276 io_get_task_refs(left);
2277 io_submit_state_start(&ctx->submit_state, left);
2279 do {
2280 const struct io_uring_sqe *sqe;
2281 struct io_kiocb *req;
2283 if (unlikely(!io_alloc_req(ctx, &req)))
2284 break;
2285 if (unlikely(!io_get_sqe(ctx, &sqe))) {
2286 io_req_add_to_cache(req, ctx);
2287 break;
2291 * Continue submitting even for sqe failure if the
2292 * ring was setup with IORING_SETUP_SUBMIT_ALL
2294 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2295 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2296 left--;
2297 break;
2299 } while (--left);
2301 if (unlikely(left)) {
2302 ret -= left;
2303 /* try again if it submitted nothing and can't allocate a req */
2304 if (!ret && io_req_cache_empty(ctx))
2305 ret = -EAGAIN;
2306 current->io_uring->cached_refs += left;
2309 io_submit_state_end(ctx);
2310 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2311 io_commit_sqring(ctx);
2312 return ret;
2315 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2316 int wake_flags, void *key)
2318 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2321 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2322 * the task, and the next invocation will do it.
2324 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2325 return autoremove_wake_function(curr, mode, wake_flags, key);
2326 return -1;
2329 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2331 if (!llist_empty(&ctx->work_llist)) {
2332 __set_current_state(TASK_RUNNING);
2333 if (io_run_local_work(ctx, INT_MAX) > 0)
2334 return 0;
2336 if (io_run_task_work() > 0)
2337 return 0;
2338 if (task_sigpending(current))
2339 return -EINTR;
2340 return 0;
2343 static bool current_pending_io(void)
2345 struct io_uring_task *tctx = current->io_uring;
2347 if (!tctx)
2348 return false;
2349 return percpu_counter_read_positive(&tctx->inflight);
2352 static enum hrtimer_restart io_cqring_timer_wakeup(struct hrtimer *timer)
2354 struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
2356 WRITE_ONCE(iowq->hit_timeout, 1);
2357 iowq->min_timeout = 0;
2358 wake_up_process(iowq->wq.private);
2359 return HRTIMER_NORESTART;
2363 * Doing min_timeout portion. If we saw any timeouts, events, or have work,
2364 * wake up. If not, and we have a normal timeout, switch to that and keep
2365 * sleeping.
2367 static enum hrtimer_restart io_cqring_min_timer_wakeup(struct hrtimer *timer)
2369 struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
2370 struct io_ring_ctx *ctx = iowq->ctx;
2372 /* no general timeout, or shorter (or equal), we are done */
2373 if (iowq->timeout == KTIME_MAX ||
2374 ktime_compare(iowq->min_timeout, iowq->timeout) >= 0)
2375 goto out_wake;
2376 /* work we may need to run, wake function will see if we need to wake */
2377 if (io_has_work(ctx))
2378 goto out_wake;
2379 /* got events since we started waiting, min timeout is done */
2380 if (iowq->cq_min_tail != READ_ONCE(ctx->rings->cq.tail))
2381 goto out_wake;
2382 /* if we have any events and min timeout expired, we're done */
2383 if (io_cqring_events(ctx))
2384 goto out_wake;
2387 * If using deferred task_work running and application is waiting on
2388 * more than one request, ensure we reset it now where we are switching
2389 * to normal sleeps. Any request completion post min_wait should wake
2390 * the task and return.
2392 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2393 atomic_set(&ctx->cq_wait_nr, 1);
2394 smp_mb();
2395 if (!llist_empty(&ctx->work_llist))
2396 goto out_wake;
2399 iowq->t.function = io_cqring_timer_wakeup;
2400 hrtimer_set_expires(timer, iowq->timeout);
2401 return HRTIMER_RESTART;
2402 out_wake:
2403 return io_cqring_timer_wakeup(timer);
2406 static int io_cqring_schedule_timeout(struct io_wait_queue *iowq,
2407 clockid_t clock_id, ktime_t start_time)
2409 ktime_t timeout;
2411 if (iowq->min_timeout) {
2412 timeout = ktime_add_ns(iowq->min_timeout, start_time);
2413 hrtimer_setup_on_stack(&iowq->t, io_cqring_min_timer_wakeup, clock_id,
2414 HRTIMER_MODE_ABS);
2415 } else {
2416 timeout = iowq->timeout;
2417 hrtimer_setup_on_stack(&iowq->t, io_cqring_timer_wakeup, clock_id,
2418 HRTIMER_MODE_ABS);
2421 hrtimer_set_expires_range_ns(&iowq->t, timeout, 0);
2422 hrtimer_start_expires(&iowq->t, HRTIMER_MODE_ABS);
2424 if (!READ_ONCE(iowq->hit_timeout))
2425 schedule();
2427 hrtimer_cancel(&iowq->t);
2428 destroy_hrtimer_on_stack(&iowq->t);
2429 __set_current_state(TASK_RUNNING);
2431 return READ_ONCE(iowq->hit_timeout) ? -ETIME : 0;
2434 static int __io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2435 struct io_wait_queue *iowq,
2436 ktime_t start_time)
2438 int ret = 0;
2441 * Mark us as being in io_wait if we have pending requests, so cpufreq
2442 * can take into account that the task is waiting for IO - turns out
2443 * to be important for low QD IO.
2445 if (current_pending_io())
2446 current->in_iowait = 1;
2447 if (iowq->timeout != KTIME_MAX || iowq->min_timeout)
2448 ret = io_cqring_schedule_timeout(iowq, ctx->clockid, start_time);
2449 else
2450 schedule();
2451 current->in_iowait = 0;
2452 return ret;
2455 /* If this returns > 0, the caller should retry */
2456 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2457 struct io_wait_queue *iowq,
2458 ktime_t start_time)
2460 if (unlikely(READ_ONCE(ctx->check_cq)))
2461 return 1;
2462 if (unlikely(!llist_empty(&ctx->work_llist)))
2463 return 1;
2464 if (unlikely(task_work_pending(current)))
2465 return 1;
2466 if (unlikely(task_sigpending(current)))
2467 return -EINTR;
2468 if (unlikely(io_should_wake(iowq)))
2469 return 0;
2471 return __io_cqring_wait_schedule(ctx, iowq, start_time);
2474 struct ext_arg {
2475 size_t argsz;
2476 struct timespec64 ts;
2477 const sigset_t __user *sig;
2478 ktime_t min_time;
2479 bool ts_set;
2483 * Wait until events become available, if we don't already have some. The
2484 * application must reap them itself, as they reside on the shared cq ring.
2486 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events, u32 flags,
2487 struct ext_arg *ext_arg)
2489 struct io_wait_queue iowq;
2490 struct io_rings *rings = ctx->rings;
2491 ktime_t start_time;
2492 int ret;
2494 if (!io_allowed_run_tw(ctx))
2495 return -EEXIST;
2496 if (!llist_empty(&ctx->work_llist))
2497 io_run_local_work(ctx, min_events);
2498 io_run_task_work();
2500 if (unlikely(test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)))
2501 io_cqring_do_overflow_flush(ctx);
2502 if (__io_cqring_events_user(ctx) >= min_events)
2503 return 0;
2505 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2506 iowq.wq.private = current;
2507 INIT_LIST_HEAD(&iowq.wq.entry);
2508 iowq.ctx = ctx;
2509 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2510 iowq.cq_min_tail = READ_ONCE(ctx->rings->cq.tail);
2511 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2512 iowq.hit_timeout = 0;
2513 iowq.min_timeout = ext_arg->min_time;
2514 iowq.timeout = KTIME_MAX;
2515 start_time = io_get_time(ctx);
2517 if (ext_arg->ts_set) {
2518 iowq.timeout = timespec64_to_ktime(ext_arg->ts);
2519 if (!(flags & IORING_ENTER_ABS_TIMER))
2520 iowq.timeout = ktime_add(iowq.timeout, start_time);
2523 if (ext_arg->sig) {
2524 #ifdef CONFIG_COMPAT
2525 if (in_compat_syscall())
2526 ret = set_compat_user_sigmask((const compat_sigset_t __user *)ext_arg->sig,
2527 ext_arg->argsz);
2528 else
2529 #endif
2530 ret = set_user_sigmask(ext_arg->sig, ext_arg->argsz);
2532 if (ret)
2533 return ret;
2536 io_napi_busy_loop(ctx, &iowq);
2538 trace_io_uring_cqring_wait(ctx, min_events);
2539 do {
2540 unsigned long check_cq;
2541 int nr_wait;
2543 /* if min timeout has been hit, don't reset wait count */
2544 if (!iowq.hit_timeout)
2545 nr_wait = (int) iowq.cq_tail -
2546 READ_ONCE(ctx->rings->cq.tail);
2547 else
2548 nr_wait = 1;
2550 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2551 atomic_set(&ctx->cq_wait_nr, nr_wait);
2552 set_current_state(TASK_INTERRUPTIBLE);
2553 } else {
2554 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2555 TASK_INTERRUPTIBLE);
2558 ret = io_cqring_wait_schedule(ctx, &iowq, start_time);
2559 __set_current_state(TASK_RUNNING);
2560 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
2563 * Run task_work after scheduling and before io_should_wake().
2564 * If we got woken because of task_work being processed, run it
2565 * now rather than let the caller do another wait loop.
2567 if (!llist_empty(&ctx->work_llist))
2568 io_run_local_work(ctx, nr_wait);
2569 io_run_task_work();
2572 * Non-local task_work will be run on exit to userspace, but
2573 * if we're using DEFER_TASKRUN, then we could have waited
2574 * with a timeout for a number of requests. If the timeout
2575 * hits, we could have some requests ready to process. Ensure
2576 * this break is _after_ we have run task_work, to avoid
2577 * deferring running potentially pending requests until the
2578 * next time we wait for events.
2580 if (ret < 0)
2581 break;
2583 check_cq = READ_ONCE(ctx->check_cq);
2584 if (unlikely(check_cq)) {
2585 /* let the caller flush overflows, retry */
2586 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2587 io_cqring_do_overflow_flush(ctx);
2588 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2589 ret = -EBADR;
2590 break;
2594 if (io_should_wake(&iowq)) {
2595 ret = 0;
2596 break;
2598 cond_resched();
2599 } while (1);
2601 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2602 finish_wait(&ctx->cq_wait, &iowq.wq);
2603 restore_saved_sigmask_unless(ret == -EINTR);
2605 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2608 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2609 size_t size)
2611 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2612 size);
2615 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2616 size_t size)
2618 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2619 size);
2622 static void io_rings_free(struct io_ring_ctx *ctx)
2624 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2625 io_pages_unmap(ctx->rings, &ctx->ring_pages, &ctx->n_ring_pages,
2626 true);
2627 io_pages_unmap(ctx->sq_sqes, &ctx->sqe_pages, &ctx->n_sqe_pages,
2628 true);
2629 } else {
2630 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
2631 ctx->n_ring_pages = 0;
2632 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
2633 ctx->n_sqe_pages = 0;
2634 vunmap(ctx->rings);
2635 vunmap(ctx->sq_sqes);
2638 ctx->rings = NULL;
2639 ctx->sq_sqes = NULL;
2642 unsigned long rings_size(unsigned int flags, unsigned int sq_entries,
2643 unsigned int cq_entries, size_t *sq_offset)
2645 struct io_rings *rings;
2646 size_t off, sq_array_size;
2648 off = struct_size(rings, cqes, cq_entries);
2649 if (off == SIZE_MAX)
2650 return SIZE_MAX;
2651 if (flags & IORING_SETUP_CQE32) {
2652 if (check_shl_overflow(off, 1, &off))
2653 return SIZE_MAX;
2656 #ifdef CONFIG_SMP
2657 off = ALIGN(off, SMP_CACHE_BYTES);
2658 if (off == 0)
2659 return SIZE_MAX;
2660 #endif
2662 if (flags & IORING_SETUP_NO_SQARRAY) {
2663 *sq_offset = SIZE_MAX;
2664 return off;
2667 *sq_offset = off;
2669 sq_array_size = array_size(sizeof(u32), sq_entries);
2670 if (sq_array_size == SIZE_MAX)
2671 return SIZE_MAX;
2673 if (check_add_overflow(off, sq_array_size, &off))
2674 return SIZE_MAX;
2676 return off;
2679 static void io_req_caches_free(struct io_ring_ctx *ctx)
2681 struct io_kiocb *req;
2682 int nr = 0;
2684 mutex_lock(&ctx->uring_lock);
2686 while (!io_req_cache_empty(ctx)) {
2687 req = io_extract_req(ctx);
2688 kmem_cache_free(req_cachep, req);
2689 nr++;
2691 if (nr)
2692 percpu_ref_put_many(&ctx->refs, nr);
2693 mutex_unlock(&ctx->uring_lock);
2696 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2698 io_sq_thread_finish(ctx);
2700 mutex_lock(&ctx->uring_lock);
2701 io_sqe_buffers_unregister(ctx);
2702 io_sqe_files_unregister(ctx);
2703 io_cqring_overflow_kill(ctx);
2704 io_eventfd_unregister(ctx);
2705 io_alloc_cache_free(&ctx->apoll_cache, kfree);
2706 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
2707 io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
2708 io_alloc_cache_free(&ctx->uring_cache, kfree);
2709 io_alloc_cache_free(&ctx->msg_cache, io_msg_cache_free);
2710 io_futex_cache_free(ctx);
2711 io_destroy_buffers(ctx);
2712 io_free_region(ctx, &ctx->param_region);
2713 mutex_unlock(&ctx->uring_lock);
2714 if (ctx->sq_creds)
2715 put_cred(ctx->sq_creds);
2716 if (ctx->submitter_task)
2717 put_task_struct(ctx->submitter_task);
2719 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2721 if (ctx->mm_account) {
2722 mmdrop(ctx->mm_account);
2723 ctx->mm_account = NULL;
2725 io_rings_free(ctx);
2727 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2728 static_branch_dec(&io_key_has_sqarray);
2730 percpu_ref_exit(&ctx->refs);
2731 free_uid(ctx->user);
2732 io_req_caches_free(ctx);
2733 if (ctx->hash_map)
2734 io_wq_put_hash(ctx->hash_map);
2735 io_napi_free(ctx);
2736 kvfree(ctx->cancel_table.hbs);
2737 xa_destroy(&ctx->io_bl_xa);
2738 kfree(ctx);
2741 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2743 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2744 poll_wq_task_work);
2746 mutex_lock(&ctx->uring_lock);
2747 ctx->poll_activated = true;
2748 mutex_unlock(&ctx->uring_lock);
2751 * Wake ups for some events between start of polling and activation
2752 * might've been lost due to loose synchronisation.
2754 wake_up_all(&ctx->poll_wq);
2755 percpu_ref_put(&ctx->refs);
2758 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2760 spin_lock(&ctx->completion_lock);
2761 /* already activated or in progress */
2762 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2763 goto out;
2764 if (WARN_ON_ONCE(!ctx->task_complete))
2765 goto out;
2766 if (!ctx->submitter_task)
2767 goto out;
2769 * with ->submitter_task only the submitter task completes requests, we
2770 * only need to sync with it, which is done by injecting a tw
2772 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2773 percpu_ref_get(&ctx->refs);
2774 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2775 percpu_ref_put(&ctx->refs);
2776 out:
2777 spin_unlock(&ctx->completion_lock);
2780 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2782 struct io_ring_ctx *ctx = file->private_data;
2783 __poll_t mask = 0;
2785 if (unlikely(!ctx->poll_activated))
2786 io_activate_pollwq(ctx);
2788 poll_wait(file, &ctx->poll_wq, wait);
2790 * synchronizes with barrier from wq_has_sleeper call in
2791 * io_commit_cqring
2793 smp_rmb();
2794 if (!io_sqring_full(ctx))
2795 mask |= EPOLLOUT | EPOLLWRNORM;
2798 * Don't flush cqring overflow list here, just do a simple check.
2799 * Otherwise there could possible be ABBA deadlock:
2800 * CPU0 CPU1
2801 * ---- ----
2802 * lock(&ctx->uring_lock);
2803 * lock(&ep->mtx);
2804 * lock(&ctx->uring_lock);
2805 * lock(&ep->mtx);
2807 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2808 * pushes them to do the flush.
2811 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2812 mask |= EPOLLIN | EPOLLRDNORM;
2814 return mask;
2817 struct io_tctx_exit {
2818 struct callback_head task_work;
2819 struct completion completion;
2820 struct io_ring_ctx *ctx;
2823 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2825 struct io_uring_task *tctx = current->io_uring;
2826 struct io_tctx_exit *work;
2828 work = container_of(cb, struct io_tctx_exit, task_work);
2830 * When @in_cancel, we're in cancellation and it's racy to remove the
2831 * node. It'll be removed by the end of cancellation, just ignore it.
2832 * tctx can be NULL if the queueing of this task_work raced with
2833 * work cancelation off the exec path.
2835 if (tctx && !atomic_read(&tctx->in_cancel))
2836 io_uring_del_tctx_node((unsigned long)work->ctx);
2837 complete(&work->completion);
2840 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
2842 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2844 return req->ctx == data;
2847 static __cold void io_ring_exit_work(struct work_struct *work)
2849 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2850 unsigned long timeout = jiffies + HZ * 60 * 5;
2851 unsigned long interval = HZ / 20;
2852 struct io_tctx_exit exit;
2853 struct io_tctx_node *node;
2854 int ret;
2857 * If we're doing polled IO and end up having requests being
2858 * submitted async (out-of-line), then completions can come in while
2859 * we're waiting for refs to drop. We need to reap these manually,
2860 * as nobody else will be looking for them.
2862 do {
2863 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2864 mutex_lock(&ctx->uring_lock);
2865 io_cqring_overflow_kill(ctx);
2866 mutex_unlock(&ctx->uring_lock);
2869 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2870 io_move_task_work_from_local(ctx);
2872 while (io_uring_try_cancel_requests(ctx, NULL, true))
2873 cond_resched();
2875 if (ctx->sq_data) {
2876 struct io_sq_data *sqd = ctx->sq_data;
2877 struct task_struct *tsk;
2879 io_sq_thread_park(sqd);
2880 tsk = sqd->thread;
2881 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2882 io_wq_cancel_cb(tsk->io_uring->io_wq,
2883 io_cancel_ctx_cb, ctx, true);
2884 io_sq_thread_unpark(sqd);
2887 io_req_caches_free(ctx);
2889 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2890 /* there is little hope left, don't run it too often */
2891 interval = HZ * 60;
2894 * This is really an uninterruptible wait, as it has to be
2895 * complete. But it's also run from a kworker, which doesn't
2896 * take signals, so it's fine to make it interruptible. This
2897 * avoids scenarios where we knowingly can wait much longer
2898 * on completions, for example if someone does a SIGSTOP on
2899 * a task that needs to finish task_work to make this loop
2900 * complete. That's a synthetic situation that should not
2901 * cause a stuck task backtrace, and hence a potential panic
2902 * on stuck tasks if that is enabled.
2904 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
2906 init_completion(&exit.completion);
2907 init_task_work(&exit.task_work, io_tctx_exit_cb);
2908 exit.ctx = ctx;
2910 mutex_lock(&ctx->uring_lock);
2911 while (!list_empty(&ctx->tctx_list)) {
2912 WARN_ON_ONCE(time_after(jiffies, timeout));
2914 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2915 ctx_node);
2916 /* don't spin on a single task if cancellation failed */
2917 list_rotate_left(&ctx->tctx_list);
2918 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2919 if (WARN_ON_ONCE(ret))
2920 continue;
2922 mutex_unlock(&ctx->uring_lock);
2924 * See comment above for
2925 * wait_for_completion_interruptible_timeout() on why this
2926 * wait is marked as interruptible.
2928 wait_for_completion_interruptible(&exit.completion);
2929 mutex_lock(&ctx->uring_lock);
2931 mutex_unlock(&ctx->uring_lock);
2932 spin_lock(&ctx->completion_lock);
2933 spin_unlock(&ctx->completion_lock);
2935 /* pairs with RCU read section in io_req_local_work_add() */
2936 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2937 synchronize_rcu();
2939 io_ring_ctx_free(ctx);
2942 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2944 unsigned long index;
2945 struct creds *creds;
2947 mutex_lock(&ctx->uring_lock);
2948 percpu_ref_kill(&ctx->refs);
2949 xa_for_each(&ctx->personalities, index, creds)
2950 io_unregister_personality(ctx, index);
2951 mutex_unlock(&ctx->uring_lock);
2953 flush_delayed_work(&ctx->fallback_work);
2955 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2957 * Use system_unbound_wq to avoid spawning tons of event kworkers
2958 * if we're exiting a ton of rings at the same time. It just adds
2959 * noise and overhead, there's no discernable change in runtime
2960 * over using system_wq.
2962 queue_work(iou_wq, &ctx->exit_work);
2965 static int io_uring_release(struct inode *inode, struct file *file)
2967 struct io_ring_ctx *ctx = file->private_data;
2969 file->private_data = NULL;
2970 io_ring_ctx_wait_and_kill(ctx);
2971 return 0;
2974 struct io_task_cancel {
2975 struct io_uring_task *tctx;
2976 bool all;
2979 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
2981 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2982 struct io_task_cancel *cancel = data;
2984 return io_match_task_safe(req, cancel->tctx, cancel->all);
2987 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
2988 struct io_uring_task *tctx,
2989 bool cancel_all)
2991 struct io_defer_entry *de;
2992 LIST_HEAD(list);
2994 spin_lock(&ctx->completion_lock);
2995 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
2996 if (io_match_task_safe(de->req, tctx, cancel_all)) {
2997 list_cut_position(&list, &ctx->defer_list, &de->list);
2998 break;
3001 spin_unlock(&ctx->completion_lock);
3002 if (list_empty(&list))
3003 return false;
3005 while (!list_empty(&list)) {
3006 de = list_first_entry(&list, struct io_defer_entry, list);
3007 list_del_init(&de->list);
3008 io_req_task_queue_fail(de->req, -ECANCELED);
3009 kfree(de);
3011 return true;
3014 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3016 struct io_tctx_node *node;
3017 enum io_wq_cancel cret;
3018 bool ret = false;
3020 mutex_lock(&ctx->uring_lock);
3021 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3022 struct io_uring_task *tctx = node->task->io_uring;
3025 * io_wq will stay alive while we hold uring_lock, because it's
3026 * killed after ctx nodes, which requires to take the lock.
3028 if (!tctx || !tctx->io_wq)
3029 continue;
3030 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3031 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3033 mutex_unlock(&ctx->uring_lock);
3035 return ret;
3038 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3039 struct io_uring_task *tctx,
3040 bool cancel_all)
3042 struct io_task_cancel cancel = { .tctx = tctx, .all = cancel_all, };
3043 enum io_wq_cancel cret;
3044 bool ret = false;
3046 /* set it so io_req_local_work_add() would wake us up */
3047 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3048 atomic_set(&ctx->cq_wait_nr, 1);
3049 smp_mb();
3052 /* failed during ring init, it couldn't have issued any requests */
3053 if (!ctx->rings)
3054 return false;
3056 if (!tctx) {
3057 ret |= io_uring_try_cancel_iowq(ctx);
3058 } else if (tctx->io_wq) {
3060 * Cancels requests of all rings, not only @ctx, but
3061 * it's fine as the task is in exit/exec.
3063 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3064 &cancel, true);
3065 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3068 /* SQPOLL thread does its own polling */
3069 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3070 (ctx->sq_data && ctx->sq_data->thread == current)) {
3071 while (!wq_list_empty(&ctx->iopoll_list)) {
3072 io_iopoll_try_reap_events(ctx);
3073 ret = true;
3074 cond_resched();
3078 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3079 io_allowed_defer_tw_run(ctx))
3080 ret |= io_run_local_work(ctx, INT_MAX) > 0;
3081 ret |= io_cancel_defer_files(ctx, tctx, cancel_all);
3082 mutex_lock(&ctx->uring_lock);
3083 ret |= io_poll_remove_all(ctx, tctx, cancel_all);
3084 ret |= io_waitid_remove_all(ctx, tctx, cancel_all);
3085 ret |= io_futex_remove_all(ctx, tctx, cancel_all);
3086 ret |= io_uring_try_cancel_uring_cmd(ctx, tctx, cancel_all);
3087 mutex_unlock(&ctx->uring_lock);
3088 ret |= io_kill_timeouts(ctx, tctx, cancel_all);
3089 if (tctx)
3090 ret |= io_run_task_work() > 0;
3091 else
3092 ret |= flush_delayed_work(&ctx->fallback_work);
3093 return ret;
3096 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3098 if (tracked)
3099 return atomic_read(&tctx->inflight_tracked);
3100 return percpu_counter_sum(&tctx->inflight);
3104 * Find any io_uring ctx that this task has registered or done IO on, and cancel
3105 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3107 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3109 struct io_uring_task *tctx = current->io_uring;
3110 struct io_ring_ctx *ctx;
3111 struct io_tctx_node *node;
3112 unsigned long index;
3113 s64 inflight;
3114 DEFINE_WAIT(wait);
3116 WARN_ON_ONCE(sqd && sqd->thread != current);
3118 if (!current->io_uring)
3119 return;
3120 if (tctx->io_wq)
3121 io_wq_exit_start(tctx->io_wq);
3123 atomic_inc(&tctx->in_cancel);
3124 do {
3125 bool loop = false;
3127 io_uring_drop_tctx_refs(current);
3128 if (!tctx_inflight(tctx, !cancel_all))
3129 break;
3131 /* read completions before cancelations */
3132 inflight = tctx_inflight(tctx, false);
3133 if (!inflight)
3134 break;
3136 if (!sqd) {
3137 xa_for_each(&tctx->xa, index, node) {
3138 /* sqpoll task will cancel all its requests */
3139 if (node->ctx->sq_data)
3140 continue;
3141 loop |= io_uring_try_cancel_requests(node->ctx,
3142 current->io_uring,
3143 cancel_all);
3145 } else {
3146 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3147 loop |= io_uring_try_cancel_requests(ctx,
3148 current->io_uring,
3149 cancel_all);
3152 if (loop) {
3153 cond_resched();
3154 continue;
3157 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3158 io_run_task_work();
3159 io_uring_drop_tctx_refs(current);
3160 xa_for_each(&tctx->xa, index, node) {
3161 if (!llist_empty(&node->ctx->work_llist)) {
3162 WARN_ON_ONCE(node->ctx->submitter_task &&
3163 node->ctx->submitter_task != current);
3164 goto end_wait;
3168 * If we've seen completions, retry without waiting. This
3169 * avoids a race where a completion comes in before we did
3170 * prepare_to_wait().
3172 if (inflight == tctx_inflight(tctx, !cancel_all))
3173 schedule();
3174 end_wait:
3175 finish_wait(&tctx->wait, &wait);
3176 } while (1);
3178 io_uring_clean_tctx(tctx);
3179 if (cancel_all) {
3181 * We shouldn't run task_works after cancel, so just leave
3182 * ->in_cancel set for normal exit.
3184 atomic_dec(&tctx->in_cancel);
3185 /* for exec all current's requests should be gone, kill tctx */
3186 __io_uring_free(current);
3190 void __io_uring_cancel(bool cancel_all)
3192 io_uring_cancel_generic(cancel_all, NULL);
3195 static struct io_uring_reg_wait *io_get_ext_arg_reg(struct io_ring_ctx *ctx,
3196 const struct io_uring_getevents_arg __user *uarg)
3198 unsigned long size = sizeof(struct io_uring_reg_wait);
3199 unsigned long offset = (uintptr_t)uarg;
3200 unsigned long end;
3202 if (unlikely(offset % sizeof(long)))
3203 return ERR_PTR(-EFAULT);
3205 /* also protects from NULL ->cq_wait_arg as the size would be 0 */
3206 if (unlikely(check_add_overflow(offset, size, &end) ||
3207 end > ctx->cq_wait_size))
3208 return ERR_PTR(-EFAULT);
3210 return ctx->cq_wait_arg + offset;
3213 static int io_validate_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
3214 const void __user *argp, size_t argsz)
3216 struct io_uring_getevents_arg arg;
3218 if (!(flags & IORING_ENTER_EXT_ARG))
3219 return 0;
3220 if (flags & IORING_ENTER_EXT_ARG_REG)
3221 return -EINVAL;
3222 if (argsz != sizeof(arg))
3223 return -EINVAL;
3224 if (copy_from_user(&arg, argp, sizeof(arg)))
3225 return -EFAULT;
3226 return 0;
3229 static int io_get_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
3230 const void __user *argp, struct ext_arg *ext_arg)
3232 const struct io_uring_getevents_arg __user *uarg = argp;
3233 struct io_uring_getevents_arg arg;
3236 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3237 * is just a pointer to the sigset_t.
3239 if (!(flags & IORING_ENTER_EXT_ARG)) {
3240 ext_arg->sig = (const sigset_t __user *) argp;
3241 return 0;
3244 if (flags & IORING_ENTER_EXT_ARG_REG) {
3245 struct io_uring_reg_wait *w;
3247 if (ext_arg->argsz != sizeof(struct io_uring_reg_wait))
3248 return -EINVAL;
3249 w = io_get_ext_arg_reg(ctx, argp);
3250 if (IS_ERR(w))
3251 return PTR_ERR(w);
3253 if (w->flags & ~IORING_REG_WAIT_TS)
3254 return -EINVAL;
3255 ext_arg->min_time = READ_ONCE(w->min_wait_usec) * NSEC_PER_USEC;
3256 ext_arg->sig = u64_to_user_ptr(READ_ONCE(w->sigmask));
3257 ext_arg->argsz = READ_ONCE(w->sigmask_sz);
3258 if (w->flags & IORING_REG_WAIT_TS) {
3259 ext_arg->ts.tv_sec = READ_ONCE(w->ts.tv_sec);
3260 ext_arg->ts.tv_nsec = READ_ONCE(w->ts.tv_nsec);
3261 ext_arg->ts_set = true;
3263 return 0;
3267 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3268 * timespec and sigset_t pointers if good.
3270 if (ext_arg->argsz != sizeof(arg))
3271 return -EINVAL;
3272 #ifdef CONFIG_64BIT
3273 if (!user_access_begin(uarg, sizeof(*uarg)))
3274 return -EFAULT;
3275 unsafe_get_user(arg.sigmask, &uarg->sigmask, uaccess_end);
3276 unsafe_get_user(arg.sigmask_sz, &uarg->sigmask_sz, uaccess_end);
3277 unsafe_get_user(arg.min_wait_usec, &uarg->min_wait_usec, uaccess_end);
3278 unsafe_get_user(arg.ts, &uarg->ts, uaccess_end);
3279 user_access_end();
3280 #else
3281 if (copy_from_user(&arg, uarg, sizeof(arg)))
3282 return -EFAULT;
3283 #endif
3284 ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC;
3285 ext_arg->sig = u64_to_user_ptr(arg.sigmask);
3286 ext_arg->argsz = arg.sigmask_sz;
3287 if (arg.ts) {
3288 if (get_timespec64(&ext_arg->ts, u64_to_user_ptr(arg.ts)))
3289 return -EFAULT;
3290 ext_arg->ts_set = true;
3292 return 0;
3293 #ifdef CONFIG_64BIT
3294 uaccess_end:
3295 user_access_end();
3296 return -EFAULT;
3297 #endif
3300 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3301 u32, min_complete, u32, flags, const void __user *, argp,
3302 size_t, argsz)
3304 struct io_ring_ctx *ctx;
3305 struct file *file;
3306 long ret;
3308 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3309 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3310 IORING_ENTER_REGISTERED_RING |
3311 IORING_ENTER_ABS_TIMER |
3312 IORING_ENTER_EXT_ARG_REG)))
3313 return -EINVAL;
3316 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3317 * need only dereference our task private array to find it.
3319 if (flags & IORING_ENTER_REGISTERED_RING) {
3320 struct io_uring_task *tctx = current->io_uring;
3322 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3323 return -EINVAL;
3324 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3325 file = tctx->registered_rings[fd];
3326 if (unlikely(!file))
3327 return -EBADF;
3328 } else {
3329 file = fget(fd);
3330 if (unlikely(!file))
3331 return -EBADF;
3332 ret = -EOPNOTSUPP;
3333 if (unlikely(!io_is_uring_fops(file)))
3334 goto out;
3337 ctx = file->private_data;
3338 ret = -EBADFD;
3339 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3340 goto out;
3343 * For SQ polling, the thread will do all submissions and completions.
3344 * Just return the requested submit count, and wake the thread if
3345 * we were asked to.
3347 ret = 0;
3348 if (ctx->flags & IORING_SETUP_SQPOLL) {
3349 if (unlikely(ctx->sq_data->thread == NULL)) {
3350 ret = -EOWNERDEAD;
3351 goto out;
3353 if (flags & IORING_ENTER_SQ_WAKEUP)
3354 wake_up(&ctx->sq_data->wait);
3355 if (flags & IORING_ENTER_SQ_WAIT)
3356 io_sqpoll_wait_sq(ctx);
3358 ret = to_submit;
3359 } else if (to_submit) {
3360 ret = io_uring_add_tctx_node(ctx);
3361 if (unlikely(ret))
3362 goto out;
3364 mutex_lock(&ctx->uring_lock);
3365 ret = io_submit_sqes(ctx, to_submit);
3366 if (ret != to_submit) {
3367 mutex_unlock(&ctx->uring_lock);
3368 goto out;
3370 if (flags & IORING_ENTER_GETEVENTS) {
3371 if (ctx->syscall_iopoll)
3372 goto iopoll_locked;
3374 * Ignore errors, we'll soon call io_cqring_wait() and
3375 * it should handle ownership problems if any.
3377 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3378 (void)io_run_local_work_locked(ctx, min_complete);
3380 mutex_unlock(&ctx->uring_lock);
3383 if (flags & IORING_ENTER_GETEVENTS) {
3384 int ret2;
3386 if (ctx->syscall_iopoll) {
3388 * We disallow the app entering submit/complete with
3389 * polling, but we still need to lock the ring to
3390 * prevent racing with polled issue that got punted to
3391 * a workqueue.
3393 mutex_lock(&ctx->uring_lock);
3394 iopoll_locked:
3395 ret2 = io_validate_ext_arg(ctx, flags, argp, argsz);
3396 if (likely(!ret2)) {
3397 min_complete = min(min_complete,
3398 ctx->cq_entries);
3399 ret2 = io_iopoll_check(ctx, min_complete);
3401 mutex_unlock(&ctx->uring_lock);
3402 } else {
3403 struct ext_arg ext_arg = { .argsz = argsz };
3405 ret2 = io_get_ext_arg(ctx, flags, argp, &ext_arg);
3406 if (likely(!ret2)) {
3407 min_complete = min(min_complete,
3408 ctx->cq_entries);
3409 ret2 = io_cqring_wait(ctx, min_complete, flags,
3410 &ext_arg);
3414 if (!ret) {
3415 ret = ret2;
3418 * EBADR indicates that one or more CQE were dropped.
3419 * Once the user has been informed we can clear the bit
3420 * as they are obviously ok with those drops.
3422 if (unlikely(ret2 == -EBADR))
3423 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3424 &ctx->check_cq);
3427 out:
3428 if (!(flags & IORING_ENTER_REGISTERED_RING))
3429 fput(file);
3430 return ret;
3433 static const struct file_operations io_uring_fops = {
3434 .release = io_uring_release,
3435 .mmap = io_uring_mmap,
3436 .get_unmapped_area = io_uring_get_unmapped_area,
3437 #ifndef CONFIG_MMU
3438 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3439 #endif
3440 .poll = io_uring_poll,
3441 #ifdef CONFIG_PROC_FS
3442 .show_fdinfo = io_uring_show_fdinfo,
3443 #endif
3446 bool io_is_uring_fops(struct file *file)
3448 return file->f_op == &io_uring_fops;
3451 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3452 struct io_uring_params *p)
3454 struct io_rings *rings;
3455 size_t size, sq_array_offset;
3456 void *ptr;
3458 /* make sure these are sane, as we already accounted them */
3459 ctx->sq_entries = p->sq_entries;
3460 ctx->cq_entries = p->cq_entries;
3462 size = rings_size(ctx->flags, p->sq_entries, p->cq_entries,
3463 &sq_array_offset);
3464 if (size == SIZE_MAX)
3465 return -EOVERFLOW;
3467 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3468 rings = io_pages_map(&ctx->ring_pages, &ctx->n_ring_pages, size);
3469 else
3470 rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3472 if (IS_ERR(rings))
3473 return PTR_ERR(rings);
3475 ctx->rings = rings;
3476 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3477 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3478 rings->sq_ring_mask = p->sq_entries - 1;
3479 rings->cq_ring_mask = p->cq_entries - 1;
3480 rings->sq_ring_entries = p->sq_entries;
3481 rings->cq_ring_entries = p->cq_entries;
3483 if (p->flags & IORING_SETUP_SQE128)
3484 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3485 else
3486 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3487 if (size == SIZE_MAX) {
3488 io_rings_free(ctx);
3489 return -EOVERFLOW;
3492 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3493 ptr = io_pages_map(&ctx->sqe_pages, &ctx->n_sqe_pages, size);
3494 else
3495 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3497 if (IS_ERR(ptr)) {
3498 io_rings_free(ctx);
3499 return PTR_ERR(ptr);
3502 ctx->sq_sqes = ptr;
3503 return 0;
3506 static int io_uring_install_fd(struct file *file)
3508 int fd;
3510 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3511 if (fd < 0)
3512 return fd;
3513 fd_install(fd, file);
3514 return fd;
3518 * Allocate an anonymous fd, this is what constitutes the application
3519 * visible backing of an io_uring instance. The application mmaps this
3520 * fd to gain access to the SQ/CQ ring details.
3522 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3524 /* Create a new inode so that the LSM can block the creation. */
3525 return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
3526 O_RDWR | O_CLOEXEC, NULL);
3529 int io_uring_fill_params(unsigned entries, struct io_uring_params *p)
3531 if (!entries)
3532 return -EINVAL;
3533 if (entries > IORING_MAX_ENTRIES) {
3534 if (!(p->flags & IORING_SETUP_CLAMP))
3535 return -EINVAL;
3536 entries = IORING_MAX_ENTRIES;
3539 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3540 && !(p->flags & IORING_SETUP_NO_MMAP))
3541 return -EINVAL;
3544 * Use twice as many entries for the CQ ring. It's possible for the
3545 * application to drive a higher depth than the size of the SQ ring,
3546 * since the sqes are only used at submission time. This allows for
3547 * some flexibility in overcommitting a bit. If the application has
3548 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3549 * of CQ ring entries manually.
3551 p->sq_entries = roundup_pow_of_two(entries);
3552 if (p->flags & IORING_SETUP_CQSIZE) {
3554 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3555 * to a power-of-two, if it isn't already. We do NOT impose
3556 * any cq vs sq ring sizing.
3558 if (!p->cq_entries)
3559 return -EINVAL;
3560 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3561 if (!(p->flags & IORING_SETUP_CLAMP))
3562 return -EINVAL;
3563 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3565 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3566 if (p->cq_entries < p->sq_entries)
3567 return -EINVAL;
3568 } else {
3569 p->cq_entries = 2 * p->sq_entries;
3572 p->sq_off.head = offsetof(struct io_rings, sq.head);
3573 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3574 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3575 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3576 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3577 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3578 p->sq_off.resv1 = 0;
3579 if (!(p->flags & IORING_SETUP_NO_MMAP))
3580 p->sq_off.user_addr = 0;
3582 p->cq_off.head = offsetof(struct io_rings, cq.head);
3583 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3584 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3585 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3586 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3587 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3588 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3589 p->cq_off.resv1 = 0;
3590 if (!(p->flags & IORING_SETUP_NO_MMAP))
3591 p->cq_off.user_addr = 0;
3593 return 0;
3596 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3597 struct io_uring_params __user *params)
3599 struct io_ring_ctx *ctx;
3600 struct io_uring_task *tctx;
3601 struct file *file;
3602 int ret;
3604 ret = io_uring_fill_params(entries, p);
3605 if (unlikely(ret))
3606 return ret;
3608 ctx = io_ring_ctx_alloc(p);
3609 if (!ctx)
3610 return -ENOMEM;
3612 ctx->clockid = CLOCK_MONOTONIC;
3613 ctx->clock_offset = 0;
3615 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3616 static_branch_inc(&io_key_has_sqarray);
3618 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3619 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3620 !(ctx->flags & IORING_SETUP_SQPOLL))
3621 ctx->task_complete = true;
3623 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3624 ctx->lockless_cq = true;
3627 * lazy poll_wq activation relies on ->task_complete for synchronisation
3628 * purposes, see io_activate_pollwq()
3630 if (!ctx->task_complete)
3631 ctx->poll_activated = true;
3634 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3635 * space applications don't need to do io completion events
3636 * polling again, they can rely on io_sq_thread to do polling
3637 * work, which can reduce cpu usage and uring_lock contention.
3639 if (ctx->flags & IORING_SETUP_IOPOLL &&
3640 !(ctx->flags & IORING_SETUP_SQPOLL))
3641 ctx->syscall_iopoll = 1;
3643 ctx->compat = in_compat_syscall();
3644 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3645 ctx->user = get_uid(current_user());
3648 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3649 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3651 ret = -EINVAL;
3652 if (ctx->flags & IORING_SETUP_SQPOLL) {
3653 /* IPI related flags don't make sense with SQPOLL */
3654 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3655 IORING_SETUP_TASKRUN_FLAG |
3656 IORING_SETUP_DEFER_TASKRUN))
3657 goto err;
3658 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3659 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3660 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3661 } else {
3662 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
3663 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
3664 goto err;
3665 ctx->notify_method = TWA_SIGNAL;
3668 /* HYBRID_IOPOLL only valid with IOPOLL */
3669 if ((ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_HYBRID_IOPOLL)) ==
3670 IORING_SETUP_HYBRID_IOPOLL)
3671 goto err;
3674 * For DEFER_TASKRUN we require the completion task to be the same as the
3675 * submission task. This implies that there is only one submitter, so enforce
3676 * that.
3678 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
3679 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
3680 goto err;
3684 * This is just grabbed for accounting purposes. When a process exits,
3685 * the mm is exited and dropped before the files, hence we need to hang
3686 * on to this mm purely for the purposes of being able to unaccount
3687 * memory (locked/pinned vm). It's not used for anything else.
3689 mmgrab(current->mm);
3690 ctx->mm_account = current->mm;
3692 ret = io_allocate_scq_urings(ctx, p);
3693 if (ret)
3694 goto err;
3696 if (!(p->flags & IORING_SETUP_NO_SQARRAY))
3697 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3699 ret = io_sq_offload_create(ctx, p);
3700 if (ret)
3701 goto err;
3703 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3704 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
3705 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
3706 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
3707 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
3708 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
3709 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING |
3710 IORING_FEAT_RECVSEND_BUNDLE | IORING_FEAT_MIN_TIMEOUT;
3712 if (copy_to_user(params, p, sizeof(*p))) {
3713 ret = -EFAULT;
3714 goto err;
3717 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
3718 && !(ctx->flags & IORING_SETUP_R_DISABLED))
3719 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
3721 file = io_uring_get_file(ctx);
3722 if (IS_ERR(file)) {
3723 ret = PTR_ERR(file);
3724 goto err;
3727 ret = __io_uring_add_tctx_node(ctx);
3728 if (ret)
3729 goto err_fput;
3730 tctx = current->io_uring;
3733 * Install ring fd as the very last thing, so we don't risk someone
3734 * having closed it before we finish setup
3736 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3737 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
3738 else
3739 ret = io_uring_install_fd(file);
3740 if (ret < 0)
3741 goto err_fput;
3743 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3744 return ret;
3745 err:
3746 io_ring_ctx_wait_and_kill(ctx);
3747 return ret;
3748 err_fput:
3749 fput(file);
3750 return ret;
3754 * Sets up an aio uring context, and returns the fd. Applications asks for a
3755 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3756 * params structure passed in.
3758 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3760 struct io_uring_params p;
3761 int i;
3763 if (copy_from_user(&p, params, sizeof(p)))
3764 return -EFAULT;
3765 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3766 if (p.resv[i])
3767 return -EINVAL;
3770 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3771 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
3772 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
3773 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
3774 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
3775 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
3776 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
3777 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
3778 IORING_SETUP_NO_SQARRAY | IORING_SETUP_HYBRID_IOPOLL))
3779 return -EINVAL;
3781 return io_uring_create(entries, &p, params);
3784 static inline bool io_uring_allowed(void)
3786 int disabled = READ_ONCE(sysctl_io_uring_disabled);
3787 kgid_t io_uring_group;
3789 if (disabled == 2)
3790 return false;
3792 if (disabled == 0 || capable(CAP_SYS_ADMIN))
3793 return true;
3795 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
3796 if (!gid_valid(io_uring_group))
3797 return false;
3799 return in_group_p(io_uring_group);
3802 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3803 struct io_uring_params __user *, params)
3805 if (!io_uring_allowed())
3806 return -EPERM;
3808 return io_uring_setup(entries, params);
3811 static int __init io_uring_init(void)
3813 struct kmem_cache_args kmem_args = {
3814 .useroffset = offsetof(struct io_kiocb, cmd.data),
3815 .usersize = sizeof_field(struct io_kiocb, cmd.data),
3816 .freeptr_offset = offsetof(struct io_kiocb, work),
3817 .use_freeptr_offset = true,
3820 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
3821 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
3822 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
3823 } while (0)
3825 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
3826 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
3827 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
3828 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
3829 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
3830 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
3831 BUILD_BUG_SQE_ELEM(1, __u8, flags);
3832 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
3833 BUILD_BUG_SQE_ELEM(4, __s32, fd);
3834 BUILD_BUG_SQE_ELEM(8, __u64, off);
3835 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
3836 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
3837 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
3838 BUILD_BUG_SQE_ELEM(16, __u64, addr);
3839 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
3840 BUILD_BUG_SQE_ELEM(24, __u32, len);
3841 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
3842 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
3843 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
3844 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
3845 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
3846 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
3847 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
3848 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
3849 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
3850 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
3851 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
3852 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
3853 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
3854 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
3855 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
3856 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
3857 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
3858 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
3859 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
3860 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
3861 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
3862 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
3863 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
3864 BUILD_BUG_SQE_ELEM(42, __u16, personality);
3865 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
3866 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
3867 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
3868 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
3869 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
3870 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
3871 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
3873 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3874 sizeof(struct io_uring_rsrc_update));
3875 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3876 sizeof(struct io_uring_rsrc_update2));
3878 /* ->buf_index is u16 */
3879 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3880 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3881 offsetof(struct io_uring_buf_ring, tail));
3883 /* should fit into one byte */
3884 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
3885 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
3886 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
3888 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
3890 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
3892 /* top 8bits are for internal use */
3893 BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
3895 io_uring_optable_init();
3898 * Allow user copy in the per-command field, which starts after the
3899 * file in io_kiocb and until the opcode field. The openat2 handling
3900 * requires copying in user memory into the io_kiocb object in that
3901 * range, and HARDENED_USERCOPY will complain if we haven't
3902 * correctly annotated this range.
3904 req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
3905 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
3906 SLAB_TYPESAFE_BY_RCU);
3907 io_buf_cachep = KMEM_CACHE(io_buffer,
3908 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT);
3910 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
3912 #ifdef CONFIG_SYSCTL
3913 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
3914 #endif
3916 return 0;
3918 __initcall(io_uring_init);