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;
306 struct file *put_file;
310 struct io_timeout_data {
311 struct io_kiocb *req;
312 struct hrtimer timer;
313 struct timespec64 ts;
314 enum hrtimer_mode mode;
320 struct sockaddr __user *addr;
321 int __user *addr_len;
346 /* NOTE: kiocb has the file as the first member, so don't do it here */
354 struct sockaddr __user *addr;
360 struct user_msghdr __user *msg;
368 const char __user *fname;
369 struct filename *filename;
373 struct io_async_connect {
374 struct sockaddr_storage address;
377 struct io_async_msghdr {
378 struct iovec fast_iov[UIO_FASTIOV];
380 struct sockaddr __user *uaddr;
385 struct iovec fast_iov[UIO_FASTIOV];
391 struct io_async_open {
392 struct filename *filename;
395 struct io_async_ctx {
397 struct io_async_rw rw;
398 struct io_async_msghdr msg;
399 struct io_async_connect connect;
400 struct io_timeout_data timeout;
401 struct io_async_open open;
406 * NOTE! Each of the iocb union members has the file pointer
407 * as the first entry in their struct definition. So you can
408 * access the file pointer through any of the sub-structs,
409 * or directly as just 'ki_filp' in this struct.
415 struct io_poll_iocb poll;
416 struct io_accept accept;
418 struct io_cancel cancel;
419 struct io_timeout timeout;
420 struct io_connect connect;
421 struct io_sr_msg sr_msg;
423 struct io_close close;
426 struct io_async_ctx *io;
427 struct file *ring_file;
431 bool needs_fixed_file;
434 struct io_ring_ctx *ctx;
436 struct list_head list;
437 struct hlist_node hash_node;
439 struct list_head link_list;
442 #define REQ_F_NOWAIT 1 /* must not punt to workers */
443 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
444 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
445 #define REQ_F_LINK_NEXT 8 /* already grabbed next link */
446 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
447 #define REQ_F_IO_DRAINED 32 /* drain done */
448 #define REQ_F_LINK 64 /* linked sqes */
449 #define REQ_F_LINK_TIMEOUT 128 /* has linked timeout */
450 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
451 #define REQ_F_DRAIN_LINK 512 /* link should be fully drained */
452 #define REQ_F_TIMEOUT 1024 /* timeout request */
453 #define REQ_F_ISREG 2048 /* regular file */
454 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
455 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
456 #define REQ_F_INFLIGHT 16384 /* on inflight list */
457 #define REQ_F_COMP_LOCKED 32768 /* completion under lock */
458 #define REQ_F_HARDLINK 65536 /* doesn't sever on completion < 0 */
463 struct list_head inflight_entry;
465 struct io_wq_work work;
468 #define IO_PLUG_THRESHOLD 2
469 #define IO_IOPOLL_BATCH 8
471 struct io_submit_state {
472 struct blk_plug plug;
475 * io_kiocb alloc cache
477 void *reqs[IO_IOPOLL_BATCH];
478 unsigned int free_reqs;
479 unsigned int cur_req;
482 * File reference cache
486 unsigned int has_refs;
487 unsigned int used_refs;
488 unsigned int ios_left;
491 static void io_wq_submit_work(struct io_wq_work **workptr);
492 static void io_cqring_fill_event(struct io_kiocb *req, long res);
493 static void __io_free_req(struct io_kiocb *req);
494 static void io_put_req(struct io_kiocb *req);
495 static void io_double_put_req(struct io_kiocb *req);
496 static void __io_double_put_req(struct io_kiocb *req);
497 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
498 static void io_queue_linked_timeout(struct io_kiocb *req);
500 static struct kmem_cache *req_cachep;
502 static const struct file_operations io_uring_fops;
504 struct sock *io_uring_get_socket(struct file *file)
506 #if defined(CONFIG_UNIX)
507 if (file->f_op == &io_uring_fops) {
508 struct io_ring_ctx *ctx = file->private_data;
510 return ctx->ring_sock->sk;
515 EXPORT_SYMBOL(io_uring_get_socket);
517 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
519 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
521 complete(&ctx->completions[0]);
524 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
526 struct io_ring_ctx *ctx;
529 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
533 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
534 if (!ctx->fallback_req)
537 ctx->completions = kmalloc(2 * sizeof(struct completion), GFP_KERNEL);
538 if (!ctx->completions)
542 * Use 5 bits less than the max cq entries, that should give us around
543 * 32 entries per hash list if totally full and uniformly spread.
545 hash_bits = ilog2(p->cq_entries);
549 ctx->cancel_hash_bits = hash_bits;
550 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
552 if (!ctx->cancel_hash)
554 __hash_init(ctx->cancel_hash, 1U << hash_bits);
556 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
557 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
560 ctx->flags = p->flags;
561 init_waitqueue_head(&ctx->cq_wait);
562 INIT_LIST_HEAD(&ctx->cq_overflow_list);
563 init_completion(&ctx->completions[0]);
564 init_completion(&ctx->completions[1]);
565 mutex_init(&ctx->uring_lock);
566 init_waitqueue_head(&ctx->wait);
567 spin_lock_init(&ctx->completion_lock);
568 INIT_LIST_HEAD(&ctx->poll_list);
569 INIT_LIST_HEAD(&ctx->defer_list);
570 INIT_LIST_HEAD(&ctx->timeout_list);
571 init_waitqueue_head(&ctx->inflight_wait);
572 spin_lock_init(&ctx->inflight_lock);
573 INIT_LIST_HEAD(&ctx->inflight_list);
576 if (ctx->fallback_req)
577 kmem_cache_free(req_cachep, ctx->fallback_req);
578 kfree(ctx->completions);
579 kfree(ctx->cancel_hash);
584 static inline bool __req_need_defer(struct io_kiocb *req)
586 struct io_ring_ctx *ctx = req->ctx;
588 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
589 + atomic_read(&ctx->cached_cq_overflow);
592 static inline bool req_need_defer(struct io_kiocb *req)
594 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) == REQ_F_IO_DRAIN)
595 return __req_need_defer(req);
600 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
602 struct io_kiocb *req;
604 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
605 if (req && !req_need_defer(req)) {
606 list_del_init(&req->list);
613 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
615 struct io_kiocb *req;
617 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
619 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
621 if (!__req_need_defer(req)) {
622 list_del_init(&req->list);
630 static void __io_commit_cqring(struct io_ring_ctx *ctx)
632 struct io_rings *rings = ctx->rings;
634 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
635 /* order cqe stores with ring update */
636 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
638 if (wq_has_sleeper(&ctx->cq_wait)) {
639 wake_up_interruptible(&ctx->cq_wait);
640 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
645 static inline bool io_req_needs_user(struct io_kiocb *req)
647 return !(req->opcode == IORING_OP_READ_FIXED ||
648 req->opcode == IORING_OP_WRITE_FIXED);
651 static inline bool io_prep_async_work(struct io_kiocb *req,
652 struct io_kiocb **link)
654 bool do_hashed = false;
656 switch (req->opcode) {
657 case IORING_OP_WRITEV:
658 case IORING_OP_WRITE_FIXED:
659 /* only regular files should be hashed for writes */
660 if (req->flags & REQ_F_ISREG)
663 case IORING_OP_READV:
664 case IORING_OP_READ_FIXED:
665 case IORING_OP_SENDMSG:
666 case IORING_OP_RECVMSG:
667 case IORING_OP_ACCEPT:
668 case IORING_OP_POLL_ADD:
669 case IORING_OP_CONNECT:
671 * We know REQ_F_ISREG is not set on some of these
672 * opcodes, but this enables us to keep the check in
675 if (!(req->flags & REQ_F_ISREG))
676 req->work.flags |= IO_WQ_WORK_UNBOUND;
679 if (io_req_needs_user(req))
680 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
682 *link = io_prep_linked_timeout(req);
686 static inline void io_queue_async_work(struct io_kiocb *req)
688 struct io_ring_ctx *ctx = req->ctx;
689 struct io_kiocb *link;
692 do_hashed = io_prep_async_work(req, &link);
694 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
697 io_wq_enqueue(ctx->io_wq, &req->work);
699 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
700 file_inode(req->file));
704 io_queue_linked_timeout(link);
707 static void io_kill_timeout(struct io_kiocb *req)
711 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
713 atomic_inc(&req->ctx->cq_timeouts);
714 list_del_init(&req->list);
715 io_cqring_fill_event(req, 0);
720 static void io_kill_timeouts(struct io_ring_ctx *ctx)
722 struct io_kiocb *req, *tmp;
724 spin_lock_irq(&ctx->completion_lock);
725 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
726 io_kill_timeout(req);
727 spin_unlock_irq(&ctx->completion_lock);
730 static void io_commit_cqring(struct io_ring_ctx *ctx)
732 struct io_kiocb *req;
734 while ((req = io_get_timeout_req(ctx)) != NULL)
735 io_kill_timeout(req);
737 __io_commit_cqring(ctx);
739 while ((req = io_get_deferred_req(ctx)) != NULL) {
740 req->flags |= REQ_F_IO_DRAINED;
741 io_queue_async_work(req);
745 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
747 struct io_rings *rings = ctx->rings;
750 tail = ctx->cached_cq_tail;
752 * writes to the cq entry need to come after reading head; the
753 * control dependency is enough as we're using WRITE_ONCE to
756 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
759 ctx->cached_cq_tail++;
760 return &rings->cqes[tail & ctx->cq_mask];
763 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
765 if (waitqueue_active(&ctx->wait))
767 if (waitqueue_active(&ctx->sqo_wait))
768 wake_up(&ctx->sqo_wait);
770 eventfd_signal(ctx->cq_ev_fd, 1);
773 /* Returns true if there are no backlogged entries after the flush */
774 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
776 struct io_rings *rings = ctx->rings;
777 struct io_uring_cqe *cqe;
778 struct io_kiocb *req;
783 if (list_empty_careful(&ctx->cq_overflow_list))
785 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
786 rings->cq_ring_entries))
790 spin_lock_irqsave(&ctx->completion_lock, flags);
792 /* if force is set, the ring is going away. always drop after that */
794 ctx->cq_overflow_flushed = true;
797 while (!list_empty(&ctx->cq_overflow_list)) {
798 cqe = io_get_cqring(ctx);
802 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
804 list_move(&req->list, &list);
806 WRITE_ONCE(cqe->user_data, req->user_data);
807 WRITE_ONCE(cqe->res, req->result);
808 WRITE_ONCE(cqe->flags, 0);
810 WRITE_ONCE(ctx->rings->cq_overflow,
811 atomic_inc_return(&ctx->cached_cq_overflow));
815 io_commit_cqring(ctx);
816 spin_unlock_irqrestore(&ctx->completion_lock, flags);
817 io_cqring_ev_posted(ctx);
819 while (!list_empty(&list)) {
820 req = list_first_entry(&list, struct io_kiocb, list);
821 list_del(&req->list);
828 static void io_cqring_fill_event(struct io_kiocb *req, long res)
830 struct io_ring_ctx *ctx = req->ctx;
831 struct io_uring_cqe *cqe;
833 trace_io_uring_complete(ctx, req->user_data, res);
836 * If we can't get a cq entry, userspace overflowed the
837 * submission (by quite a lot). Increment the overflow count in
840 cqe = io_get_cqring(ctx);
842 WRITE_ONCE(cqe->user_data, req->user_data);
843 WRITE_ONCE(cqe->res, res);
844 WRITE_ONCE(cqe->flags, 0);
845 } else if (ctx->cq_overflow_flushed) {
846 WRITE_ONCE(ctx->rings->cq_overflow,
847 atomic_inc_return(&ctx->cached_cq_overflow));
849 refcount_inc(&req->refs);
851 list_add_tail(&req->list, &ctx->cq_overflow_list);
855 static void io_cqring_add_event(struct io_kiocb *req, long res)
857 struct io_ring_ctx *ctx = req->ctx;
860 spin_lock_irqsave(&ctx->completion_lock, flags);
861 io_cqring_fill_event(req, res);
862 io_commit_cqring(ctx);
863 spin_unlock_irqrestore(&ctx->completion_lock, flags);
865 io_cqring_ev_posted(ctx);
868 static inline bool io_is_fallback_req(struct io_kiocb *req)
870 return req == (struct io_kiocb *)
871 ((unsigned long) req->ctx->fallback_req & ~1UL);
874 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
876 struct io_kiocb *req;
878 req = ctx->fallback_req;
879 if (!test_and_set_bit_lock(0, (unsigned long *) ctx->fallback_req))
885 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
886 struct io_submit_state *state)
888 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
889 struct io_kiocb *req;
891 if (!percpu_ref_tryget(&ctx->refs))
895 req = kmem_cache_alloc(req_cachep, gfp);
898 } else if (!state->free_reqs) {
902 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
903 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
906 * Bulk alloc is all-or-nothing. If we fail to get a batch,
907 * retry single alloc to be on the safe side.
909 if (unlikely(ret <= 0)) {
910 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
915 state->free_reqs = ret - 1;
917 req = state->reqs[0];
919 req = state->reqs[state->cur_req];
926 req->ring_file = NULL;
930 /* one is dropped after submission, the other at completion */
931 refcount_set(&req->refs, 2);
933 INIT_IO_WORK(&req->work, io_wq_submit_work);
936 req = io_get_fallback_req(ctx);
939 percpu_ref_put(&ctx->refs);
943 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
946 kmem_cache_free_bulk(req_cachep, *nr, reqs);
947 percpu_ref_put_many(&ctx->refs, *nr);
952 static void __io_free_req(struct io_kiocb *req)
954 struct io_ring_ctx *ctx = req->ctx;
958 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
960 if (req->flags & REQ_F_INFLIGHT) {
963 spin_lock_irqsave(&ctx->inflight_lock, flags);
964 list_del(&req->inflight_entry);
965 if (waitqueue_active(&ctx->inflight_wait))
966 wake_up(&ctx->inflight_wait);
967 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
969 percpu_ref_put(&ctx->refs);
970 if (likely(!io_is_fallback_req(req)))
971 kmem_cache_free(req_cachep, req);
973 clear_bit_unlock(0, (unsigned long *) ctx->fallback_req);
976 static bool io_link_cancel_timeout(struct io_kiocb *req)
978 struct io_ring_ctx *ctx = req->ctx;
981 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
983 io_cqring_fill_event(req, -ECANCELED);
984 io_commit_cqring(ctx);
985 req->flags &= ~REQ_F_LINK;
993 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
995 struct io_ring_ctx *ctx = req->ctx;
996 bool wake_ev = false;
998 /* Already got next link */
999 if (req->flags & REQ_F_LINK_NEXT)
1003 * The list should never be empty when we are called here. But could
1004 * potentially happen if the chain is messed up, check to be on the
1007 while (!list_empty(&req->link_list)) {
1008 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1009 struct io_kiocb, link_list);
1011 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1012 (nxt->flags & REQ_F_TIMEOUT))) {
1013 list_del_init(&nxt->link_list);
1014 wake_ev |= io_link_cancel_timeout(nxt);
1015 req->flags &= ~REQ_F_LINK_TIMEOUT;
1019 list_del_init(&req->link_list);
1020 if (!list_empty(&nxt->link_list))
1021 nxt->flags |= REQ_F_LINK;
1026 req->flags |= REQ_F_LINK_NEXT;
1028 io_cqring_ev_posted(ctx);
1032 * Called if REQ_F_LINK is set, and we fail the head request
1034 static void io_fail_links(struct io_kiocb *req)
1036 struct io_ring_ctx *ctx = req->ctx;
1037 unsigned long flags;
1039 spin_lock_irqsave(&ctx->completion_lock, flags);
1041 while (!list_empty(&req->link_list)) {
1042 struct io_kiocb *link = list_first_entry(&req->link_list,
1043 struct io_kiocb, link_list);
1045 list_del_init(&link->link_list);
1046 trace_io_uring_fail_link(req, link);
1048 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1049 link->opcode == IORING_OP_LINK_TIMEOUT) {
1050 io_link_cancel_timeout(link);
1052 io_cqring_fill_event(link, -ECANCELED);
1053 __io_double_put_req(link);
1055 req->flags &= ~REQ_F_LINK_TIMEOUT;
1058 io_commit_cqring(ctx);
1059 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1060 io_cqring_ev_posted(ctx);
1063 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1065 if (likely(!(req->flags & REQ_F_LINK)))
1069 * If LINK is set, we have dependent requests in this chain. If we
1070 * didn't fail this request, queue the first one up, moving any other
1071 * dependencies to the next request. In case of failure, fail the rest
1074 if (req->flags & REQ_F_FAIL_LINK) {
1076 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1077 REQ_F_LINK_TIMEOUT) {
1078 struct io_ring_ctx *ctx = req->ctx;
1079 unsigned long flags;
1082 * If this is a timeout link, we could be racing with the
1083 * timeout timer. Grab the completion lock for this case to
1084 * protect against that.
1086 spin_lock_irqsave(&ctx->completion_lock, flags);
1087 io_req_link_next(req, nxt);
1088 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1090 io_req_link_next(req, nxt);
1094 static void io_free_req(struct io_kiocb *req)
1096 struct io_kiocb *nxt = NULL;
1098 io_req_find_next(req, &nxt);
1102 io_queue_async_work(nxt);
1106 * Drop reference to request, return next in chain (if there is one) if this
1107 * was the last reference to this request.
1109 __attribute__((nonnull))
1110 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1112 io_req_find_next(req, nxtptr);
1114 if (refcount_dec_and_test(&req->refs))
1118 static void io_put_req(struct io_kiocb *req)
1120 if (refcount_dec_and_test(&req->refs))
1125 * Must only be used if we don't need to care about links, usually from
1126 * within the completion handling itself.
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 void io_double_put_req(struct io_kiocb *req)
1137 /* drop both submit and complete references */
1138 if (refcount_sub_and_test(2, &req->refs))
1142 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1144 struct io_rings *rings = ctx->rings;
1147 * noflush == true is from the waitqueue handler, just ensure we wake
1148 * up the task, and the next invocation will flush the entries. We
1149 * cannot safely to it from here.
1151 if (noflush && !list_empty(&ctx->cq_overflow_list))
1154 io_cqring_overflow_flush(ctx, false);
1156 /* See comment at the top of this file */
1158 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
1161 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1163 struct io_rings *rings = ctx->rings;
1165 /* make sure SQ entry isn't read before tail */
1166 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1170 * Find and free completed poll iocbs
1172 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1173 struct list_head *done)
1175 void *reqs[IO_IOPOLL_BATCH];
1176 struct io_kiocb *req;
1180 while (!list_empty(done)) {
1181 req = list_first_entry(done, struct io_kiocb, list);
1182 list_del(&req->list);
1184 io_cqring_fill_event(req, req->result);
1187 if (refcount_dec_and_test(&req->refs)) {
1188 /* If we're not using fixed files, we have to pair the
1189 * completion part with the file put. Use regular
1190 * completions for those, only batch free for fixed
1191 * file and non-linked commands.
1193 if (((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
1194 REQ_F_FIXED_FILE) && !io_is_fallback_req(req) &&
1196 reqs[to_free++] = req;
1197 if (to_free == ARRAY_SIZE(reqs))
1198 io_free_req_many(ctx, reqs, &to_free);
1205 io_commit_cqring(ctx);
1206 io_free_req_many(ctx, reqs, &to_free);
1209 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1212 struct io_kiocb *req, *tmp;
1218 * Only spin for completions if we don't have multiple devices hanging
1219 * off our complete list, and we're under the requested amount.
1221 spin = !ctx->poll_multi_file && *nr_events < min;
1224 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1225 struct kiocb *kiocb = &req->rw.kiocb;
1228 * Move completed entries to our local list. If we find a
1229 * request that requires polling, break out and complete
1230 * the done list first, if we have entries there.
1232 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
1233 list_move_tail(&req->list, &done);
1236 if (!list_empty(&done))
1239 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1248 if (!list_empty(&done))
1249 io_iopoll_complete(ctx, nr_events, &done);
1255 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1256 * non-spinning poll check - we'll still enter the driver poll loop, but only
1257 * as a non-spinning completion check.
1259 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1262 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1265 ret = io_do_iopoll(ctx, nr_events, min);
1268 if (!min || *nr_events >= min)
1276 * We can't just wait for polled events to come to us, we have to actively
1277 * find and complete them.
1279 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1281 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1284 mutex_lock(&ctx->uring_lock);
1285 while (!list_empty(&ctx->poll_list)) {
1286 unsigned int nr_events = 0;
1288 io_iopoll_getevents(ctx, &nr_events, 1);
1291 * Ensure we allow local-to-the-cpu processing to take place,
1292 * in this case we need to ensure that we reap all events.
1296 mutex_unlock(&ctx->uring_lock);
1299 static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1302 int iters = 0, ret = 0;
1308 * Don't enter poll loop if we already have events pending.
1309 * If we do, we can potentially be spinning for commands that
1310 * already triggered a CQE (eg in error).
1312 if (io_cqring_events(ctx, false))
1316 * If a submit got punted to a workqueue, we can have the
1317 * application entering polling for a command before it gets
1318 * issued. That app will hold the uring_lock for the duration
1319 * of the poll right here, so we need to take a breather every
1320 * now and then to ensure that the issue has a chance to add
1321 * the poll to the issued list. Otherwise we can spin here
1322 * forever, while the workqueue is stuck trying to acquire the
1325 if (!(++iters & 7)) {
1326 mutex_unlock(&ctx->uring_lock);
1327 mutex_lock(&ctx->uring_lock);
1330 if (*nr_events < min)
1331 tmin = min - *nr_events;
1333 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1337 } while (min && !*nr_events && !need_resched());
1342 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1348 * We disallow the app entering submit/complete with polling, but we
1349 * still need to lock the ring to prevent racing with polled issue
1350 * that got punted to a workqueue.
1352 mutex_lock(&ctx->uring_lock);
1353 ret = __io_iopoll_check(ctx, nr_events, min);
1354 mutex_unlock(&ctx->uring_lock);
1358 static void kiocb_end_write(struct io_kiocb *req)
1361 * Tell lockdep we inherited freeze protection from submission
1364 if (req->flags & REQ_F_ISREG) {
1365 struct inode *inode = file_inode(req->file);
1367 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
1369 file_end_write(req->file);
1372 static inline void req_set_fail_links(struct io_kiocb *req)
1374 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1375 req->flags |= REQ_F_FAIL_LINK;
1378 static void io_complete_rw_common(struct kiocb *kiocb, long res)
1380 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1382 if (kiocb->ki_flags & IOCB_WRITE)
1383 kiocb_end_write(req);
1385 if (res != req->result)
1386 req_set_fail_links(req);
1387 io_cqring_add_event(req, res);
1390 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1392 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1394 io_complete_rw_common(kiocb, res);
1398 static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1400 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1401 struct io_kiocb *nxt = NULL;
1403 io_complete_rw_common(kiocb, res);
1404 io_put_req_find_next(req, &nxt);
1409 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1411 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
1413 if (kiocb->ki_flags & IOCB_WRITE)
1414 kiocb_end_write(req);
1416 if (res != req->result)
1417 req_set_fail_links(req);
1420 req->flags |= REQ_F_IOPOLL_COMPLETED;
1424 * After the iocb has been issued, it's safe to be found on the poll list.
1425 * Adding the kiocb to the list AFTER submission ensures that we don't
1426 * find it from a io_iopoll_getevents() thread before the issuer is done
1427 * accessing the kiocb cookie.
1429 static void io_iopoll_req_issued(struct io_kiocb *req)
1431 struct io_ring_ctx *ctx = req->ctx;
1434 * Track whether we have multiple files in our lists. This will impact
1435 * how we do polling eventually, not spinning if we're on potentially
1436 * different devices.
1438 if (list_empty(&ctx->poll_list)) {
1439 ctx->poll_multi_file = false;
1440 } else if (!ctx->poll_multi_file) {
1441 struct io_kiocb *list_req;
1443 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1445 if (list_req->file != req->file)
1446 ctx->poll_multi_file = true;
1450 * For fast devices, IO may have already completed. If it has, add
1451 * it to the front so we find it first.
1453 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1454 list_add(&req->list, &ctx->poll_list);
1456 list_add_tail(&req->list, &ctx->poll_list);
1459 static void io_file_put(struct io_submit_state *state)
1462 int diff = state->has_refs - state->used_refs;
1465 fput_many(state->file, diff);
1471 * Get as many references to a file as we have IOs left in this submission,
1472 * assuming most submissions are for one file, or at least that each file
1473 * has more than one submission.
1475 static struct file *io_file_get(struct io_submit_state *state, int fd)
1481 if (state->fd == fd) {
1488 state->file = fget_many(fd, state->ios_left);
1493 state->has_refs = state->ios_left;
1494 state->used_refs = 1;
1500 * If we tracked the file through the SCM inflight mechanism, we could support
1501 * any file. For now, just ensure that anything potentially problematic is done
1504 static bool io_file_supports_async(struct file *file)
1506 umode_t mode = file_inode(file)->i_mode;
1508 if (S_ISBLK(mode) || S_ISCHR(mode) || S_ISSOCK(mode))
1510 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1516 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1517 bool force_nonblock)
1519 struct io_ring_ctx *ctx = req->ctx;
1520 struct kiocb *kiocb = &req->rw.kiocb;
1527 if (S_ISREG(file_inode(req->file)->i_mode))
1528 req->flags |= REQ_F_ISREG;
1530 kiocb->ki_pos = READ_ONCE(sqe->off);
1531 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1532 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1534 ioprio = READ_ONCE(sqe->ioprio);
1536 ret = ioprio_check_cap(ioprio);
1540 kiocb->ki_ioprio = ioprio;
1542 kiocb->ki_ioprio = get_current_ioprio();
1544 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1548 /* don't allow async punt if RWF_NOWAIT was requested */
1549 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1550 (req->file->f_flags & O_NONBLOCK))
1551 req->flags |= REQ_F_NOWAIT;
1554 kiocb->ki_flags |= IOCB_NOWAIT;
1556 if (ctx->flags & IORING_SETUP_IOPOLL) {
1557 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1558 !kiocb->ki_filp->f_op->iopoll)
1561 kiocb->ki_flags |= IOCB_HIPRI;
1562 kiocb->ki_complete = io_complete_rw_iopoll;
1565 if (kiocb->ki_flags & IOCB_HIPRI)
1567 kiocb->ki_complete = io_complete_rw;
1570 req->rw.addr = READ_ONCE(sqe->addr);
1571 req->rw.len = READ_ONCE(sqe->len);
1572 /* we own ->private, reuse it for the buffer index */
1573 req->rw.kiocb.private = (void *) (unsigned long)
1574 READ_ONCE(sqe->buf_index);
1578 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1584 case -ERESTARTNOINTR:
1585 case -ERESTARTNOHAND:
1586 case -ERESTART_RESTARTBLOCK:
1588 * We can't just restart the syscall, since previously
1589 * submitted sqes may already be in progress. Just fail this
1595 kiocb->ki_complete(kiocb, ret, 0);
1599 static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1602 if (in_async && ret >= 0 && kiocb->ki_complete == io_complete_rw)
1603 *nxt = __io_complete_rw(kiocb, ret);
1605 io_rw_done(kiocb, ret);
1608 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
1609 struct iov_iter *iter)
1611 struct io_ring_ctx *ctx = req->ctx;
1612 size_t len = req->rw.len;
1613 struct io_mapped_ubuf *imu;
1614 unsigned index, buf_index;
1618 /* attempt to use fixed buffers without having provided iovecs */
1619 if (unlikely(!ctx->user_bufs))
1622 buf_index = (unsigned long) req->rw.kiocb.private;
1623 if (unlikely(buf_index >= ctx->nr_user_bufs))
1626 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1627 imu = &ctx->user_bufs[index];
1628 buf_addr = req->rw.addr;
1631 if (buf_addr + len < buf_addr)
1633 /* not inside the mapped region */
1634 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1638 * May not be a start of buffer, set size appropriately
1639 * and advance us to the beginning.
1641 offset = buf_addr - imu->ubuf;
1642 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1646 * Don't use iov_iter_advance() here, as it's really slow for
1647 * using the latter parts of a big fixed buffer - it iterates
1648 * over each segment manually. We can cheat a bit here, because
1651 * 1) it's a BVEC iter, we set it up
1652 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1653 * first and last bvec
1655 * So just find our index, and adjust the iterator afterwards.
1656 * If the offset is within the first bvec (or the whole first
1657 * bvec, just use iov_iter_advance(). This makes it easier
1658 * since we can just skip the first segment, which may not
1659 * be PAGE_SIZE aligned.
1661 const struct bio_vec *bvec = imu->bvec;
1663 if (offset <= bvec->bv_len) {
1664 iov_iter_advance(iter, offset);
1666 unsigned long seg_skip;
1668 /* skip first vec */
1669 offset -= bvec->bv_len;
1670 seg_skip = 1 + (offset >> PAGE_SHIFT);
1672 iter->bvec = bvec + seg_skip;
1673 iter->nr_segs -= seg_skip;
1674 iter->count -= bvec->bv_len + offset;
1675 iter->iov_offset = offset & ~PAGE_MASK;
1682 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
1683 struct iovec **iovec, struct iov_iter *iter)
1685 void __user *buf = u64_to_user_ptr(req->rw.addr);
1686 size_t sqe_len = req->rw.len;
1689 opcode = req->opcode;
1690 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
1692 return io_import_fixed(req, rw, iter);
1695 /* buffer index only valid with fixed read/write */
1696 if (req->rw.kiocb.private)
1700 struct io_async_rw *iorw = &req->io->rw;
1703 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
1704 if (iorw->iov == iorw->fast_iov)
1712 #ifdef CONFIG_COMPAT
1713 if (req->ctx->compat)
1714 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1718 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1722 * For files that don't have ->read_iter() and ->write_iter(), handle them
1723 * by looping over ->read() or ->write() manually.
1725 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1726 struct iov_iter *iter)
1731 * Don't support polled IO through this interface, and we can't
1732 * support non-blocking either. For the latter, this just causes
1733 * the kiocb to be handled from an async context.
1735 if (kiocb->ki_flags & IOCB_HIPRI)
1737 if (kiocb->ki_flags & IOCB_NOWAIT)
1740 while (iov_iter_count(iter)) {
1744 if (!iov_iter_is_bvec(iter)) {
1745 iovec = iov_iter_iovec(iter);
1747 /* fixed buffers import bvec */
1748 iovec.iov_base = kmap(iter->bvec->bv_page)
1750 iovec.iov_len = min(iter->count,
1751 iter->bvec->bv_len - iter->iov_offset);
1755 nr = file->f_op->read(file, iovec.iov_base,
1756 iovec.iov_len, &kiocb->ki_pos);
1758 nr = file->f_op->write(file, iovec.iov_base,
1759 iovec.iov_len, &kiocb->ki_pos);
1762 if (iov_iter_is_bvec(iter))
1763 kunmap(iter->bvec->bv_page);
1771 if (nr != iovec.iov_len)
1773 iov_iter_advance(iter, nr);
1779 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
1780 struct iovec *iovec, struct iovec *fast_iov,
1781 struct iov_iter *iter)
1783 req->io->rw.nr_segs = iter->nr_segs;
1784 req->io->rw.size = io_size;
1785 req->io->rw.iov = iovec;
1786 if (!req->io->rw.iov) {
1787 req->io->rw.iov = req->io->rw.fast_iov;
1788 memcpy(req->io->rw.iov, fast_iov,
1789 sizeof(struct iovec) * iter->nr_segs);
1793 static int io_alloc_async_ctx(struct io_kiocb *req)
1795 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
1796 return req->io == NULL;
1799 static void io_rw_async(struct io_wq_work **workptr)
1801 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
1802 struct iovec *iov = NULL;
1804 if (req->io->rw.iov != req->io->rw.fast_iov)
1805 iov = req->io->rw.iov;
1806 io_wq_submit_work(workptr);
1810 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
1811 struct iovec *iovec, struct iovec *fast_iov,
1812 struct iov_iter *iter)
1814 if (req->opcode == IORING_OP_READ_FIXED ||
1815 req->opcode == IORING_OP_WRITE_FIXED)
1817 if (!req->io && io_alloc_async_ctx(req))
1820 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
1821 req->work.func = io_rw_async;
1825 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1826 bool force_nonblock)
1828 struct io_async_ctx *io;
1829 struct iov_iter iter;
1832 ret = io_prep_rw(req, sqe, force_nonblock);
1836 if (unlikely(!(req->file->f_mode & FMODE_READ)))
1843 io->rw.iov = io->rw.fast_iov;
1845 ret = io_import_iovec(READ, req, &io->rw.iov, &iter);
1850 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
1854 static int io_read(struct io_kiocb *req, struct io_kiocb **nxt,
1855 bool force_nonblock)
1857 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1858 struct kiocb *kiocb = &req->rw.kiocb;
1859 struct iov_iter iter;
1861 ssize_t io_size, ret;
1863 ret = io_import_iovec(READ, req, &iovec, &iter);
1867 /* Ensure we clear previously set non-block flag */
1868 if (!force_nonblock)
1869 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
1873 if (req->flags & REQ_F_LINK)
1874 req->result = io_size;
1877 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1878 * we know to async punt it even if it was opened O_NONBLOCK
1880 if (force_nonblock && !io_file_supports_async(req->file)) {
1881 req->flags |= REQ_F_MUST_PUNT;
1885 iov_count = iov_iter_count(&iter);
1886 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
1890 if (req->file->f_op->read_iter)
1891 ret2 = call_read_iter(req->file, kiocb, &iter);
1893 ret2 = loop_rw_iter(READ, req->file, kiocb, &iter);
1895 /* Catch -EAGAIN return for forced non-blocking submission */
1896 if (!force_nonblock || ret2 != -EAGAIN) {
1897 kiocb_done(kiocb, ret2, nxt, req->in_async);
1900 ret = io_setup_async_rw(req, io_size, iovec,
1901 inline_vecs, &iter);
1908 if (!io_wq_current_is_worker())
1913 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1914 bool force_nonblock)
1916 struct io_async_ctx *io;
1917 struct iov_iter iter;
1920 ret = io_prep_rw(req, sqe, force_nonblock);
1924 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
1931 io->rw.iov = io->rw.fast_iov;
1933 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter);
1938 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
1942 static int io_write(struct io_kiocb *req, struct io_kiocb **nxt,
1943 bool force_nonblock)
1945 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1946 struct kiocb *kiocb = &req->rw.kiocb;
1947 struct iov_iter iter;
1949 ssize_t ret, io_size;
1951 ret = io_import_iovec(WRITE, req, &iovec, &iter);
1955 /* Ensure we clear previously set non-block flag */
1956 if (!force_nonblock)
1957 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
1961 if (req->flags & REQ_F_LINK)
1962 req->result = io_size;
1965 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1966 * we know to async punt it even if it was opened O_NONBLOCK
1968 if (force_nonblock && !io_file_supports_async(req->file)) {
1969 req->flags |= REQ_F_MUST_PUNT;
1973 /* file path doesn't support NOWAIT for non-direct_IO */
1974 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
1975 (req->flags & REQ_F_ISREG))
1978 iov_count = iov_iter_count(&iter);
1979 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
1984 * Open-code file_start_write here to grab freeze protection,
1985 * which will be released by another thread in
1986 * io_complete_rw(). Fool lockdep by telling it the lock got
1987 * released so that it doesn't complain about the held lock when
1988 * we return to userspace.
1990 if (req->flags & REQ_F_ISREG) {
1991 __sb_start_write(file_inode(req->file)->i_sb,
1992 SB_FREEZE_WRITE, true);
1993 __sb_writers_release(file_inode(req->file)->i_sb,
1996 kiocb->ki_flags |= IOCB_WRITE;
1998 if (req->file->f_op->write_iter)
1999 ret2 = call_write_iter(req->file, kiocb, &iter);
2001 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
2002 if (!force_nonblock || ret2 != -EAGAIN) {
2003 kiocb_done(kiocb, ret2, nxt, req->in_async);
2006 ret = io_setup_async_rw(req, io_size, iovec,
2007 inline_vecs, &iter);
2014 if (!io_wq_current_is_worker())
2020 * IORING_OP_NOP just posts a completion event, nothing else.
2022 static int io_nop(struct io_kiocb *req)
2024 struct io_ring_ctx *ctx = req->ctx;
2026 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2029 io_cqring_add_event(req, 0);
2034 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2036 struct io_ring_ctx *ctx = req->ctx;
2041 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2043 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2046 req->sync.flags = READ_ONCE(sqe->fsync_flags);
2047 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
2050 req->sync.off = READ_ONCE(sqe->off);
2051 req->sync.len = READ_ONCE(sqe->len);
2055 static bool io_req_cancelled(struct io_kiocb *req)
2057 if (req->work.flags & IO_WQ_WORK_CANCEL) {
2058 req_set_fail_links(req);
2059 io_cqring_add_event(req, -ECANCELED);
2067 static void io_link_work_cb(struct io_wq_work **workptr)
2069 struct io_wq_work *work = *workptr;
2070 struct io_kiocb *link = work->data;
2072 io_queue_linked_timeout(link);
2073 work->func = io_wq_submit_work;
2076 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
2078 struct io_kiocb *link;
2080 io_prep_async_work(nxt, &link);
2081 *workptr = &nxt->work;
2083 nxt->work.flags |= IO_WQ_WORK_CB;
2084 nxt->work.func = io_link_work_cb;
2085 nxt->work.data = link;
2089 static void io_fsync_finish(struct io_wq_work **workptr)
2091 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2092 loff_t end = req->sync.off + req->sync.len;
2093 struct io_kiocb *nxt = NULL;
2096 if (io_req_cancelled(req))
2099 ret = vfs_fsync_range(req->file, req->sync.off,
2100 end > 0 ? end : LLONG_MAX,
2101 req->sync.flags & IORING_FSYNC_DATASYNC);
2103 req_set_fail_links(req);
2104 io_cqring_add_event(req, ret);
2105 io_put_req_find_next(req, &nxt);
2107 io_wq_assign_next(workptr, nxt);
2110 static int io_fsync(struct io_kiocb *req, struct io_kiocb **nxt,
2111 bool force_nonblock)
2113 struct io_wq_work *work, *old_work;
2115 /* fsync always requires a blocking context */
2116 if (force_nonblock) {
2118 req->work.func = io_fsync_finish;
2122 work = old_work = &req->work;
2123 io_fsync_finish(&work);
2124 if (work && work != old_work)
2125 *nxt = container_of(work, struct io_kiocb, work);
2129 static void io_fallocate_finish(struct io_wq_work **workptr)
2131 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2132 struct io_kiocb *nxt = NULL;
2135 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
2138 req_set_fail_links(req);
2139 io_cqring_add_event(req, ret);
2140 io_put_req_find_next(req, &nxt);
2142 io_wq_assign_next(workptr, nxt);
2145 static int io_fallocate_prep(struct io_kiocb *req,
2146 const struct io_uring_sqe *sqe)
2148 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
2151 req->sync.off = READ_ONCE(sqe->off);
2152 req->sync.len = READ_ONCE(sqe->addr);
2153 req->sync.mode = READ_ONCE(sqe->len);
2157 static int io_fallocate(struct io_kiocb *req, struct io_kiocb **nxt,
2158 bool force_nonblock)
2160 struct io_wq_work *work, *old_work;
2162 /* fallocate always requiring blocking context */
2163 if (force_nonblock) {
2165 req->work.func = io_fallocate_finish;
2169 work = old_work = &req->work;
2170 io_fallocate_finish(&work);
2171 if (work && work != old_work)
2172 *nxt = container_of(work, struct io_kiocb, work);
2177 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2181 if (sqe->ioprio || sqe->buf_index)
2184 req->open.dfd = READ_ONCE(sqe->fd);
2185 req->open.mode = READ_ONCE(sqe->len);
2186 req->open.fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
2187 req->open.flags = READ_ONCE(sqe->open_flags);
2189 req->open.filename = getname(req->open.fname);
2190 if (IS_ERR(req->open.filename)) {
2191 ret = PTR_ERR(req->open.filename);
2192 req->open.filename = NULL;
2199 static int io_openat(struct io_kiocb *req, struct io_kiocb **nxt,
2200 bool force_nonblock)
2202 struct open_flags op;
2203 struct open_how how;
2207 if (force_nonblock) {
2208 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2212 how = build_open_how(req->open.flags, req->open.mode);
2213 ret = build_open_flags(&how, &op);
2217 ret = get_unused_fd_flags(how.flags);
2221 file = do_filp_open(req->open.dfd, req->open.filename, &op);
2224 ret = PTR_ERR(file);
2226 fsnotify_open(file);
2227 fd_install(ret, file);
2230 putname(req->open.filename);
2232 req_set_fail_links(req);
2233 io_cqring_add_event(req, ret);
2234 io_put_req_find_next(req, nxt);
2238 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2241 * If we queue this for async, it must not be cancellable. That would
2242 * leave the 'file' in an undeterminate state.
2244 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
2246 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
2247 sqe->rw_flags || sqe->buf_index)
2249 if (sqe->flags & IOSQE_FIXED_FILE)
2252 req->close.fd = READ_ONCE(sqe->fd);
2253 if (req->file->f_op == &io_uring_fops ||
2254 req->close.fd == req->ring_fd)
2260 static void io_close_finish(struct io_wq_work **workptr)
2262 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2263 struct io_kiocb *nxt = NULL;
2265 /* Invoked with files, we need to do the close */
2266 if (req->work.files) {
2269 ret = filp_close(req->close.put_file, req->work.files);
2271 req_set_fail_links(req);
2273 io_cqring_add_event(req, ret);
2276 fput(req->close.put_file);
2278 /* we bypassed the re-issue, drop the submission reference */
2280 io_put_req_find_next(req, &nxt);
2282 io_wq_assign_next(workptr, nxt);
2285 static int io_close(struct io_kiocb *req, struct io_kiocb **nxt,
2286 bool force_nonblock)
2290 req->close.put_file = NULL;
2291 ret = __close_fd_get_file(req->close.fd, &req->close.put_file);
2295 /* if the file has a flush method, be safe and punt to async */
2296 if (req->close.put_file->f_op->flush && !io_wq_current_is_worker()) {
2297 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2302 * No ->flush(), safely close from here and just punt the
2303 * fput() to async context.
2305 ret = filp_close(req->close.put_file, current->files);
2308 req_set_fail_links(req);
2309 io_cqring_add_event(req, ret);
2311 if (io_wq_current_is_worker()) {
2312 struct io_wq_work *old_work, *work;
2314 old_work = work = &req->work;
2315 io_close_finish(&work);
2316 if (work && work != old_work)
2317 *nxt = container_of(work, struct io_kiocb, work);
2322 req->work.func = io_close_finish;
2326 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2328 struct io_ring_ctx *ctx = req->ctx;
2333 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2335 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
2338 req->sync.off = READ_ONCE(sqe->off);
2339 req->sync.len = READ_ONCE(sqe->len);
2340 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
2344 static void io_sync_file_range_finish(struct io_wq_work **workptr)
2346 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2347 struct io_kiocb *nxt = NULL;
2350 if (io_req_cancelled(req))
2353 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
2356 req_set_fail_links(req);
2357 io_cqring_add_event(req, ret);
2358 io_put_req_find_next(req, &nxt);
2360 io_wq_assign_next(workptr, nxt);
2363 static int io_sync_file_range(struct io_kiocb *req, struct io_kiocb **nxt,
2364 bool force_nonblock)
2366 struct io_wq_work *work, *old_work;
2368 /* sync_file_range always requires a blocking context */
2369 if (force_nonblock) {
2371 req->work.func = io_sync_file_range_finish;
2375 work = old_work = &req->work;
2376 io_sync_file_range_finish(&work);
2377 if (work && work != old_work)
2378 *nxt = container_of(work, struct io_kiocb, work);
2382 #if defined(CONFIG_NET)
2383 static void io_sendrecv_async(struct io_wq_work **workptr)
2385 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2386 struct iovec *iov = NULL;
2388 if (req->io->rw.iov != req->io->rw.fast_iov)
2389 iov = req->io->msg.iov;
2390 io_wq_submit_work(workptr);
2395 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2397 #if defined(CONFIG_NET)
2398 struct io_sr_msg *sr = &req->sr_msg;
2399 struct io_async_ctx *io = req->io;
2401 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2402 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2407 io->msg.iov = io->msg.fast_iov;
2408 return sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2415 static int io_sendmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2416 bool force_nonblock)
2418 #if defined(CONFIG_NET)
2419 struct io_async_msghdr *kmsg = NULL;
2420 struct socket *sock;
2423 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2426 sock = sock_from_file(req->file, &ret);
2428 struct io_async_ctx io;
2429 struct sockaddr_storage addr;
2433 kmsg = &req->io->msg;
2434 kmsg->msg.msg_name = &addr;
2435 /* if iov is set, it's allocated already */
2437 kmsg->iov = kmsg->fast_iov;
2438 kmsg->msg.msg_iter.iov = kmsg->iov;
2440 struct io_sr_msg *sr = &req->sr_msg;
2443 kmsg->msg.msg_name = &addr;
2445 io.msg.iov = io.msg.fast_iov;
2446 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
2447 sr->msg_flags, &io.msg.iov);
2452 flags = req->sr_msg.msg_flags;
2453 if (flags & MSG_DONTWAIT)
2454 req->flags |= REQ_F_NOWAIT;
2455 else if (force_nonblock)
2456 flags |= MSG_DONTWAIT;
2458 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
2459 if (force_nonblock && ret == -EAGAIN) {
2462 if (io_alloc_async_ctx(req))
2464 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2465 req->work.func = io_sendrecv_async;
2468 if (ret == -ERESTARTSYS)
2472 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2474 io_cqring_add_event(req, ret);
2476 req_set_fail_links(req);
2477 io_put_req_find_next(req, nxt);
2484 static int io_recvmsg_prep(struct io_kiocb *req,
2485 const struct io_uring_sqe *sqe)
2487 #if defined(CONFIG_NET)
2488 struct io_sr_msg *sr = &req->sr_msg;
2489 struct io_async_ctx *io = req->io;
2491 sr->msg_flags = READ_ONCE(sqe->msg_flags);
2492 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
2497 io->msg.iov = io->msg.fast_iov;
2498 return recvmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
2499 &io->msg.uaddr, &io->msg.iov);
2505 static int io_recvmsg(struct io_kiocb *req, struct io_kiocb **nxt,
2506 bool force_nonblock)
2508 #if defined(CONFIG_NET)
2509 struct io_async_msghdr *kmsg = NULL;
2510 struct socket *sock;
2513 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2516 sock = sock_from_file(req->file, &ret);
2518 struct io_async_ctx io;
2519 struct sockaddr_storage addr;
2523 kmsg = &req->io->msg;
2524 kmsg->msg.msg_name = &addr;
2525 /* if iov is set, it's allocated already */
2527 kmsg->iov = kmsg->fast_iov;
2528 kmsg->msg.msg_iter.iov = kmsg->iov;
2530 struct io_sr_msg *sr = &req->sr_msg;
2533 kmsg->msg.msg_name = &addr;
2535 io.msg.iov = io.msg.fast_iov;
2536 ret = recvmsg_copy_msghdr(&io.msg.msg, sr->msg,
2537 sr->msg_flags, &io.msg.uaddr,
2543 flags = req->sr_msg.msg_flags;
2544 if (flags & MSG_DONTWAIT)
2545 req->flags |= REQ_F_NOWAIT;
2546 else if (force_nonblock)
2547 flags |= MSG_DONTWAIT;
2549 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
2550 kmsg->uaddr, flags);
2551 if (force_nonblock && ret == -EAGAIN) {
2554 if (io_alloc_async_ctx(req))
2556 memcpy(&req->io->msg, &io.msg, sizeof(io.msg));
2557 req->work.func = io_sendrecv_async;
2560 if (ret == -ERESTARTSYS)
2564 if (!io_wq_current_is_worker() && kmsg && kmsg->iov != kmsg->fast_iov)
2566 io_cqring_add_event(req, ret);
2568 req_set_fail_links(req);
2569 io_put_req_find_next(req, nxt);
2576 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2578 #if defined(CONFIG_NET)
2579 struct io_accept *accept = &req->accept;
2581 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2583 if (sqe->ioprio || sqe->len || sqe->buf_index)
2586 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
2587 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
2588 accept->flags = READ_ONCE(sqe->accept_flags);
2595 #if defined(CONFIG_NET)
2596 static int __io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2597 bool force_nonblock)
2599 struct io_accept *accept = &req->accept;
2600 unsigned file_flags;
2603 file_flags = force_nonblock ? O_NONBLOCK : 0;
2604 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
2605 accept->addr_len, accept->flags);
2606 if (ret == -EAGAIN && force_nonblock)
2608 if (ret == -ERESTARTSYS)
2611 req_set_fail_links(req);
2612 io_cqring_add_event(req, ret);
2613 io_put_req_find_next(req, nxt);
2617 static void io_accept_finish(struct io_wq_work **workptr)
2619 struct io_kiocb *req = container_of(*workptr, struct io_kiocb, work);
2620 struct io_kiocb *nxt = NULL;
2622 if (io_req_cancelled(req))
2624 __io_accept(req, &nxt, false);
2626 io_wq_assign_next(workptr, nxt);
2630 static int io_accept(struct io_kiocb *req, struct io_kiocb **nxt,
2631 bool force_nonblock)
2633 #if defined(CONFIG_NET)
2636 ret = __io_accept(req, nxt, force_nonblock);
2637 if (ret == -EAGAIN && force_nonblock) {
2638 req->work.func = io_accept_finish;
2639 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
2649 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2651 #if defined(CONFIG_NET)
2652 struct io_connect *conn = &req->connect;
2653 struct io_async_ctx *io = req->io;
2655 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
2657 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
2660 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
2661 conn->addr_len = READ_ONCE(sqe->addr2);
2666 return move_addr_to_kernel(conn->addr, conn->addr_len,
2667 &io->connect.address);
2673 static int io_connect(struct io_kiocb *req, struct io_kiocb **nxt,
2674 bool force_nonblock)
2676 #if defined(CONFIG_NET)
2677 struct io_async_ctx __io, *io;
2678 unsigned file_flags;
2684 ret = move_addr_to_kernel(req->connect.addr,
2685 req->connect.addr_len,
2686 &__io.connect.address);
2692 file_flags = force_nonblock ? O_NONBLOCK : 0;
2694 ret = __sys_connect_file(req->file, &io->connect.address,
2695 req->connect.addr_len, file_flags);
2696 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
2699 if (io_alloc_async_ctx(req)) {
2703 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
2706 if (ret == -ERESTARTSYS)
2710 req_set_fail_links(req);
2711 io_cqring_add_event(req, ret);
2712 io_put_req_find_next(req, nxt);
2719 static void io_poll_remove_one(struct io_kiocb *req)
2721 struct io_poll_iocb *poll = &req->poll;
2723 spin_lock(&poll->head->lock);
2724 WRITE_ONCE(poll->canceled, true);
2725 if (!list_empty(&poll->wait.entry)) {
2726 list_del_init(&poll->wait.entry);
2727 io_queue_async_work(req);
2729 spin_unlock(&poll->head->lock);
2730 hash_del(&req->hash_node);
2733 static void io_poll_remove_all(struct io_ring_ctx *ctx)
2735 struct hlist_node *tmp;
2736 struct io_kiocb *req;
2739 spin_lock_irq(&ctx->completion_lock);
2740 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
2741 struct hlist_head *list;
2743 list = &ctx->cancel_hash[i];
2744 hlist_for_each_entry_safe(req, tmp, list, hash_node)
2745 io_poll_remove_one(req);
2747 spin_unlock_irq(&ctx->completion_lock);
2750 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
2752 struct hlist_head *list;
2753 struct io_kiocb *req;
2755 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
2756 hlist_for_each_entry(req, list, hash_node) {
2757 if (sqe_addr == req->user_data) {
2758 io_poll_remove_one(req);
2766 static int io_poll_remove_prep(struct io_kiocb *req,
2767 const struct io_uring_sqe *sqe)
2769 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2771 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
2775 req->poll.addr = READ_ONCE(sqe->addr);
2780 * Find a running poll command that matches one specified in sqe->addr,
2781 * and remove it if found.
2783 static int io_poll_remove(struct io_kiocb *req)
2785 struct io_ring_ctx *ctx = req->ctx;
2789 addr = req->poll.addr;
2790 spin_lock_irq(&ctx->completion_lock);
2791 ret = io_poll_cancel(ctx, addr);
2792 spin_unlock_irq(&ctx->completion_lock);
2794 io_cqring_add_event(req, ret);
2796 req_set_fail_links(req);
2801 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
2803 struct io_ring_ctx *ctx = req->ctx;
2805 req->poll.done = true;
2807 io_cqring_fill_event(req, error);
2809 io_cqring_fill_event(req, mangle_poll(mask));
2810 io_commit_cqring(ctx);
2813 static void io_poll_complete_work(struct io_wq_work **workptr)
2815 struct io_wq_work *work = *workptr;
2816 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2817 struct io_poll_iocb *poll = &req->poll;
2818 struct poll_table_struct pt = { ._key = poll->events };
2819 struct io_ring_ctx *ctx = req->ctx;
2820 struct io_kiocb *nxt = NULL;
2824 if (work->flags & IO_WQ_WORK_CANCEL) {
2825 WRITE_ONCE(poll->canceled, true);
2827 } else if (READ_ONCE(poll->canceled)) {
2831 if (ret != -ECANCELED)
2832 mask = vfs_poll(poll->file, &pt) & poll->events;
2835 * Note that ->ki_cancel callers also delete iocb from active_reqs after
2836 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
2837 * synchronize with them. In the cancellation case the list_del_init
2838 * itself is not actually needed, but harmless so we keep it in to
2839 * avoid further branches in the fast path.
2841 spin_lock_irq(&ctx->completion_lock);
2842 if (!mask && ret != -ECANCELED) {
2843 add_wait_queue(poll->head, &poll->wait);
2844 spin_unlock_irq(&ctx->completion_lock);
2847 hash_del(&req->hash_node);
2848 io_poll_complete(req, mask, ret);
2849 spin_unlock_irq(&ctx->completion_lock);
2851 io_cqring_ev_posted(ctx);
2854 req_set_fail_links(req);
2855 io_put_req_find_next(req, &nxt);
2857 io_wq_assign_next(workptr, nxt);
2860 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
2863 struct io_poll_iocb *poll = wait->private;
2864 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
2865 struct io_ring_ctx *ctx = req->ctx;
2866 __poll_t mask = key_to_poll(key);
2867 unsigned long flags;
2869 /* for instances that support it check for an event match first: */
2870 if (mask && !(mask & poll->events))
2873 list_del_init(&poll->wait.entry);
2876 * Run completion inline if we can. We're using trylock here because
2877 * we are violating the completion_lock -> poll wq lock ordering.
2878 * If we have a link timeout we're going to need the completion_lock
2879 * for finalizing the request, mark us as having grabbed that already.
2881 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
2882 hash_del(&req->hash_node);
2883 io_poll_complete(req, mask, 0);
2884 req->flags |= REQ_F_COMP_LOCKED;
2886 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2888 io_cqring_ev_posted(ctx);
2890 io_queue_async_work(req);
2896 struct io_poll_table {
2897 struct poll_table_struct pt;
2898 struct io_kiocb *req;
2902 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
2903 struct poll_table_struct *p)
2905 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
2907 if (unlikely(pt->req->poll.head)) {
2908 pt->error = -EINVAL;
2913 pt->req->poll.head = head;
2914 add_wait_queue(head, &pt->req->poll.wait);
2917 static void io_poll_req_insert(struct io_kiocb *req)
2919 struct io_ring_ctx *ctx = req->ctx;
2920 struct hlist_head *list;
2922 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
2923 hlist_add_head(&req->hash_node, list);
2926 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2928 struct io_poll_iocb *poll = &req->poll;
2931 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
2933 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
2938 events = READ_ONCE(sqe->poll_events);
2939 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
2943 static int io_poll_add(struct io_kiocb *req, struct io_kiocb **nxt)
2945 struct io_poll_iocb *poll = &req->poll;
2946 struct io_ring_ctx *ctx = req->ctx;
2947 struct io_poll_table ipt;
2948 bool cancel = false;
2951 INIT_IO_WORK(&req->work, io_poll_complete_work);
2952 INIT_HLIST_NODE(&req->hash_node);
2956 poll->canceled = false;
2958 ipt.pt._qproc = io_poll_queue_proc;
2959 ipt.pt._key = poll->events;
2961 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
2963 /* initialized the list so that we can do list_empty checks */
2964 INIT_LIST_HEAD(&poll->wait.entry);
2965 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
2966 poll->wait.private = poll;
2968 INIT_LIST_HEAD(&req->list);
2970 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
2972 spin_lock_irq(&ctx->completion_lock);
2973 if (likely(poll->head)) {
2974 spin_lock(&poll->head->lock);
2975 if (unlikely(list_empty(&poll->wait.entry))) {
2981 if (mask || ipt.error)
2982 list_del_init(&poll->wait.entry);
2984 WRITE_ONCE(poll->canceled, true);
2985 else if (!poll->done) /* actually waiting for an event */
2986 io_poll_req_insert(req);
2987 spin_unlock(&poll->head->lock);
2989 if (mask) { /* no async, we'd stolen it */
2991 io_poll_complete(req, mask, 0);
2993 spin_unlock_irq(&ctx->completion_lock);
2996 io_cqring_ev_posted(ctx);
2997 io_put_req_find_next(req, nxt);
3002 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
3004 struct io_timeout_data *data = container_of(timer,
3005 struct io_timeout_data, timer);
3006 struct io_kiocb *req = data->req;
3007 struct io_ring_ctx *ctx = req->ctx;
3008 unsigned long flags;
3010 atomic_inc(&ctx->cq_timeouts);
3012 spin_lock_irqsave(&ctx->completion_lock, flags);
3014 * We could be racing with timeout deletion. If the list is empty,
3015 * then timeout lookup already found it and will be handling it.
3017 if (!list_empty(&req->list)) {
3018 struct io_kiocb *prev;
3021 * Adjust the reqs sequence before the current one because it
3022 * will consume a slot in the cq_ring and the cq_tail
3023 * pointer will be increased, otherwise other timeout reqs may
3024 * return in advance without waiting for enough wait_nr.
3027 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
3029 list_del_init(&req->list);
3032 io_cqring_fill_event(req, -ETIME);
3033 io_commit_cqring(ctx);
3034 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3036 io_cqring_ev_posted(ctx);
3037 req_set_fail_links(req);
3039 return HRTIMER_NORESTART;
3042 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
3044 struct io_kiocb *req;
3047 list_for_each_entry(req, &ctx->timeout_list, list) {
3048 if (user_data == req->user_data) {
3049 list_del_init(&req->list);
3058 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
3062 req_set_fail_links(req);
3063 io_cqring_fill_event(req, -ECANCELED);
3068 static int io_timeout_remove_prep(struct io_kiocb *req,
3069 const struct io_uring_sqe *sqe)
3071 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3073 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
3076 req->timeout.addr = READ_ONCE(sqe->addr);
3077 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
3078 if (req->timeout.flags)
3085 * Remove or update an existing timeout command
3087 static int io_timeout_remove(struct io_kiocb *req)
3089 struct io_ring_ctx *ctx = req->ctx;
3092 spin_lock_irq(&ctx->completion_lock);
3093 ret = io_timeout_cancel(ctx, req->timeout.addr);
3095 io_cqring_fill_event(req, ret);
3096 io_commit_cqring(ctx);
3097 spin_unlock_irq(&ctx->completion_lock);
3098 io_cqring_ev_posted(ctx);
3100 req_set_fail_links(req);
3105 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3106 bool is_timeout_link)
3108 struct io_timeout_data *data;
3111 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3113 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
3115 if (sqe->off && is_timeout_link)
3117 flags = READ_ONCE(sqe->timeout_flags);
3118 if (flags & ~IORING_TIMEOUT_ABS)
3121 req->timeout.count = READ_ONCE(sqe->off);
3123 if (!req->io && io_alloc_async_ctx(req))
3126 data = &req->io->timeout;
3128 req->flags |= REQ_F_TIMEOUT;
3130 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
3133 if (flags & IORING_TIMEOUT_ABS)
3134 data->mode = HRTIMER_MODE_ABS;
3136 data->mode = HRTIMER_MODE_REL;
3138 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
3142 static int io_timeout(struct io_kiocb *req)
3145 struct io_ring_ctx *ctx = req->ctx;
3146 struct io_timeout_data *data;
3147 struct list_head *entry;
3150 data = &req->io->timeout;
3153 * sqe->off holds how many events that need to occur for this
3154 * timeout event to be satisfied. If it isn't set, then this is
3155 * a pure timeout request, sequence isn't used.
3157 count = req->timeout.count;
3159 req->flags |= REQ_F_TIMEOUT_NOSEQ;
3160 spin_lock_irq(&ctx->completion_lock);
3161 entry = ctx->timeout_list.prev;
3165 req->sequence = ctx->cached_sq_head + count - 1;
3166 data->seq_offset = count;
3169 * Insertion sort, ensuring the first entry in the list is always
3170 * the one we need first.
3172 spin_lock_irq(&ctx->completion_lock);
3173 list_for_each_prev(entry, &ctx->timeout_list) {
3174 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
3175 unsigned nxt_sq_head;
3176 long long tmp, tmp_nxt;
3177 u32 nxt_offset = nxt->io->timeout.seq_offset;
3179 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
3183 * Since cached_sq_head + count - 1 can overflow, use type long
3186 tmp = (long long)ctx->cached_sq_head + count - 1;
3187 nxt_sq_head = nxt->sequence - nxt_offset + 1;
3188 tmp_nxt = (long long)nxt_sq_head + nxt_offset - 1;
3191 * cached_sq_head may overflow, and it will never overflow twice
3192 * once there is some timeout req still be valid.
3194 if (ctx->cached_sq_head < nxt_sq_head)
3201 * Sequence of reqs after the insert one and itself should
3202 * be adjusted because each timeout req consumes a slot.
3207 req->sequence -= span;
3209 list_add(&req->list, entry);
3210 data->timer.function = io_timeout_fn;
3211 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
3212 spin_unlock_irq(&ctx->completion_lock);
3216 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3218 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3220 return req->user_data == (unsigned long) data;
3223 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
3225 enum io_wq_cancel cancel_ret;
3228 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
3229 switch (cancel_ret) {
3230 case IO_WQ_CANCEL_OK:
3233 case IO_WQ_CANCEL_RUNNING:
3236 case IO_WQ_CANCEL_NOTFOUND:
3244 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
3245 struct io_kiocb *req, __u64 sqe_addr,
3246 struct io_kiocb **nxt, int success_ret)
3248 unsigned long flags;
3251 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
3252 if (ret != -ENOENT) {
3253 spin_lock_irqsave(&ctx->completion_lock, flags);
3257 spin_lock_irqsave(&ctx->completion_lock, flags);
3258 ret = io_timeout_cancel(ctx, sqe_addr);
3261 ret = io_poll_cancel(ctx, sqe_addr);
3265 io_cqring_fill_event(req, ret);
3266 io_commit_cqring(ctx);
3267 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3268 io_cqring_ev_posted(ctx);
3271 req_set_fail_links(req);
3272 io_put_req_find_next(req, nxt);
3275 static int io_async_cancel_prep(struct io_kiocb *req,
3276 const struct io_uring_sqe *sqe)
3278 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3280 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
3284 req->cancel.addr = READ_ONCE(sqe->addr);
3288 static int io_async_cancel(struct io_kiocb *req, struct io_kiocb **nxt)
3290 struct io_ring_ctx *ctx = req->ctx;
3292 io_async_find_and_cancel(ctx, req, req->cancel.addr, nxt, 0);
3296 static int io_req_defer_prep(struct io_kiocb *req,
3297 const struct io_uring_sqe *sqe)
3301 switch (req->opcode) {
3304 case IORING_OP_READV:
3305 case IORING_OP_READ_FIXED:
3306 ret = io_read_prep(req, sqe, true);
3308 case IORING_OP_WRITEV:
3309 case IORING_OP_WRITE_FIXED:
3310 ret = io_write_prep(req, sqe, true);
3312 case IORING_OP_POLL_ADD:
3313 ret = io_poll_add_prep(req, sqe);
3315 case IORING_OP_POLL_REMOVE:
3316 ret = io_poll_remove_prep(req, sqe);
3318 case IORING_OP_FSYNC:
3319 ret = io_prep_fsync(req, sqe);
3321 case IORING_OP_SYNC_FILE_RANGE:
3322 ret = io_prep_sfr(req, sqe);
3324 case IORING_OP_SENDMSG:
3325 ret = io_sendmsg_prep(req, sqe);
3327 case IORING_OP_RECVMSG:
3328 ret = io_recvmsg_prep(req, sqe);
3330 case IORING_OP_CONNECT:
3331 ret = io_connect_prep(req, sqe);
3333 case IORING_OP_TIMEOUT:
3334 ret = io_timeout_prep(req, sqe, false);
3336 case IORING_OP_TIMEOUT_REMOVE:
3337 ret = io_timeout_remove_prep(req, sqe);
3339 case IORING_OP_ASYNC_CANCEL:
3340 ret = io_async_cancel_prep(req, sqe);
3342 case IORING_OP_LINK_TIMEOUT:
3343 ret = io_timeout_prep(req, sqe, true);
3345 case IORING_OP_ACCEPT:
3346 ret = io_accept_prep(req, sqe);
3348 case IORING_OP_FALLOCATE:
3349 ret = io_fallocate_prep(req, sqe);
3351 case IORING_OP_OPENAT:
3352 ret = io_openat_prep(req, sqe);
3354 case IORING_OP_CLOSE:
3355 ret = io_close_prep(req, sqe);
3358 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
3367 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3369 struct io_ring_ctx *ctx = req->ctx;
3372 /* Still need defer if there is pending req in defer list. */
3373 if (!req_need_defer(req) && list_empty(&ctx->defer_list))
3376 if (!req->io && io_alloc_async_ctx(req))
3379 ret = io_req_defer_prep(req, sqe);
3383 spin_lock_irq(&ctx->completion_lock);
3384 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
3385 spin_unlock_irq(&ctx->completion_lock);
3389 trace_io_uring_defer(ctx, req, req->user_data);
3390 list_add_tail(&req->list, &ctx->defer_list);
3391 spin_unlock_irq(&ctx->completion_lock);
3392 return -EIOCBQUEUED;
3395 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3396 struct io_kiocb **nxt, bool force_nonblock)
3398 struct io_ring_ctx *ctx = req->ctx;
3401 switch (req->opcode) {
3405 case IORING_OP_READV:
3406 case IORING_OP_READ_FIXED:
3408 ret = io_read_prep(req, sqe, force_nonblock);
3412 ret = io_read(req, nxt, force_nonblock);
3414 case IORING_OP_WRITEV:
3415 case IORING_OP_WRITE_FIXED:
3417 ret = io_write_prep(req, sqe, force_nonblock);
3421 ret = io_write(req, nxt, force_nonblock);
3423 case IORING_OP_FSYNC:
3425 ret = io_prep_fsync(req, sqe);
3429 ret = io_fsync(req, nxt, force_nonblock);
3431 case IORING_OP_POLL_ADD:
3433 ret = io_poll_add_prep(req, sqe);
3437 ret = io_poll_add(req, nxt);
3439 case IORING_OP_POLL_REMOVE:
3441 ret = io_poll_remove_prep(req, sqe);
3445 ret = io_poll_remove(req);
3447 case IORING_OP_SYNC_FILE_RANGE:
3449 ret = io_prep_sfr(req, sqe);
3453 ret = io_sync_file_range(req, nxt, force_nonblock);
3455 case IORING_OP_SENDMSG:
3457 ret = io_sendmsg_prep(req, sqe);
3461 ret = io_sendmsg(req, nxt, force_nonblock);
3463 case IORING_OP_RECVMSG:
3465 ret = io_recvmsg_prep(req, sqe);
3469 ret = io_recvmsg(req, nxt, force_nonblock);
3471 case IORING_OP_TIMEOUT:
3473 ret = io_timeout_prep(req, sqe, false);
3477 ret = io_timeout(req);
3479 case IORING_OP_TIMEOUT_REMOVE:
3481 ret = io_timeout_remove_prep(req, sqe);
3485 ret = io_timeout_remove(req);
3487 case IORING_OP_ACCEPT:
3489 ret = io_accept_prep(req, sqe);
3493 ret = io_accept(req, nxt, force_nonblock);
3495 case IORING_OP_CONNECT:
3497 ret = io_connect_prep(req, sqe);
3501 ret = io_connect(req, nxt, force_nonblock);
3503 case IORING_OP_ASYNC_CANCEL:
3505 ret = io_async_cancel_prep(req, sqe);
3509 ret = io_async_cancel(req, nxt);
3511 case IORING_OP_FALLOCATE:
3513 ret = io_fallocate_prep(req, sqe);
3517 ret = io_fallocate(req, nxt, force_nonblock);
3519 case IORING_OP_OPENAT:
3521 ret = io_openat_prep(req, sqe);
3525 ret = io_openat(req, nxt, force_nonblock);
3527 case IORING_OP_CLOSE:
3529 ret = io_close_prep(req, sqe);
3533 ret = io_close(req, nxt, force_nonblock);
3543 if (ctx->flags & IORING_SETUP_IOPOLL) {
3544 const bool in_async = io_wq_current_is_worker();
3546 if (req->result == -EAGAIN)
3549 /* workqueue context doesn't hold uring_lock, grab it now */
3551 mutex_lock(&ctx->uring_lock);
3553 io_iopoll_req_issued(req);
3556 mutex_unlock(&ctx->uring_lock);
3562 static void io_wq_submit_work(struct io_wq_work **workptr)
3564 struct io_wq_work *work = *workptr;
3565 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3566 struct io_kiocb *nxt = NULL;
3569 /* if NO_CANCEL is set, we must still run the work */
3570 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
3571 IO_WQ_WORK_CANCEL) {
3576 req->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
3577 req->in_async = true;
3579 ret = io_issue_sqe(req, NULL, &nxt, false);
3581 * We can get EAGAIN for polled IO even though we're
3582 * forcing a sync submission from here, since we can't
3583 * wait for request slots on the block side.
3591 /* drop submission reference */
3595 req_set_fail_links(req);
3596 io_cqring_add_event(req, ret);
3600 /* if a dependent link is ready, pass it back */
3602 io_wq_assign_next(workptr, nxt);
3605 static bool io_req_op_valid(int op)
3607 return op >= IORING_OP_NOP && op < IORING_OP_LAST;
3610 static int io_req_needs_file(struct io_kiocb *req, int fd)
3612 switch (req->opcode) {
3614 case IORING_OP_POLL_REMOVE:
3615 case IORING_OP_TIMEOUT:
3616 case IORING_OP_TIMEOUT_REMOVE:
3617 case IORING_OP_ASYNC_CANCEL:
3618 case IORING_OP_LINK_TIMEOUT:
3620 case IORING_OP_OPENAT:
3623 if (io_req_op_valid(req->opcode))
3629 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
3632 struct fixed_file_table *table;
3634 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
3635 return table->files[index & IORING_FILE_TABLE_MASK];
3638 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
3639 const struct io_uring_sqe *sqe)
3641 struct io_ring_ctx *ctx = req->ctx;
3645 flags = READ_ONCE(sqe->flags);
3646 fd = READ_ONCE(sqe->fd);
3648 if (flags & IOSQE_IO_DRAIN)
3649 req->flags |= REQ_F_IO_DRAIN;
3651 ret = io_req_needs_file(req, fd);
3655 if (flags & IOSQE_FIXED_FILE) {
3656 if (unlikely(!ctx->file_table ||
3657 (unsigned) fd >= ctx->nr_user_files))
3659 fd = array_index_nospec(fd, ctx->nr_user_files);
3660 req->file = io_file_from_index(ctx, fd);
3663 req->flags |= REQ_F_FIXED_FILE;
3665 if (req->needs_fixed_file)
3667 trace_io_uring_file_get(ctx, fd);
3668 req->file = io_file_get(state, fd);
3669 if (unlikely(!req->file))
3676 static int io_grab_files(struct io_kiocb *req)
3679 struct io_ring_ctx *ctx = req->ctx;
3681 if (!req->ring_file)
3685 spin_lock_irq(&ctx->inflight_lock);
3687 * We use the f_ops->flush() handler to ensure that we can flush
3688 * out work accessing these files if the fd is closed. Check if
3689 * the fd has changed since we started down this path, and disallow
3690 * this operation if it has.
3692 if (fcheck(req->ring_fd) == req->ring_file) {
3693 list_add(&req->inflight_entry, &ctx->inflight_list);
3694 req->flags |= REQ_F_INFLIGHT;
3695 req->work.files = current->files;
3698 spin_unlock_irq(&ctx->inflight_lock);
3704 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
3706 struct io_timeout_data *data = container_of(timer,
3707 struct io_timeout_data, timer);
3708 struct io_kiocb *req = data->req;
3709 struct io_ring_ctx *ctx = req->ctx;
3710 struct io_kiocb *prev = NULL;
3711 unsigned long flags;
3713 spin_lock_irqsave(&ctx->completion_lock, flags);
3716 * We don't expect the list to be empty, that will only happen if we
3717 * race with the completion of the linked work.
3719 if (!list_empty(&req->link_list)) {
3720 prev = list_entry(req->link_list.prev, struct io_kiocb,
3722 if (refcount_inc_not_zero(&prev->refs)) {
3723 list_del_init(&req->link_list);
3724 prev->flags &= ~REQ_F_LINK_TIMEOUT;
3729 spin_unlock_irqrestore(&ctx->completion_lock, flags);
3732 req_set_fail_links(prev);
3733 io_async_find_and_cancel(ctx, req, prev->user_data, NULL,
3737 io_cqring_add_event(req, -ETIME);
3740 return HRTIMER_NORESTART;
3743 static void io_queue_linked_timeout(struct io_kiocb *req)
3745 struct io_ring_ctx *ctx = req->ctx;
3748 * If the list is now empty, then our linked request finished before
3749 * we got a chance to setup the timer
3751 spin_lock_irq(&ctx->completion_lock);
3752 if (!list_empty(&req->link_list)) {
3753 struct io_timeout_data *data = &req->io->timeout;
3755 data->timer.function = io_link_timeout_fn;
3756 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
3759 spin_unlock_irq(&ctx->completion_lock);
3761 /* drop submission reference */
3765 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
3767 struct io_kiocb *nxt;
3769 if (!(req->flags & REQ_F_LINK))
3772 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
3774 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
3777 req->flags |= REQ_F_LINK_TIMEOUT;
3781 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3783 struct io_kiocb *linked_timeout;
3784 struct io_kiocb *nxt = NULL;
3788 linked_timeout = io_prep_linked_timeout(req);
3790 ret = io_issue_sqe(req, sqe, &nxt, true);
3793 * We async punt it if the file wasn't marked NOWAIT, or if the file
3794 * doesn't support non-blocking read/write attempts
3796 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
3797 (req->flags & REQ_F_MUST_PUNT))) {
3798 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
3799 ret = io_grab_files(req);
3805 * Queued up for async execution, worker will release
3806 * submit reference when the iocb is actually submitted.
3808 io_queue_async_work(req);
3813 /* drop submission reference */
3816 if (linked_timeout) {
3818 io_queue_linked_timeout(linked_timeout);
3820 io_put_req(linked_timeout);
3823 /* and drop final reference, if we failed */
3825 io_cqring_add_event(req, ret);
3826 req_set_fail_links(req);
3837 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3841 if (unlikely(req->ctx->drain_next)) {
3842 req->flags |= REQ_F_IO_DRAIN;
3843 req->ctx->drain_next = false;
3845 req->ctx->drain_next = (req->flags & REQ_F_DRAIN_LINK);
3847 ret = io_req_defer(req, sqe);
3849 if (ret != -EIOCBQUEUED) {
3850 io_cqring_add_event(req, ret);
3851 req_set_fail_links(req);
3852 io_double_put_req(req);
3855 __io_queue_sqe(req, sqe);
3858 static inline void io_queue_link_head(struct io_kiocb *req)
3860 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
3861 io_cqring_add_event(req, -ECANCELED);
3862 io_double_put_req(req);
3864 io_queue_sqe(req, NULL);
3867 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
3870 static bool io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3871 struct io_submit_state *state, struct io_kiocb **link)
3873 struct io_ring_ctx *ctx = req->ctx;
3876 /* enforce forwards compatibility on users */
3877 if (unlikely(sqe->flags & ~SQE_VALID_FLAGS)) {
3882 ret = io_req_set_file(state, req, sqe);
3883 if (unlikely(ret)) {
3885 io_cqring_add_event(req, ret);
3886 io_double_put_req(req);
3891 * If we already have a head request, queue this one for async
3892 * submittal once the head completes. If we don't have a head but
3893 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
3894 * submitted sync once the chain is complete. If none of those
3895 * conditions are true (normal request), then just queue it.
3898 struct io_kiocb *prev = *link;
3900 if (sqe->flags & IOSQE_IO_DRAIN)
3901 (*link)->flags |= REQ_F_DRAIN_LINK | REQ_F_IO_DRAIN;
3903 if (sqe->flags & IOSQE_IO_HARDLINK)
3904 req->flags |= REQ_F_HARDLINK;
3906 if (io_alloc_async_ctx(req)) {
3911 ret = io_req_defer_prep(req, sqe);
3913 /* fail even hard links since we don't submit */
3914 prev->flags |= REQ_F_FAIL_LINK;
3917 trace_io_uring_link(ctx, req, prev);
3918 list_add_tail(&req->link_list, &prev->link_list);
3919 } else if (sqe->flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) {
3920 req->flags |= REQ_F_LINK;
3921 if (sqe->flags & IOSQE_IO_HARDLINK)
3922 req->flags |= REQ_F_HARDLINK;
3924 INIT_LIST_HEAD(&req->link_list);
3925 ret = io_req_defer_prep(req, sqe);
3927 req->flags |= REQ_F_FAIL_LINK;
3930 io_queue_sqe(req, sqe);
3937 * Batched submission is done, ensure local IO is flushed out.
3939 static void io_submit_state_end(struct io_submit_state *state)
3941 blk_finish_plug(&state->plug);
3943 if (state->free_reqs)
3944 kmem_cache_free_bulk(req_cachep, state->free_reqs,
3945 &state->reqs[state->cur_req]);
3949 * Start submission side cache.
3951 static void io_submit_state_start(struct io_submit_state *state,
3952 unsigned int max_ios)
3954 blk_start_plug(&state->plug);
3955 state->free_reqs = 0;
3957 state->ios_left = max_ios;
3960 static void io_commit_sqring(struct io_ring_ctx *ctx)
3962 struct io_rings *rings = ctx->rings;
3964 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
3966 * Ensure any loads from the SQEs are done at this point,
3967 * since once we write the new head, the application could
3968 * write new data to them.
3970 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
3975 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
3976 * that is mapped by userspace. This means that care needs to be taken to
3977 * ensure that reads are stable, as we cannot rely on userspace always
3978 * being a good citizen. If members of the sqe are validated and then later
3979 * used, it's important that those reads are done through READ_ONCE() to
3980 * prevent a re-load down the line.
3982 static bool io_get_sqring(struct io_ring_ctx *ctx, struct io_kiocb *req,
3983 const struct io_uring_sqe **sqe_ptr)
3985 struct io_rings *rings = ctx->rings;
3986 u32 *sq_array = ctx->sq_array;
3990 * The cached sq head (or cq tail) serves two purposes:
3992 * 1) allows us to batch the cost of updating the user visible
3994 * 2) allows the kernel side to track the head on its own, even
3995 * though the application is the one updating it.
3997 head = ctx->cached_sq_head;
3998 /* make sure SQ entry isn't read before tail */
3999 if (unlikely(head == smp_load_acquire(&rings->sq.tail)))
4002 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
4003 if (likely(head < ctx->sq_entries)) {
4005 * All io need record the previous position, if LINK vs DARIN,
4006 * it can be used to mark the position of the first IO in the
4009 req->sequence = ctx->cached_sq_head;
4010 *sqe_ptr = &ctx->sq_sqes[head];
4011 req->opcode = READ_ONCE((*sqe_ptr)->opcode);
4012 req->user_data = READ_ONCE((*sqe_ptr)->user_data);
4013 ctx->cached_sq_head++;
4017 /* drop invalid entries */
4018 ctx->cached_sq_head++;
4019 ctx->cached_sq_dropped++;
4020 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
4024 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
4025 struct file *ring_file, int ring_fd,
4026 struct mm_struct **mm, bool async)
4028 struct io_submit_state state, *statep = NULL;
4029 struct io_kiocb *link = NULL;
4030 int i, submitted = 0;
4031 bool mm_fault = false;
4033 /* if we have a backlog and couldn't flush it all, return BUSY */
4034 if (!list_empty(&ctx->cq_overflow_list) &&
4035 !io_cqring_overflow_flush(ctx, false))
4038 if (nr > IO_PLUG_THRESHOLD) {
4039 io_submit_state_start(&state, nr);
4043 for (i = 0; i < nr; i++) {
4044 const struct io_uring_sqe *sqe;
4045 struct io_kiocb *req;
4046 unsigned int sqe_flags;
4048 req = io_get_req(ctx, statep);
4049 if (unlikely(!req)) {
4051 submitted = -EAGAIN;
4054 if (!io_get_sqring(ctx, req, &sqe)) {
4059 if (io_req_needs_user(req) && !*mm) {
4060 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
4062 use_mm(ctx->sqo_mm);
4068 sqe_flags = sqe->flags;
4070 req->ring_file = ring_file;
4071 req->ring_fd = ring_fd;
4072 req->has_user = *mm != NULL;
4073 req->in_async = async;
4074 req->needs_fixed_file = async;
4075 trace_io_uring_submit_sqe(ctx, req->user_data, true, async);
4076 if (!io_submit_sqe(req, sqe, statep, &link))
4079 * If previous wasn't linked and we have a linked command,
4080 * that's the end of the chain. Submit the previous link.
4082 if (!(sqe_flags & (IOSQE_IO_LINK|IOSQE_IO_HARDLINK)) && link) {
4083 io_queue_link_head(link);
4089 io_queue_link_head(link);
4091 io_submit_state_end(&state);
4093 /* Commit SQ ring head once we've consumed and submitted all SQEs */
4094 io_commit_sqring(ctx);
4099 static int io_sq_thread(void *data)
4101 struct io_ring_ctx *ctx = data;
4102 struct mm_struct *cur_mm = NULL;
4103 const struct cred *old_cred;
4104 mm_segment_t old_fs;
4107 unsigned long timeout;
4110 complete(&ctx->completions[1]);
4114 old_cred = override_creds(ctx->creds);
4116 ret = timeout = inflight = 0;
4117 while (!kthread_should_park()) {
4118 unsigned int to_submit;
4121 unsigned nr_events = 0;
4123 if (ctx->flags & IORING_SETUP_IOPOLL) {
4125 * inflight is the count of the maximum possible
4126 * entries we submitted, but it can be smaller
4127 * if we dropped some of them. If we don't have
4128 * poll entries available, then we know that we
4129 * have nothing left to poll for. Reset the
4130 * inflight count to zero in that case.
4132 mutex_lock(&ctx->uring_lock);
4133 if (!list_empty(&ctx->poll_list))
4134 __io_iopoll_check(ctx, &nr_events, 0);
4137 mutex_unlock(&ctx->uring_lock);
4140 * Normal IO, just pretend everything completed.
4141 * We don't have to poll completions for that.
4143 nr_events = inflight;
4146 inflight -= nr_events;
4148 timeout = jiffies + ctx->sq_thread_idle;
4151 to_submit = io_sqring_entries(ctx);
4154 * If submit got -EBUSY, flag us as needing the application
4155 * to enter the kernel to reap and flush events.
4157 if (!to_submit || ret == -EBUSY) {
4159 * We're polling. If we're within the defined idle
4160 * period, then let us spin without work before going
4161 * to sleep. The exception is if we got EBUSY doing
4162 * more IO, we should wait for the application to
4163 * reap events and wake us up.
4166 (!time_after(jiffies, timeout) && ret != -EBUSY)) {
4172 * Drop cur_mm before scheduling, we can't hold it for
4173 * long periods (or over schedule()). Do this before
4174 * adding ourselves to the waitqueue, as the unuse/drop
4183 prepare_to_wait(&ctx->sqo_wait, &wait,
4184 TASK_INTERRUPTIBLE);
4186 /* Tell userspace we may need a wakeup call */
4187 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
4188 /* make sure to read SQ tail after writing flags */
4191 to_submit = io_sqring_entries(ctx);
4192 if (!to_submit || ret == -EBUSY) {
4193 if (kthread_should_park()) {
4194 finish_wait(&ctx->sqo_wait, &wait);
4197 if (signal_pending(current))
4198 flush_signals(current);
4200 finish_wait(&ctx->sqo_wait, &wait);
4202 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4205 finish_wait(&ctx->sqo_wait, &wait);
4207 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
4210 to_submit = min(to_submit, ctx->sq_entries);
4211 mutex_lock(&ctx->uring_lock);
4212 ret = io_submit_sqes(ctx, to_submit, NULL, -1, &cur_mm, true);
4213 mutex_unlock(&ctx->uring_lock);
4223 revert_creds(old_cred);
4230 struct io_wait_queue {
4231 struct wait_queue_entry wq;
4232 struct io_ring_ctx *ctx;
4234 unsigned nr_timeouts;
4237 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
4239 struct io_ring_ctx *ctx = iowq->ctx;
4242 * Wake up if we have enough events, or if a timeout occurred since we
4243 * started waiting. For timeouts, we always want to return to userspace,
4244 * regardless of event count.
4246 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
4247 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4250 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4251 int wake_flags, void *key)
4253 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4256 /* use noflush == true, as we can't safely rely on locking context */
4257 if (!io_should_wake(iowq, true))
4260 return autoremove_wake_function(curr, mode, wake_flags, key);
4264 * Wait until events become available, if we don't already have some. The
4265 * application must reap them itself, as they reside on the shared cq ring.
4267 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
4268 const sigset_t __user *sig, size_t sigsz)
4270 struct io_wait_queue iowq = {
4273 .func = io_wake_function,
4274 .entry = LIST_HEAD_INIT(iowq.wq.entry),
4277 .to_wait = min_events,
4279 struct io_rings *rings = ctx->rings;
4282 if (io_cqring_events(ctx, false) >= min_events)
4286 #ifdef CONFIG_COMPAT
4287 if (in_compat_syscall())
4288 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
4292 ret = set_user_sigmask(sig, sigsz);
4298 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4299 trace_io_uring_cqring_wait(ctx, min_events);
4301 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
4302 TASK_INTERRUPTIBLE);
4303 if (io_should_wake(&iowq, false))
4306 if (signal_pending(current)) {
4311 finish_wait(&ctx->wait, &iowq.wq);
4313 restore_saved_sigmask_unless(ret == -EINTR);
4315 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4318 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4320 #if defined(CONFIG_UNIX)
4321 if (ctx->ring_sock) {
4322 struct sock *sock = ctx->ring_sock->sk;
4323 struct sk_buff *skb;
4325 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4331 for (i = 0; i < ctx->nr_user_files; i++) {
4334 file = io_file_from_index(ctx, i);
4341 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4343 unsigned nr_tables, i;
4345 if (!ctx->file_table)
4348 __io_sqe_files_unregister(ctx);
4349 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
4350 for (i = 0; i < nr_tables; i++)
4351 kfree(ctx->file_table[i].files);
4352 kfree(ctx->file_table);
4353 ctx->file_table = NULL;
4354 ctx->nr_user_files = 0;
4358 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
4360 if (ctx->sqo_thread) {
4361 wait_for_completion(&ctx->completions[1]);
4363 * The park is a bit of a work-around, without it we get
4364 * warning spews on shutdown with SQPOLL set and affinity
4365 * set to a single CPU.
4367 kthread_park(ctx->sqo_thread);
4368 kthread_stop(ctx->sqo_thread);
4369 ctx->sqo_thread = NULL;
4373 static void io_finish_async(struct io_ring_ctx *ctx)
4375 io_sq_thread_stop(ctx);
4378 io_wq_destroy(ctx->io_wq);
4383 #if defined(CONFIG_UNIX)
4384 static void io_destruct_skb(struct sk_buff *skb)
4386 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
4389 io_wq_flush(ctx->io_wq);
4391 unix_destruct_scm(skb);
4395 * Ensure the UNIX gc is aware of our file set, so we are certain that
4396 * the io_uring can be safely unregistered on process exit, even if we have
4397 * loops in the file referencing.
4399 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
4401 struct sock *sk = ctx->ring_sock->sk;
4402 struct scm_fp_list *fpl;
4403 struct sk_buff *skb;
4406 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
4407 unsigned long inflight = ctx->user->unix_inflight + nr;
4409 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
4413 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4417 skb = alloc_skb(0, GFP_KERNEL);
4426 fpl->user = get_uid(ctx->user);
4427 for (i = 0; i < nr; i++) {
4428 struct file *file = io_file_from_index(ctx, i + offset);
4432 fpl->fp[nr_files] = get_file(file);
4433 unix_inflight(fpl->user, fpl->fp[nr_files]);
4438 fpl->max = SCM_MAX_FD;
4439 fpl->count = nr_files;
4440 UNIXCB(skb).fp = fpl;
4441 skb->destructor = io_destruct_skb;
4442 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4443 skb_queue_head(&sk->sk_receive_queue, skb);
4445 for (i = 0; i < nr_files; i++)
4456 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
4457 * causes regular reference counting to break down. We rely on the UNIX
4458 * garbage collection to take care of this problem for us.
4460 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4462 unsigned left, total;
4466 left = ctx->nr_user_files;
4468 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
4470 ret = __io_sqe_files_scm(ctx, this_files, total);
4474 total += this_files;
4480 while (total < ctx->nr_user_files) {
4481 struct file *file = io_file_from_index(ctx, total);
4491 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
4497 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
4502 for (i = 0; i < nr_tables; i++) {
4503 struct fixed_file_table *table = &ctx->file_table[i];
4504 unsigned this_files;
4506 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
4507 table->files = kcalloc(this_files, sizeof(struct file *),
4511 nr_files -= this_files;
4517 for (i = 0; i < nr_tables; i++) {
4518 struct fixed_file_table *table = &ctx->file_table[i];
4519 kfree(table->files);
4524 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4527 __s32 __user *fds = (__s32 __user *) arg;
4532 if (ctx->file_table)
4536 if (nr_args > IORING_MAX_FIXED_FILES)
4539 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
4540 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
4542 if (!ctx->file_table)
4545 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
4546 kfree(ctx->file_table);
4547 ctx->file_table = NULL;
4551 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4552 struct fixed_file_table *table;
4556 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
4558 /* allow sparse sets */
4564 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4565 index = i & IORING_FILE_TABLE_MASK;
4566 table->files[index] = fget(fd);
4569 if (!table->files[index])
4572 * Don't allow io_uring instances to be registered. If UNIX
4573 * isn't enabled, then this causes a reference cycle and this
4574 * instance can never get freed. If UNIX is enabled we'll
4575 * handle it just fine, but there's still no point in allowing
4576 * a ring fd as it doesn't support regular read/write anyway.
4578 if (table->files[index]->f_op == &io_uring_fops) {
4579 fput(table->files[index]);
4586 for (i = 0; i < ctx->nr_user_files; i++) {
4589 file = io_file_from_index(ctx, i);
4593 for (i = 0; i < nr_tables; i++)
4594 kfree(ctx->file_table[i].files);
4596 kfree(ctx->file_table);
4597 ctx->file_table = NULL;
4598 ctx->nr_user_files = 0;
4602 ret = io_sqe_files_scm(ctx);
4604 io_sqe_files_unregister(ctx);
4609 static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
4611 #if defined(CONFIG_UNIX)
4612 struct file *file = io_file_from_index(ctx, index);
4613 struct sock *sock = ctx->ring_sock->sk;
4614 struct sk_buff_head list, *head = &sock->sk_receive_queue;
4615 struct sk_buff *skb;
4618 __skb_queue_head_init(&list);
4621 * Find the skb that holds this file in its SCM_RIGHTS. When found,
4622 * remove this entry and rearrange the file array.
4624 skb = skb_dequeue(head);
4626 struct scm_fp_list *fp;
4628 fp = UNIXCB(skb).fp;
4629 for (i = 0; i < fp->count; i++) {
4632 if (fp->fp[i] != file)
4635 unix_notinflight(fp->user, fp->fp[i]);
4636 left = fp->count - 1 - i;
4638 memmove(&fp->fp[i], &fp->fp[i + 1],
4639 left * sizeof(struct file *));
4646 __skb_queue_tail(&list, skb);
4656 __skb_queue_tail(&list, skb);
4658 skb = skb_dequeue(head);
4661 if (skb_peek(&list)) {
4662 spin_lock_irq(&head->lock);
4663 while ((skb = __skb_dequeue(&list)) != NULL)
4664 __skb_queue_tail(head, skb);
4665 spin_unlock_irq(&head->lock);
4668 fput(io_file_from_index(ctx, index));
4672 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
4675 #if defined(CONFIG_UNIX)
4676 struct sock *sock = ctx->ring_sock->sk;
4677 struct sk_buff_head *head = &sock->sk_receive_queue;
4678 struct sk_buff *skb;
4681 * See if we can merge this file into an existing skb SCM_RIGHTS
4682 * file set. If there's no room, fall back to allocating a new skb
4683 * and filling it in.
4685 spin_lock_irq(&head->lock);
4686 skb = skb_peek(head);
4688 struct scm_fp_list *fpl = UNIXCB(skb).fp;
4690 if (fpl->count < SCM_MAX_FD) {
4691 __skb_unlink(skb, head);
4692 spin_unlock_irq(&head->lock);
4693 fpl->fp[fpl->count] = get_file(file);
4694 unix_inflight(fpl->user, fpl->fp[fpl->count]);
4696 spin_lock_irq(&head->lock);
4697 __skb_queue_head(head, skb);
4702 spin_unlock_irq(&head->lock);
4709 return __io_sqe_files_scm(ctx, 1, index);
4715 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
4718 struct io_uring_files_update up;
4723 if (!ctx->file_table)
4727 if (copy_from_user(&up, arg, sizeof(up)))
4731 if (check_add_overflow(up.offset, nr_args, &done))
4733 if (done > ctx->nr_user_files)
4737 fds = u64_to_user_ptr(up.fds);
4739 struct fixed_file_table *table;
4743 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
4747 i = array_index_nospec(up.offset, ctx->nr_user_files);
4748 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
4749 index = i & IORING_FILE_TABLE_MASK;
4750 if (table->files[index]) {
4751 io_sqe_file_unregister(ctx, i);
4752 table->files[index] = NULL;
4763 * Don't allow io_uring instances to be registered. If
4764 * UNIX isn't enabled, then this causes a reference
4765 * cycle and this instance can never get freed. If UNIX
4766 * is enabled we'll handle it just fine, but there's
4767 * still no point in allowing a ring fd as it doesn't
4768 * support regular read/write anyway.
4770 if (file->f_op == &io_uring_fops) {
4775 table->files[index] = file;
4776 err = io_sqe_file_register(ctx, file, i);
4785 return done ? done : err;
4788 static void io_put_work(struct io_wq_work *work)
4790 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4795 static void io_get_work(struct io_wq_work *work)
4797 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
4799 refcount_inc(&req->refs);
4802 static int io_sq_offload_start(struct io_ring_ctx *ctx,
4803 struct io_uring_params *p)
4805 struct io_wq_data data;
4806 unsigned concurrency;
4809 init_waitqueue_head(&ctx->sqo_wait);
4810 mmgrab(current->mm);
4811 ctx->sqo_mm = current->mm;
4813 if (ctx->flags & IORING_SETUP_SQPOLL) {
4815 if (!capable(CAP_SYS_ADMIN))
4818 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
4819 if (!ctx->sq_thread_idle)
4820 ctx->sq_thread_idle = HZ;
4822 if (p->flags & IORING_SETUP_SQ_AFF) {
4823 int cpu = p->sq_thread_cpu;
4826 if (cpu >= nr_cpu_ids)
4828 if (!cpu_online(cpu))
4831 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
4835 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
4838 if (IS_ERR(ctx->sqo_thread)) {
4839 ret = PTR_ERR(ctx->sqo_thread);
4840 ctx->sqo_thread = NULL;
4843 wake_up_process(ctx->sqo_thread);
4844 } else if (p->flags & IORING_SETUP_SQ_AFF) {
4845 /* Can't have SQ_AFF without SQPOLL */
4850 data.mm = ctx->sqo_mm;
4851 data.user = ctx->user;
4852 data.creds = ctx->creds;
4853 data.get_work = io_get_work;
4854 data.put_work = io_put_work;
4856 /* Do QD, or 4 * CPUS, whatever is smallest */
4857 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
4858 ctx->io_wq = io_wq_create(concurrency, &data);
4859 if (IS_ERR(ctx->io_wq)) {
4860 ret = PTR_ERR(ctx->io_wq);
4867 io_finish_async(ctx);
4868 mmdrop(ctx->sqo_mm);
4873 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
4875 atomic_long_sub(nr_pages, &user->locked_vm);
4878 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
4880 unsigned long page_limit, cur_pages, new_pages;
4882 /* Don't allow more pages than we can safely lock */
4883 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
4886 cur_pages = atomic_long_read(&user->locked_vm);
4887 new_pages = cur_pages + nr_pages;
4888 if (new_pages > page_limit)
4890 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
4891 new_pages) != cur_pages);
4896 static void io_mem_free(void *ptr)
4903 page = virt_to_head_page(ptr);
4904 if (put_page_testzero(page))
4905 free_compound_page(page);
4908 static void *io_mem_alloc(size_t size)
4910 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
4913 return (void *) __get_free_pages(gfp_flags, get_order(size));
4916 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
4919 struct io_rings *rings;
4920 size_t off, sq_array_size;
4922 off = struct_size(rings, cqes, cq_entries);
4923 if (off == SIZE_MAX)
4927 off = ALIGN(off, SMP_CACHE_BYTES);
4932 sq_array_size = array_size(sizeof(u32), sq_entries);
4933 if (sq_array_size == SIZE_MAX)
4936 if (check_add_overflow(off, sq_array_size, &off))
4945 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
4949 pages = (size_t)1 << get_order(
4950 rings_size(sq_entries, cq_entries, NULL));
4951 pages += (size_t)1 << get_order(
4952 array_size(sizeof(struct io_uring_sqe), sq_entries));
4957 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
4961 if (!ctx->user_bufs)
4964 for (i = 0; i < ctx->nr_user_bufs; i++) {
4965 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
4967 for (j = 0; j < imu->nr_bvecs; j++)
4968 put_user_page(imu->bvec[j].bv_page);
4970 if (ctx->account_mem)
4971 io_unaccount_mem(ctx->user, imu->nr_bvecs);
4976 kfree(ctx->user_bufs);
4977 ctx->user_bufs = NULL;
4978 ctx->nr_user_bufs = 0;
4982 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
4983 void __user *arg, unsigned index)
4985 struct iovec __user *src;
4987 #ifdef CONFIG_COMPAT
4989 struct compat_iovec __user *ciovs;
4990 struct compat_iovec ciov;
4992 ciovs = (struct compat_iovec __user *) arg;
4993 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
4996 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
4997 dst->iov_len = ciov.iov_len;
5001 src = (struct iovec __user *) arg;
5002 if (copy_from_user(dst, &src[index], sizeof(*dst)))
5007 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
5010 struct vm_area_struct **vmas = NULL;
5011 struct page **pages = NULL;
5012 int i, j, got_pages = 0;
5017 if (!nr_args || nr_args > UIO_MAXIOV)
5020 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
5022 if (!ctx->user_bufs)
5025 for (i = 0; i < nr_args; i++) {
5026 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
5027 unsigned long off, start, end, ubuf;
5032 ret = io_copy_iov(ctx, &iov, arg, i);
5037 * Don't impose further limits on the size and buffer
5038 * constraints here, we'll -EINVAL later when IO is
5039 * submitted if they are wrong.
5042 if (!iov.iov_base || !iov.iov_len)
5045 /* arbitrary limit, but we need something */
5046 if (iov.iov_len > SZ_1G)
5049 ubuf = (unsigned long) iov.iov_base;
5050 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5051 start = ubuf >> PAGE_SHIFT;
5052 nr_pages = end - start;
5054 if (ctx->account_mem) {
5055 ret = io_account_mem(ctx->user, nr_pages);
5061 if (!pages || nr_pages > got_pages) {
5064 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
5066 vmas = kvmalloc_array(nr_pages,
5067 sizeof(struct vm_area_struct *),
5069 if (!pages || !vmas) {
5071 if (ctx->account_mem)
5072 io_unaccount_mem(ctx->user, nr_pages);
5075 got_pages = nr_pages;
5078 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
5082 if (ctx->account_mem)
5083 io_unaccount_mem(ctx->user, nr_pages);
5088 down_read(¤t->mm->mmap_sem);
5089 pret = get_user_pages(ubuf, nr_pages,
5090 FOLL_WRITE | FOLL_LONGTERM,
5092 if (pret == nr_pages) {
5093 /* don't support file backed memory */
5094 for (j = 0; j < nr_pages; j++) {
5095 struct vm_area_struct *vma = vmas[j];
5098 !is_file_hugepages(vma->vm_file)) {
5104 ret = pret < 0 ? pret : -EFAULT;
5106 up_read(¤t->mm->mmap_sem);
5109 * if we did partial map, or found file backed vmas,
5110 * release any pages we did get
5113 put_user_pages(pages, pret);
5114 if (ctx->account_mem)
5115 io_unaccount_mem(ctx->user, nr_pages);
5120 off = ubuf & ~PAGE_MASK;
5122 for (j = 0; j < nr_pages; j++) {
5125 vec_len = min_t(size_t, size, PAGE_SIZE - off);
5126 imu->bvec[j].bv_page = pages[j];
5127 imu->bvec[j].bv_len = vec_len;
5128 imu->bvec[j].bv_offset = off;
5132 /* store original address for later verification */
5134 imu->len = iov.iov_len;
5135 imu->nr_bvecs = nr_pages;
5137 ctx->nr_user_bufs++;
5145 io_sqe_buffer_unregister(ctx);
5149 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
5151 __s32 __user *fds = arg;
5157 if (copy_from_user(&fd, fds, sizeof(*fds)))
5160 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
5161 if (IS_ERR(ctx->cq_ev_fd)) {
5162 int ret = PTR_ERR(ctx->cq_ev_fd);
5163 ctx->cq_ev_fd = NULL;
5170 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5172 if (ctx->cq_ev_fd) {
5173 eventfd_ctx_put(ctx->cq_ev_fd);
5174 ctx->cq_ev_fd = NULL;
5181 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
5183 io_finish_async(ctx);
5185 mmdrop(ctx->sqo_mm);
5187 io_iopoll_reap_events(ctx);
5188 io_sqe_buffer_unregister(ctx);
5189 io_sqe_files_unregister(ctx);
5190 io_eventfd_unregister(ctx);
5192 #if defined(CONFIG_UNIX)
5193 if (ctx->ring_sock) {
5194 ctx->ring_sock->file = NULL; /* so that iput() is called */
5195 sock_release(ctx->ring_sock);
5199 io_mem_free(ctx->rings);
5200 io_mem_free(ctx->sq_sqes);
5202 percpu_ref_exit(&ctx->refs);
5203 if (ctx->account_mem)
5204 io_unaccount_mem(ctx->user,
5205 ring_pages(ctx->sq_entries, ctx->cq_entries));
5206 free_uid(ctx->user);
5207 put_cred(ctx->creds);
5208 kfree(ctx->completions);
5209 kfree(ctx->cancel_hash);
5210 kmem_cache_free(req_cachep, ctx->fallback_req);
5214 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5216 struct io_ring_ctx *ctx = file->private_data;
5219 poll_wait(file, &ctx->cq_wait, wait);
5221 * synchronizes with barrier from wq_has_sleeper call in
5225 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
5226 ctx->rings->sq_ring_entries)
5227 mask |= EPOLLOUT | EPOLLWRNORM;
5228 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
5229 mask |= EPOLLIN | EPOLLRDNORM;
5234 static int io_uring_fasync(int fd, struct file *file, int on)
5236 struct io_ring_ctx *ctx = file->private_data;
5238 return fasync_helper(fd, file, on, &ctx->cq_fasync);
5241 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5243 mutex_lock(&ctx->uring_lock);
5244 percpu_ref_kill(&ctx->refs);
5245 mutex_unlock(&ctx->uring_lock);
5247 io_kill_timeouts(ctx);
5248 io_poll_remove_all(ctx);
5251 io_wq_cancel_all(ctx->io_wq);
5253 io_iopoll_reap_events(ctx);
5254 /* if we failed setting up the ctx, we might not have any rings */
5256 io_cqring_overflow_flush(ctx, true);
5257 wait_for_completion(&ctx->completions[0]);
5258 io_ring_ctx_free(ctx);
5261 static int io_uring_release(struct inode *inode, struct file *file)
5263 struct io_ring_ctx *ctx = file->private_data;
5265 file->private_data = NULL;
5266 io_ring_ctx_wait_and_kill(ctx);
5270 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
5271 struct files_struct *files)
5273 struct io_kiocb *req;
5276 while (!list_empty_careful(&ctx->inflight_list)) {
5277 struct io_kiocb *cancel_req = NULL;
5279 spin_lock_irq(&ctx->inflight_lock);
5280 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
5281 if (req->work.files != files)
5283 /* req is being completed, ignore */
5284 if (!refcount_inc_not_zero(&req->refs))
5290 prepare_to_wait(&ctx->inflight_wait, &wait,
5291 TASK_UNINTERRUPTIBLE);
5292 spin_unlock_irq(&ctx->inflight_lock);
5294 /* We need to keep going until we don't find a matching req */
5298 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
5299 io_put_req(cancel_req);
5302 finish_wait(&ctx->inflight_wait, &wait);
5305 static int io_uring_flush(struct file *file, void *data)
5307 struct io_ring_ctx *ctx = file->private_data;
5309 io_uring_cancel_files(ctx, data);
5310 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
5311 io_cqring_overflow_flush(ctx, true);
5312 io_wq_cancel_all(ctx->io_wq);
5317 static void *io_uring_validate_mmap_request(struct file *file,
5318 loff_t pgoff, size_t sz)
5320 struct io_ring_ctx *ctx = file->private_data;
5321 loff_t offset = pgoff << PAGE_SHIFT;
5326 case IORING_OFF_SQ_RING:
5327 case IORING_OFF_CQ_RING:
5330 case IORING_OFF_SQES:
5334 return ERR_PTR(-EINVAL);
5337 page = virt_to_head_page(ptr);
5338 if (sz > page_size(page))
5339 return ERR_PTR(-EINVAL);
5346 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5348 size_t sz = vma->vm_end - vma->vm_start;
5352 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
5354 return PTR_ERR(ptr);
5356 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
5357 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
5360 #else /* !CONFIG_MMU */
5362 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
5364 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
5367 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
5369 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
5372 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
5373 unsigned long addr, unsigned long len,
5374 unsigned long pgoff, unsigned long flags)
5378 ptr = io_uring_validate_mmap_request(file, pgoff, len);
5380 return PTR_ERR(ptr);
5382 return (unsigned long) ptr;
5385 #endif /* !CONFIG_MMU */
5387 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
5388 u32, min_complete, u32, flags, const sigset_t __user *, sig,
5391 struct io_ring_ctx *ctx;
5396 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
5404 if (f.file->f_op != &io_uring_fops)
5408 ctx = f.file->private_data;
5409 if (!percpu_ref_tryget(&ctx->refs))
5413 * For SQ polling, the thread will do all submissions and completions.
5414 * Just return the requested submit count, and wake the thread if
5418 if (ctx->flags & IORING_SETUP_SQPOLL) {
5419 if (!list_empty_careful(&ctx->cq_overflow_list))
5420 io_cqring_overflow_flush(ctx, false);
5421 if (flags & IORING_ENTER_SQ_WAKEUP)
5422 wake_up(&ctx->sqo_wait);
5423 submitted = to_submit;
5424 } else if (to_submit) {
5425 struct mm_struct *cur_mm;
5427 if (current->mm != ctx->sqo_mm ||
5428 current_cred() != ctx->creds) {
5433 to_submit = min(to_submit, ctx->sq_entries);
5434 mutex_lock(&ctx->uring_lock);
5435 /* already have mm, so io_submit_sqes() won't try to grab it */
5436 cur_mm = ctx->sqo_mm;
5437 submitted = io_submit_sqes(ctx, to_submit, f.file, fd,
5439 mutex_unlock(&ctx->uring_lock);
5441 if (submitted != to_submit)
5444 if (flags & IORING_ENTER_GETEVENTS) {
5445 unsigned nr_events = 0;
5447 min_complete = min(min_complete, ctx->cq_entries);
5449 if (ctx->flags & IORING_SETUP_IOPOLL) {
5450 ret = io_iopoll_check(ctx, &nr_events, min_complete);
5452 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
5457 percpu_ref_put(&ctx->refs);
5460 return submitted ? submitted : ret;
5463 static const struct file_operations io_uring_fops = {
5464 .release = io_uring_release,
5465 .flush = io_uring_flush,
5466 .mmap = io_uring_mmap,
5468 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
5469 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
5471 .poll = io_uring_poll,
5472 .fasync = io_uring_fasync,
5475 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
5476 struct io_uring_params *p)
5478 struct io_rings *rings;
5479 size_t size, sq_array_offset;
5481 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
5482 if (size == SIZE_MAX)
5485 rings = io_mem_alloc(size);
5490 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
5491 rings->sq_ring_mask = p->sq_entries - 1;
5492 rings->cq_ring_mask = p->cq_entries - 1;
5493 rings->sq_ring_entries = p->sq_entries;
5494 rings->cq_ring_entries = p->cq_entries;
5495 ctx->sq_mask = rings->sq_ring_mask;
5496 ctx->cq_mask = rings->cq_ring_mask;
5497 ctx->sq_entries = rings->sq_ring_entries;
5498 ctx->cq_entries = rings->cq_ring_entries;
5500 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
5501 if (size == SIZE_MAX) {
5502 io_mem_free(ctx->rings);
5507 ctx->sq_sqes = io_mem_alloc(size);
5508 if (!ctx->sq_sqes) {
5509 io_mem_free(ctx->rings);
5518 * Allocate an anonymous fd, this is what constitutes the application
5519 * visible backing of an io_uring instance. The application mmaps this
5520 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
5521 * we have to tie this fd to a socket for file garbage collection purposes.
5523 static int io_uring_get_fd(struct io_ring_ctx *ctx)
5528 #if defined(CONFIG_UNIX)
5529 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
5535 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
5539 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
5540 O_RDWR | O_CLOEXEC);
5543 ret = PTR_ERR(file);
5547 #if defined(CONFIG_UNIX)
5548 ctx->ring_sock->file = file;
5549 ctx->ring_sock->sk->sk_user_data = ctx;
5551 fd_install(ret, file);
5554 #if defined(CONFIG_UNIX)
5555 sock_release(ctx->ring_sock);
5556 ctx->ring_sock = NULL;
5561 static int io_uring_create(unsigned entries, struct io_uring_params *p)
5563 struct user_struct *user = NULL;
5564 struct io_ring_ctx *ctx;
5568 if (!entries || entries > IORING_MAX_ENTRIES)
5572 * Use twice as many entries for the CQ ring. It's possible for the
5573 * application to drive a higher depth than the size of the SQ ring,
5574 * since the sqes are only used at submission time. This allows for
5575 * some flexibility in overcommitting a bit. If the application has
5576 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
5577 * of CQ ring entries manually.
5579 p->sq_entries = roundup_pow_of_two(entries);
5580 if (p->flags & IORING_SETUP_CQSIZE) {
5582 * If IORING_SETUP_CQSIZE is set, we do the same roundup
5583 * to a power-of-two, if it isn't already. We do NOT impose
5584 * any cq vs sq ring sizing.
5586 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
5588 p->cq_entries = roundup_pow_of_two(p->cq_entries);
5590 p->cq_entries = 2 * p->sq_entries;
5593 user = get_uid(current_user());
5594 account_mem = !capable(CAP_IPC_LOCK);
5597 ret = io_account_mem(user,
5598 ring_pages(p->sq_entries, p->cq_entries));
5605 ctx = io_ring_ctx_alloc(p);
5608 io_unaccount_mem(user, ring_pages(p->sq_entries,
5613 ctx->compat = in_compat_syscall();
5614 ctx->account_mem = account_mem;
5616 ctx->creds = get_current_cred();
5618 ret = io_allocate_scq_urings(ctx, p);
5622 ret = io_sq_offload_start(ctx, p);
5626 memset(&p->sq_off, 0, sizeof(p->sq_off));
5627 p->sq_off.head = offsetof(struct io_rings, sq.head);
5628 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
5629 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
5630 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
5631 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
5632 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
5633 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
5635 memset(&p->cq_off, 0, sizeof(p->cq_off));
5636 p->cq_off.head = offsetof(struct io_rings, cq.head);
5637 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
5638 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
5639 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
5640 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
5641 p->cq_off.cqes = offsetof(struct io_rings, cqes);
5644 * Install ring fd as the very last thing, so we don't risk someone
5645 * having closed it before we finish setup
5647 ret = io_uring_get_fd(ctx);
5651 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
5652 IORING_FEAT_SUBMIT_STABLE;
5653 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
5656 io_ring_ctx_wait_and_kill(ctx);
5661 * Sets up an aio uring context, and returns the fd. Applications asks for a
5662 * ring size, we return the actual sq/cq ring sizes (among other things) in the
5663 * params structure passed in.
5665 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
5667 struct io_uring_params p;
5671 if (copy_from_user(&p, params, sizeof(p)))
5673 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
5678 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
5679 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
5682 ret = io_uring_create(entries, &p);
5686 if (copy_to_user(params, &p, sizeof(p)))
5692 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
5693 struct io_uring_params __user *, params)
5695 return io_uring_setup(entries, params);
5698 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
5699 void __user *arg, unsigned nr_args)
5700 __releases(ctx->uring_lock)
5701 __acquires(ctx->uring_lock)
5706 * We're inside the ring mutex, if the ref is already dying, then
5707 * someone else killed the ctx or is already going through
5708 * io_uring_register().
5710 if (percpu_ref_is_dying(&ctx->refs))
5713 percpu_ref_kill(&ctx->refs);
5716 * Drop uring mutex before waiting for references to exit. If another
5717 * thread is currently inside io_uring_enter() it might need to grab
5718 * the uring_lock to make progress. If we hold it here across the drain
5719 * wait, then we can deadlock. It's safe to drop the mutex here, since
5720 * no new references will come in after we've killed the percpu ref.
5722 mutex_unlock(&ctx->uring_lock);
5723 wait_for_completion(&ctx->completions[0]);
5724 mutex_lock(&ctx->uring_lock);
5727 case IORING_REGISTER_BUFFERS:
5728 ret = io_sqe_buffer_register(ctx, arg, nr_args);
5730 case IORING_UNREGISTER_BUFFERS:
5734 ret = io_sqe_buffer_unregister(ctx);
5736 case IORING_REGISTER_FILES:
5737 ret = io_sqe_files_register(ctx, arg, nr_args);
5739 case IORING_UNREGISTER_FILES:
5743 ret = io_sqe_files_unregister(ctx);
5745 case IORING_REGISTER_FILES_UPDATE:
5746 ret = io_sqe_files_update(ctx, arg, nr_args);
5748 case IORING_REGISTER_EVENTFD:
5752 ret = io_eventfd_register(ctx, arg);
5754 case IORING_UNREGISTER_EVENTFD:
5758 ret = io_eventfd_unregister(ctx);
5765 /* bring the ctx back to life */
5766 reinit_completion(&ctx->completions[0]);
5767 percpu_ref_reinit(&ctx->refs);
5771 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
5772 void __user *, arg, unsigned int, nr_args)
5774 struct io_ring_ctx *ctx;
5783 if (f.file->f_op != &io_uring_fops)
5786 ctx = f.file->private_data;
5788 mutex_lock(&ctx->uring_lock);
5789 ret = __io_uring_register(ctx, opcode, arg, nr_args);
5790 mutex_unlock(&ctx->uring_lock);
5791 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
5792 ctx->cq_ev_fd != NULL, ret);
5798 static int __init io_uring_init(void)
5800 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
5803 __initcall(io_uring_init);