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/workqueue.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
74 #include <uapi/linux/io_uring.h>
78 #define IORING_MAX_ENTRIES 4096
79 #define IORING_MAX_FIXED_FILES 1024
82 u32 head ____cacheline_aligned_in_smp;
83 u32 tail ____cacheline_aligned_in_smp;
87 * This data is shared with the application through the mmap at offset
90 * The offsets to the member fields are published through struct
91 * io_sqring_offsets when calling io_uring_setup.
95 * Head and tail offsets into the ring; the offsets need to be
96 * masked to get valid indices.
98 * The kernel controls head and the application controls tail.
102 * Bitmask to apply to head and tail offsets (constant, equals
106 /* Ring size (constant, power of 2) */
109 * Number of invalid entries dropped by the kernel due to
110 * invalid index stored in array
112 * Written by the kernel, shouldn't be modified by the
113 * application (i.e. get number of "new events" by comparing to
116 * After a new SQ head value was read by the application this
117 * counter includes all submissions that were dropped reaching
118 * the new SQ head (and possibly more).
124 * Written by the kernel, shouldn't be modified by the
127 * The application needs a full memory barrier before checking
128 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
132 * Ring buffer of indices into array of io_uring_sqe, which is
133 * mmapped by the application using the IORING_OFF_SQES offset.
135 * This indirection could e.g. be used to assign fixed
136 * io_uring_sqe entries to operations and only submit them to
137 * the queue when needed.
139 * The kernel modifies neither the indices array nor the entries
146 * This data is shared with the application through the mmap at offset
147 * IORING_OFF_CQ_RING.
149 * The offsets to the member fields are published through struct
150 * io_cqring_offsets when calling io_uring_setup.
154 * Head and tail offsets into the ring; the offsets need to be
155 * masked to get valid indices.
157 * The application controls head and the kernel tail.
161 * Bitmask to apply to head and tail offsets (constant, equals
165 /* Ring size (constant, power of 2) */
168 * Number of completion events lost because the queue was full;
169 * this should be avoided by the application by making sure
170 * there are not more requests pending thatn there is space in
171 * the completion queue.
173 * Written by the kernel, shouldn't be modified by the
174 * application (i.e. get number of "new events" by comparing to
177 * As completion events come in out of order this counter is not
178 * ordered with any other data.
182 * Ring buffer of completion events.
184 * The kernel writes completion events fresh every time they are
185 * produced, so the application is allowed to modify pending
188 struct io_uring_cqe cqes[];
191 struct io_mapped_ubuf {
194 struct bio_vec *bvec;
195 unsigned int nr_bvecs;
201 struct list_head list;
210 struct percpu_ref refs;
211 } ____cacheline_aligned_in_smp;
219 struct io_sq_ring *sq_ring;
220 unsigned cached_sq_head;
223 unsigned sq_thread_idle;
224 struct io_uring_sqe *sq_sqes;
226 struct list_head defer_list;
227 } ____cacheline_aligned_in_smp;
230 struct workqueue_struct *sqo_wq;
231 struct task_struct *sqo_thread; /* if using sq thread polling */
232 struct mm_struct *sqo_mm;
233 wait_queue_head_t sqo_wait;
238 struct io_cq_ring *cq_ring;
239 unsigned cached_cq_tail;
242 struct wait_queue_head cq_wait;
243 struct fasync_struct *cq_fasync;
244 struct eventfd_ctx *cq_ev_fd;
245 } ____cacheline_aligned_in_smp;
248 * If used, fixed file set. Writers must ensure that ->refs is dead,
249 * readers must ensure that ->refs is alive as long as the file* is
250 * used. Only updated through io_uring_register(2).
252 struct file **user_files;
253 unsigned nr_user_files;
255 /* if used, fixed mapped user buffers */
256 unsigned nr_user_bufs;
257 struct io_mapped_ubuf *user_bufs;
259 struct user_struct *user;
261 struct completion ctx_done;
264 struct mutex uring_lock;
265 wait_queue_head_t wait;
266 } ____cacheline_aligned_in_smp;
269 spinlock_t completion_lock;
270 bool poll_multi_file;
272 * ->poll_list is protected by the ctx->uring_lock for
273 * io_uring instances that don't use IORING_SETUP_SQPOLL.
274 * For SQPOLL, only the single threaded io_sq_thread() will
275 * manipulate the list, hence no extra locking is needed there.
277 struct list_head poll_list;
278 struct list_head cancel_list;
279 } ____cacheline_aligned_in_smp;
281 struct async_list pending_async[2];
283 #if defined(CONFIG_UNIX)
284 struct socket *ring_sock;
289 const struct io_uring_sqe *sqe;
290 unsigned short index;
293 bool needs_fixed_file;
297 * First field must be the file pointer in all the
298 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
300 struct io_poll_iocb {
302 struct wait_queue_head *head;
306 struct wait_queue_entry wait;
310 * NOTE! Each of the iocb union members has the file pointer
311 * as the first entry in their struct definition. So you can
312 * access the file pointer through any of the sub-structs,
313 * or directly as just 'ki_filp' in this struct.
319 struct io_poll_iocb poll;
322 struct sqe_submit submit;
324 struct io_ring_ctx *ctx;
325 struct list_head list;
328 #define REQ_F_NOWAIT 1 /* must not punt to workers */
329 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
330 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
331 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
332 #define REQ_F_PREPPED 16 /* prep already done */
333 #define REQ_F_IO_DRAIN 32 /* drain existing IO first */
334 #define REQ_F_IO_DRAINED 64 /* drain done */
336 u32 error; /* iopoll result from callback */
339 struct work_struct work;
342 #define IO_PLUG_THRESHOLD 2
343 #define IO_IOPOLL_BATCH 8
345 struct io_submit_state {
346 struct blk_plug plug;
349 * io_kiocb alloc cache
351 void *reqs[IO_IOPOLL_BATCH];
352 unsigned int free_reqs;
353 unsigned int cur_req;
356 * File reference cache
360 unsigned int has_refs;
361 unsigned int used_refs;
362 unsigned int ios_left;
365 static void io_sq_wq_submit_work(struct work_struct *work);
367 static struct kmem_cache *req_cachep;
369 static const struct file_operations io_uring_fops;
371 struct sock *io_uring_get_socket(struct file *file)
373 #if defined(CONFIG_UNIX)
374 if (file->f_op == &io_uring_fops) {
375 struct io_ring_ctx *ctx = file->private_data;
377 return ctx->ring_sock->sk;
382 EXPORT_SYMBOL(io_uring_get_socket);
384 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
386 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
388 complete(&ctx->ctx_done);
391 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
393 struct io_ring_ctx *ctx;
396 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
400 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
405 ctx->flags = p->flags;
406 init_waitqueue_head(&ctx->cq_wait);
407 init_completion(&ctx->ctx_done);
408 mutex_init(&ctx->uring_lock);
409 init_waitqueue_head(&ctx->wait);
410 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
411 spin_lock_init(&ctx->pending_async[i].lock);
412 INIT_LIST_HEAD(&ctx->pending_async[i].list);
413 atomic_set(&ctx->pending_async[i].cnt, 0);
415 spin_lock_init(&ctx->completion_lock);
416 INIT_LIST_HEAD(&ctx->poll_list);
417 INIT_LIST_HEAD(&ctx->cancel_list);
418 INIT_LIST_HEAD(&ctx->defer_list);
422 static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
423 struct io_kiocb *req)
425 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
428 return req->sequence > ctx->cached_cq_tail + ctx->sq_ring->dropped;
431 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
433 struct io_kiocb *req;
435 if (list_empty(&ctx->defer_list))
438 req = list_first_entry(&ctx->defer_list, struct io_kiocb, list);
439 if (!io_sequence_defer(ctx, req)) {
440 list_del_init(&req->list);
447 static void __io_commit_cqring(struct io_ring_ctx *ctx)
449 struct io_cq_ring *ring = ctx->cq_ring;
451 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
452 /* order cqe stores with ring update */
453 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
455 if (wq_has_sleeper(&ctx->cq_wait)) {
456 wake_up_interruptible(&ctx->cq_wait);
457 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
462 static void io_commit_cqring(struct io_ring_ctx *ctx)
464 struct io_kiocb *req;
466 __io_commit_cqring(ctx);
468 while ((req = io_get_deferred_req(ctx)) != NULL) {
469 req->flags |= REQ_F_IO_DRAINED;
470 queue_work(ctx->sqo_wq, &req->work);
474 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
476 struct io_cq_ring *ring = ctx->cq_ring;
479 tail = ctx->cached_cq_tail;
481 * writes to the cq entry need to come after reading head; the
482 * control dependency is enough as we're using WRITE_ONCE to
485 if (tail - READ_ONCE(ring->r.head) == ring->ring_entries)
488 ctx->cached_cq_tail++;
489 return &ring->cqes[tail & ctx->cq_mask];
492 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
493 long res, unsigned ev_flags)
495 struct io_uring_cqe *cqe;
498 * If we can't get a cq entry, userspace overflowed the
499 * submission (by quite a lot). Increment the overflow count in
502 cqe = io_get_cqring(ctx);
504 WRITE_ONCE(cqe->user_data, ki_user_data);
505 WRITE_ONCE(cqe->res, res);
506 WRITE_ONCE(cqe->flags, ev_flags);
508 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
510 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
514 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
516 if (waitqueue_active(&ctx->wait))
518 if (waitqueue_active(&ctx->sqo_wait))
519 wake_up(&ctx->sqo_wait);
521 eventfd_signal(ctx->cq_ev_fd, 1);
524 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
525 long res, unsigned ev_flags)
529 spin_lock_irqsave(&ctx->completion_lock, flags);
530 io_cqring_fill_event(ctx, user_data, res, ev_flags);
531 io_commit_cqring(ctx);
532 spin_unlock_irqrestore(&ctx->completion_lock, flags);
534 io_cqring_ev_posted(ctx);
537 static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
539 percpu_ref_put_many(&ctx->refs, refs);
541 if (waitqueue_active(&ctx->wait))
545 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
546 struct io_submit_state *state)
548 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
549 struct io_kiocb *req;
551 if (!percpu_ref_tryget(&ctx->refs))
555 req = kmem_cache_alloc(req_cachep, gfp);
558 } else if (!state->free_reqs) {
562 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
563 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
566 * Bulk alloc is all-or-nothing. If we fail to get a batch,
567 * retry single alloc to be on the safe side.
569 if (unlikely(ret <= 0)) {
570 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
575 state->free_reqs = ret - 1;
577 req = state->reqs[0];
579 req = state->reqs[state->cur_req];
586 /* one is dropped after submission, the other at completion */
587 refcount_set(&req->refs, 2);
590 io_ring_drop_ctx_refs(ctx, 1);
594 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
597 kmem_cache_free_bulk(req_cachep, *nr, reqs);
598 io_ring_drop_ctx_refs(ctx, *nr);
603 static void io_free_req(struct io_kiocb *req)
605 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
607 io_ring_drop_ctx_refs(req->ctx, 1);
608 kmem_cache_free(req_cachep, req);
611 static void io_put_req(struct io_kiocb *req)
613 if (refcount_dec_and_test(&req->refs))
618 * Find and free completed poll iocbs
620 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
621 struct list_head *done)
623 void *reqs[IO_IOPOLL_BATCH];
624 struct io_kiocb *req;
628 while (!list_empty(done)) {
629 req = list_first_entry(done, struct io_kiocb, list);
630 list_del(&req->list);
632 io_cqring_fill_event(ctx, req->user_data, req->error, 0);
635 if (refcount_dec_and_test(&req->refs)) {
636 /* If we're not using fixed files, we have to pair the
637 * completion part with the file put. Use regular
638 * completions for those, only batch free for fixed
641 if (req->flags & REQ_F_FIXED_FILE) {
642 reqs[to_free++] = req;
643 if (to_free == ARRAY_SIZE(reqs))
644 io_free_req_many(ctx, reqs, &to_free);
651 io_commit_cqring(ctx);
652 io_free_req_many(ctx, reqs, &to_free);
655 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
658 struct io_kiocb *req, *tmp;
664 * Only spin for completions if we don't have multiple devices hanging
665 * off our complete list, and we're under the requested amount.
667 spin = !ctx->poll_multi_file && *nr_events < min;
670 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
671 struct kiocb *kiocb = &req->rw;
674 * Move completed entries to our local list. If we find a
675 * request that requires polling, break out and complete
676 * the done list first, if we have entries there.
678 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
679 list_move_tail(&req->list, &done);
682 if (!list_empty(&done))
685 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
694 if (!list_empty(&done))
695 io_iopoll_complete(ctx, nr_events, &done);
701 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
702 * non-spinning poll check - we'll still enter the driver poll loop, but only
703 * as a non-spinning completion check.
705 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
708 while (!list_empty(&ctx->poll_list)) {
711 ret = io_do_iopoll(ctx, nr_events, min);
714 if (!min || *nr_events >= min)
722 * We can't just wait for polled events to come to us, we have to actively
723 * find and complete them.
725 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
727 if (!(ctx->flags & IORING_SETUP_IOPOLL))
730 mutex_lock(&ctx->uring_lock);
731 while (!list_empty(&ctx->poll_list)) {
732 unsigned int nr_events = 0;
734 io_iopoll_getevents(ctx, &nr_events, 1);
736 mutex_unlock(&ctx->uring_lock);
739 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
747 if (*nr_events < min)
748 tmin = min - *nr_events;
750 ret = io_iopoll_getevents(ctx, nr_events, tmin);
754 } while (min && !*nr_events && !need_resched());
759 static void kiocb_end_write(struct kiocb *kiocb)
761 if (kiocb->ki_flags & IOCB_WRITE) {
762 struct inode *inode = file_inode(kiocb->ki_filp);
765 * Tell lockdep we inherited freeze protection from submission
768 if (S_ISREG(inode->i_mode))
769 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
770 file_end_write(kiocb->ki_filp);
774 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
776 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
778 kiocb_end_write(kiocb);
780 io_cqring_add_event(req->ctx, req->user_data, res, 0);
784 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
786 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
788 kiocb_end_write(kiocb);
792 req->flags |= REQ_F_IOPOLL_COMPLETED;
796 * After the iocb has been issued, it's safe to be found on the poll list.
797 * Adding the kiocb to the list AFTER submission ensures that we don't
798 * find it from a io_iopoll_getevents() thread before the issuer is done
799 * accessing the kiocb cookie.
801 static void io_iopoll_req_issued(struct io_kiocb *req)
803 struct io_ring_ctx *ctx = req->ctx;
806 * Track whether we have multiple files in our lists. This will impact
807 * how we do polling eventually, not spinning if we're on potentially
810 if (list_empty(&ctx->poll_list)) {
811 ctx->poll_multi_file = false;
812 } else if (!ctx->poll_multi_file) {
813 struct io_kiocb *list_req;
815 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
817 if (list_req->rw.ki_filp != req->rw.ki_filp)
818 ctx->poll_multi_file = true;
822 * For fast devices, IO may have already completed. If it has, add
823 * it to the front so we find it first.
825 if (req->flags & REQ_F_IOPOLL_COMPLETED)
826 list_add(&req->list, &ctx->poll_list);
828 list_add_tail(&req->list, &ctx->poll_list);
831 static void io_file_put(struct io_submit_state *state)
834 int diff = state->has_refs - state->used_refs;
837 fput_many(state->file, diff);
843 * Get as many references to a file as we have IOs left in this submission,
844 * assuming most submissions are for one file, or at least that each file
845 * has more than one submission.
847 static struct file *io_file_get(struct io_submit_state *state, int fd)
853 if (state->fd == fd) {
860 state->file = fget_many(fd, state->ios_left);
865 state->has_refs = state->ios_left;
866 state->used_refs = 1;
872 * If we tracked the file through the SCM inflight mechanism, we could support
873 * any file. For now, just ensure that anything potentially problematic is done
876 static bool io_file_supports_async(struct file *file)
878 umode_t mode = file_inode(file)->i_mode;
880 if (S_ISBLK(mode) || S_ISCHR(mode))
882 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
888 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
891 const struct io_uring_sqe *sqe = s->sqe;
892 struct io_ring_ctx *ctx = req->ctx;
893 struct kiocb *kiocb = &req->rw;
899 /* For -EAGAIN retry, everything is already prepped */
900 if (req->flags & REQ_F_PREPPED)
903 if (force_nonblock && !io_file_supports_async(req->file))
904 force_nonblock = false;
906 kiocb->ki_pos = READ_ONCE(sqe->off);
907 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
908 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
910 ioprio = READ_ONCE(sqe->ioprio);
912 ret = ioprio_check_cap(ioprio);
916 kiocb->ki_ioprio = ioprio;
918 kiocb->ki_ioprio = get_current_ioprio();
920 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
924 /* don't allow async punt if RWF_NOWAIT was requested */
925 if (kiocb->ki_flags & IOCB_NOWAIT)
926 req->flags |= REQ_F_NOWAIT;
929 kiocb->ki_flags |= IOCB_NOWAIT;
931 if (ctx->flags & IORING_SETUP_IOPOLL) {
932 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
933 !kiocb->ki_filp->f_op->iopoll)
937 kiocb->ki_flags |= IOCB_HIPRI;
938 kiocb->ki_complete = io_complete_rw_iopoll;
940 if (kiocb->ki_flags & IOCB_HIPRI)
942 kiocb->ki_complete = io_complete_rw;
944 req->flags |= REQ_F_PREPPED;
948 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
954 case -ERESTARTNOINTR:
955 case -ERESTARTNOHAND:
956 case -ERESTART_RESTARTBLOCK:
958 * We can't just restart the syscall, since previously
959 * submitted sqes may already be in progress. Just fail this
965 kiocb->ki_complete(kiocb, ret, 0);
969 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
970 const struct io_uring_sqe *sqe,
971 struct iov_iter *iter)
973 size_t len = READ_ONCE(sqe->len);
974 struct io_mapped_ubuf *imu;
975 unsigned index, buf_index;
979 /* attempt to use fixed buffers without having provided iovecs */
980 if (unlikely(!ctx->user_bufs))
983 buf_index = READ_ONCE(sqe->buf_index);
984 if (unlikely(buf_index >= ctx->nr_user_bufs))
987 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
988 imu = &ctx->user_bufs[index];
989 buf_addr = READ_ONCE(sqe->addr);
992 if (buf_addr + len < buf_addr)
994 /* not inside the mapped region */
995 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
999 * May not be a start of buffer, set size appropriately
1000 * and advance us to the beginning.
1002 offset = buf_addr - imu->ubuf;
1003 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1005 iov_iter_advance(iter, offset);
1007 /* don't drop a reference to these pages */
1008 iter->type |= ITER_BVEC_FLAG_NO_REF;
1012 static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
1013 const struct sqe_submit *s, struct iovec **iovec,
1014 struct iov_iter *iter)
1016 const struct io_uring_sqe *sqe = s->sqe;
1017 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1018 size_t sqe_len = READ_ONCE(sqe->len);
1022 * We're reading ->opcode for the second time, but the first read
1023 * doesn't care whether it's _FIXED or not, so it doesn't matter
1024 * whether ->opcode changes concurrently. The first read does care
1025 * about whether it is a READ or a WRITE, so we don't trust this read
1026 * for that purpose and instead let the caller pass in the read/write
1029 opcode = READ_ONCE(sqe->opcode);
1030 if (opcode == IORING_OP_READ_FIXED ||
1031 opcode == IORING_OP_WRITE_FIXED) {
1032 int ret = io_import_fixed(ctx, rw, sqe, iter);
1040 #ifdef CONFIG_COMPAT
1042 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1046 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1050 * Make a note of the last file/offset/direction we punted to async
1051 * context. We'll use this information to see if we can piggy back a
1052 * sequential request onto the previous one, if it's still hasn't been
1053 * completed by the async worker.
1055 static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1057 struct async_list *async_list = &req->ctx->pending_async[rw];
1058 struct kiocb *kiocb = &req->rw;
1059 struct file *filp = kiocb->ki_filp;
1060 off_t io_end = kiocb->ki_pos + len;
1062 if (filp == async_list->file && kiocb->ki_pos == async_list->io_end) {
1063 unsigned long max_pages;
1065 /* Use 8x RA size as a decent limiter for both reads/writes */
1066 max_pages = filp->f_ra.ra_pages;
1068 max_pages = VM_READAHEAD_PAGES;
1071 /* If max pages are exceeded, reset the state */
1073 if (async_list->io_pages + len <= max_pages) {
1074 req->flags |= REQ_F_SEQ_PREV;
1075 async_list->io_pages += len;
1078 async_list->io_pages = 0;
1082 /* New file? Reset state. */
1083 if (async_list->file != filp) {
1084 async_list->io_pages = 0;
1085 async_list->file = filp;
1087 async_list->io_end = io_end;
1090 static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1091 bool force_nonblock)
1093 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1094 struct kiocb *kiocb = &req->rw;
1095 struct iov_iter iter;
1100 ret = io_prep_rw(req, s, force_nonblock);
1103 file = kiocb->ki_filp;
1105 if (unlikely(!(file->f_mode & FMODE_READ)))
1107 if (unlikely(!file->f_op->read_iter))
1110 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
1114 iov_count = iov_iter_count(&iter);
1115 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1119 /* Catch -EAGAIN return for forced non-blocking submission */
1120 ret2 = call_read_iter(file, kiocb, &iter);
1121 if (!force_nonblock || ret2 != -EAGAIN) {
1122 io_rw_done(kiocb, ret2);
1125 * If ->needs_lock is true, we're already in async
1129 io_async_list_note(READ, req, iov_count);
1137 static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1138 bool force_nonblock)
1140 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1141 struct kiocb *kiocb = &req->rw;
1142 struct iov_iter iter;
1147 ret = io_prep_rw(req, s, force_nonblock);
1151 file = kiocb->ki_filp;
1152 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1154 if (unlikely(!file->f_op->write_iter))
1157 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1161 iov_count = iov_iter_count(&iter);
1164 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1165 /* If ->needs_lock is true, we're already in async context. */
1167 io_async_list_note(WRITE, req, iov_count);
1171 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1176 * Open-code file_start_write here to grab freeze protection,
1177 * which will be released by another thread in
1178 * io_complete_rw(). Fool lockdep by telling it the lock got
1179 * released so that it doesn't complain about the held lock when
1180 * we return to userspace.
1182 if (S_ISREG(file_inode(file)->i_mode)) {
1183 __sb_start_write(file_inode(file)->i_sb,
1184 SB_FREEZE_WRITE, true);
1185 __sb_writers_release(file_inode(file)->i_sb,
1188 kiocb->ki_flags |= IOCB_WRITE;
1190 ret2 = call_write_iter(file, kiocb, &iter);
1191 if (!force_nonblock || ret2 != -EAGAIN) {
1192 io_rw_done(kiocb, ret2);
1195 * If ->needs_lock is true, we're already in async
1199 io_async_list_note(WRITE, req, iov_count);
1209 * IORING_OP_NOP just posts a completion event, nothing else.
1211 static int io_nop(struct io_kiocb *req, u64 user_data)
1213 struct io_ring_ctx *ctx = req->ctx;
1216 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1219 io_cqring_add_event(ctx, user_data, err, 0);
1224 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1226 struct io_ring_ctx *ctx = req->ctx;
1230 /* Prep already done (EAGAIN retry) */
1231 if (req->flags & REQ_F_PREPPED)
1234 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1236 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1239 req->flags |= REQ_F_PREPPED;
1243 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1244 bool force_nonblock)
1246 loff_t sqe_off = READ_ONCE(sqe->off);
1247 loff_t sqe_len = READ_ONCE(sqe->len);
1248 loff_t end = sqe_off + sqe_len;
1249 unsigned fsync_flags;
1252 fsync_flags = READ_ONCE(sqe->fsync_flags);
1253 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1256 ret = io_prep_fsync(req, sqe);
1260 /* fsync always requires a blocking context */
1264 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1265 end > 0 ? end : LLONG_MAX,
1266 fsync_flags & IORING_FSYNC_DATASYNC);
1268 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
1273 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1275 struct io_ring_ctx *ctx = req->ctx;
1280 /* Prep already done (EAGAIN retry) */
1281 if (req->flags & REQ_F_PREPPED)
1284 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1286 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1289 req->flags |= REQ_F_PREPPED;
1293 static int io_sync_file_range(struct io_kiocb *req,
1294 const struct io_uring_sqe *sqe,
1295 bool force_nonblock)
1302 ret = io_prep_sfr(req, sqe);
1306 /* sync_file_range always requires a blocking context */
1310 sqe_off = READ_ONCE(sqe->off);
1311 sqe_len = READ_ONCE(sqe->len);
1312 flags = READ_ONCE(sqe->sync_range_flags);
1314 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1316 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
1321 static void io_poll_remove_one(struct io_kiocb *req)
1323 struct io_poll_iocb *poll = &req->poll;
1325 spin_lock(&poll->head->lock);
1326 WRITE_ONCE(poll->canceled, true);
1327 if (!list_empty(&poll->wait.entry)) {
1328 list_del_init(&poll->wait.entry);
1329 queue_work(req->ctx->sqo_wq, &req->work);
1331 spin_unlock(&poll->head->lock);
1333 list_del_init(&req->list);
1336 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1338 struct io_kiocb *req;
1340 spin_lock_irq(&ctx->completion_lock);
1341 while (!list_empty(&ctx->cancel_list)) {
1342 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1343 io_poll_remove_one(req);
1345 spin_unlock_irq(&ctx->completion_lock);
1349 * Find a running poll command that matches one specified in sqe->addr,
1350 * and remove it if found.
1352 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1354 struct io_ring_ctx *ctx = req->ctx;
1355 struct io_kiocb *poll_req, *next;
1358 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1360 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1364 spin_lock_irq(&ctx->completion_lock);
1365 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1366 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1367 io_poll_remove_one(poll_req);
1372 spin_unlock_irq(&ctx->completion_lock);
1374 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
1379 static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1382 req->poll.done = true;
1383 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask), 0);
1384 io_commit_cqring(ctx);
1387 static void io_poll_complete_work(struct work_struct *work)
1389 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1390 struct io_poll_iocb *poll = &req->poll;
1391 struct poll_table_struct pt = { ._key = poll->events };
1392 struct io_ring_ctx *ctx = req->ctx;
1395 if (!READ_ONCE(poll->canceled))
1396 mask = vfs_poll(poll->file, &pt) & poll->events;
1399 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1400 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1401 * synchronize with them. In the cancellation case the list_del_init
1402 * itself is not actually needed, but harmless so we keep it in to
1403 * avoid further branches in the fast path.
1405 spin_lock_irq(&ctx->completion_lock);
1406 if (!mask && !READ_ONCE(poll->canceled)) {
1407 add_wait_queue(poll->head, &poll->wait);
1408 spin_unlock_irq(&ctx->completion_lock);
1411 list_del_init(&req->list);
1412 io_poll_complete(ctx, req, mask);
1413 spin_unlock_irq(&ctx->completion_lock);
1415 io_cqring_ev_posted(ctx);
1419 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1422 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1424 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1425 struct io_ring_ctx *ctx = req->ctx;
1426 __poll_t mask = key_to_poll(key);
1427 unsigned long flags;
1429 /* for instances that support it check for an event match first: */
1430 if (mask && !(mask & poll->events))
1433 list_del_init(&poll->wait.entry);
1435 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1436 list_del(&req->list);
1437 io_poll_complete(ctx, req, mask);
1438 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1440 io_cqring_ev_posted(ctx);
1443 queue_work(ctx->sqo_wq, &req->work);
1449 struct io_poll_table {
1450 struct poll_table_struct pt;
1451 struct io_kiocb *req;
1455 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1456 struct poll_table_struct *p)
1458 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1460 if (unlikely(pt->req->poll.head)) {
1461 pt->error = -EINVAL;
1466 pt->req->poll.head = head;
1467 add_wait_queue(head, &pt->req->poll.wait);
1470 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1472 struct io_poll_iocb *poll = &req->poll;
1473 struct io_ring_ctx *ctx = req->ctx;
1474 struct io_poll_table ipt;
1475 bool cancel = false;
1479 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1481 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1486 INIT_WORK(&req->work, io_poll_complete_work);
1487 events = READ_ONCE(sqe->poll_events);
1488 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1492 poll->canceled = false;
1494 ipt.pt._qproc = io_poll_queue_proc;
1495 ipt.pt._key = poll->events;
1497 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1499 /* initialized the list so that we can do list_empty checks */
1500 INIT_LIST_HEAD(&poll->wait.entry);
1501 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1503 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1505 spin_lock_irq(&ctx->completion_lock);
1506 if (likely(poll->head)) {
1507 spin_lock(&poll->head->lock);
1508 if (unlikely(list_empty(&poll->wait.entry))) {
1514 if (mask || ipt.error)
1515 list_del_init(&poll->wait.entry);
1517 WRITE_ONCE(poll->canceled, true);
1518 else if (!poll->done) /* actually waiting for an event */
1519 list_add_tail(&req->list, &ctx->cancel_list);
1520 spin_unlock(&poll->head->lock);
1522 if (mask) { /* no async, we'd stolen it */
1524 io_poll_complete(ctx, req, mask);
1526 spin_unlock_irq(&ctx->completion_lock);
1529 io_cqring_ev_posted(ctx);
1535 static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1536 const struct io_uring_sqe *sqe)
1538 struct io_uring_sqe *sqe_copy;
1540 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1543 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1547 spin_lock_irq(&ctx->completion_lock);
1548 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1549 spin_unlock_irq(&ctx->completion_lock);
1554 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1555 req->submit.sqe = sqe_copy;
1557 INIT_WORK(&req->work, io_sq_wq_submit_work);
1558 list_add_tail(&req->list, &ctx->defer_list);
1559 spin_unlock_irq(&ctx->completion_lock);
1560 return -EIOCBQUEUED;
1563 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1564 const struct sqe_submit *s, bool force_nonblock)
1568 if (unlikely(s->index >= ctx->sq_entries))
1570 req->user_data = READ_ONCE(s->sqe->user_data);
1572 opcode = READ_ONCE(s->sqe->opcode);
1575 ret = io_nop(req, req->user_data);
1577 case IORING_OP_READV:
1578 if (unlikely(s->sqe->buf_index))
1580 ret = io_read(req, s, force_nonblock);
1582 case IORING_OP_WRITEV:
1583 if (unlikely(s->sqe->buf_index))
1585 ret = io_write(req, s, force_nonblock);
1587 case IORING_OP_READ_FIXED:
1588 ret = io_read(req, s, force_nonblock);
1590 case IORING_OP_WRITE_FIXED:
1591 ret = io_write(req, s, force_nonblock);
1593 case IORING_OP_FSYNC:
1594 ret = io_fsync(req, s->sqe, force_nonblock);
1596 case IORING_OP_POLL_ADD:
1597 ret = io_poll_add(req, s->sqe);
1599 case IORING_OP_POLL_REMOVE:
1600 ret = io_poll_remove(req, s->sqe);
1602 case IORING_OP_SYNC_FILE_RANGE:
1603 ret = io_sync_file_range(req, s->sqe, force_nonblock);
1613 if (ctx->flags & IORING_SETUP_IOPOLL) {
1614 if (req->error == -EAGAIN)
1617 /* workqueue context doesn't hold uring_lock, grab it now */
1619 mutex_lock(&ctx->uring_lock);
1620 io_iopoll_req_issued(req);
1622 mutex_unlock(&ctx->uring_lock);
1628 static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1629 const struct io_uring_sqe *sqe)
1631 switch (sqe->opcode) {
1632 case IORING_OP_READV:
1633 case IORING_OP_READ_FIXED:
1634 return &ctx->pending_async[READ];
1635 case IORING_OP_WRITEV:
1636 case IORING_OP_WRITE_FIXED:
1637 return &ctx->pending_async[WRITE];
1643 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1645 u8 opcode = READ_ONCE(sqe->opcode);
1647 return !(opcode == IORING_OP_READ_FIXED ||
1648 opcode == IORING_OP_WRITE_FIXED);
1651 static void io_sq_wq_submit_work(struct work_struct *work)
1653 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1654 struct io_ring_ctx *ctx = req->ctx;
1655 struct mm_struct *cur_mm = NULL;
1656 struct async_list *async_list;
1657 LIST_HEAD(req_list);
1658 mm_segment_t old_fs;
1661 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1664 struct sqe_submit *s = &req->submit;
1665 const struct io_uring_sqe *sqe = s->sqe;
1667 /* Ensure we clear previously set non-block flag */
1668 req->rw.ki_flags &= ~IOCB_NOWAIT;
1671 if (io_sqe_needs_user(sqe) && !cur_mm) {
1672 if (!mmget_not_zero(ctx->sqo_mm)) {
1675 cur_mm = ctx->sqo_mm;
1683 s->has_user = cur_mm != NULL;
1684 s->needs_lock = true;
1686 ret = __io_submit_sqe(ctx, req, s, false);
1688 * We can get EAGAIN for polled IO even though
1689 * we're forcing a sync submission from here,
1690 * since we can't wait for request slots on the
1699 /* drop submission reference */
1703 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
1707 /* async context always use a copy of the sqe */
1712 if (!list_empty(&req_list)) {
1713 req = list_first_entry(&req_list, struct io_kiocb,
1715 list_del(&req->list);
1718 if (list_empty(&async_list->list))
1722 spin_lock(&async_list->lock);
1723 if (list_empty(&async_list->list)) {
1724 spin_unlock(&async_list->lock);
1727 list_splice_init(&async_list->list, &req_list);
1728 spin_unlock(&async_list->lock);
1730 req = list_first_entry(&req_list, struct io_kiocb, list);
1731 list_del(&req->list);
1735 * Rare case of racing with a submitter. If we find the count has
1736 * dropped to zero AND we have pending work items, then restart
1737 * the processing. This is a tiny race window.
1740 ret = atomic_dec_return(&async_list->cnt);
1741 while (!ret && !list_empty(&async_list->list)) {
1742 spin_lock(&async_list->lock);
1743 atomic_inc(&async_list->cnt);
1744 list_splice_init(&async_list->list, &req_list);
1745 spin_unlock(&async_list->lock);
1747 if (!list_empty(&req_list)) {
1748 req = list_first_entry(&req_list,
1749 struct io_kiocb, list);
1750 list_del(&req->list);
1753 ret = atomic_dec_return(&async_list->cnt);
1765 * See if we can piggy back onto previously submitted work, that is still
1766 * running. We currently only allow this if the new request is sequential
1767 * to the previous one we punted.
1769 static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1775 if (!(req->flags & REQ_F_SEQ_PREV))
1777 if (!atomic_read(&list->cnt))
1781 spin_lock(&list->lock);
1782 list_add_tail(&req->list, &list->list);
1783 if (!atomic_read(&list->cnt)) {
1784 list_del_init(&req->list);
1787 spin_unlock(&list->lock);
1791 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
1793 int op = READ_ONCE(sqe->opcode);
1797 case IORING_OP_POLL_REMOVE:
1804 static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
1805 struct io_submit_state *state, struct io_kiocb *req)
1810 flags = READ_ONCE(s->sqe->flags);
1811 fd = READ_ONCE(s->sqe->fd);
1813 if (flags & IOSQE_IO_DRAIN) {
1814 req->flags |= REQ_F_IO_DRAIN;
1815 req->sequence = ctx->cached_sq_head - 1;
1818 if (!io_op_needs_file(s->sqe)) {
1823 if (flags & IOSQE_FIXED_FILE) {
1824 if (unlikely(!ctx->user_files ||
1825 (unsigned) fd >= ctx->nr_user_files))
1827 req->file = ctx->user_files[fd];
1828 req->flags |= REQ_F_FIXED_FILE;
1830 if (s->needs_fixed_file)
1832 req->file = io_file_get(state, fd);
1833 if (unlikely(!req->file))
1840 static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1841 struct io_submit_state *state)
1843 struct io_kiocb *req;
1846 /* enforce forwards compatibility on users */
1847 if (unlikely(s->sqe->flags & ~(IOSQE_FIXED_FILE | IOSQE_IO_DRAIN)))
1850 req = io_get_req(ctx, state);
1854 ret = io_req_set_file(ctx, s, state, req);
1858 ret = io_req_defer(ctx, req, s->sqe);
1860 if (ret == -EIOCBQUEUED)
1865 ret = __io_submit_sqe(ctx, req, s, true);
1866 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
1867 struct io_uring_sqe *sqe_copy;
1869 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1871 struct async_list *list;
1873 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1876 memcpy(&req->submit, s, sizeof(*s));
1877 list = io_async_list_from_sqe(ctx, s->sqe);
1878 if (!io_add_to_prev_work(list, req)) {
1880 atomic_inc(&list->cnt);
1881 INIT_WORK(&req->work, io_sq_wq_submit_work);
1882 queue_work(ctx->sqo_wq, &req->work);
1886 * Queued up for async execution, worker will release
1887 * submit reference when the iocb is actually
1895 /* drop submission reference */
1898 /* and drop final reference, if we failed */
1906 * Batched submission is done, ensure local IO is flushed out.
1908 static void io_submit_state_end(struct io_submit_state *state)
1910 blk_finish_plug(&state->plug);
1912 if (state->free_reqs)
1913 kmem_cache_free_bulk(req_cachep, state->free_reqs,
1914 &state->reqs[state->cur_req]);
1918 * Start submission side cache.
1920 static void io_submit_state_start(struct io_submit_state *state,
1921 struct io_ring_ctx *ctx, unsigned max_ios)
1923 blk_start_plug(&state->plug);
1924 state->free_reqs = 0;
1926 state->ios_left = max_ios;
1929 static void io_commit_sqring(struct io_ring_ctx *ctx)
1931 struct io_sq_ring *ring = ctx->sq_ring;
1933 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1935 * Ensure any loads from the SQEs are done at this point,
1936 * since once we write the new head, the application could
1937 * write new data to them.
1939 smp_store_release(&ring->r.head, ctx->cached_sq_head);
1944 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1945 * that is mapped by userspace. This means that care needs to be taken to
1946 * ensure that reads are stable, as we cannot rely on userspace always
1947 * being a good citizen. If members of the sqe are validated and then later
1948 * used, it's important that those reads are done through READ_ONCE() to
1949 * prevent a re-load down the line.
1951 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1953 struct io_sq_ring *ring = ctx->sq_ring;
1957 * The cached sq head (or cq tail) serves two purposes:
1959 * 1) allows us to batch the cost of updating the user visible
1961 * 2) allows the kernel side to track the head on its own, even
1962 * though the application is the one updating it.
1964 head = ctx->cached_sq_head;
1965 /* make sure SQ entry isn't read before tail */
1966 if (head == smp_load_acquire(&ring->r.tail))
1969 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1970 if (head < ctx->sq_entries) {
1972 s->sqe = &ctx->sq_sqes[head];
1973 ctx->cached_sq_head++;
1977 /* drop invalid entries */
1978 ctx->cached_sq_head++;
1983 static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
1984 unsigned int nr, bool has_user, bool mm_fault)
1986 struct io_submit_state state, *statep = NULL;
1987 int ret, i, submitted = 0;
1989 if (nr > IO_PLUG_THRESHOLD) {
1990 io_submit_state_start(&state, ctx, nr);
1994 for (i = 0; i < nr; i++) {
1995 if (unlikely(mm_fault)) {
1998 sqes[i].has_user = has_user;
1999 sqes[i].needs_lock = true;
2000 sqes[i].needs_fixed_file = true;
2001 ret = io_submit_sqe(ctx, &sqes[i], statep);
2008 io_cqring_add_event(ctx, sqes[i].sqe->user_data, ret, 0);
2012 io_submit_state_end(&state);
2017 static int io_sq_thread(void *data)
2019 struct sqe_submit sqes[IO_IOPOLL_BATCH];
2020 struct io_ring_ctx *ctx = data;
2021 struct mm_struct *cur_mm = NULL;
2022 mm_segment_t old_fs;
2025 unsigned long timeout;
2030 timeout = inflight = 0;
2031 while (!kthread_should_stop() && !ctx->sqo_stop) {
2032 bool all_fixed, mm_fault = false;
2036 unsigned nr_events = 0;
2038 if (ctx->flags & IORING_SETUP_IOPOLL) {
2040 * We disallow the app entering submit/complete
2041 * with polling, but we still need to lock the
2042 * ring to prevent racing with polled issue
2043 * that got punted to a workqueue.
2045 mutex_lock(&ctx->uring_lock);
2046 io_iopoll_check(ctx, &nr_events, 0);
2047 mutex_unlock(&ctx->uring_lock);
2050 * Normal IO, just pretend everything completed.
2051 * We don't have to poll completions for that.
2053 nr_events = inflight;
2056 inflight -= nr_events;
2058 timeout = jiffies + ctx->sq_thread_idle;
2061 if (!io_get_sqring(ctx, &sqes[0])) {
2063 * We're polling. If we're within the defined idle
2064 * period, then let us spin without work before going
2067 if (inflight || !time_after(jiffies, timeout)) {
2073 * Drop cur_mm before scheduling, we can't hold it for
2074 * long periods (or over schedule()). Do this before
2075 * adding ourselves to the waitqueue, as the unuse/drop
2084 prepare_to_wait(&ctx->sqo_wait, &wait,
2085 TASK_INTERRUPTIBLE);
2087 /* Tell userspace we may need a wakeup call */
2088 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
2089 /* make sure to read SQ tail after writing flags */
2092 if (!io_get_sqring(ctx, &sqes[0])) {
2093 if (kthread_should_stop()) {
2094 finish_wait(&ctx->sqo_wait, &wait);
2097 if (signal_pending(current))
2098 flush_signals(current);
2100 finish_wait(&ctx->sqo_wait, &wait);
2102 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
2105 finish_wait(&ctx->sqo_wait, &wait);
2107 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
2113 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2117 if (i == ARRAY_SIZE(sqes))
2119 } while (io_get_sqring(ctx, &sqes[i]));
2121 /* Unless all new commands are FIXED regions, grab mm */
2122 if (!all_fixed && !cur_mm) {
2123 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2125 use_mm(ctx->sqo_mm);
2126 cur_mm = ctx->sqo_mm;
2130 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2133 /* Commit SQ ring head once we've consumed all SQEs */
2134 io_commit_sqring(ctx);
2143 if (kthread_should_park())
2149 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2151 struct io_submit_state state, *statep = NULL;
2154 if (to_submit > IO_PLUG_THRESHOLD) {
2155 io_submit_state_start(&state, ctx, to_submit);
2159 for (i = 0; i < to_submit; i++) {
2160 struct sqe_submit s;
2163 if (!io_get_sqring(ctx, &s))
2167 s.needs_lock = false;
2168 s.needs_fixed_file = false;
2171 ret = io_submit_sqe(ctx, &s, statep);
2173 io_cqring_add_event(ctx, s.sqe->user_data, ret, 0);
2175 io_commit_sqring(ctx);
2178 io_submit_state_end(statep);
2183 static unsigned io_cqring_events(struct io_cq_ring *ring)
2185 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
2189 * Wait until events become available, if we don't already have some. The
2190 * application must reap them itself, as they reside on the shared cq ring.
2192 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2193 const sigset_t __user *sig, size_t sigsz)
2195 struct io_cq_ring *ring = ctx->cq_ring;
2196 sigset_t ksigmask, sigsaved;
2200 /* See comment at the top of this file */
2202 if (io_cqring_events(ring) >= min_events)
2206 #ifdef CONFIG_COMPAT
2207 if (in_compat_syscall())
2208 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2209 &ksigmask, &sigsaved, sigsz);
2212 ret = set_user_sigmask(sig, &ksigmask,
2220 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
2223 /* See comment at the top of this file */
2225 if (io_cqring_events(ring) >= min_events)
2231 if (signal_pending(current))
2235 finish_wait(&ctx->wait, &wait);
2238 restore_user_sigmask(sig, &sigsaved);
2240 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2243 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2245 #if defined(CONFIG_UNIX)
2246 if (ctx->ring_sock) {
2247 struct sock *sock = ctx->ring_sock->sk;
2248 struct sk_buff *skb;
2250 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2256 for (i = 0; i < ctx->nr_user_files; i++)
2257 fput(ctx->user_files[i]);
2261 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2263 if (!ctx->user_files)
2266 __io_sqe_files_unregister(ctx);
2267 kfree(ctx->user_files);
2268 ctx->user_files = NULL;
2269 ctx->nr_user_files = 0;
2273 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2275 if (ctx->sqo_thread) {
2278 kthread_park(ctx->sqo_thread);
2279 kthread_stop(ctx->sqo_thread);
2280 ctx->sqo_thread = NULL;
2284 static void io_finish_async(struct io_ring_ctx *ctx)
2286 io_sq_thread_stop(ctx);
2289 destroy_workqueue(ctx->sqo_wq);
2294 #if defined(CONFIG_UNIX)
2295 static void io_destruct_skb(struct sk_buff *skb)
2297 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2299 io_finish_async(ctx);
2300 unix_destruct_scm(skb);
2304 * Ensure the UNIX gc is aware of our file set, so we are certain that
2305 * the io_uring can be safely unregistered on process exit, even if we have
2306 * loops in the file referencing.
2308 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2310 struct sock *sk = ctx->ring_sock->sk;
2311 struct scm_fp_list *fpl;
2312 struct sk_buff *skb;
2315 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2316 unsigned long inflight = ctx->user->unix_inflight + nr;
2318 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2322 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2326 skb = alloc_skb(0, GFP_KERNEL);
2333 skb->destructor = io_destruct_skb;
2335 fpl->user = get_uid(ctx->user);
2336 for (i = 0; i < nr; i++) {
2337 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2338 unix_inflight(fpl->user, fpl->fp[i]);
2341 fpl->max = fpl->count = nr;
2342 UNIXCB(skb).fp = fpl;
2343 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2344 skb_queue_head(&sk->sk_receive_queue, skb);
2346 for (i = 0; i < nr; i++)
2353 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2354 * causes regular reference counting to break down. We rely on the UNIX
2355 * garbage collection to take care of this problem for us.
2357 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2359 unsigned left, total;
2363 left = ctx->nr_user_files;
2365 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2367 ret = __io_sqe_files_scm(ctx, this_files, total);
2371 total += this_files;
2377 while (total < ctx->nr_user_files) {
2378 fput(ctx->user_files[total]);
2385 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2391 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2394 __s32 __user *fds = (__s32 __user *) arg;
2398 if (ctx->user_files)
2402 if (nr_args > IORING_MAX_FIXED_FILES)
2405 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2406 if (!ctx->user_files)
2409 for (i = 0; i < nr_args; i++) {
2411 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2414 ctx->user_files[i] = fget(fd);
2417 if (!ctx->user_files[i])
2420 * Don't allow io_uring instances to be registered. If UNIX
2421 * isn't enabled, then this causes a reference cycle and this
2422 * instance can never get freed. If UNIX is enabled we'll
2423 * handle it just fine, but there's still no point in allowing
2424 * a ring fd as it doesn't support regular read/write anyway.
2426 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2427 fput(ctx->user_files[i]);
2430 ctx->nr_user_files++;
2435 for (i = 0; i < ctx->nr_user_files; i++)
2436 fput(ctx->user_files[i]);
2438 kfree(ctx->user_files);
2439 ctx->user_files = NULL;
2440 ctx->nr_user_files = 0;
2444 ret = io_sqe_files_scm(ctx);
2446 io_sqe_files_unregister(ctx);
2451 static int io_sq_offload_start(struct io_ring_ctx *ctx,
2452 struct io_uring_params *p)
2456 init_waitqueue_head(&ctx->sqo_wait);
2457 mmgrab(current->mm);
2458 ctx->sqo_mm = current->mm;
2460 if (ctx->flags & IORING_SETUP_SQPOLL) {
2462 if (!capable(CAP_SYS_ADMIN))
2465 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2466 if (!ctx->sq_thread_idle)
2467 ctx->sq_thread_idle = HZ;
2469 if (p->flags & IORING_SETUP_SQ_AFF) {
2470 int cpu = array_index_nospec(p->sq_thread_cpu,
2474 if (!cpu_online(cpu))
2477 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2481 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2484 if (IS_ERR(ctx->sqo_thread)) {
2485 ret = PTR_ERR(ctx->sqo_thread);
2486 ctx->sqo_thread = NULL;
2489 wake_up_process(ctx->sqo_thread);
2490 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2491 /* Can't have SQ_AFF without SQPOLL */
2496 /* Do QD, or 2 * CPUS, whatever is smallest */
2497 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2498 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2506 io_sq_thread_stop(ctx);
2507 mmdrop(ctx->sqo_mm);
2512 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2514 atomic_long_sub(nr_pages, &user->locked_vm);
2517 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2519 unsigned long page_limit, cur_pages, new_pages;
2521 /* Don't allow more pages than we can safely lock */
2522 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2525 cur_pages = atomic_long_read(&user->locked_vm);
2526 new_pages = cur_pages + nr_pages;
2527 if (new_pages > page_limit)
2529 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2530 new_pages) != cur_pages);
2535 static void io_mem_free(void *ptr)
2542 page = virt_to_head_page(ptr);
2543 if (put_page_testzero(page))
2544 free_compound_page(page);
2547 static void *io_mem_alloc(size_t size)
2549 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2552 return (void *) __get_free_pages(gfp_flags, get_order(size));
2555 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2557 struct io_sq_ring *sq_ring;
2558 struct io_cq_ring *cq_ring;
2561 bytes = struct_size(sq_ring, array, sq_entries);
2562 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2563 bytes += struct_size(cq_ring, cqes, cq_entries);
2565 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2568 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2572 if (!ctx->user_bufs)
2575 for (i = 0; i < ctx->nr_user_bufs; i++) {
2576 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2578 for (j = 0; j < imu->nr_bvecs; j++)
2579 put_page(imu->bvec[j].bv_page);
2581 if (ctx->account_mem)
2582 io_unaccount_mem(ctx->user, imu->nr_bvecs);
2587 kfree(ctx->user_bufs);
2588 ctx->user_bufs = NULL;
2589 ctx->nr_user_bufs = 0;
2593 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2594 void __user *arg, unsigned index)
2596 struct iovec __user *src;
2598 #ifdef CONFIG_COMPAT
2600 struct compat_iovec __user *ciovs;
2601 struct compat_iovec ciov;
2603 ciovs = (struct compat_iovec __user *) arg;
2604 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2607 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2608 dst->iov_len = ciov.iov_len;
2612 src = (struct iovec __user *) arg;
2613 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2618 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2621 struct vm_area_struct **vmas = NULL;
2622 struct page **pages = NULL;
2623 int i, j, got_pages = 0;
2628 if (!nr_args || nr_args > UIO_MAXIOV)
2631 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2633 if (!ctx->user_bufs)
2636 for (i = 0; i < nr_args; i++) {
2637 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2638 unsigned long off, start, end, ubuf;
2643 ret = io_copy_iov(ctx, &iov, arg, i);
2648 * Don't impose further limits on the size and buffer
2649 * constraints here, we'll -EINVAL later when IO is
2650 * submitted if they are wrong.
2653 if (!iov.iov_base || !iov.iov_len)
2656 /* arbitrary limit, but we need something */
2657 if (iov.iov_len > SZ_1G)
2660 ubuf = (unsigned long) iov.iov_base;
2661 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2662 start = ubuf >> PAGE_SHIFT;
2663 nr_pages = end - start;
2665 if (ctx->account_mem) {
2666 ret = io_account_mem(ctx->user, nr_pages);
2672 if (!pages || nr_pages > got_pages) {
2675 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
2677 vmas = kvmalloc_array(nr_pages,
2678 sizeof(struct vm_area_struct *),
2680 if (!pages || !vmas) {
2682 if (ctx->account_mem)
2683 io_unaccount_mem(ctx->user, nr_pages);
2686 got_pages = nr_pages;
2689 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
2693 if (ctx->account_mem)
2694 io_unaccount_mem(ctx->user, nr_pages);
2699 down_read(¤t->mm->mmap_sem);
2700 pret = get_user_pages_longterm(ubuf, nr_pages, FOLL_WRITE,
2702 if (pret == nr_pages) {
2703 /* don't support file backed memory */
2704 for (j = 0; j < nr_pages; j++) {
2705 struct vm_area_struct *vma = vmas[j];
2708 !is_file_hugepages(vma->vm_file)) {
2714 ret = pret < 0 ? pret : -EFAULT;
2716 up_read(¤t->mm->mmap_sem);
2719 * if we did partial map, or found file backed vmas,
2720 * release any pages we did get
2723 for (j = 0; j < pret; j++)
2726 if (ctx->account_mem)
2727 io_unaccount_mem(ctx->user, nr_pages);
2732 off = ubuf & ~PAGE_MASK;
2734 for (j = 0; j < nr_pages; j++) {
2737 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2738 imu->bvec[j].bv_page = pages[j];
2739 imu->bvec[j].bv_len = vec_len;
2740 imu->bvec[j].bv_offset = off;
2744 /* store original address for later verification */
2746 imu->len = iov.iov_len;
2747 imu->nr_bvecs = nr_pages;
2749 ctx->nr_user_bufs++;
2757 io_sqe_buffer_unregister(ctx);
2761 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
2763 __s32 __user *fds = arg;
2769 if (copy_from_user(&fd, fds, sizeof(*fds)))
2772 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
2773 if (IS_ERR(ctx->cq_ev_fd)) {
2774 int ret = PTR_ERR(ctx->cq_ev_fd);
2775 ctx->cq_ev_fd = NULL;
2782 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2784 if (ctx->cq_ev_fd) {
2785 eventfd_ctx_put(ctx->cq_ev_fd);
2786 ctx->cq_ev_fd = NULL;
2793 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2795 io_finish_async(ctx);
2797 mmdrop(ctx->sqo_mm);
2799 io_iopoll_reap_events(ctx);
2800 io_sqe_buffer_unregister(ctx);
2801 io_sqe_files_unregister(ctx);
2802 io_eventfd_unregister(ctx);
2804 #if defined(CONFIG_UNIX)
2806 sock_release(ctx->ring_sock);
2809 io_mem_free(ctx->sq_ring);
2810 io_mem_free(ctx->sq_sqes);
2811 io_mem_free(ctx->cq_ring);
2813 percpu_ref_exit(&ctx->refs);
2814 if (ctx->account_mem)
2815 io_unaccount_mem(ctx->user,
2816 ring_pages(ctx->sq_entries, ctx->cq_entries));
2817 free_uid(ctx->user);
2821 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2823 struct io_ring_ctx *ctx = file->private_data;
2826 poll_wait(file, &ctx->cq_wait, wait);
2828 * synchronizes with barrier from wq_has_sleeper call in
2832 if (READ_ONCE(ctx->sq_ring->r.tail) - ctx->cached_sq_head !=
2833 ctx->sq_ring->ring_entries)
2834 mask |= EPOLLOUT | EPOLLWRNORM;
2835 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2836 mask |= EPOLLIN | EPOLLRDNORM;
2841 static int io_uring_fasync(int fd, struct file *file, int on)
2843 struct io_ring_ctx *ctx = file->private_data;
2845 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2848 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2850 mutex_lock(&ctx->uring_lock);
2851 percpu_ref_kill(&ctx->refs);
2852 mutex_unlock(&ctx->uring_lock);
2854 io_poll_remove_all(ctx);
2855 io_iopoll_reap_events(ctx);
2856 wait_for_completion(&ctx->ctx_done);
2857 io_ring_ctx_free(ctx);
2860 static int io_uring_release(struct inode *inode, struct file *file)
2862 struct io_ring_ctx *ctx = file->private_data;
2864 file->private_data = NULL;
2865 io_ring_ctx_wait_and_kill(ctx);
2869 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2871 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
2872 unsigned long sz = vma->vm_end - vma->vm_start;
2873 struct io_ring_ctx *ctx = file->private_data;
2879 case IORING_OFF_SQ_RING:
2882 case IORING_OFF_SQES:
2885 case IORING_OFF_CQ_RING:
2892 page = virt_to_head_page(ptr);
2893 if (sz > (PAGE_SIZE << compound_order(page)))
2896 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2897 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2900 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2901 u32, min_complete, u32, flags, const sigset_t __user *, sig,
2904 struct io_ring_ctx *ctx;
2909 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2917 if (f.file->f_op != &io_uring_fops)
2921 ctx = f.file->private_data;
2922 if (!percpu_ref_tryget(&ctx->refs))
2926 * For SQ polling, the thread will do all submissions and completions.
2927 * Just return the requested submit count, and wake the thread if
2930 if (ctx->flags & IORING_SETUP_SQPOLL) {
2931 if (flags & IORING_ENTER_SQ_WAKEUP)
2932 wake_up(&ctx->sqo_wait);
2933 submitted = to_submit;
2939 to_submit = min(to_submit, ctx->sq_entries);
2941 mutex_lock(&ctx->uring_lock);
2942 submitted = io_ring_submit(ctx, to_submit);
2943 mutex_unlock(&ctx->uring_lock);
2945 if (flags & IORING_ENTER_GETEVENTS) {
2946 unsigned nr_events = 0;
2948 min_complete = min(min_complete, ctx->cq_entries);
2950 if (ctx->flags & IORING_SETUP_IOPOLL) {
2951 mutex_lock(&ctx->uring_lock);
2952 ret = io_iopoll_check(ctx, &nr_events, min_complete);
2953 mutex_unlock(&ctx->uring_lock);
2955 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
2960 io_ring_drop_ctx_refs(ctx, 1);
2963 return submitted ? submitted : ret;
2966 static const struct file_operations io_uring_fops = {
2967 .release = io_uring_release,
2968 .mmap = io_uring_mmap,
2969 .poll = io_uring_poll,
2970 .fasync = io_uring_fasync,
2973 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2974 struct io_uring_params *p)
2976 struct io_sq_ring *sq_ring;
2977 struct io_cq_ring *cq_ring;
2980 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
2984 ctx->sq_ring = sq_ring;
2985 sq_ring->ring_mask = p->sq_entries - 1;
2986 sq_ring->ring_entries = p->sq_entries;
2987 ctx->sq_mask = sq_ring->ring_mask;
2988 ctx->sq_entries = sq_ring->ring_entries;
2990 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
2991 if (size == SIZE_MAX)
2994 ctx->sq_sqes = io_mem_alloc(size);
2998 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
3002 ctx->cq_ring = cq_ring;
3003 cq_ring->ring_mask = p->cq_entries - 1;
3004 cq_ring->ring_entries = p->cq_entries;
3005 ctx->cq_mask = cq_ring->ring_mask;
3006 ctx->cq_entries = cq_ring->ring_entries;
3011 * Allocate an anonymous fd, this is what constitutes the application
3012 * visible backing of an io_uring instance. The application mmaps this
3013 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3014 * we have to tie this fd to a socket for file garbage collection purposes.
3016 static int io_uring_get_fd(struct io_ring_ctx *ctx)
3021 #if defined(CONFIG_UNIX)
3022 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3028 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3032 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3033 O_RDWR | O_CLOEXEC);
3036 ret = PTR_ERR(file);
3040 #if defined(CONFIG_UNIX)
3041 ctx->ring_sock->file = file;
3042 ctx->ring_sock->sk->sk_user_data = ctx;
3044 fd_install(ret, file);
3047 #if defined(CONFIG_UNIX)
3048 sock_release(ctx->ring_sock);
3049 ctx->ring_sock = NULL;
3054 static int io_uring_create(unsigned entries, struct io_uring_params *p)
3056 struct user_struct *user = NULL;
3057 struct io_ring_ctx *ctx;
3061 if (!entries || entries > IORING_MAX_ENTRIES)
3065 * Use twice as many entries for the CQ ring. It's possible for the
3066 * application to drive a higher depth than the size of the SQ ring,
3067 * since the sqes are only used at submission time. This allows for
3068 * some flexibility in overcommitting a bit.
3070 p->sq_entries = roundup_pow_of_two(entries);
3071 p->cq_entries = 2 * p->sq_entries;
3073 user = get_uid(current_user());
3074 account_mem = !capable(CAP_IPC_LOCK);
3077 ret = io_account_mem(user,
3078 ring_pages(p->sq_entries, p->cq_entries));
3085 ctx = io_ring_ctx_alloc(p);
3088 io_unaccount_mem(user, ring_pages(p->sq_entries,
3093 ctx->compat = in_compat_syscall();
3094 ctx->account_mem = account_mem;
3097 ret = io_allocate_scq_urings(ctx, p);
3101 ret = io_sq_offload_start(ctx, p);
3105 ret = io_uring_get_fd(ctx);
3109 memset(&p->sq_off, 0, sizeof(p->sq_off));
3110 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
3111 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
3112 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
3113 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
3114 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
3115 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
3116 p->sq_off.array = offsetof(struct io_sq_ring, array);
3118 memset(&p->cq_off, 0, sizeof(p->cq_off));
3119 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
3120 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
3121 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
3122 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
3123 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
3124 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
3127 io_ring_ctx_wait_and_kill(ctx);
3132 * Sets up an aio uring context, and returns the fd. Applications asks for a
3133 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3134 * params structure passed in.
3136 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3138 struct io_uring_params p;
3142 if (copy_from_user(&p, params, sizeof(p)))
3144 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3149 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3150 IORING_SETUP_SQ_AFF))
3153 ret = io_uring_create(entries, &p);
3157 if (copy_to_user(params, &p, sizeof(p)))
3163 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3164 struct io_uring_params __user *, params)
3166 return io_uring_setup(entries, params);
3169 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3170 void __user *arg, unsigned nr_args)
3171 __releases(ctx->uring_lock)
3172 __acquires(ctx->uring_lock)
3177 * We're inside the ring mutex, if the ref is already dying, then
3178 * someone else killed the ctx or is already going through
3179 * io_uring_register().
3181 if (percpu_ref_is_dying(&ctx->refs))
3184 percpu_ref_kill(&ctx->refs);
3187 * Drop uring mutex before waiting for references to exit. If another
3188 * thread is currently inside io_uring_enter() it might need to grab
3189 * the uring_lock to make progress. If we hold it here across the drain
3190 * wait, then we can deadlock. It's safe to drop the mutex here, since
3191 * no new references will come in after we've killed the percpu ref.
3193 mutex_unlock(&ctx->uring_lock);
3194 wait_for_completion(&ctx->ctx_done);
3195 mutex_lock(&ctx->uring_lock);
3198 case IORING_REGISTER_BUFFERS:
3199 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3201 case IORING_UNREGISTER_BUFFERS:
3205 ret = io_sqe_buffer_unregister(ctx);
3207 case IORING_REGISTER_FILES:
3208 ret = io_sqe_files_register(ctx, arg, nr_args);
3210 case IORING_UNREGISTER_FILES:
3214 ret = io_sqe_files_unregister(ctx);
3216 case IORING_REGISTER_EVENTFD:
3220 ret = io_eventfd_register(ctx, arg);
3222 case IORING_UNREGISTER_EVENTFD:
3226 ret = io_eventfd_unregister(ctx);
3233 /* bring the ctx back to life */
3234 reinit_completion(&ctx->ctx_done);
3235 percpu_ref_reinit(&ctx->refs);
3239 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3240 void __user *, arg, unsigned int, nr_args)
3242 struct io_ring_ctx *ctx;
3251 if (f.file->f_op != &io_uring_fops)
3254 ctx = f.file->private_data;
3256 mutex_lock(&ctx->uring_lock);
3257 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3258 mutex_unlock(&ctx->uring_lock);
3264 static int __init io_uring_init(void)
3266 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3269 __initcall(io_uring_init);