1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
50 #include <linux/sched/signal.h>
52 #include <linux/file.h>
53 #include <linux/fdtable.h>
55 #include <linux/mman.h>
56 #include <linux/mmu_context.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/kthread.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
79 #include <uapi/linux/io_uring.h>
84 #define IORING_MAX_ENTRIES 32768
85 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
88 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
90 #define IORING_FILE_TABLE_SHIFT 9
91 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
92 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
93 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
96 u32 head ____cacheline_aligned_in_smp;
97 u32 tail ____cacheline_aligned_in_smp;
101 * This data is shared with the application through the mmap at offsets
102 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
104 * The offsets to the member fields are published through struct
105 * io_sqring_offsets when calling io_uring_setup.
109 * Head and tail offsets into the ring; the offsets need to be
110 * masked to get valid indices.
112 * The kernel controls head of the sq ring and the tail of the cq ring,
113 * and the application controls tail of the sq ring and the head of the
116 struct io_uring sq, cq;
118 * Bitmasks to apply to head and tail offsets (constant, equals
121 u32 sq_ring_mask, cq_ring_mask;
122 /* Ring sizes (constant, power of 2) */
123 u32 sq_ring_entries, cq_ring_entries;
125 * Number of invalid entries dropped by the kernel due to
126 * invalid index stored in array
128 * Written by the kernel, shouldn't be modified by the
129 * application (i.e. get number of "new events" by comparing to
132 * After a new SQ head value was read by the application this
133 * counter includes all submissions that were dropped reaching
134 * the new SQ head (and possibly more).
140 * Written by the kernel, shouldn't be modified by the
143 * The application needs a full memory barrier before checking
144 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
148 * Number of completion events lost because the queue was full;
149 * this should be avoided by the application by making sure
150 * there are not more requests pending than there is space in
151 * the completion queue.
153 * Written by the kernel, shouldn't be modified by the
154 * application (i.e. get number of "new events" by comparing to
157 * As completion events come in out of order this counter is not
158 * ordered with any other data.
162 * Ring buffer of completion events.
164 * The kernel writes completion events fresh every time they are
165 * produced, so the application is allowed to modify pending
168 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
171 struct io_mapped_ubuf {
174 struct bio_vec *bvec;
175 unsigned int nr_bvecs;
178 struct fixed_file_table {
184 struct percpu_ref refs;
185 } ____cacheline_aligned_in_smp;
191 bool cq_overflow_flushed;
195 * Ring buffer of indices into array of io_uring_sqe, which is
196 * mmapped by the application using the IORING_OFF_SQES offset.
198 * This indirection could e.g. be used to assign fixed
199 * io_uring_sqe entries to operations and only submit them to
200 * the queue when needed.
202 * The kernel modifies neither the indices array nor the entries
206 unsigned cached_sq_head;
209 unsigned sq_thread_idle;
210 unsigned cached_sq_dropped;
211 atomic_t cached_cq_overflow;
212 struct io_uring_sqe *sq_sqes;
214 struct list_head defer_list;
215 struct list_head timeout_list;
216 struct list_head cq_overflow_list;
218 wait_queue_head_t inflight_wait;
219 } ____cacheline_aligned_in_smp;
221 struct io_rings *rings;
225 struct task_struct *sqo_thread; /* if using sq thread polling */
226 struct mm_struct *sqo_mm;
227 wait_queue_head_t sqo_wait;
230 * If used, fixed file set. Writers must ensure that ->refs is dead,
231 * readers must ensure that ->refs is alive as long as the file* is
232 * used. Only updated through io_uring_register(2).
234 struct fixed_file_table *file_table;
235 unsigned nr_user_files;
237 /* if used, fixed mapped user buffers */
238 unsigned nr_user_bufs;
239 struct io_mapped_ubuf *user_bufs;
241 struct user_struct *user;
243 const struct cred *creds;
245 /* 0 is for ctx quiesce/reinit/free, 1 is for sqo_thread started */
246 struct completion *completions;
248 /* if all else fails... */
249 struct io_kiocb *fallback_req;
251 #if defined(CONFIG_UNIX)
252 struct socket *ring_sock;
256 unsigned cached_cq_tail;
259 atomic_t cq_timeouts;
260 struct wait_queue_head cq_wait;
261 struct fasync_struct *cq_fasync;
262 struct eventfd_ctx *cq_ev_fd;
263 } ____cacheline_aligned_in_smp;
266 struct mutex uring_lock;
267 wait_queue_head_t wait;
268 } ____cacheline_aligned_in_smp;
271 spinlock_t completion_lock;
272 bool poll_multi_file;
274 * ->poll_list is protected by the ctx->uring_lock for
275 * io_uring instances that don't use IORING_SETUP_SQPOLL.
276 * For SQPOLL, only the single threaded io_sq_thread() will
277 * manipulate the list, hence no extra locking is needed there.
279 struct list_head poll_list;
280 struct hlist_head *cancel_hash;
281 unsigned cancel_hash_bits;
283 spinlock_t inflight_lock;
284 struct list_head inflight_list;
285 } ____cacheline_aligned_in_smp;
289 * First field must be the file pointer in all the
290 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
292 struct io_poll_iocb {
295 struct wait_queue_head *head;
301 struct wait_queue_entry wait;
304 struct io_timeout_data {
305 struct io_kiocb *req;
306 struct hrtimer timer;
307 struct timespec64 ts;
308 enum hrtimer_mode mode;
314 struct sockaddr __user *addr;
315 int __user *addr_len;
340 /* NOTE: kiocb has the file as the first member, so don't do it here */
348 struct sockaddr __user *addr;
354 struct user_msghdr __user *msg;
362 const char __user *fname;
363 struct filename *filename;
367 struct io_async_connect {
368 struct sockaddr_storage address;
371 struct io_async_msghdr {
372 struct iovec fast_iov[UIO_FASTIOV];
374 struct sockaddr __user *uaddr;
379 struct iovec fast_iov[UIO_FASTIOV];
385 struct io_async_open {
386 struct filename *filename;
389 struct io_async_ctx {
391 struct io_async_rw rw;
392 struct io_async_msghdr msg;
393 struct io_async_connect connect;
394 struct io_timeout_data timeout;
395 struct io_async_open open;
400 * NOTE! Each of the iocb union members has the file pointer
401 * as the first entry in their struct definition. So you can
402 * access the file pointer through any of the sub-structs,
403 * or directly as just 'ki_filp' in this struct.
409 struct io_poll_iocb poll;
410 struct io_accept accept;
412 struct io_cancel cancel;
413 struct io_timeout timeout;
414 struct io_connect connect;
415 struct io_sr_msg sr_msg;
419 struct io_async_ctx *io;
420 struct file *ring_file;
424 bool needs_fixed_file;
427 struct io_ring_ctx *ctx;
429 struct list_head list;
430 struct hlist_node hash_node;
432 struct list_head link_list;
435 #define REQ_F_NOWAIT 1 /* must not punt to workers */
436 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
437 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
438 #define REQ_F_LINK_NEXT 8 /* already grabbed next link */
439 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
440 #define REQ_F_IO_DRAINED 32 /* drain done */
441 #define REQ_F_LINK 64 /* linked sqes */
442 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
443 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
444 #define REQ_F_DRAIN_LINK 512 /* link should be fully drained */
445 #define REQ_F_TIMEOUT 1024 /* timeout request */
446 #define REQ_F_ISREG 2048 /* regular file */
447 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
448 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
449 #define REQ_F_INFLIGHT 16384 /* on inflight list */
450 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
451 #define REQ_F_HARDLINK 65536 /* doesn't sever on completion < 0 */
456 struct list_head inflight_entry;
458 struct io_wq_work work;
461 #define IO_PLUG_THRESHOLD 2
462 #define IO_IOPOLL_BATCH 8
464 struct io_submit_state {
465 struct blk_plug plug;
468 * io_kiocb alloc cache
470 void *reqs[IO_IOPOLL_BATCH];
471 unsigned int free_reqs;
472 unsigned int cur_req;
475 * File reference cache
479 unsigned int has_refs;
480 unsigned int used_refs;
481 unsigned int ios_left;
484 static void io_wq_submit_work(struct io_wq_work **workptr);
485 static void io_cqring_fill_event(struct io_kiocb *req, long res);
486 static void __io_free_req(struct io_kiocb *req);
487 static void io_put_req(struct io_kiocb *req);
488 static void io_double_put_req(struct io_kiocb *req);
489 static void __io_double_put_req(struct io_kiocb *req);
490 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
491 static void io_queue_linked_timeout(struct io_kiocb *req);
493 static struct kmem_cache *req_cachep;
495 static const struct file_operations io_uring_fops;
497 struct sock *io_uring_get_socket(struct file *file)
499 #if defined(CONFIG_UNIX)
500 if (file->f_op == &io_uring_fops) {
501 struct io_ring_ctx *ctx = file->private_data;
503 return ctx->ring_sock->sk;
508 EXPORT_SYMBOL(io_uring_get_socket);
510 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
512 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
514 complete(&ctx->completions[0]);
517 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
519 struct io_ring_ctx *ctx;
522 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
526 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
527 if (!ctx->fallback_req)
530 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
531 if (!ctx->completions)
535 * Use 5 bits less than the max cq entries, that should give us around
536 * 32 entries per hash list if totally full and uniformly spread.
538 hash_bits = ilog2(p->cq_entries);
542 ctx->cancel_hash_bits = hash_bits;
543 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
545 if (!ctx->cancel_hash)
547 __hash_init(ctx->cancel_hash, 1U << hash_bits);
549 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
550 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
553 ctx->flags = p->flags;
554 init_waitqueue_head(&ctx->cq_wait);
555 INIT_LIST_HEAD(&ctx->cq_overflow_list);
556 init_completion(&ctx->completions[0]);
557 init_completion(&ctx->completions[1]);
558 mutex_init(&ctx->uring_lock);
559 init_waitqueue_head(&ctx->wait);
560 spin_lock_init(&ctx->completion_lock);
561 INIT_LIST_HEAD(&ctx->poll_list);
562 INIT_LIST_HEAD(&ctx->defer_list);
563 INIT_LIST_HEAD(&ctx->timeout_list);
564 init_waitqueue_head(&ctx->inflight_wait);
565 spin_lock_init(&ctx->inflight_lock);
566 INIT_LIST_HEAD(&ctx->inflight_list);
569 if (ctx->fallback_req)
570 kmem_cache_free(req_cachep, ctx->fallback_req);
571 kfree(ctx->completions);
572 kfree(ctx->cancel_hash);
577 static inline bool __req_need_defer(struct io_kiocb *req)
579 struct io_ring_ctx *ctx = req->ctx;
581 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
582 + atomic_read(&ctx->cached_cq_overflow);
585 static inline bool req_need_defer(struct io_kiocb *req)
587 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
588 return __req_need_defer(req);
593 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
595 struct io_kiocb *req;
597 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
598 if (req && !req_need_defer(req)) {
599 list_del_init(&req->list);
606 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
608 struct io_kiocb *req;
610 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
612 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
614 if (!__req_need_defer(req)) {
615 list_del_init(&req->list);
623 static void __io_commit_cqring(struct io_ring_ctx *ctx)
625 struct io_rings *rings = ctx->rings;
627 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
628 /* order cqe stores with ring update */
629 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
631 if (wq_has_sleeper(&ctx->cq_wait)) {
632 wake_up_interruptible(&ctx->cq_wait);
633 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
638 static inline bool io_req_needs_user(struct io_kiocb *req)
640 return !(req->opcode == IORING_OP_READ_FIXED ||
641 req->opcode == IORING_OP_WRITE_FIXED);
644 static inline bool io_prep_async_work(struct io_kiocb *req,
645 struct io_kiocb **link)
647 bool do_hashed = false;
649 switch (req->opcode) {
650 case IORING_OP_WRITEV:
651 case IORING_OP_WRITE_FIXED:
652 /* only regular files should be hashed for writes */
653 if (req->flags & REQ_F_ISREG)
656 case IORING_OP_READV:
657 case IORING_OP_READ_FIXED:
658 case IORING_OP_SENDMSG:
659 case IORING_OP_RECVMSG:
660 case IORING_OP_ACCEPT:
661 case IORING_OP_POLL_ADD:
662 case IORING_OP_CONNECT:
664 * We know REQ_F_ISREG is not set on some of these
665 * opcodes, but this enables us to keep the check in
668 if (!(req->flags & REQ_F_ISREG))
669 req->work.flags |= IO_WQ_WORK_UNBOUND;
672 if (io_req_needs_user(req))
673 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
675 *link = io_prep_linked_timeout(req);
679 static inline void io_queue_async_work(struct io_kiocb *req)
681 struct io_ring_ctx *ctx = req->ctx;
682 struct io_kiocb *link;
685 do_hashed = io_prep_async_work(req, &link);
687 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
690 io_wq_enqueue(ctx->io_wq, &req->work);
692 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
693 file_inode(req->file));
697 io_queue_linked_timeout(link);
700 static void io_kill_timeout(struct io_kiocb *req)
704 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
706 atomic_inc(&req->ctx->cq_timeouts);
707 list_del_init(&req->list);
708 io_cqring_fill_event(req, 0);
713 static void io_kill_timeouts(struct io_ring_ctx *ctx)
715 struct io_kiocb *req, *tmp;
717 spin_lock_irq(&ctx->completion_lock);
718 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
719 io_kill_timeout(req);
720 spin_unlock_irq(&ctx->completion_lock);
723 static void io_commit_cqring(struct io_ring_ctx *ctx)
725 struct io_kiocb *req;
727 while ((req = io_get_timeout_req(ctx)) != NULL)
728 io_kill_timeout(req);
730 __io_commit_cqring(ctx);
732 while ((req = io_get_deferred_req(ctx)) != NULL) {
733 req->flags |= REQ_F_IO_DRAINED;
734 io_queue_async_work(req);
738 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
740 struct io_rings *rings = ctx->rings;
743 tail = ctx->cached_cq_tail;
745 * writes to the cq entry need to come after reading head; the
746 * control dependency is enough as we're using WRITE_ONCE to
749 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
752 ctx->cached_cq_tail++;
753 return &rings->cqes[tail & ctx->cq_mask];
756 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
758 if (waitqueue_active(&ctx->wait))
760 if (waitqueue_active(&ctx->sqo_wait))
761 wake_up(&ctx->sqo_wait);
763 eventfd_signal(ctx->cq_ev_fd, 1);
766 /* Returns true if there are no backlogged entries after the flush */
767 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
769 struct io_rings *rings = ctx->rings;
770 struct io_uring_cqe *cqe;
771 struct io_kiocb *req;
776 if (list_empty_careful(&ctx->cq_overflow_list))
778 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
779 rings->cq_ring_entries))
783 spin_lock_irqsave(&ctx->completion_lock, flags);
785 /* if force is set, the ring is going away. always drop after that */
787 ctx->cq_overflow_flushed = true;
790 while (!list_empty(&ctx->cq_overflow_list)) {
791 cqe = io_get_cqring(ctx);
795 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
797 list_move(&req->list, &list);
799 WRITE_ONCE(cqe->user_data, req->user_data);
800 WRITE_ONCE(cqe->res, req->result);
801 WRITE_ONCE(cqe->flags, 0);
803 WRITE_ONCE(ctx->rings->cq_overflow,
804 atomic_inc_return(&ctx->cached_cq_overflow));
808 io_commit_cqring(ctx);
809 spin_unlock_irqrestore(&ctx->completion_lock, flags);
810 io_cqring_ev_posted(ctx);
812 while (!list_empty(&list)) {
813 req = list_first_entry(&list, struct io_kiocb, list);
814 list_del(&req->list);
821 static void io_cqring_fill_event(struct io_kiocb *req, long res)
823 struct io_ring_ctx *ctx = req->ctx;
824 struct io_uring_cqe *cqe;
826 trace_io_uring_complete(ctx, req->user_data, res);
829 * If we can't get a cq entry, userspace overflowed the
830 * submission (by quite a lot). Increment the overflow count in
833 cqe = io_get_cqring(ctx);
835 WRITE_ONCE(cqe->user_data, req->user_data);
836 WRITE_ONCE(cqe->res, res);
837 WRITE_ONCE(cqe->flags, 0);
838 } else if (ctx->cq_overflow_flushed) {
839 WRITE_ONCE(ctx->rings->cq_overflow,
840 atomic_inc_return(&ctx->cached_cq_overflow));
842 refcount_inc(&req->refs);
844 list_add_tail(&req->list, &ctx->cq_overflow_list);
848 static void io_cqring_add_event(struct io_kiocb *req, long res)
850 struct io_ring_ctx *ctx = req->ctx;
853 spin_lock_irqsave(&ctx->completion_lock, flags);
854 io_cqring_fill_event(req, res);
855 io_commit_cqring(ctx);
856 spin_unlock_irqrestore(&ctx->completion_lock, flags);
858 io_cqring_ev_posted(ctx);
861 static inline bool io_is_fallback_req(struct io_kiocb *req)
863 return req == (struct io_kiocb *)
864 ((unsigned long) req->ctx->fallback_req & ~1UL);
867 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
869 struct io_kiocb *req;
871 req = ctx->fallback_req;
872 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
878 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
879 struct io_submit_state *state)
881 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
882 struct io_kiocb *req;
884 if (!percpu_ref_tryget(&ctx->refs))
888 req = kmem_cache_alloc(req_cachep, gfp);
891 } else if (!state->free_reqs) {
895 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
896 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
899 * Bulk alloc is all-or-nothing. If we fail to get a batch,
900 * retry single alloc to be on the safe side.
902 if (unlikely(ret <= 0)) {
903 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
908 state->free_reqs = ret - 1;
910 req = state->reqs[0];
912 req = state->reqs[state->cur_req];
919 req->ring_file = NULL;
923 /* one is dropped after submission, the other at completion */
924 refcount_set(&req->refs, 2);
926 INIT_IO_WORK(&req->work, io_wq_submit_work);
929 req = io_get_fallback_req(ctx);
932 percpu_ref_put(&ctx->refs);
936 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
939 kmem_cache_free_bulk(req_cachep, *nr, reqs);
940 percpu_ref_put_many(&ctx->refs, *nr);
945 static void __io_free_req(struct io_kiocb *req)
947 struct io_ring_ctx *ctx = req->ctx;
951 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
953 if (req->flags & REQ_F_INFLIGHT) {
956 spin_lock_irqsave(&ctx->inflight_lock, flags);
957 list_del(&req->inflight_entry);
958 if (waitqueue_active(&ctx->inflight_wait))
959 wake_up(&ctx->inflight_wait);
960 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
962 percpu_ref_put(&ctx->refs);
963 if (likely(!io_is_fallback_req(req)))
964 kmem_cache_free(req_cachep, req);
966 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
969 static bool io_link_cancel_timeout(struct io_kiocb *req)
971 struct io_ring_ctx *ctx = req->ctx;
974 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
976 io_cqring_fill_event(req, -ECANCELED);
977 io_commit_cqring(ctx);
978 req->flags &= ~REQ_F_LINK;
986 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
988 struct io_ring_ctx *ctx = req->ctx;
989 bool wake_ev = false;
991 /* Already got next link */
992 if (req->flags & REQ_F_LINK_NEXT)
996 * The list should never be empty when we are called here. But could
997 * potentially happen if the chain is messed up, check to be on the
1000 while (!list_empty(&req->link_list)) {
1001 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1002 struct io_kiocb, link_list);
1004 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1005 (nxt->flags & REQ_F_TIMEOUT))) {
1006 list_del_init(&nxt->link_list);
1007 wake_ev |= io_link_cancel_timeout(nxt);
1008 req->flags &= ~REQ_F_LINK_TIMEOUT;
1012 list_del_init(&req->link_list);
1013 if (!list_empty(&nxt->link_list))
1014 nxt->flags |= REQ_F_LINK;
1019 req->flags |= REQ_F_LINK_NEXT;
1021 io_cqring_ev_posted(ctx);
1025 * Called if REQ_F_LINK is set, and we fail the head request
1027 static void io_fail_links(struct io_kiocb *req)
1029 struct io_ring_ctx *ctx = req->ctx;
1030 unsigned long flags;
1032 spin_lock_irqsave(&ctx->completion_lock, flags);
1034 while (!list_empty(&req->link_list)) {
1035 struct io_kiocb *link = list_first_entry(&req->link_list,
1036 struct io_kiocb, link_list);
1038 list_del_init(&link->link_list);
1039 trace_io_uring_fail_link(req, link);
1041 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1042 link->opcode == IORING_OP_LINK_TIMEOUT) {
1043 io_link_cancel_timeout(link);
1045 io_cqring_fill_event(link, -ECANCELED);
1046 __io_double_put_req(link);
1048 req->flags &= ~REQ_F_LINK_TIMEOUT;
1051 io_commit_cqring(ctx);
1052 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1053 io_cqring_ev_posted(ctx);
1056 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1058 if (likely(!(req->flags & REQ_F_LINK)))
1062 * If LINK is set, we have dependent requests in this chain. If we
1063 * didn't fail this request, queue the first one up, moving any other
1064 * dependencies to the next request. In case of failure, fail the rest
1067 if (req->flags & REQ_F_FAIL_LINK) {
1069 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1070 REQ_F_LINK_TIMEOUT) {
1071 struct io_ring_ctx *ctx = req->ctx;
1072 unsigned long flags;
1075 * If this is a timeout link, we could be racing with the
1076 * timeout timer. Grab the completion lock for this case to
1077 * protect against that.
1079 spin_lock_irqsave(&ctx->completion_lock, flags);
1080 io_req_link_next(req, nxt);
1081 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1083 io_req_link_next(req, nxt);
1087 static void io_free_req(struct io_kiocb *req)
1089 struct io_kiocb *nxt = NULL;
1091 io_req_find_next(req, &nxt);
1095 io_queue_async_work(nxt);
1099 * Drop reference to request, return next in chain (if there is one) if this
1100 * was the last reference to this request.
1102 __attribute__((nonnull))
1103 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1105 io_req_find_next(req, nxtptr);
1107 if (refcount_dec_and_test(&req->refs))
1111 static void io_put_req(struct io_kiocb *req)
1113 if (refcount_dec_and_test(&req->refs))
1118 * Must only be used if we don't need to care about links, usually from
1119 * within the completion handling itself.
1121 static void __io_double_put_req(struct io_kiocb *req)
1123 /* drop both submit and complete references */
1124 if (refcount_sub_and_test(2, &req->refs))
1128 static void io_double_put_req(struct io_kiocb *req)
1130 /* drop both submit and complete references */
1131 if (refcount_sub_and_test(2, &req->refs))
1135 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1137 struct io_rings *rings = ctx->rings;
1140 * noflush == true is from the waitqueue handler, just ensure we wake
1141 * up the task, and the next invocation will flush the entries. We
1142 * cannot safely to it from here.
1144 if (noflush && !list_empty(&ctx->cq_overflow_list))
1147 io_cqring_overflow_flush(ctx, false);
1149 /* See comment at the top of this file */
1151 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1154 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1156 struct io_rings *rings = ctx->rings;
1158 /* make sure SQ entry isn't read before tail */
1159 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1163 * Find and free completed poll iocbs
1165 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1166 struct list_head *done)
1168 void *reqs[IO_IOPOLL_BATCH];
1169 struct io_kiocb *req;
1173 while (!list_empty(done)) {
1174 req = list_first_entry(done, struct io_kiocb, list);
1175 list_del(&req->list);
1177 io_cqring_fill_event(req, req->result);
1180 if (refcount_dec_and_test(&req->refs)) {
1181 /* If we're not using fixed files, we have to pair the
1182 * completion part with the file put. Use regular
1183 * completions for those, only batch free for fixed
1184 * file and non-linked commands.
1186 if (((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
1187 REQ_F_FIXED_FILE) && !io_is_fallback_req(req) &&
1189 reqs[to_free++] = req;
1190 if (to_free == ARRAY_SIZE(reqs))
1191 io_free_req_many(ctx, reqs, &to_free);
1198 io_commit_cqring(ctx);
1199 io_free_req_many(ctx, reqs, &to_free);
1202 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1205 struct io_kiocb *req, *tmp;
1211 * Only spin for completions if we don't have multiple devices hanging
1212 * off our complete list, and we're under the requested amount.
1214 spin = !ctx->poll_multi_file && *nr_events < min;
1217 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1218 struct kiocb *kiocb = &req->rw.kiocb;
1221 * Move completed entries to our local list. If we find a
1222 * request that requires polling, break out and complete
1223 * the done list first, if we have entries there.
1225 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1226 list_move_tail(&req->list, &done);
1229 if (!list_empty(&done))
1232 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1241 if (!list_empty(&done))
1242 io_iopoll_complete(ctx, nr_events, &done);
1248 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1249 * non-spinning poll check - we'll still enter the driver poll loop, but only
1250 * as a non-spinning completion check.
1252 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1255 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1258 ret = io_do_iopoll(ctx, nr_events, min);
1261 if (!min || *nr_events >= min)
1269 * We can't just wait for polled events to come to us, we have to actively
1270 * find and complete them.
1272 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1274 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1277 mutex_lock(&ctx->uring_lock);
1278 while (!list_empty(&ctx->poll_list)) {
1279 unsigned int nr_events = 0;
1281 io_iopoll_getevents(ctx, &nr_events, 1);
1284 * Ensure we allow local-to-the-cpu processing to take place,
1285 * in this case we need to ensure that we reap all events.
1289 mutex_unlock(&ctx->uring_lock);
1292 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1295 int iters = 0, ret = 0;
1301 * Don't enter poll loop if we already have events pending.
1302 * If we do, we can potentially be spinning for commands that
1303 * already triggered a CQE (eg in error).
1305 if (io_cqring_events(ctx, false))
1309 * If a submit got punted to a workqueue, we can have the
1310 * application entering polling for a command before it gets
1311 * issued. That app will hold the uring_lock for the duration
1312 * of the poll right here, so we need to take a breather every
1313 * now and then to ensure that the issue has a chance to add
1314 * the poll to the issued list. Otherwise we can spin here
1315 * forever, while the workqueue is stuck trying to acquire the
1318 if (!(++iters & 7)) {
1319 mutex_unlock(&ctx->uring_lock);
1320 mutex_lock(&ctx->uring_lock);
1323 if (*nr_events < min)
1324 tmin = min - *nr_events;
1326 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1330 } while (min && !*nr_events && !need_resched());
1335 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1341 * We disallow the app entering submit/complete with polling, but we
1342 * still need to lock the ring to prevent racing with polled issue
1343 * that got punted to a workqueue.
1345 mutex_lock(&ctx->uring_lock);
1346 ret = __io_iopoll_check(ctx, nr_events, min);
1347 mutex_unlock(&ctx->uring_lock);
1351 static void kiocb_end_write(struct io_kiocb *req)
1354 * Tell lockdep we inherited freeze protection from submission
1357 if (req->flags & REQ_F_ISREG) {
1358 struct inode *inode = file_inode(req->file);
1360 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1362 file_end_write(req->file);
1365 static inline void req_set_fail_links(struct io_kiocb *req)
1367 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1368 req->flags |= REQ_F_FAIL_LINK;
1371 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1373 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1375 if (kiocb->ki_flags & IOCB_WRITE)
1376 kiocb_end_write(req);
1378 if (res != req->result)
1379 req_set_fail_links(req);
1380 io_cqring_add_event(req, res);
1383 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1385 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1387 io_complete_rw_common(kiocb, res);
1391 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1393 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1394 struct io_kiocb *nxt = NULL;
1396 io_complete_rw_common(kiocb, res);
1397 io_put_req_find_next(req, &nxt);
1402 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1404 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1406 if (kiocb->ki_flags & IOCB_WRITE)
1407 kiocb_end_write(req);
1409 if (res != req->result)
1410 req_set_fail_links(req);
1413 req->flags |= REQ_F_IOPOLL_COMPLETED;
1417 * After the iocb has been issued, it's safe to be found on the poll list.
1418 * Adding the kiocb to the list AFTER submission ensures that we don't
1419 * find it from a io_iopoll_getevents() thread before the issuer is done
1420 * accessing the kiocb cookie.
1422 static void io_iopoll_req_issued(struct io_kiocb *req)
1424 struct io_ring_ctx *ctx = req->ctx;
1427 * Track whether we have multiple files in our lists. This will impact
1428 * how we do polling eventually, not spinning if we're on potentially
1429 * different devices.
1431 if (list_empty(&ctx->poll_list)) {
1432 ctx->poll_multi_file = false;
1433 } else if (!ctx->poll_multi_file) {
1434 struct io_kiocb *list_req;
1436 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1438 if (list_req->file != req->file)
1439 ctx->poll_multi_file = true;
1443 * For fast devices, IO may have already completed. If it has, add
1444 * it to the front so we find it first.
1446 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1447 list_add(&req->list, &ctx->poll_list);
1449 list_add_tail(&req->list, &ctx->poll_list);
1452 static void io_file_put(struct io_submit_state *state)
1455 int diff = state->has_refs - state->used_refs;
1458 fput_many(state->file, diff);
1464 * Get as many references to a file as we have IOs left in this submission,
1465 * assuming most submissions are for one file, or at least that each file
1466 * has more than one submission.
1468 static struct file *io_file_get(struct io_submit_state *state, int fd)
1474 if (state->fd == fd) {
1481 state->file = fget_many(fd, state->ios_left);
1486 state->has_refs = state->ios_left;
1487 state->used_refs = 1;
1493 * If we tracked the file through the SCM inflight mechanism, we could support
1494 * any file. For now, just ensure that anything potentially problematic is done
1497 static bool io_file_supports_async(struct file *file)
1499 umode_t mode = file_inode(file)->i_mode;
1501 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1503 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1509 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1510 bool force_nonblock)
1512 struct io_ring_ctx *ctx = req->ctx;
1513 struct kiocb *kiocb = &req->rw.kiocb;
1520 if (S_ISREG(file_inode(req->file)->i_mode))
1521 req->flags |= REQ_F_ISREG;
1523 kiocb->ki_pos = READ_ONCE(sqe->off);
1524 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1525 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1527 ioprio = READ_ONCE(sqe->ioprio);
1529 ret = ioprio_check_cap(ioprio);
1533 kiocb->ki_ioprio = ioprio;
1535 kiocb->ki_ioprio = get_current_ioprio();
1537 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1541 /* don't allow async punt if RWF_NOWAIT was requested */
1542 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1543 (req->file->f_flags & O_NONBLOCK))
1544 req->flags |= REQ_F_NOWAIT;
1547 kiocb->ki_flags |= IOCB_NOWAIT;
1549 if (ctx->flags & IORING_SETUP_IOPOLL) {
1550 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1551 !kiocb->ki_filp->f_op->iopoll)
1554 kiocb->ki_flags |= IOCB_HIPRI;
1555 kiocb->ki_complete = io_complete_rw_iopoll;
1558 if (kiocb->ki_flags & IOCB_HIPRI)
1560 kiocb->ki_complete = io_complete_rw;
1563 req->rw.addr = READ_ONCE(sqe->addr);
1564 req->rw.len = READ_ONCE(sqe->len);
1565 /* we own ->private, reuse it for the buffer index */
1566 req->rw.kiocb.private = (void *) (unsigned long)
1567 READ_ONCE(sqe->buf_index);
1571 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1577 case -ERESTARTNOINTR:
1578 case -ERESTARTNOHAND:
1579 case -ERESTART_RESTARTBLOCK:
1581 * We can't just restart the syscall, since previously
1582 * submitted sqes may already be in progress. Just fail this
1588 kiocb->ki_complete(kiocb, ret, 0);
1592 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1595 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1596 *nxt = __io_complete_rw(kiocb, ret);
1598 io_rw_done(kiocb, ret);
1601 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1602 struct iov_iter *iter)
1604 struct io_ring_ctx *ctx = req->ctx;
1605 size_t len = req->rw.len;
1606 struct io_mapped_ubuf *imu;
1607 unsigned index, buf_index;
1611 /* attempt to use fixed buffers without having provided iovecs */
1612 if (unlikely(!ctx->user_bufs))
1615 buf_index = (unsigned long) req->rw.kiocb.private;
1616 if (unlikely(buf_index >= ctx->nr_user_bufs))
1619 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1620 imu = &ctx->user_bufs[index];
1621 buf_addr = req->rw.addr;
1624 if (buf_addr + len < buf_addr)
1626 /* not inside the mapped region */
1627 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1631 * May not be a start of buffer, set size appropriately
1632 * and advance us to the beginning.
1634 offset = buf_addr - imu->ubuf;
1635 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1639 * Don't use iov_iter_advance() here, as it's really slow for
1640 * using the latter parts of a big fixed buffer - it iterates
1641 * over each segment manually. We can cheat a bit here, because
1644 * 1) it's a BVEC iter, we set it up
1645 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1646 * first and last bvec
1648 * So just find our index, and adjust the iterator afterwards.
1649 * If the offset is within the first bvec (or the whole first
1650 * bvec, just use iov_iter_advance(). This makes it easier
1651 * since we can just skip the first segment, which may not
1652 * be PAGE_SIZE aligned.
1654 const struct bio_vec *bvec = imu->bvec;
1656 if (offset <= bvec->bv_len) {
1657 iov_iter_advance(iter, offset);
1659 unsigned long seg_skip;
1661 /* skip first vec */
1662 offset -= bvec->bv_len;
1663 seg_skip = 1 + (offset >> PAGE_SHIFT);
1665 iter->bvec = bvec + seg_skip;
1666 iter->nr_segs -= seg_skip;
1667 iter->count -= bvec->bv_len + offset;
1668 iter->iov_offset = offset & ~PAGE_MASK;
1675 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1676 struct iovec **iovec, struct iov_iter *iter)
1678 void __user *buf = u64_to_user_ptr(req->rw.addr);
1679 size_t sqe_len = req->rw.len;
1682 opcode = req->opcode;
1683 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1685 return io_import_fixed(req, rw, iter);
1688 /* buffer index only valid with fixed read/write */
1689 if (req->rw.kiocb.private)
1693 struct io_async_rw *iorw = &req->io->rw;
1696 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1697 if (iorw->iov == iorw->fast_iov)
1705 #ifdef CONFIG_COMPAT
1706 if (req->ctx->compat)
1707 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1711 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1715 * For files that don't have ->read_iter() and ->write_iter(), handle them
1716 * by looping over ->read() or ->write() manually.
1718 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1719 struct iov_iter *iter)
1724 * Don't support polled IO through this interface, and we can't
1725 * support non-blocking either. For the latter, this just causes
1726 * the kiocb to be handled from an async context.
1728 if (kiocb->ki_flags & IOCB_HIPRI)
1730 if (kiocb->ki_flags & IOCB_NOWAIT)
1733 while (iov_iter_count(iter)) {
1737 if (!iov_iter_is_bvec(iter)) {
1738 iovec = iov_iter_iovec(iter);
1740 /* fixed buffers import bvec */
1741 iovec.iov_base = kmap(iter->bvec->bv_page)
1743 iovec.iov_len = min(iter->count,
1744 iter->bvec->bv_len - iter->iov_offset);
1748 nr = file->f_op->read(file, iovec.iov_base,
1749 iovec.iov_len, &kiocb->ki_pos);
1751 nr = file->f_op->write(file, iovec.iov_base,
1752 iovec.iov_len, &kiocb->ki_pos);
1755 if (iov_iter_is_bvec(iter))
1756 kunmap(iter->bvec->bv_page);
1764 if (nr != iovec.iov_len)
1766 iov_iter_advance(iter, nr);
1772 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
1773 struct iovec *iovec, struct iovec *fast_iov,
1774 struct iov_iter *iter)
1776 req->io->rw.nr_segs = iter->nr_segs;
1777 req->io->rw.size = io_size;
1778 req->io->rw.iov = iovec;
1779 if (!req->io->rw.iov) {
1780 req->io->rw.iov = req->io->rw.fast_iov;
1781 memcpy(req->io->rw.iov, fast_iov,
1782 sizeof(struct iovec) * iter->nr_segs);
1786 static int io_alloc_async_ctx(struct io_kiocb *req)
1788 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
1789 return req->io == NULL;
1792 static void io_rw_async(struct io_wq_work **workptr)
1794 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1795 struct iovec *iov = NULL;
1797 if (req->io->rw.iov != req->io->rw.fast_iov)
1798 iov = req->io->rw.iov;
1799 io_wq_submit_work(workptr);
1803 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
1804 struct iovec *iovec, struct iovec *fast_iov,
1805 struct iov_iter *iter)
1807 if (req->opcode == IORING_OP_READ_FIXED ||
1808 req->opcode == IORING_OP_WRITE_FIXED)
1810 if (!req->io && io_alloc_async_ctx(req))
1813 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
1814 req->work.func = io_rw_async;
1818 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1819 bool force_nonblock)
1821 struct io_async_ctx *io;
1822 struct iov_iter iter;
1825 ret = io_prep_rw(req, sqe, force_nonblock);
1829 if (unlikely(!(req->file->f_mode & FMODE_READ)))
1836 io->rw.iov = io->rw.fast_iov;
1838 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
1843 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
1847 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1848 bool force_nonblock)
1850 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1851 struct kiocb *kiocb = &req->rw.kiocb;
1852 struct iov_iter iter;
1854 ssize_t io_size, ret;
1856 ret = io_import_iovec(READ, req, &iovec, &iter);
1860 /* Ensure we clear previously set non-block flag */
1861 if (!force_nonblock)
1862 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
1866 if (req->flags & REQ_F_LINK)
1867 req->result = io_size;
1870 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1871 * we know to async punt it even if it was opened O_NONBLOCK
1873 if (force_nonblock && !io_file_supports_async(req->file)) {
1874 req->flags |= REQ_F_MUST_PUNT;
1878 iov_count = iov_iter_count(&iter);
1879 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
1883 if (req->file->f_op->read_iter)
1884 ret2 = call_read_iter(req->file, kiocb, &iter);
1886 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
1888 /* Catch -EAGAIN return for forced non-blocking submission */
1889 if (!force_nonblock || ret2 != -EAGAIN) {
1890 kiocb_done(kiocb, ret2, nxt, req->in_async);
1893 ret = io_setup_async_rw(req, io_size, iovec,
1894 inline_vecs, &iter);
1901 if (!io_wq_current_is_worker())
1906 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1907 bool force_nonblock)
1909 struct io_async_ctx *io;
1910 struct iov_iter iter;
1913 ret = io_prep_rw(req, sqe, force_nonblock);
1917 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
1924 io->rw.iov = io->rw.fast_iov;
1926 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
1931 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
1935 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1936 bool force_nonblock)
1938 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1939 struct kiocb *kiocb = &req->rw.kiocb;
1940 struct iov_iter iter;
1942 ssize_t ret, io_size;
1944 ret = io_import_iovec(WRITE, req, &iovec, &iter);
1948 /* Ensure we clear previously set non-block flag */
1949 if (!force_nonblock)
1950 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
1954 if (req->flags & REQ_F_LINK)
1955 req->result = io_size;
1958 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1959 * we know to async punt it even if it was opened O_NONBLOCK
1961 if (force_nonblock && !io_file_supports_async(req->file)) {
1962 req->flags |= REQ_F_MUST_PUNT;
1966 /* file path doesn't support NOWAIT for non-direct_IO */
1967 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
1968 (req->flags & REQ_F_ISREG))
1971 iov_count = iov_iter_count(&iter);
1972 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
1977 * Open-code file_start_write here to grab freeze protection,
1978 * which will be released by another thread in
1979 * io_complete_rw(). Fool lockdep by telling it the lock got
1980 * released so that it doesn't complain about the held lock when
1981 * we return to userspace.
1983 if (req->flags & REQ_F_ISREG) {
1984 __sb_start_write(file_inode(req->file)->i_sb,
1985 SB_FREEZE_WRITE, true);
1986 __sb_writers_release(file_inode(req->file)->i_sb,
1989 kiocb->ki_flags |= IOCB_WRITE;
1991 if (req->file->f_op->write_iter)
1992 ret2 = call_write_iter(req->file, kiocb, &iter);
1994 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
1995 if (!force_nonblock || ret2 != -EAGAIN) {
1996 kiocb_done(kiocb, ret2, nxt, req->in_async);
1999 ret = io_setup_async_rw(req, io_size, iovec,
2000 inline_vecs, &iter);
2007 if (!io_wq_current_is_worker())
2013 * IORING_OP_NOP just posts a completion event, nothing else.
2015 static int io_nop(struct io_kiocb *req)
2017 struct io_ring_ctx *ctx = req->ctx;
2019 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2022 io_cqring_add_event(req, 0);
2027 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2029 struct io_ring_ctx *ctx = req->ctx;
2034 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2036 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2039 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2040 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2043 req->sync.off = READ_ONCE(sqe->off);
2044 req->sync.len = READ_ONCE(sqe->len);
2048 static bool io_req_cancelled(struct io_kiocb *req)
2050 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2051 req_set_fail_links(req);
2052 io_cqring_add_event(req, -ECANCELED);
2060 static void io_link_work_cb(struct io_wq_work **workptr)
2062 struct io_wq_work *work = *workptr;
2063 struct io_kiocb *link = work->data;
2065 io_queue_linked_timeout(link);
2066 work->func = io_wq_submit_work;
2069 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2071 struct io_kiocb *link;
2073 io_prep_async_work(nxt, &link);
2074 *workptr = &nxt->work;
2076 nxt->work.flags |= IO_WQ_WORK_CB;
2077 nxt->work.func = io_link_work_cb;
2078 nxt->work.data = link;
2082 static void io_fsync_finish(struct io_wq_work **workptr)
2084 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2085 loff_t end = req->sync.off + req->sync.len;
2086 struct io_kiocb *nxt = NULL;
2089 if (io_req_cancelled(req))
2092 ret = vfs_fsync_range(req->file, req->sync.off,
2093 end > 0 ? end : LLONG_MAX,
2094 req->sync.flags & IORING_FSYNC_DATASYNC);
2096 req_set_fail_links(req);
2097 io_cqring_add_event(req, ret);
2098 io_put_req_find_next(req, &nxt);
2100 io_wq_assign_next(workptr, nxt);
2103 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2104 bool force_nonblock)
2106 struct io_wq_work *work, *old_work;
2108 /* fsync always requires a blocking context */
2109 if (force_nonblock) {
2111 req->work.func = io_fsync_finish;
2115 work = old_work = &req->work;
2116 io_fsync_finish(&work);
2117 if (work && work != old_work)
2118 *nxt = container_of(work, struct io_kiocb, work);
2122 static void io_fallocate_finish(struct io_wq_work **workptr)
2124 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2125 struct io_kiocb *nxt = NULL;
2128 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2131 req_set_fail_links(req);
2132 io_cqring_add_event(req, ret);
2133 io_put_req_find_next(req, &nxt);
2135 io_wq_assign_next(workptr, nxt);
2138 static int io_fallocate_prep(struct io_kiocb *req,
2139 const struct io_uring_sqe *sqe)
2141 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2144 req->sync.off = READ_ONCE(sqe->off);
2145 req->sync.len = READ_ONCE(sqe->addr);
2146 req->sync.mode = READ_ONCE(sqe->len);
2150 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2151 bool force_nonblock)
2153 struct io_wq_work *work, *old_work;
2155 /* fallocate always requiring blocking context */
2156 if (force_nonblock) {
2158 req->work.func = io_fallocate_finish;
2162 work = old_work = &req->work;
2163 io_fallocate_finish(&work);
2164 if (work && work != old_work)
2165 *nxt = container_of(work, struct io_kiocb, work);
2170 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2174 if (sqe->ioprio || sqe->buf_index)
2177 req->open.dfd = READ_ONCE(sqe->fd);
2178 req->open.mode = READ_ONCE(sqe->len);
2179 req->open.fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2180 req->open.flags = READ_ONCE(sqe->open_flags);
2182 req->open.filename = getname(req->open.fname);
2183 if (IS_ERR(req->open.filename)) {
2184 ret = PTR_ERR(req->open.filename);
2185 req->open.filename = NULL;
2192 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2193 bool force_nonblock)
2195 struct open_flags op;
2196 struct open_how how;
2200 if (force_nonblock) {
2201 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2205 how = build_open_how(req->open.flags, req->open.mode);
2206 ret = build_open_flags(&how, &op);
2210 ret = get_unused_fd_flags(how.flags);
2214 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2217 ret = PTR_ERR(file);
2219 fsnotify_open(file);
2220 fd_install(ret, file);
2223 putname(req->open.filename);
2225 req_set_fail_links(req);
2226 io_cqring_add_event(req, ret);
2227 io_put_req_find_next(req, nxt);
2231 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2233 struct io_ring_ctx *ctx = req->ctx;
2238 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2240 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2243 req->sync.off = READ_ONCE(sqe->off);
2244 req->sync.len = READ_ONCE(sqe->len);
2245 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2249 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2251 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2252 struct io_kiocb *nxt = NULL;
2255 if (io_req_cancelled(req))
2258 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2261 req_set_fail_links(req);
2262 io_cqring_add_event(req, ret);
2263 io_put_req_find_next(req, &nxt);
2265 io_wq_assign_next(workptr, nxt);
2268 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2269 bool force_nonblock)
2271 struct io_wq_work *work, *old_work;
2273 /* sync_file_range always requires a blocking context */
2274 if (force_nonblock) {
2276 req->work.func = io_sync_file_range_finish;
2280 work = old_work = &req->work;
2281 io_sync_file_range_finish(&work);
2282 if (work && work != old_work)
2283 *nxt = container_of(work, struct io_kiocb, work);
2287 #if defined(CONFIG_NET)
2288 static void io_sendrecv_async(struct io_wq_work **workptr)
2290 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2291 struct iovec *iov = NULL;
2293 if (req->io->rw.iov != req->io->rw.fast_iov)
2294 iov = req->io->msg.iov;
2295 io_wq_submit_work(workptr);
2300 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2302 #if defined(CONFIG_NET)
2303 struct io_sr_msg *sr = &req->sr_msg;
2304 struct io_async_ctx *io = req->io;
2306 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2307 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2312 io->msg.iov = io->msg.fast_iov;
2313 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2320 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2321 bool force_nonblock)
2323 #if defined(CONFIG_NET)
2324 struct io_async_msghdr *kmsg = NULL;
2325 struct socket *sock;
2328 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2331 sock = sock_from_file(req->file, &ret);
2333 struct io_async_ctx io;
2334 struct sockaddr_storage addr;
2338 kmsg = &req->io->msg;
2339 kmsg->msg.msg_name = &addr;
2340 /* if iov is set, it's allocated already */
2342 kmsg->iov = kmsg->fast_iov;
2343 kmsg->msg.msg_iter.iov = kmsg->iov;
2345 struct io_sr_msg *sr = &req->sr_msg;
2348 kmsg->msg.msg_name = &addr;
2350 io.msg.iov = io.msg.fast_iov;
2351 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2352 sr->msg_flags, &io.msg.iov);
2357 flags = req->sr_msg.msg_flags;
2358 if (flags & MSG_DONTWAIT)
2359 req->flags |= REQ_F_NOWAIT;
2360 else if (force_nonblock)
2361 flags |= MSG_DONTWAIT;
2363 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2364 if (force_nonblock && ret == -EAGAIN) {
2367 if (io_alloc_async_ctx(req))
2369 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2370 req->work.func = io_sendrecv_async;
2373 if (ret == -ERESTARTSYS)
2377 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2379 io_cqring_add_event(req, ret);
2381 req_set_fail_links(req);
2382 io_put_req_find_next(req, nxt);
2389 static int io_recvmsg_prep(struct io_kiocb *req,
2390 const struct io_uring_sqe *sqe)
2392 #if defined(CONFIG_NET)
2393 struct io_sr_msg *sr = &req->sr_msg;
2394 struct io_async_ctx *io = req->io;
2396 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2397 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2402 io->msg.iov = io->msg.fast_iov;
2403 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2404 &io->msg.uaddr, &io->msg.iov);
2410 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2411 bool force_nonblock)
2413 #if defined(CONFIG_NET)
2414 struct io_async_msghdr *kmsg = NULL;
2415 struct socket *sock;
2418 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2421 sock = sock_from_file(req->file, &ret);
2423 struct io_async_ctx io;
2424 struct sockaddr_storage addr;
2428 kmsg = &req->io->msg;
2429 kmsg->msg.msg_name = &addr;
2430 /* if iov is set, it's allocated already */
2432 kmsg->iov = kmsg->fast_iov;
2433 kmsg->msg.msg_iter.iov = kmsg->iov;
2435 struct io_sr_msg *sr = &req->sr_msg;
2438 kmsg->msg.msg_name = &addr;
2440 io.msg.iov = io.msg.fast_iov;
2441 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
2442 sr->msg_flags, &io.msg.uaddr,
2448 flags = req->sr_msg.msg_flags;
2449 if (flags & MSG_DONTWAIT)
2450 req->flags |= REQ_F_NOWAIT;
2451 else if (force_nonblock)
2452 flags |= MSG_DONTWAIT;
2454 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
2455 kmsg->uaddr, flags);
2456 if (force_nonblock && ret == -EAGAIN) {
2459 if (io_alloc_async_ctx(req))
2461 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2462 req->work.func = io_sendrecv_async;
2465 if (ret == -ERESTARTSYS)
2469 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2471 io_cqring_add_event(req, ret);
2473 req_set_fail_links(req);
2474 io_put_req_find_next(req, nxt);
2481 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2483 #if defined(CONFIG_NET)
2484 struct io_accept *accept = &req->accept;
2486 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2488 if (sqe->ioprio || sqe->len || sqe->buf_index)
2491 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
2492 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2493 accept->flags = READ_ONCE(sqe->accept_flags);
2500 #if defined(CONFIG_NET)
2501 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2502 bool force_nonblock)
2504 struct io_accept *accept = &req->accept;
2505 unsigned file_flags;
2508 file_flags = force_nonblock ? O_NONBLOCK : 0;
2509 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
2510 accept->addr_len, accept->flags);
2511 if (ret == -EAGAIN && force_nonblock)
2513 if (ret == -ERESTARTSYS)
2516 req_set_fail_links(req);
2517 io_cqring_add_event(req, ret);
2518 io_put_req_find_next(req, nxt);
2522 static void io_accept_finish(struct io_wq_work **workptr)
2524 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2525 struct io_kiocb *nxt = NULL;
2527 if (io_req_cancelled(req))
2529 __io_accept(req, &nxt, false);
2531 io_wq_assign_next(workptr, nxt);
2535 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2536 bool force_nonblock)
2538 #if defined(CONFIG_NET)
2541 ret = __io_accept(req, nxt, force_nonblock);
2542 if (ret == -EAGAIN && force_nonblock) {
2543 req->work.func = io_accept_finish;
2544 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2554 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2556 #if defined(CONFIG_NET)
2557 struct io_connect *conn = &req->connect;
2558 struct io_async_ctx *io = req->io;
2560 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2562 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
2565 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
2566 conn->addr_len = READ_ONCE(sqe->addr2);
2571 return move_addr_to_kernel(conn->addr, conn->addr_len,
2572 &io->connect.address);
2578 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
2579 bool force_nonblock)
2581 #if defined(CONFIG_NET)
2582 struct io_async_ctx __io, *io;
2583 unsigned file_flags;
2589 ret = move_addr_to_kernel(req->connect.addr,
2590 req->connect.addr_len,
2591 &__io.connect.address);
2597 file_flags = force_nonblock ? O_NONBLOCK : 0;
2599 ret = __sys_connect_file(req->file, &io->connect.address,
2600 req->connect.addr_len, file_flags);
2601 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
2604 if (io_alloc_async_ctx(req)) {
2608 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
2611 if (ret == -ERESTARTSYS)
2615 req_set_fail_links(req);
2616 io_cqring_add_event(req, ret);
2617 io_put_req_find_next(req, nxt);
2624 static void io_poll_remove_one(struct io_kiocb *req)
2626 struct io_poll_iocb *poll = &req->poll;
2628 spin_lock(&poll->head->lock);
2629 WRITE_ONCE(poll->canceled, true);
2630 if (!list_empty(&poll->wait.entry)) {
2631 list_del_init(&poll->wait.entry);
2632 io_queue_async_work(req);
2634 spin_unlock(&poll->head->lock);
2635 hash_del(&req->hash_node);
2638 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2640 struct hlist_node *tmp;
2641 struct io_kiocb *req;
2644 spin_lock_irq(&ctx->completion_lock);
2645 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
2646 struct hlist_head *list;
2648 list = &ctx->cancel_hash[i];
2649 hlist_for_each_entry_safe(req, tmp, list, hash_node)
2650 io_poll_remove_one(req);
2652 spin_unlock_irq(&ctx->completion_lock);
2655 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2657 struct hlist_head *list;
2658 struct io_kiocb *req;
2660 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
2661 hlist_for_each_entry(req, list, hash_node) {
2662 if (sqe_addr == req->user_data) {
2663 io_poll_remove_one(req);
2671 static int io_poll_remove_prep(struct io_kiocb *req,
2672 const struct io_uring_sqe *sqe)
2674 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2676 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2680 req->poll.addr = READ_ONCE(sqe->addr);
2685 * Find a running poll command that matches one specified in sqe->addr,
2686 * and remove it if found.
2688 static int io_poll_remove(struct io_kiocb *req)
2690 struct io_ring_ctx *ctx = req->ctx;
2694 addr = req->poll.addr;
2695 spin_lock_irq(&ctx->completion_lock);
2696 ret = io_poll_cancel(ctx, addr);
2697 spin_unlock_irq(&ctx->completion_lock);
2699 io_cqring_add_event(req, ret);
2701 req_set_fail_links(req);
2706 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
2708 struct io_ring_ctx *ctx = req->ctx;
2710 req->poll.done = true;
2712 io_cqring_fill_event(req, error);
2714 io_cqring_fill_event(req, mangle_poll(mask));
2715 io_commit_cqring(ctx);
2718 static void io_poll_complete_work(struct io_wq_work **workptr)
2720 struct io_wq_work *work = *workptr;
2721 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2722 struct io_poll_iocb *poll = &req->poll;
2723 struct poll_table_struct pt = { ._key = poll->events };
2724 struct io_ring_ctx *ctx = req->ctx;
2725 struct io_kiocb *nxt = NULL;
2729 if (work->flags & IO_WQ_WORK_CANCEL) {
2730 WRITE_ONCE(poll->canceled, true);
2732 } else if (READ_ONCE(poll->canceled)) {
2736 if (ret != -ECANCELED)
2737 mask = vfs_poll(poll->file, &pt) & poll->events;
2740 * Note that ->ki_cancel callers also delete iocb from active_reqs after
2741 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
2742 * synchronize with them. In the cancellation case the list_del_init
2743 * itself is not actually needed, but harmless so we keep it in to
2744 * avoid further branches in the fast path.
2746 spin_lock_irq(&ctx->completion_lock);
2747 if (!mask && ret != -ECANCELED) {
2748 add_wait_queue(poll->head, &poll->wait);
2749 spin_unlock_irq(&ctx->completion_lock);
2752 hash_del(&req->hash_node);
2753 io_poll_complete(req, mask, ret);
2754 spin_unlock_irq(&ctx->completion_lock);
2756 io_cqring_ev_posted(ctx);
2759 req_set_fail_links(req);
2760 io_put_req_find_next(req, &nxt);
2762 io_wq_assign_next(workptr, nxt);
2765 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2768 struct io_poll_iocb *poll = wait->private;
2769 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2770 struct io_ring_ctx *ctx = req->ctx;
2771 __poll_t mask = key_to_poll(key);
2772 unsigned long flags;
2774 /* for instances that support it check for an event match first: */
2775 if (mask && !(mask & poll->events))
2778 list_del_init(&poll->wait.entry);
2781 * Run completion inline if we can. We're using trylock here because
2782 * we are violating the completion_lock -> poll wq lock ordering.
2783 * If we have a link timeout we're going to need the completion_lock
2784 * for finalizing the request, mark us as having grabbed that already.
2786 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2787 hash_del(&req->hash_node);
2788 io_poll_complete(req, mask, 0);
2789 req->flags |= REQ_F_COMP_LOCKED;
2791 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2793 io_cqring_ev_posted(ctx);
2795 io_queue_async_work(req);
2801 struct io_poll_table {
2802 struct poll_table_struct pt;
2803 struct io_kiocb *req;
2807 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2808 struct poll_table_struct *p)
2810 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2812 if (unlikely(pt->req->poll.head)) {
2813 pt->error = -EINVAL;
2818 pt->req->poll.head = head;
2819 add_wait_queue(head, &pt->req->poll.wait);
2822 static void io_poll_req_insert(struct io_kiocb *req)
2824 struct io_ring_ctx *ctx = req->ctx;
2825 struct hlist_head *list;
2827 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
2828 hlist_add_head(&req->hash_node, list);
2831 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2833 struct io_poll_iocb *poll = &req->poll;
2836 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2838 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2843 events = READ_ONCE(sqe->poll_events);
2844 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2848 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
2850 struct io_poll_iocb *poll = &req->poll;
2851 struct io_ring_ctx *ctx = req->ctx;
2852 struct io_poll_table ipt;
2853 bool cancel = false;
2856 INIT_IO_WORK(&req->work, io_poll_complete_work);
2857 INIT_HLIST_NODE(&req->hash_node);
2861 poll->canceled = false;
2863 ipt.pt._qproc = io_poll_queue_proc;
2864 ipt.pt._key = poll->events;
2866 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2868 /* initialized the list so that we can do list_empty checks */
2869 INIT_LIST_HEAD(&poll->wait.entry);
2870 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
2871 poll->wait.private = poll;
2873 INIT_LIST_HEAD(&req->list);
2875 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2877 spin_lock_irq(&ctx->completion_lock);
2878 if (likely(poll->head)) {
2879 spin_lock(&poll->head->lock);
2880 if (unlikely(list_empty(&poll->wait.entry))) {
2886 if (mask || ipt.error)
2887 list_del_init(&poll->wait.entry);
2889 WRITE_ONCE(poll->canceled, true);
2890 else if (!poll->done) /* actually waiting for an event */
2891 io_poll_req_insert(req);
2892 spin_unlock(&poll->head->lock);
2894 if (mask) { /* no async, we'd stolen it */
2896 io_poll_complete(req, mask, 0);
2898 spin_unlock_irq(&ctx->completion_lock);
2901 io_cqring_ev_posted(ctx);
2902 io_put_req_find_next(req, nxt);
2907 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
2909 struct io_timeout_data *data = container_of(timer,
2910 struct io_timeout_data, timer);
2911 struct io_kiocb *req = data->req;
2912 struct io_ring_ctx *ctx = req->ctx;
2913 unsigned long flags;
2915 atomic_inc(&ctx->cq_timeouts);
2917 spin_lock_irqsave(&ctx->completion_lock, flags);
2919 * We could be racing with timeout deletion. If the list is empty,
2920 * then timeout lookup already found it and will be handling it.
2922 if (!list_empty(&req->list)) {
2923 struct io_kiocb *prev;
2926 * Adjust the reqs sequence before the current one because it
2927 * will consume a slot in the cq_ring and the cq_tail
2928 * pointer will be increased, otherwise other timeout reqs may
2929 * return in advance without waiting for enough wait_nr.
2932 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
2934 list_del_init(&req->list);
2937 io_cqring_fill_event(req, -ETIME);
2938 io_commit_cqring(ctx);
2939 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2941 io_cqring_ev_posted(ctx);
2942 req_set_fail_links(req);
2944 return HRTIMER_NORESTART;
2947 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
2949 struct io_kiocb *req;
2952 list_for_each_entry(req, &ctx->timeout_list, list) {
2953 if (user_data == req->user_data) {
2954 list_del_init(&req->list);
2963 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
2967 req_set_fail_links(req);
2968 io_cqring_fill_event(req, -ECANCELED);
2973 static int io_timeout_remove_prep(struct io_kiocb *req,
2974 const struct io_uring_sqe *sqe)
2976 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2978 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2981 req->timeout.addr = READ_ONCE(sqe->addr);
2982 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
2983 if (req->timeout.flags)
2990 * Remove or update an existing timeout command
2992 static int io_timeout_remove(struct io_kiocb *req)
2994 struct io_ring_ctx *ctx = req->ctx;
2997 spin_lock_irq(&ctx->completion_lock);
2998 ret = io_timeout_cancel(ctx, req->timeout.addr);
3000 io_cqring_fill_event(req, ret);
3001 io_commit_cqring(ctx);
3002 spin_unlock_irq(&ctx->completion_lock);
3003 io_cqring_ev_posted(ctx);
3005 req_set_fail_links(req);
3010 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3011 bool is_timeout_link)
3013 struct io_timeout_data *data;
3016 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3018 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3020 if (sqe->off && is_timeout_link)
3022 flags = READ_ONCE(sqe->timeout_flags);
3023 if (flags & ~IORING_TIMEOUT_ABS)
3026 req->timeout.count = READ_ONCE(sqe->off);
3028 if (!req->io && io_alloc_async_ctx(req))
3031 data = &req->io->timeout;
3033 req->flags |= REQ_F_TIMEOUT;
3035 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3038 if (flags & IORING_TIMEOUT_ABS)
3039 data->mode = HRTIMER_MODE_ABS;
3041 data->mode = HRTIMER_MODE_REL;
3043 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3047 static int io_timeout(struct io_kiocb *req)
3050 struct io_ring_ctx *ctx = req->ctx;
3051 struct io_timeout_data *data;
3052 struct list_head *entry;
3055 data = &req->io->timeout;
3058 * sqe->off holds how many events that need to occur for this
3059 * timeout event to be satisfied. If it isn't set, then this is
3060 * a pure timeout request, sequence isn't used.
3062 count = req->timeout.count;
3064 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3065 spin_lock_irq(&ctx->completion_lock);
3066 entry = ctx->timeout_list.prev;
3070 req->sequence = ctx->cached_sq_head + count - 1;
3071 data->seq_offset = count;
3074 * Insertion sort, ensuring the first entry in the list is always
3075 * the one we need first.
3077 spin_lock_irq(&ctx->completion_lock);
3078 list_for_each_prev(entry, &ctx->timeout_list) {
3079 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3080 unsigned nxt_sq_head;
3081 long long tmp, tmp_nxt;
3082 u32 nxt_offset = nxt->io->timeout.seq_offset;
3084 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3088 * Since cached_sq_head + count - 1 can overflow, use type long
3091 tmp = (long long)ctx->cached_sq_head + count - 1;
3092 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3093 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3096 * cached_sq_head may overflow, and it will never overflow twice
3097 * once there is some timeout req still be valid.
3099 if (ctx->cached_sq_head < nxt_sq_head)
3106 * Sequence of reqs after the insert one and itself should
3107 * be adjusted because each timeout req consumes a slot.
3112 req->sequence -= span;
3114 list_add(&req->list, entry);
3115 data->timer.function = io_timeout_fn;
3116 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3117 spin_unlock_irq(&ctx->completion_lock);
3121 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3123 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3125 return req->user_data == (unsigned long) data;
3128 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3130 enum io_wq_cancel cancel_ret;
3133 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3134 switch (cancel_ret) {
3135 case IO_WQ_CANCEL_OK:
3138 case IO_WQ_CANCEL_RUNNING:
3141 case IO_WQ_CANCEL_NOTFOUND:
3149 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3150 struct io_kiocb *req, __u64 sqe_addr,
3151 struct io_kiocb **nxt, int success_ret)
3153 unsigned long flags;
3156 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3157 if (ret != -ENOENT) {
3158 spin_lock_irqsave(&ctx->completion_lock, flags);
3162 spin_lock_irqsave(&ctx->completion_lock, flags);
3163 ret = io_timeout_cancel(ctx, sqe_addr);
3166 ret = io_poll_cancel(ctx, sqe_addr);
3170 io_cqring_fill_event(req, ret);
3171 io_commit_cqring(ctx);
3172 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3173 io_cqring_ev_posted(ctx);
3176 req_set_fail_links(req);
3177 io_put_req_find_next(req, nxt);
3180 static int io_async_cancel_prep(struct io_kiocb *req,
3181 const struct io_uring_sqe *sqe)
3183 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3185 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3189 req->cancel.addr = READ_ONCE(sqe->addr);
3193 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3195 struct io_ring_ctx *ctx = req->ctx;
3197 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3201 static int io_req_defer_prep(struct io_kiocb *req,
3202 const struct io_uring_sqe *sqe)
3206 switch (req->opcode) {
3209 case IORING_OP_READV:
3210 case IORING_OP_READ_FIXED:
3211 ret = io_read_prep(req, sqe, true);
3213 case IORING_OP_WRITEV:
3214 case IORING_OP_WRITE_FIXED:
3215 ret = io_write_prep(req, sqe, true);
3217 case IORING_OP_POLL_ADD:
3218 ret = io_poll_add_prep(req, sqe);
3220 case IORING_OP_POLL_REMOVE:
3221 ret = io_poll_remove_prep(req, sqe);
3223 case IORING_OP_FSYNC:
3224 ret = io_prep_fsync(req, sqe);
3226 case IORING_OP_SYNC_FILE_RANGE:
3227 ret = io_prep_sfr(req, sqe);
3229 case IORING_OP_SENDMSG:
3230 ret = io_sendmsg_prep(req, sqe);
3232 case IORING_OP_RECVMSG:
3233 ret = io_recvmsg_prep(req, sqe);
3235 case IORING_OP_CONNECT:
3236 ret = io_connect_prep(req, sqe);
3238 case IORING_OP_TIMEOUT:
3239 ret = io_timeout_prep(req, sqe, false);
3241 case IORING_OP_TIMEOUT_REMOVE:
3242 ret = io_timeout_remove_prep(req, sqe);
3244 case IORING_OP_ASYNC_CANCEL:
3245 ret = io_async_cancel_prep(req, sqe);
3247 case IORING_OP_LINK_TIMEOUT:
3248 ret = io_timeout_prep(req, sqe, true);
3250 case IORING_OP_ACCEPT:
3251 ret = io_accept_prep(req, sqe);
3253 case IORING_OP_FALLOCATE:
3254 ret = io_fallocate_prep(req, sqe);
3256 case IORING_OP_OPENAT:
3257 ret = io_openat_prep(req, sqe);
3260 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
3269 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3271 struct io_ring_ctx *ctx = req->ctx;
3274 /* Still need defer if there is pending req in defer list. */
3275 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
3278 if (!req->io && io_alloc_async_ctx(req))
3281 ret = io_req_defer_prep(req, sqe);
3285 spin_lock_irq(&ctx->completion_lock);
3286 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
3287 spin_unlock_irq(&ctx->completion_lock);
3291 trace_io_uring_defer(ctx, req, req->user_data);
3292 list_add_tail(&req->list, &ctx->defer_list);
3293 spin_unlock_irq(&ctx->completion_lock);
3294 return -EIOCBQUEUED;
3297 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3298 struct io_kiocb **nxt, bool force_nonblock)
3300 struct io_ring_ctx *ctx = req->ctx;
3303 switch (req->opcode) {
3307 case IORING_OP_READV:
3308 case IORING_OP_READ_FIXED:
3310 ret = io_read_prep(req, sqe, force_nonblock);
3314 ret = io_read(req, nxt, force_nonblock);
3316 case IORING_OP_WRITEV:
3317 case IORING_OP_WRITE_FIXED:
3319 ret = io_write_prep(req, sqe, force_nonblock);
3323 ret = io_write(req, nxt, force_nonblock);
3325 case IORING_OP_FSYNC:
3327 ret = io_prep_fsync(req, sqe);
3331 ret = io_fsync(req, nxt, force_nonblock);
3333 case IORING_OP_POLL_ADD:
3335 ret = io_poll_add_prep(req, sqe);
3339 ret = io_poll_add(req, nxt);
3341 case IORING_OP_POLL_REMOVE:
3343 ret = io_poll_remove_prep(req, sqe);
3347 ret = io_poll_remove(req);
3349 case IORING_OP_SYNC_FILE_RANGE:
3351 ret = io_prep_sfr(req, sqe);
3355 ret = io_sync_file_range(req, nxt, force_nonblock);
3357 case IORING_OP_SENDMSG:
3359 ret = io_sendmsg_prep(req, sqe);
3363 ret = io_sendmsg(req, nxt, force_nonblock);
3365 case IORING_OP_RECVMSG:
3367 ret = io_recvmsg_prep(req, sqe);
3371 ret = io_recvmsg(req, nxt, force_nonblock);
3373 case IORING_OP_TIMEOUT:
3375 ret = io_timeout_prep(req, sqe, false);
3379 ret = io_timeout(req);
3381 case IORING_OP_TIMEOUT_REMOVE:
3383 ret = io_timeout_remove_prep(req, sqe);
3387 ret = io_timeout_remove(req);
3389 case IORING_OP_ACCEPT:
3391 ret = io_accept_prep(req, sqe);
3395 ret = io_accept(req, nxt, force_nonblock);
3397 case IORING_OP_CONNECT:
3399 ret = io_connect_prep(req, sqe);
3403 ret = io_connect(req, nxt, force_nonblock);
3405 case IORING_OP_ASYNC_CANCEL:
3407 ret = io_async_cancel_prep(req, sqe);
3411 ret = io_async_cancel(req, nxt);
3413 case IORING_OP_FALLOCATE:
3415 ret = io_fallocate_prep(req, sqe);
3419 ret = io_fallocate(req, nxt, force_nonblock);
3421 case IORING_OP_OPENAT:
3423 ret = io_openat_prep(req, sqe);
3427 ret = io_openat(req, nxt, force_nonblock);
3437 if (ctx->flags & IORING_SETUP_IOPOLL) {
3438 const bool in_async = io_wq_current_is_worker();
3440 if (req->result == -EAGAIN)
3443 /* workqueue context doesn't hold uring_lock, grab it now */
3445 mutex_lock(&ctx->uring_lock);
3447 io_iopoll_req_issued(req);
3450 mutex_unlock(&ctx->uring_lock);
3456 static void io_wq_submit_work(struct io_wq_work **workptr)
3458 struct io_wq_work *work = *workptr;
3459 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3460 struct io_kiocb *nxt = NULL;
3463 if (work->flags & IO_WQ_WORK_CANCEL)
3467 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
3468 req->in_async = true;
3470 ret = io_issue_sqe(req, NULL, &nxt, false);
3472 * We can get EAGAIN for polled IO even though we're
3473 * forcing a sync submission from here, since we can't
3474 * wait for request slots on the block side.
3482 /* drop submission reference */
3486 req_set_fail_links(req);
3487 io_cqring_add_event(req, ret);
3491 /* if a dependent link is ready, pass it back */
3493 io_wq_assign_next(workptr, nxt);
3496 static bool io_req_op_valid(int op)
3498 return op >= IORING_OP_NOP && op < IORING_OP_LAST;
3501 static int io_req_needs_file(struct io_kiocb *req, int fd)
3503 switch (req->opcode) {
3505 case IORING_OP_POLL_REMOVE:
3506 case IORING_OP_TIMEOUT:
3507 case IORING_OP_TIMEOUT_REMOVE:
3508 case IORING_OP_ASYNC_CANCEL:
3509 case IORING_OP_LINK_TIMEOUT:
3511 case IORING_OP_OPENAT:
3514 if (io_req_op_valid(req->opcode))
3520 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
3523 struct fixed_file_table *table;
3525 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
3526 return table->files[index & IORING_FILE_TABLE_MASK];
3529 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
3530 const struct io_uring_sqe *sqe)
3532 struct io_ring_ctx *ctx = req->ctx;
3536 flags = READ_ONCE(sqe->flags);
3537 fd = READ_ONCE(sqe->fd);
3539 if (flags & IOSQE_IO_DRAIN)
3540 req->flags |= REQ_F_IO_DRAIN;
3542 ret = io_req_needs_file(req, fd);
3546 if (flags & IOSQE_FIXED_FILE) {
3547 if (unlikely(!ctx->file_table ||
3548 (unsigned) fd >= ctx->nr_user_files))
3550 fd = array_index_nospec(fd, ctx->nr_user_files);
3551 req->file = io_file_from_index(ctx, fd);
3554 req->flags |= REQ_F_FIXED_FILE;
3556 if (req->needs_fixed_file)
3558 trace_io_uring_file_get(ctx, fd);
3559 req->file = io_file_get(state, fd);
3560 if (unlikely(!req->file))
3567 static int io_grab_files(struct io_kiocb *req)
3570 struct io_ring_ctx *ctx = req->ctx;
3573 spin_lock_irq(&ctx->inflight_lock);
3575 * We use the f_ops->flush() handler to ensure that we can flush
3576 * out work accessing these files if the fd is closed. Check if
3577 * the fd has changed since we started down this path, and disallow
3578 * this operation if it has.
3580 if (fcheck(req->ring_fd) == req->ring_file) {
3581 list_add(&req->inflight_entry, &ctx->inflight_list);
3582 req->flags |= REQ_F_INFLIGHT;
3583 req->work.files = current->files;
3586 spin_unlock_irq(&ctx->inflight_lock);
3592 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
3594 struct io_timeout_data *data = container_of(timer,
3595 struct io_timeout_data, timer);
3596 struct io_kiocb *req = data->req;
3597 struct io_ring_ctx *ctx = req->ctx;
3598 struct io_kiocb *prev = NULL;
3599 unsigned long flags;
3601 spin_lock_irqsave(&ctx->completion_lock, flags);
3604 * We don't expect the list to be empty, that will only happen if we
3605 * race with the completion of the linked work.
3607 if (!list_empty(&req->link_list)) {
3608 prev = list_entry(req->link_list.prev, struct io_kiocb,
3610 if (refcount_inc_not_zero(&prev->refs)) {
3611 list_del_init(&req->link_list);
3612 prev->flags &= ~REQ_F_LINK_TIMEOUT;
3617 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3620 req_set_fail_links(prev);
3621 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
3625 io_cqring_add_event(req, -ETIME);
3628 return HRTIMER_NORESTART;
3631 static void io_queue_linked_timeout(struct io_kiocb *req)
3633 struct io_ring_ctx *ctx = req->ctx;
3636 * If the list is now empty, then our linked request finished before
3637 * we got a chance to setup the timer
3639 spin_lock_irq(&ctx->completion_lock);
3640 if (!list_empty(&req->link_list)) {
3641 struct io_timeout_data *data = &req->io->timeout;
3643 data->timer.function = io_link_timeout_fn;
3644 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
3647 spin_unlock_irq(&ctx->completion_lock);
3649 /* drop submission reference */
3653 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
3655 struct io_kiocb *nxt;
3657 if (!(req->flags & REQ_F_LINK))
3660 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
3662 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
3665 req->flags |= REQ_F_LINK_TIMEOUT;
3669 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3671 struct io_kiocb *linked_timeout;
3672 struct io_kiocb *nxt = NULL;
3676 linked_timeout = io_prep_linked_timeout(req);
3678 ret = io_issue_sqe(req, sqe, &nxt, true);
3681 * We async punt it if the file wasn't marked NOWAIT, or if the file
3682 * doesn't support non-blocking read/write attempts
3684 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
3685 (req->flags & REQ_F_MUST_PUNT))) {
3686 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
3687 ret = io_grab_files(req);
3693 * Queued up for async execution, worker will release
3694 * submit reference when the iocb is actually submitted.
3696 io_queue_async_work(req);
3701 /* drop submission reference */
3704 if (linked_timeout) {
3706 io_queue_linked_timeout(linked_timeout);
3708 io_put_req(linked_timeout);
3711 /* and drop final reference, if we failed */
3713 io_cqring_add_event(req, ret);
3714 req_set_fail_links(req);
3725 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3729 if (unlikely(req->ctx->drain_next)) {
3730 req->flags |= REQ_F_IO_DRAIN;
3731 req->ctx->drain_next = false;
3733 req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
3735 ret = io_req_defer(req, sqe);
3737 if (ret != -EIOCBQUEUED) {
3738 io_cqring_add_event(req, ret);
3739 req_set_fail_links(req);
3740 io_double_put_req(req);
3743 __io_queue_sqe(req, sqe);
3746 static inline void io_queue_link_head(struct io_kiocb *req)
3748 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
3749 io_cqring_add_event(req, -ECANCELED);
3750 io_double_put_req(req);
3752 io_queue_sqe(req, NULL);
3755 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
3758 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3759 struct io_submit_state *state, struct io_kiocb **link)
3761 struct io_ring_ctx *ctx = req->ctx;
3764 /* enforce forwards compatibility on users */
3765 if (unlikely(sqe->flags & ~SQE_VALID_FLAGS)) {
3770 ret = io_req_set_file(state, req, sqe);
3771 if (unlikely(ret)) {
3773 io_cqring_add_event(req, ret);
3774 io_double_put_req(req);
3779 * If we already have a head request, queue this one for async
3780 * submittal once the head completes. If we don't have a head but
3781 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3782 * submitted sync once the chain is complete. If none of those
3783 * conditions are true (normal request), then just queue it.
3786 struct io_kiocb *prev = *link;
3788 if (sqe->flags & IOSQE_IO_DRAIN)
3789 (*link)->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
3791 if (sqe->flags & IOSQE_IO_HARDLINK)
3792 req->flags |= REQ_F_HARDLINK;
3794 if (io_alloc_async_ctx(req)) {
3799 ret = io_req_defer_prep(req, sqe);
3801 /* fail even hard links since we don't submit */
3802 prev->flags |= REQ_F_FAIL_LINK;
3805 trace_io_uring_link(ctx, req, prev);
3806 list_add_tail(&req->link_list, &prev->link_list);
3807 } else if (sqe->flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
3808 req->flags |= REQ_F_LINK;
3809 if (sqe->flags & IOSQE_IO_HARDLINK)
3810 req->flags |= REQ_F_HARDLINK;
3812 INIT_LIST_HEAD(&req->link_list);
3813 ret = io_req_defer_prep(req, sqe);
3815 req->flags |= REQ_F_FAIL_LINK;
3818 io_queue_sqe(req, sqe);
3825 * Batched submission is done, ensure local IO is flushed out.
3827 static void io_submit_state_end(struct io_submit_state *state)
3829 blk_finish_plug(&state->plug);
3831 if (state->free_reqs)
3832 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3833 &state->reqs[state->cur_req]);
3837 * Start submission side cache.
3839 static void io_submit_state_start(struct io_submit_state *state,
3840 unsigned int max_ios)
3842 blk_start_plug(&state->plug);
3843 state->free_reqs = 0;
3845 state->ios_left = max_ios;
3848 static void io_commit_sqring(struct io_ring_ctx *ctx)
3850 struct io_rings *rings = ctx->rings;
3852 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3854 * Ensure any loads from the SQEs are done at this point,
3855 * since once we write the new head, the application could
3856 * write new data to them.
3858 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3863 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
3864 * that is mapped by userspace. This means that care needs to be taken to
3865 * ensure that reads are stable, as we cannot rely on userspace always
3866 * being a good citizen. If members of the sqe are validated and then later
3867 * used, it's important that those reads are done through READ_ONCE() to
3868 * prevent a re-load down the line.
3870 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
3871 const struct io_uring_sqe **sqe_ptr)
3873 struct io_rings *rings = ctx->rings;
3874 u32 *sq_array = ctx->sq_array;
3878 * The cached sq head (or cq tail) serves two purposes:
3880 * 1) allows us to batch the cost of updating the user visible
3882 * 2) allows the kernel side to track the head on its own, even
3883 * though the application is the one updating it.
3885 head = ctx->cached_sq_head;
3886 /* make sure SQ entry isn't read before tail */
3887 if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
3890 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
3891 if (likely(head < ctx->sq_entries)) {
3893 * All io need record the previous position, if LINK vs DARIN,
3894 * it can be used to mark the position of the first IO in the
3897 req->sequence = ctx->cached_sq_head;
3898 *sqe_ptr = &ctx->sq_sqes[head];
3899 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
3900 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
3901 ctx->cached_sq_head++;
3905 /* drop invalid entries */
3906 ctx->cached_sq_head++;
3907 ctx->cached_sq_dropped++;
3908 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
3912 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
3913 struct file *ring_file, int ring_fd,
3914 struct mm_struct **mm, bool async)
3916 struct io_submit_state state, *statep = NULL;
3917 struct io_kiocb *link = NULL;
3918 int i, submitted = 0;
3919 bool mm_fault = false;
3921 /* if we have a backlog and couldn't flush it all, return BUSY */
3922 if (!list_empty(&ctx->cq_overflow_list) &&
3923 !io_cqring_overflow_flush(ctx, false))
3926 if (nr > IO_PLUG_THRESHOLD) {
3927 io_submit_state_start(&state, nr);
3931 for (i = 0; i < nr; i++) {
3932 const struct io_uring_sqe *sqe;
3933 struct io_kiocb *req;
3934 unsigned int sqe_flags;
3936 req = io_get_req(ctx, statep);
3937 if (unlikely(!req)) {
3939 submitted = -EAGAIN;
3942 if (!io_get_sqring(ctx, req, &sqe)) {
3947 if (io_req_needs_user(req) && !*mm) {
3948 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
3950 use_mm(ctx->sqo_mm);
3956 sqe_flags = sqe->flags;
3958 req->ring_file = ring_file;
3959 req->ring_fd = ring_fd;
3960 req->has_user = *mm != NULL;
3961 req->in_async = async;
3962 req->needs_fixed_file = async;
3963 trace_io_uring_submit_sqe(ctx, req->user_data, true, async);
3964 if (!io_submit_sqe(req, sqe, statep, &link))
3967 * If previous wasn't linked and we have a linked command,
3968 * that's the end of the chain. Submit the previous link.
3970 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) && link) {
3971 io_queue_link_head(link);
3977 io_queue_link_head(link);
3979 io_submit_state_end(&state);
3981 /* Commit SQ ring head once we've consumed and submitted all SQEs */
3982 io_commit_sqring(ctx);
3987 static int io_sq_thread(void *data)
3989 struct io_ring_ctx *ctx = data;
3990 struct mm_struct *cur_mm = NULL;
3991 const struct cred *old_cred;
3992 mm_segment_t old_fs;
3995 unsigned long timeout;
3998 complete(&ctx->completions[1]);
4002 old_cred = override_creds(ctx->creds);
4004 ret = timeout = inflight = 0;
4005 while (!kthread_should_park()) {
4006 unsigned int to_submit;
4009 unsigned nr_events = 0;
4011 if (ctx->flags & IORING_SETUP_IOPOLL) {
4013 * inflight is the count of the maximum possible
4014 * entries we submitted, but it can be smaller
4015 * if we dropped some of them. If we don't have
4016 * poll entries available, then we know that we
4017 * have nothing left to poll for. Reset the
4018 * inflight count to zero in that case.
4020 mutex_lock(&ctx->uring_lock);
4021 if (!list_empty(&ctx->poll_list))
4022 __io_iopoll_check(ctx, &nr_events, 0);
4025 mutex_unlock(&ctx->uring_lock);
4028 * Normal IO, just pretend everything completed.
4029 * We don't have to poll completions for that.
4031 nr_events = inflight;
4034 inflight -= nr_events;
4036 timeout = jiffies + ctx->sq_thread_idle;
4039 to_submit = io_sqring_entries(ctx);
4042 * If submit got -EBUSY, flag us as needing the application
4043 * to enter the kernel to reap and flush events.
4045 if (!to_submit || ret == -EBUSY) {
4047 * We're polling. If we're within the defined idle
4048 * period, then let us spin without work before going
4049 * to sleep. The exception is if we got EBUSY doing
4050 * more IO, we should wait for the application to
4051 * reap events and wake us up.
4054 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4060 * Drop cur_mm before scheduling, we can't hold it for
4061 * long periods (or over schedule()). Do this before
4062 * adding ourselves to the waitqueue, as the unuse/drop
4071 prepare_to_wait(&ctx->sqo_wait, &wait,
4072 TASK_INTERRUPTIBLE);
4074 /* Tell userspace we may need a wakeup call */
4075 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4076 /* make sure to read SQ tail after writing flags */
4079 to_submit = io_sqring_entries(ctx);
4080 if (!to_submit || ret == -EBUSY) {
4081 if (kthread_should_park()) {
4082 finish_wait(&ctx->sqo_wait, &wait);
4085 if (signal_pending(current))
4086 flush_signals(current);
4088 finish_wait(&ctx->sqo_wait, &wait);
4090 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4093 finish_wait(&ctx->sqo_wait, &wait);
4095 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4098 to_submit = min(to_submit, ctx->sq_entries);
4099 mutex_lock(&ctx->uring_lock);
4100 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4101 mutex_unlock(&ctx->uring_lock);
4111 revert_creds(old_cred);
4118 struct io_wait_queue {
4119 struct wait_queue_entry wq;
4120 struct io_ring_ctx *ctx;
4122 unsigned nr_timeouts;
4125 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
4127 struct io_ring_ctx *ctx = iowq->ctx;
4130 * Wake up if we have enough events, or if a timeout occurred since we
4131 * started waiting. For timeouts, we always want to return to userspace,
4132 * regardless of event count.
4134 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
4135 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4138 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4139 int wake_flags, void *key)
4141 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4144 /* use noflush == true, as we can't safely rely on locking context */
4145 if (!io_should_wake(iowq, true))
4148 return autoremove_wake_function(curr, mode, wake_flags, key);
4152 * Wait until events become available, if we don't already have some. The
4153 * application must reap them itself, as they reside on the shared cq ring.
4155 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
4156 const sigset_t __user *sig, size_t sigsz)
4158 struct io_wait_queue iowq = {
4161 .func = io_wake_function,
4162 .entry = LIST_HEAD_INIT(iowq.wq.entry),
4165 .to_wait = min_events,
4167 struct io_rings *rings = ctx->rings;
4170 if (io_cqring_events(ctx, false) >= min_events)
4174 #ifdef CONFIG_COMPAT
4175 if (in_compat_syscall())
4176 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
4180 ret = set_user_sigmask(sig, sigsz);
4186 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4187 trace_io_uring_cqring_wait(ctx, min_events);
4189 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
4190 TASK_INTERRUPTIBLE);
4191 if (io_should_wake(&iowq, false))
4194 if (signal_pending(current)) {
4199 finish_wait(&ctx->wait, &iowq.wq);
4201 restore_saved_sigmask_unless(ret == -EINTR);
4203 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4206 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4208 #if defined(CONFIG_UNIX)
4209 if (ctx->ring_sock) {
4210 struct sock *sock = ctx->ring_sock->sk;
4211 struct sk_buff *skb;
4213 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4219 for (i = 0; i < ctx->nr_user_files; i++) {
4222 file = io_file_from_index(ctx, i);
4229 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4231 unsigned nr_tables, i;
4233 if (!ctx->file_table)
4236 __io_sqe_files_unregister(ctx);
4237 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
4238 for (i = 0; i < nr_tables; i++)
4239 kfree(ctx->file_table[i].files);
4240 kfree(ctx->file_table);
4241 ctx->file_table = NULL;
4242 ctx->nr_user_files = 0;
4246 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
4248 if (ctx->sqo_thread) {
4249 wait_for_completion(&ctx->completions[1]);
4251 * The park is a bit of a work-around, without it we get
4252 * warning spews on shutdown with SQPOLL set and affinity
4253 * set to a single CPU.
4255 kthread_park(ctx->sqo_thread);
4256 kthread_stop(ctx->sqo_thread);
4257 ctx->sqo_thread = NULL;
4261 static void io_finish_async(struct io_ring_ctx *ctx)
4263 io_sq_thread_stop(ctx);
4266 io_wq_destroy(ctx->io_wq);
4271 #if defined(CONFIG_UNIX)
4272 static void io_destruct_skb(struct sk_buff *skb)
4274 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
4277 io_wq_flush(ctx->io_wq);
4279 unix_destruct_scm(skb);
4283 * Ensure the UNIX gc is aware of our file set, so we are certain that
4284 * the io_uring can be safely unregistered on process exit, even if we have
4285 * loops in the file referencing.
4287 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
4289 struct sock *sk = ctx->ring_sock->sk;
4290 struct scm_fp_list *fpl;
4291 struct sk_buff *skb;
4294 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
4295 unsigned long inflight = ctx->user->unix_inflight + nr;
4297 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
4301 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4305 skb = alloc_skb(0, GFP_KERNEL);
4314 fpl->user = get_uid(ctx->user);
4315 for (i = 0; i < nr; i++) {
4316 struct file *file = io_file_from_index(ctx, i + offset);
4320 fpl->fp[nr_files] = get_file(file);
4321 unix_inflight(fpl->user, fpl->fp[nr_files]);
4326 fpl->max = SCM_MAX_FD;
4327 fpl->count = nr_files;
4328 UNIXCB(skb).fp = fpl;
4329 skb->destructor = io_destruct_skb;
4330 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4331 skb_queue_head(&sk->sk_receive_queue, skb);
4333 for (i = 0; i < nr_files; i++)
4344 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
4345 * causes regular reference counting to break down. We rely on the UNIX
4346 * garbage collection to take care of this problem for us.
4348 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4350 unsigned left, total;
4354 left = ctx->nr_user_files;
4356 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
4358 ret = __io_sqe_files_scm(ctx, this_files, total);
4362 total += this_files;
4368 while (total < ctx->nr_user_files) {
4369 struct file *file = io_file_from_index(ctx, total);
4379 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4385 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
4390 for (i = 0; i < nr_tables; i++) {
4391 struct fixed_file_table *table = &ctx->file_table[i];
4392 unsigned this_files;
4394 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
4395 table->files = kcalloc(this_files, sizeof(struct file *),
4399 nr_files -= this_files;
4405 for (i = 0; i < nr_tables; i++) {
4406 struct fixed_file_table *table = &ctx->file_table[i];
4407 kfree(table->files);
4412 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4415 __s32 __user *fds = (__s32 __user *) arg;
4420 if (ctx->file_table)
4424 if (nr_args > IORING_MAX_FIXED_FILES)
4427 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
4428 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
4430 if (!ctx->file_table)
4433 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
4434 kfree(ctx->file_table);
4435 ctx->file_table = NULL;
4439 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4440 struct fixed_file_table *table;
4444 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
4446 /* allow sparse sets */
4452 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4453 index = i & IORING_FILE_TABLE_MASK;
4454 table->files[index] = fget(fd);
4457 if (!table->files[index])
4460 * Don't allow io_uring instances to be registered. If UNIX
4461 * isn't enabled, then this causes a reference cycle and this
4462 * instance can never get freed. If UNIX is enabled we'll
4463 * handle it just fine, but there's still no point in allowing
4464 * a ring fd as it doesn't support regular read/write anyway.
4466 if (table->files[index]->f_op == &io_uring_fops) {
4467 fput(table->files[index]);
4474 for (i = 0; i < ctx->nr_user_files; i++) {
4477 file = io_file_from_index(ctx, i);
4481 for (i = 0; i < nr_tables; i++)
4482 kfree(ctx->file_table[i].files);
4484 kfree(ctx->file_table);
4485 ctx->file_table = NULL;
4486 ctx->nr_user_files = 0;
4490 ret = io_sqe_files_scm(ctx);
4492 io_sqe_files_unregister(ctx);
4497 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
4499 #if defined(CONFIG_UNIX)
4500 struct file *file = io_file_from_index(ctx, index);
4501 struct sock *sock = ctx->ring_sock->sk;
4502 struct sk_buff_head list, *head = &sock->sk_receive_queue;
4503 struct sk_buff *skb;
4506 __skb_queue_head_init(&list);
4509 * Find the skb that holds this file in its SCM_RIGHTS. When found,
4510 * remove this entry and rearrange the file array.
4512 skb = skb_dequeue(head);
4514 struct scm_fp_list *fp;
4516 fp = UNIXCB(skb).fp;
4517 for (i = 0; i < fp->count; i++) {
4520 if (fp->fp[i] != file)
4523 unix_notinflight(fp->user, fp->fp[i]);
4524 left = fp->count - 1 - i;
4526 memmove(&fp->fp[i], &fp->fp[i + 1],
4527 left * sizeof(struct file *));
4534 __skb_queue_tail(&list, skb);
4544 __skb_queue_tail(&list, skb);
4546 skb = skb_dequeue(head);
4549 if (skb_peek(&list)) {
4550 spin_lock_irq(&head->lock);
4551 while ((skb = __skb_dequeue(&list)) != NULL)
4552 __skb_queue_tail(head, skb);
4553 spin_unlock_irq(&head->lock);
4556 fput(io_file_from_index(ctx, index));
4560 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
4563 #if defined(CONFIG_UNIX)
4564 struct sock *sock = ctx->ring_sock->sk;
4565 struct sk_buff_head *head = &sock->sk_receive_queue;
4566 struct sk_buff *skb;
4569 * See if we can merge this file into an existing skb SCM_RIGHTS
4570 * file set. If there's no room, fall back to allocating a new skb
4571 * and filling it in.
4573 spin_lock_irq(&head->lock);
4574 skb = skb_peek(head);
4576 struct scm_fp_list *fpl = UNIXCB(skb).fp;
4578 if (fpl->count < SCM_MAX_FD) {
4579 __skb_unlink(skb, head);
4580 spin_unlock_irq(&head->lock);
4581 fpl->fp[fpl->count] = get_file(file);
4582 unix_inflight(fpl->user, fpl->fp[fpl->count]);
4584 spin_lock_irq(&head->lock);
4585 __skb_queue_head(head, skb);
4590 spin_unlock_irq(&head->lock);
4597 return __io_sqe_files_scm(ctx, 1, index);
4603 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
4606 struct io_uring_files_update up;
4611 if (!ctx->file_table)
4615 if (copy_from_user(&up, arg, sizeof(up)))
4619 if (check_add_overflow(up.offset, nr_args, &done))
4621 if (done > ctx->nr_user_files)
4625 fds = u64_to_user_ptr(up.fds);
4627 struct fixed_file_table *table;
4631 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
4635 i = array_index_nospec(up.offset, ctx->nr_user_files);
4636 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4637 index = i & IORING_FILE_TABLE_MASK;
4638 if (table->files[index]) {
4639 io_sqe_file_unregister(ctx, i);
4640 table->files[index] = NULL;
4651 * Don't allow io_uring instances to be registered. If
4652 * UNIX isn't enabled, then this causes a reference
4653 * cycle and this instance can never get freed. If UNIX
4654 * is enabled we'll handle it just fine, but there's
4655 * still no point in allowing a ring fd as it doesn't
4656 * support regular read/write anyway.
4658 if (file->f_op == &io_uring_fops) {
4663 table->files[index] = file;
4664 err = io_sqe_file_register(ctx, file, i);
4673 return done ? done : err;
4676 static void io_put_work(struct io_wq_work *work)
4678 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4683 static void io_get_work(struct io_wq_work *work)
4685 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4687 refcount_inc(&req->refs);
4690 static int io_sq_offload_start(struct io_ring_ctx *ctx,
4691 struct io_uring_params *p)
4693 struct io_wq_data data;
4694 unsigned concurrency;
4697 init_waitqueue_head(&ctx->sqo_wait);
4698 mmgrab(current->mm);
4699 ctx->sqo_mm = current->mm;
4701 if (ctx->flags & IORING_SETUP_SQPOLL) {
4703 if (!capable(CAP_SYS_ADMIN))
4706 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
4707 if (!ctx->sq_thread_idle)
4708 ctx->sq_thread_idle = HZ;
4710 if (p->flags & IORING_SETUP_SQ_AFF) {
4711 int cpu = p->sq_thread_cpu;
4714 if (cpu >= nr_cpu_ids)
4716 if (!cpu_online(cpu))
4719 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
4723 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
4726 if (IS_ERR(ctx->sqo_thread)) {
4727 ret = PTR_ERR(ctx->sqo_thread);
4728 ctx->sqo_thread = NULL;
4731 wake_up_process(ctx->sqo_thread);
4732 } else if (p->flags & IORING_SETUP_SQ_AFF) {
4733 /* Can't have SQ_AFF without SQPOLL */
4738 data.mm = ctx->sqo_mm;
4739 data.user = ctx->user;
4740 data.creds = ctx->creds;
4741 data.get_work = io_get_work;
4742 data.put_work = io_put_work;
4744 /* Do QD, or 4 * CPUS, whatever is smallest */
4745 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
4746 ctx->io_wq = io_wq_create(concurrency, &data);
4747 if (IS_ERR(ctx->io_wq)) {
4748 ret = PTR_ERR(ctx->io_wq);
4755 io_finish_async(ctx);
4756 mmdrop(ctx->sqo_mm);
4761 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
4763 atomic_long_sub(nr_pages, &user->locked_vm);
4766 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
4768 unsigned long page_limit, cur_pages, new_pages;
4770 /* Don't allow more pages than we can safely lock */
4771 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4774 cur_pages = atomic_long_read(&user->locked_vm);
4775 new_pages = cur_pages + nr_pages;
4776 if (new_pages > page_limit)
4778 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4779 new_pages) != cur_pages);
4784 static void io_mem_free(void *ptr)
4791 page = virt_to_head_page(ptr);
4792 if (put_page_testzero(page))
4793 free_compound_page(page);
4796 static void *io_mem_alloc(size_t size)
4798 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4801 return (void *) __get_free_pages(gfp_flags, get_order(size));
4804 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4807 struct io_rings *rings;
4808 size_t off, sq_array_size;
4810 off = struct_size(rings, cqes, cq_entries);
4811 if (off == SIZE_MAX)
4815 off = ALIGN(off, SMP_CACHE_BYTES);
4820 sq_array_size = array_size(sizeof(u32), sq_entries);
4821 if (sq_array_size == SIZE_MAX)
4824 if (check_add_overflow(off, sq_array_size, &off))
4833 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4837 pages = (size_t)1 << get_order(
4838 rings_size(sq_entries, cq_entries, NULL));
4839 pages += (size_t)1 << get_order(
4840 array_size(sizeof(struct io_uring_sqe), sq_entries));
4845 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4849 if (!ctx->user_bufs)
4852 for (i = 0; i < ctx->nr_user_bufs; i++) {
4853 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4855 for (j = 0; j < imu->nr_bvecs; j++)
4856 put_user_page(imu->bvec[j].bv_page);
4858 if (ctx->account_mem)
4859 io_unaccount_mem(ctx->user, imu->nr_bvecs);
4864 kfree(ctx->user_bufs);
4865 ctx->user_bufs = NULL;
4866 ctx->nr_user_bufs = 0;
4870 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4871 void __user *arg, unsigned index)
4873 struct iovec __user *src;
4875 #ifdef CONFIG_COMPAT
4877 struct compat_iovec __user *ciovs;
4878 struct compat_iovec ciov;
4880 ciovs = (struct compat_iovec __user *) arg;
4881 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4884 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
4885 dst->iov_len = ciov.iov_len;
4889 src = (struct iovec __user *) arg;
4890 if (copy_from_user(dst, &src[index], sizeof(*dst)))
4895 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
4898 struct vm_area_struct **vmas = NULL;
4899 struct page **pages = NULL;
4900 int i, j, got_pages = 0;
4905 if (!nr_args || nr_args > UIO_MAXIOV)
4908 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
4910 if (!ctx->user_bufs)
4913 for (i = 0; i < nr_args; i++) {
4914 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4915 unsigned long off, start, end, ubuf;
4920 ret = io_copy_iov(ctx, &iov, arg, i);
4925 * Don't impose further limits on the size and buffer
4926 * constraints here, we'll -EINVAL later when IO is
4927 * submitted if they are wrong.
4930 if (!iov.iov_base || !iov.iov_len)
4933 /* arbitrary limit, but we need something */
4934 if (iov.iov_len > SZ_1G)
4937 ubuf = (unsigned long) iov.iov_base;
4938 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
4939 start = ubuf >> PAGE_SHIFT;
4940 nr_pages = end - start;
4942 if (ctx->account_mem) {
4943 ret = io_account_mem(ctx->user, nr_pages);
4949 if (!pages || nr_pages > got_pages) {
4952 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
4954 vmas = kvmalloc_array(nr_pages,
4955 sizeof(struct vm_area_struct *),
4957 if (!pages || !vmas) {
4959 if (ctx->account_mem)
4960 io_unaccount_mem(ctx->user, nr_pages);
4963 got_pages = nr_pages;
4966 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
4970 if (ctx->account_mem)
4971 io_unaccount_mem(ctx->user, nr_pages);
4976 down_read(¤t->mm->mmap_sem);
4977 pret = get_user_pages(ubuf, nr_pages,
4978 FOLL_WRITE | FOLL_LONGTERM,
4980 if (pret == nr_pages) {
4981 /* don't support file backed memory */
4982 for (j = 0; j < nr_pages; j++) {
4983 struct vm_area_struct *vma = vmas[j];
4986 !is_file_hugepages(vma->vm_file)) {
4992 ret = pret < 0 ? pret : -EFAULT;
4994 up_read(¤t->mm->mmap_sem);
4997 * if we did partial map, or found file backed vmas,
4998 * release any pages we did get
5001 put_user_pages(pages, pret);
5002 if (ctx->account_mem)
5003 io_unaccount_mem(ctx->user, nr_pages);
5008 off = ubuf & ~PAGE_MASK;
5010 for (j = 0; j < nr_pages; j++) {
5013 vec_len = min_t(size_t, size, PAGE_SIZE - off);
5014 imu->bvec[j].bv_page = pages[j];
5015 imu->bvec[j].bv_len = vec_len;
5016 imu->bvec[j].bv_offset = off;
5020 /* store original address for later verification */
5022 imu->len = iov.iov_len;
5023 imu->nr_bvecs = nr_pages;
5025 ctx->nr_user_bufs++;
5033 io_sqe_buffer_unregister(ctx);
5037 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
5039 __s32 __user *fds = arg;
5045 if (copy_from_user(&fd, fds, sizeof(*fds)))
5048 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
5049 if (IS_ERR(ctx->cq_ev_fd)) {
5050 int ret = PTR_ERR(ctx->cq_ev_fd);
5051 ctx->cq_ev_fd = NULL;
5058 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5060 if (ctx->cq_ev_fd) {
5061 eventfd_ctx_put(ctx->cq_ev_fd);
5062 ctx->cq_ev_fd = NULL;
5069 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
5071 io_finish_async(ctx);
5073 mmdrop(ctx->sqo_mm);
5075 io_iopoll_reap_events(ctx);
5076 io_sqe_buffer_unregister(ctx);
5077 io_sqe_files_unregister(ctx);
5078 io_eventfd_unregister(ctx);
5080 #if defined(CONFIG_UNIX)
5081 if (ctx->ring_sock) {
5082 ctx->ring_sock->file = NULL; /* so that iput() is called */
5083 sock_release(ctx->ring_sock);
5087 io_mem_free(ctx->rings);
5088 io_mem_free(ctx->sq_sqes);
5090 percpu_ref_exit(&ctx->refs);
5091 if (ctx->account_mem)
5092 io_unaccount_mem(ctx->user,
5093 ring_pages(ctx->sq_entries, ctx->cq_entries));
5094 free_uid(ctx->user);
5095 put_cred(ctx->creds);
5096 kfree(ctx->completions);
5097 kfree(ctx->cancel_hash);
5098 kmem_cache_free(req_cachep, ctx->fallback_req);
5102 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5104 struct io_ring_ctx *ctx = file->private_data;
5107 poll_wait(file, &ctx->cq_wait, wait);
5109 * synchronizes with barrier from wq_has_sleeper call in
5113 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
5114 ctx->rings->sq_ring_entries)
5115 mask |= EPOLLOUT | EPOLLWRNORM;
5116 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
5117 mask |= EPOLLIN | EPOLLRDNORM;
5122 static int io_uring_fasync(int fd, struct file *file, int on)
5124 struct io_ring_ctx *ctx = file->private_data;
5126 return fasync_helper(fd, file, on, &ctx->cq_fasync);
5129 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5131 mutex_lock(&ctx->uring_lock);
5132 percpu_ref_kill(&ctx->refs);
5133 mutex_unlock(&ctx->uring_lock);
5135 io_kill_timeouts(ctx);
5136 io_poll_remove_all(ctx);
5139 io_wq_cancel_all(ctx->io_wq);
5141 io_iopoll_reap_events(ctx);
5142 /* if we failed setting up the ctx, we might not have any rings */
5144 io_cqring_overflow_flush(ctx, true);
5145 wait_for_completion(&ctx->completions[0]);
5146 io_ring_ctx_free(ctx);
5149 static int io_uring_release(struct inode *inode, struct file *file)
5151 struct io_ring_ctx *ctx = file->private_data;
5153 file->private_data = NULL;
5154 io_ring_ctx_wait_and_kill(ctx);
5158 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
5159 struct files_struct *files)
5161 struct io_kiocb *req;
5164 while (!list_empty_careful(&ctx->inflight_list)) {
5165 struct io_kiocb *cancel_req = NULL;
5167 spin_lock_irq(&ctx->inflight_lock);
5168 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
5169 if (req->work.files != files)
5171 /* req is being completed, ignore */
5172 if (!refcount_inc_not_zero(&req->refs))
5178 prepare_to_wait(&ctx->inflight_wait, &wait,
5179 TASK_UNINTERRUPTIBLE);
5180 spin_unlock_irq(&ctx->inflight_lock);
5182 /* We need to keep going until we don't find a matching req */
5186 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
5187 io_put_req(cancel_req);
5190 finish_wait(&ctx->inflight_wait, &wait);
5193 static int io_uring_flush(struct file *file, void *data)
5195 struct io_ring_ctx *ctx = file->private_data;
5197 io_uring_cancel_files(ctx, data);
5198 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
5199 io_cqring_overflow_flush(ctx, true);
5200 io_wq_cancel_all(ctx->io_wq);
5205 static void *io_uring_validate_mmap_request(struct file *file,
5206 loff_t pgoff, size_t sz)
5208 struct io_ring_ctx *ctx = file->private_data;
5209 loff_t offset = pgoff << PAGE_SHIFT;
5214 case IORING_OFF_SQ_RING:
5215 case IORING_OFF_CQ_RING:
5218 case IORING_OFF_SQES:
5222 return ERR_PTR(-EINVAL);
5225 page = virt_to_head_page(ptr);
5226 if (sz > page_size(page))
5227 return ERR_PTR(-EINVAL);
5234 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5236 size_t sz = vma->vm_end - vma->vm_start;
5240 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5242 return PTR_ERR(ptr);
5244 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5245 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5248 #else /* !CONFIG_MMU */
5250 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5252 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5255 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5257 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5260 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5261 unsigned long addr, unsigned long len,
5262 unsigned long pgoff, unsigned long flags)
5266 ptr = io_uring_validate_mmap_request(file, pgoff, len);
5268 return PTR_ERR(ptr);
5270 return (unsigned long) ptr;
5273 #endif /* !CONFIG_MMU */
5275 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5276 u32, min_complete, u32, flags, const sigset_t __user *, sig,
5279 struct io_ring_ctx *ctx;
5284 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
5292 if (f.file->f_op != &io_uring_fops)
5296 ctx = f.file->private_data;
5297 if (!percpu_ref_tryget(&ctx->refs))
5301 * For SQ polling, the thread will do all submissions and completions.
5302 * Just return the requested submit count, and wake the thread if
5306 if (ctx->flags & IORING_SETUP_SQPOLL) {
5307 if (!list_empty_careful(&ctx->cq_overflow_list))
5308 io_cqring_overflow_flush(ctx, false);
5309 if (flags & IORING_ENTER_SQ_WAKEUP)
5310 wake_up(&ctx->sqo_wait);
5311 submitted = to_submit;
5312 } else if (to_submit) {
5313 struct mm_struct *cur_mm;
5315 if (current->mm != ctx->sqo_mm ||
5316 current_cred() != ctx->creds) {
5321 to_submit = min(to_submit, ctx->sq_entries);
5322 mutex_lock(&ctx->uring_lock);
5323 /* already have mm, so io_submit_sqes() won't try to grab it */
5324 cur_mm = ctx->sqo_mm;
5325 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
5327 mutex_unlock(&ctx->uring_lock);
5329 if (submitted != to_submit)
5332 if (flags & IORING_ENTER_GETEVENTS) {
5333 unsigned nr_events = 0;
5335 min_complete = min(min_complete, ctx->cq_entries);
5337 if (ctx->flags & IORING_SETUP_IOPOLL) {
5338 ret = io_iopoll_check(ctx, &nr_events, min_complete);
5340 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
5345 percpu_ref_put(&ctx->refs);
5348 return submitted ? submitted : ret;
5351 static const struct file_operations io_uring_fops = {
5352 .release = io_uring_release,
5353 .flush = io_uring_flush,
5354 .mmap = io_uring_mmap,
5356 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5357 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5359 .poll = io_uring_poll,
5360 .fasync = io_uring_fasync,
5363 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5364 struct io_uring_params *p)
5366 struct io_rings *rings;
5367 size_t size, sq_array_offset;
5369 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
5370 if (size == SIZE_MAX)
5373 rings = io_mem_alloc(size);
5378 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5379 rings->sq_ring_mask = p->sq_entries - 1;
5380 rings->cq_ring_mask = p->cq_entries - 1;
5381 rings->sq_ring_entries = p->sq_entries;
5382 rings->cq_ring_entries = p->cq_entries;
5383 ctx->sq_mask = rings->sq_ring_mask;
5384 ctx->cq_mask = rings->cq_ring_mask;
5385 ctx->sq_entries = rings->sq_ring_entries;
5386 ctx->cq_entries = rings->cq_ring_entries;
5388 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5389 if (size == SIZE_MAX) {
5390 io_mem_free(ctx->rings);
5395 ctx->sq_sqes = io_mem_alloc(size);
5396 if (!ctx->sq_sqes) {
5397 io_mem_free(ctx->rings);
5406 * Allocate an anonymous fd, this is what constitutes the application
5407 * visible backing of an io_uring instance. The application mmaps this
5408 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
5409 * we have to tie this fd to a socket for file garbage collection purposes.
5411 static int io_uring_get_fd(struct io_ring_ctx *ctx)
5416 #if defined(CONFIG_UNIX)
5417 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
5423 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
5427 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
5428 O_RDWR | O_CLOEXEC);
5431 ret = PTR_ERR(file);
5435 #if defined(CONFIG_UNIX)
5436 ctx->ring_sock->file = file;
5437 ctx->ring_sock->sk->sk_user_data = ctx;
5439 fd_install(ret, file);
5442 #if defined(CONFIG_UNIX)
5443 sock_release(ctx->ring_sock);
5444 ctx->ring_sock = NULL;
5449 static int io_uring_create(unsigned entries, struct io_uring_params *p)
5451 struct user_struct *user = NULL;
5452 struct io_ring_ctx *ctx;
5456 if (!entries || entries > IORING_MAX_ENTRIES)
5460 * Use twice as many entries for the CQ ring. It's possible for the
5461 * application to drive a higher depth than the size of the SQ ring,
5462 * since the sqes are only used at submission time. This allows for
5463 * some flexibility in overcommitting a bit. If the application has
5464 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
5465 * of CQ ring entries manually.
5467 p->sq_entries = roundup_pow_of_two(entries);
5468 if (p->flags & IORING_SETUP_CQSIZE) {
5470 * If IORING_SETUP_CQSIZE is set, we do the same roundup
5471 * to a power-of-two, if it isn't already. We do NOT impose
5472 * any cq vs sq ring sizing.
5474 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
5476 p->cq_entries = roundup_pow_of_two(p->cq_entries);
5478 p->cq_entries = 2 * p->sq_entries;
5481 user = get_uid(current_user());
5482 account_mem = !capable(CAP_IPC_LOCK);
5485 ret = io_account_mem(user,
5486 ring_pages(p->sq_entries, p->cq_entries));
5493 ctx = io_ring_ctx_alloc(p);
5496 io_unaccount_mem(user, ring_pages(p->sq_entries,
5501 ctx->compat = in_compat_syscall();
5502 ctx->account_mem = account_mem;
5504 ctx->creds = get_current_cred();
5506 ret = io_allocate_scq_urings(ctx, p);
5510 ret = io_sq_offload_start(ctx, p);
5514 memset(&p->sq_off, 0, sizeof(p->sq_off));
5515 p->sq_off.head = offsetof(struct io_rings, sq.head);
5516 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
5517 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
5518 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
5519 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
5520 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
5521 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
5523 memset(&p->cq_off, 0, sizeof(p->cq_off));
5524 p->cq_off.head = offsetof(struct io_rings, cq.head);
5525 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
5526 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
5527 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
5528 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
5529 p->cq_off.cqes = offsetof(struct io_rings, cqes);
5532 * Install ring fd as the very last thing, so we don't risk someone
5533 * having closed it before we finish setup
5535 ret = io_uring_get_fd(ctx);
5539 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
5540 IORING_FEAT_SUBMIT_STABLE;
5541 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
5544 io_ring_ctx_wait_and_kill(ctx);
5549 * Sets up an aio uring context, and returns the fd. Applications asks for a
5550 * ring size, we return the actual sq/cq ring sizes (among other things) in the
5551 * params structure passed in.
5553 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
5555 struct io_uring_params p;
5559 if (copy_from_user(&p, params, sizeof(p)))
5561 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
5566 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
5567 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
5570 ret = io_uring_create(entries, &p);
5574 if (copy_to_user(params, &p, sizeof(p)))
5580 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
5581 struct io_uring_params __user *, params)
5583 return io_uring_setup(entries, params);
5586 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
5587 void __user *arg, unsigned nr_args)
5588 __releases(ctx->uring_lock)
5589 __acquires(ctx->uring_lock)
5594 * We're inside the ring mutex, if the ref is already dying, then
5595 * someone else killed the ctx or is already going through
5596 * io_uring_register().
5598 if (percpu_ref_is_dying(&ctx->refs))
5601 percpu_ref_kill(&ctx->refs);
5604 * Drop uring mutex before waiting for references to exit. If another
5605 * thread is currently inside io_uring_enter() it might need to grab
5606 * the uring_lock to make progress. If we hold it here across the drain
5607 * wait, then we can deadlock. It's safe to drop the mutex here, since
5608 * no new references will come in after we've killed the percpu ref.
5610 mutex_unlock(&ctx->uring_lock);
5611 wait_for_completion(&ctx->completions[0]);
5612 mutex_lock(&ctx->uring_lock);
5615 case IORING_REGISTER_BUFFERS:
5616 ret = io_sqe_buffer_register(ctx, arg, nr_args);
5618 case IORING_UNREGISTER_BUFFERS:
5622 ret = io_sqe_buffer_unregister(ctx);
5624 case IORING_REGISTER_FILES:
5625 ret = io_sqe_files_register(ctx, arg, nr_args);
5627 case IORING_UNREGISTER_FILES:
5631 ret = io_sqe_files_unregister(ctx);
5633 case IORING_REGISTER_FILES_UPDATE:
5634 ret = io_sqe_files_update(ctx, arg, nr_args);
5636 case IORING_REGISTER_EVENTFD:
5640 ret = io_eventfd_register(ctx, arg);
5642 case IORING_UNREGISTER_EVENTFD:
5646 ret = io_eventfd_unregister(ctx);
5653 /* bring the ctx back to life */
5654 reinit_completion(&ctx->completions[0]);
5655 percpu_ref_reinit(&ctx->refs);
5659 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
5660 void __user *, arg, unsigned int, nr_args)
5662 struct io_ring_ctx *ctx;
5671 if (f.file->f_op != &io_uring_fops)
5674 ctx = f.file->private_data;
5676 mutex_lock(&ctx->uring_lock);
5677 ret = __io_uring_register(ctx, opcode, arg, nr_args);
5678 mutex_unlock(&ctx->uring_lock);
5679 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
5680 ctx->cq_ev_fd != NULL, ret);
5686 static int __init io_uring_init(void)
5688 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
5691 __initcall(io_uring_init);