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_IO_DRAIN 16 /* drain existing IO first */
333 #define REQ_F_IO_DRAINED 32 /* drain done */
335 u32 error; /* iopoll result from callback */
338 struct work_struct work;
341 #define IO_PLUG_THRESHOLD 2
342 #define IO_IOPOLL_BATCH 8
344 struct io_submit_state {
345 struct blk_plug plug;
348 * io_kiocb alloc cache
350 void *reqs[IO_IOPOLL_BATCH];
351 unsigned int free_reqs;
352 unsigned int cur_req;
355 * File reference cache
359 unsigned int has_refs;
360 unsigned int used_refs;
361 unsigned int ios_left;
364 static void io_sq_wq_submit_work(struct work_struct *work);
366 static struct kmem_cache *req_cachep;
368 static const struct file_operations io_uring_fops;
370 struct sock *io_uring_get_socket(struct file *file)
372 #if defined(CONFIG_UNIX)
373 if (file->f_op == &io_uring_fops) {
374 struct io_ring_ctx *ctx = file->private_data;
376 return ctx->ring_sock->sk;
381 EXPORT_SYMBOL(io_uring_get_socket);
383 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
385 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
387 complete(&ctx->ctx_done);
390 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
392 struct io_ring_ctx *ctx;
395 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
399 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
404 ctx->flags = p->flags;
405 init_waitqueue_head(&ctx->cq_wait);
406 init_completion(&ctx->ctx_done);
407 mutex_init(&ctx->uring_lock);
408 init_waitqueue_head(&ctx->wait);
409 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
410 spin_lock_init(&ctx->pending_async[i].lock);
411 INIT_LIST_HEAD(&ctx->pending_async[i].list);
412 atomic_set(&ctx->pending_async[i].cnt, 0);
414 spin_lock_init(&ctx->completion_lock);
415 INIT_LIST_HEAD(&ctx->poll_list);
416 INIT_LIST_HEAD(&ctx->cancel_list);
417 INIT_LIST_HEAD(&ctx->defer_list);
421 static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
422 struct io_kiocb *req)
424 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
427 return req->sequence > ctx->cached_cq_tail + ctx->sq_ring->dropped;
430 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
432 struct io_kiocb *req;
434 if (list_empty(&ctx->defer_list))
437 req = list_first_entry(&ctx->defer_list, struct io_kiocb, list);
438 if (!io_sequence_defer(ctx, req)) {
439 list_del_init(&req->list);
446 static void __io_commit_cqring(struct io_ring_ctx *ctx)
448 struct io_cq_ring *ring = ctx->cq_ring;
450 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
451 /* order cqe stores with ring update */
452 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
454 if (wq_has_sleeper(&ctx->cq_wait)) {
455 wake_up_interruptible(&ctx->cq_wait);
456 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
461 static void io_commit_cqring(struct io_ring_ctx *ctx)
463 struct io_kiocb *req;
465 __io_commit_cqring(ctx);
467 while ((req = io_get_deferred_req(ctx)) != NULL) {
468 req->flags |= REQ_F_IO_DRAINED;
469 queue_work(ctx->sqo_wq, &req->work);
473 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
475 struct io_cq_ring *ring = ctx->cq_ring;
478 tail = ctx->cached_cq_tail;
480 * writes to the cq entry need to come after reading head; the
481 * control dependency is enough as we're using WRITE_ONCE to
484 if (tail - READ_ONCE(ring->r.head) == ring->ring_entries)
487 ctx->cached_cq_tail++;
488 return &ring->cqes[tail & ctx->cq_mask];
491 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
494 struct io_uring_cqe *cqe;
497 * If we can't get a cq entry, userspace overflowed the
498 * submission (by quite a lot). Increment the overflow count in
501 cqe = io_get_cqring(ctx);
503 WRITE_ONCE(cqe->user_data, ki_user_data);
504 WRITE_ONCE(cqe->res, res);
505 WRITE_ONCE(cqe->flags, 0);
507 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
509 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
513 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
515 if (waitqueue_active(&ctx->wait))
517 if (waitqueue_active(&ctx->sqo_wait))
518 wake_up(&ctx->sqo_wait);
520 eventfd_signal(ctx->cq_ev_fd, 1);
523 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
528 spin_lock_irqsave(&ctx->completion_lock, flags);
529 io_cqring_fill_event(ctx, user_data, res);
530 io_commit_cqring(ctx);
531 spin_unlock_irqrestore(&ctx->completion_lock, flags);
533 io_cqring_ev_posted(ctx);
536 static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
538 percpu_ref_put_many(&ctx->refs, refs);
540 if (waitqueue_active(&ctx->wait))
544 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
545 struct io_submit_state *state)
547 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
548 struct io_kiocb *req;
550 if (!percpu_ref_tryget(&ctx->refs))
554 req = kmem_cache_alloc(req_cachep, gfp);
557 } else if (!state->free_reqs) {
561 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
562 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
565 * Bulk alloc is all-or-nothing. If we fail to get a batch,
566 * retry single alloc to be on the safe side.
568 if (unlikely(ret <= 0)) {
569 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
574 state->free_reqs = ret - 1;
576 req = state->reqs[0];
578 req = state->reqs[state->cur_req];
585 /* one is dropped after submission, the other at completion */
586 refcount_set(&req->refs, 2);
589 io_ring_drop_ctx_refs(ctx, 1);
593 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
596 kmem_cache_free_bulk(req_cachep, *nr, reqs);
597 io_ring_drop_ctx_refs(ctx, *nr);
602 static void io_free_req(struct io_kiocb *req)
604 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
606 io_ring_drop_ctx_refs(req->ctx, 1);
607 kmem_cache_free(req_cachep, req);
610 static void io_put_req(struct io_kiocb *req)
612 if (refcount_dec_and_test(&req->refs))
617 * Find and free completed poll iocbs
619 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
620 struct list_head *done)
622 void *reqs[IO_IOPOLL_BATCH];
623 struct io_kiocb *req;
627 while (!list_empty(done)) {
628 req = list_first_entry(done, struct io_kiocb, list);
629 list_del(&req->list);
631 io_cqring_fill_event(ctx, req->user_data, req->error);
634 if (refcount_dec_and_test(&req->refs)) {
635 /* If we're not using fixed files, we have to pair the
636 * completion part with the file put. Use regular
637 * completions for those, only batch free for fixed
640 if (req->flags & REQ_F_FIXED_FILE) {
641 reqs[to_free++] = req;
642 if (to_free == ARRAY_SIZE(reqs))
643 io_free_req_many(ctx, reqs, &to_free);
650 io_commit_cqring(ctx);
651 io_free_req_many(ctx, reqs, &to_free);
654 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
657 struct io_kiocb *req, *tmp;
663 * Only spin for completions if we don't have multiple devices hanging
664 * off our complete list, and we're under the requested amount.
666 spin = !ctx->poll_multi_file && *nr_events < min;
669 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
670 struct kiocb *kiocb = &req->rw;
673 * Move completed entries to our local list. If we find a
674 * request that requires polling, break out and complete
675 * the done list first, if we have entries there.
677 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
678 list_move_tail(&req->list, &done);
681 if (!list_empty(&done))
684 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
693 if (!list_empty(&done))
694 io_iopoll_complete(ctx, nr_events, &done);
700 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
701 * non-spinning poll check - we'll still enter the driver poll loop, but only
702 * as a non-spinning completion check.
704 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
707 while (!list_empty(&ctx->poll_list)) {
710 ret = io_do_iopoll(ctx, nr_events, min);
713 if (!min || *nr_events >= min)
721 * We can't just wait for polled events to come to us, we have to actively
722 * find and complete them.
724 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
726 if (!(ctx->flags & IORING_SETUP_IOPOLL))
729 mutex_lock(&ctx->uring_lock);
730 while (!list_empty(&ctx->poll_list)) {
731 unsigned int nr_events = 0;
733 io_iopoll_getevents(ctx, &nr_events, 1);
735 mutex_unlock(&ctx->uring_lock);
738 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
746 if (*nr_events < min)
747 tmin = min - *nr_events;
749 ret = io_iopoll_getevents(ctx, nr_events, tmin);
753 } while (min && !*nr_events && !need_resched());
758 static void kiocb_end_write(struct kiocb *kiocb)
760 if (kiocb->ki_flags & IOCB_WRITE) {
761 struct inode *inode = file_inode(kiocb->ki_filp);
764 * Tell lockdep we inherited freeze protection from submission
767 if (S_ISREG(inode->i_mode))
768 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
769 file_end_write(kiocb->ki_filp);
773 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
775 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
777 kiocb_end_write(kiocb);
779 io_cqring_add_event(req->ctx, req->user_data, res);
783 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
785 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
787 kiocb_end_write(kiocb);
791 req->flags |= REQ_F_IOPOLL_COMPLETED;
795 * After the iocb has been issued, it's safe to be found on the poll list.
796 * Adding the kiocb to the list AFTER submission ensures that we don't
797 * find it from a io_iopoll_getevents() thread before the issuer is done
798 * accessing the kiocb cookie.
800 static void io_iopoll_req_issued(struct io_kiocb *req)
802 struct io_ring_ctx *ctx = req->ctx;
805 * Track whether we have multiple files in our lists. This will impact
806 * how we do polling eventually, not spinning if we're on potentially
809 if (list_empty(&ctx->poll_list)) {
810 ctx->poll_multi_file = false;
811 } else if (!ctx->poll_multi_file) {
812 struct io_kiocb *list_req;
814 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
816 if (list_req->rw.ki_filp != req->rw.ki_filp)
817 ctx->poll_multi_file = true;
821 * For fast devices, IO may have already completed. If it has, add
822 * it to the front so we find it first.
824 if (req->flags & REQ_F_IOPOLL_COMPLETED)
825 list_add(&req->list, &ctx->poll_list);
827 list_add_tail(&req->list, &ctx->poll_list);
830 static void io_file_put(struct io_submit_state *state)
833 int diff = state->has_refs - state->used_refs;
836 fput_many(state->file, diff);
842 * Get as many references to a file as we have IOs left in this submission,
843 * assuming most submissions are for one file, or at least that each file
844 * has more than one submission.
846 static struct file *io_file_get(struct io_submit_state *state, int fd)
852 if (state->fd == fd) {
859 state->file = fget_many(fd, state->ios_left);
864 state->has_refs = state->ios_left;
865 state->used_refs = 1;
871 * If we tracked the file through the SCM inflight mechanism, we could support
872 * any file. For now, just ensure that anything potentially problematic is done
875 static bool io_file_supports_async(struct file *file)
877 umode_t mode = file_inode(file)->i_mode;
879 if (S_ISBLK(mode) || S_ISCHR(mode))
881 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
887 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
890 const struct io_uring_sqe *sqe = s->sqe;
891 struct io_ring_ctx *ctx = req->ctx;
892 struct kiocb *kiocb = &req->rw;
899 if (force_nonblock && !io_file_supports_async(req->file))
900 force_nonblock = false;
902 kiocb->ki_pos = READ_ONCE(sqe->off);
903 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
904 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
906 ioprio = READ_ONCE(sqe->ioprio);
908 ret = ioprio_check_cap(ioprio);
912 kiocb->ki_ioprio = ioprio;
914 kiocb->ki_ioprio = get_current_ioprio();
916 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
920 /* don't allow async punt if RWF_NOWAIT was requested */
921 if (kiocb->ki_flags & IOCB_NOWAIT)
922 req->flags |= REQ_F_NOWAIT;
925 kiocb->ki_flags |= IOCB_NOWAIT;
927 if (ctx->flags & IORING_SETUP_IOPOLL) {
928 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
929 !kiocb->ki_filp->f_op->iopoll)
933 kiocb->ki_flags |= IOCB_HIPRI;
934 kiocb->ki_complete = io_complete_rw_iopoll;
936 if (kiocb->ki_flags & IOCB_HIPRI)
938 kiocb->ki_complete = io_complete_rw;
943 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
949 case -ERESTARTNOINTR:
950 case -ERESTARTNOHAND:
951 case -ERESTART_RESTARTBLOCK:
953 * We can't just restart the syscall, since previously
954 * submitted sqes may already be in progress. Just fail this
960 kiocb->ki_complete(kiocb, ret, 0);
964 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
965 const struct io_uring_sqe *sqe,
966 struct iov_iter *iter)
968 size_t len = READ_ONCE(sqe->len);
969 struct io_mapped_ubuf *imu;
970 unsigned index, buf_index;
974 /* attempt to use fixed buffers without having provided iovecs */
975 if (unlikely(!ctx->user_bufs))
978 buf_index = READ_ONCE(sqe->buf_index);
979 if (unlikely(buf_index >= ctx->nr_user_bufs))
982 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
983 imu = &ctx->user_bufs[index];
984 buf_addr = READ_ONCE(sqe->addr);
987 if (buf_addr + len < buf_addr)
989 /* not inside the mapped region */
990 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
994 * May not be a start of buffer, set size appropriately
995 * and advance us to the beginning.
997 offset = buf_addr - imu->ubuf;
998 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1000 iov_iter_advance(iter, offset);
1002 /* don't drop a reference to these pages */
1003 iter->type |= ITER_BVEC_FLAG_NO_REF;
1007 static int io_import_iovec(struct io_ring_ctx *ctx, int rw,
1008 const struct sqe_submit *s, struct iovec **iovec,
1009 struct iov_iter *iter)
1011 const struct io_uring_sqe *sqe = s->sqe;
1012 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1013 size_t sqe_len = READ_ONCE(sqe->len);
1017 * We're reading ->opcode for the second time, but the first read
1018 * doesn't care whether it's _FIXED or not, so it doesn't matter
1019 * whether ->opcode changes concurrently. The first read does care
1020 * about whether it is a READ or a WRITE, so we don't trust this read
1021 * for that purpose and instead let the caller pass in the read/write
1024 opcode = READ_ONCE(sqe->opcode);
1025 if (opcode == IORING_OP_READ_FIXED ||
1026 opcode == IORING_OP_WRITE_FIXED) {
1027 int ret = io_import_fixed(ctx, rw, sqe, iter);
1035 #ifdef CONFIG_COMPAT
1037 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1041 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1045 * Make a note of the last file/offset/direction we punted to async
1046 * context. We'll use this information to see if we can piggy back a
1047 * sequential request onto the previous one, if it's still hasn't been
1048 * completed by the async worker.
1050 static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1052 struct async_list *async_list = &req->ctx->pending_async[rw];
1053 struct kiocb *kiocb = &req->rw;
1054 struct file *filp = kiocb->ki_filp;
1055 off_t io_end = kiocb->ki_pos + len;
1057 if (filp == async_list->file && kiocb->ki_pos == async_list->io_end) {
1058 unsigned long max_pages;
1060 /* Use 8x RA size as a decent limiter for both reads/writes */
1061 max_pages = filp->f_ra.ra_pages;
1063 max_pages = VM_READAHEAD_PAGES;
1066 /* If max pages are exceeded, reset the state */
1068 if (async_list->io_pages + len <= max_pages) {
1069 req->flags |= REQ_F_SEQ_PREV;
1070 async_list->io_pages += len;
1073 async_list->io_pages = 0;
1077 /* New file? Reset state. */
1078 if (async_list->file != filp) {
1079 async_list->io_pages = 0;
1080 async_list->file = filp;
1082 async_list->io_end = io_end;
1085 static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1086 bool force_nonblock)
1088 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1089 struct kiocb *kiocb = &req->rw;
1090 struct iov_iter iter;
1095 ret = io_prep_rw(req, s, force_nonblock);
1098 file = kiocb->ki_filp;
1100 if (unlikely(!(file->f_mode & FMODE_READ)))
1102 if (unlikely(!file->f_op->read_iter))
1105 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
1109 iov_count = iov_iter_count(&iter);
1110 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1114 /* Catch -EAGAIN return for forced non-blocking submission */
1115 ret2 = call_read_iter(file, kiocb, &iter);
1116 if (!force_nonblock || ret2 != -EAGAIN) {
1117 io_rw_done(kiocb, ret2);
1120 * If ->needs_lock is true, we're already in async
1124 io_async_list_note(READ, req, iov_count);
1132 static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1133 bool force_nonblock)
1135 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1136 struct kiocb *kiocb = &req->rw;
1137 struct iov_iter iter;
1142 ret = io_prep_rw(req, s, force_nonblock);
1146 file = kiocb->ki_filp;
1147 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1149 if (unlikely(!file->f_op->write_iter))
1152 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1156 iov_count = iov_iter_count(&iter);
1159 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1160 /* If ->needs_lock is true, we're already in async context. */
1162 io_async_list_note(WRITE, req, iov_count);
1166 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1171 * Open-code file_start_write here to grab freeze protection,
1172 * which will be released by another thread in
1173 * io_complete_rw(). Fool lockdep by telling it the lock got
1174 * released so that it doesn't complain about the held lock when
1175 * we return to userspace.
1177 if (S_ISREG(file_inode(file)->i_mode)) {
1178 __sb_start_write(file_inode(file)->i_sb,
1179 SB_FREEZE_WRITE, true);
1180 __sb_writers_release(file_inode(file)->i_sb,
1183 kiocb->ki_flags |= IOCB_WRITE;
1185 ret2 = call_write_iter(file, kiocb, &iter);
1186 if (!force_nonblock || ret2 != -EAGAIN) {
1187 io_rw_done(kiocb, ret2);
1190 * If ->needs_lock is true, we're already in async
1194 io_async_list_note(WRITE, req, iov_count);
1204 * IORING_OP_NOP just posts a completion event, nothing else.
1206 static int io_nop(struct io_kiocb *req, u64 user_data)
1208 struct io_ring_ctx *ctx = req->ctx;
1211 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1214 io_cqring_add_event(ctx, user_data, err);
1219 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1221 struct io_ring_ctx *ctx = req->ctx;
1226 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1228 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1234 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1235 bool force_nonblock)
1237 loff_t sqe_off = READ_ONCE(sqe->off);
1238 loff_t sqe_len = READ_ONCE(sqe->len);
1239 loff_t end = sqe_off + sqe_len;
1240 unsigned fsync_flags;
1243 fsync_flags = READ_ONCE(sqe->fsync_flags);
1244 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1247 ret = io_prep_fsync(req, sqe);
1251 /* fsync always requires a blocking context */
1255 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1256 end > 0 ? end : LLONG_MAX,
1257 fsync_flags & IORING_FSYNC_DATASYNC);
1259 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1264 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1266 struct io_ring_ctx *ctx = req->ctx;
1272 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1274 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1280 static int io_sync_file_range(struct io_kiocb *req,
1281 const struct io_uring_sqe *sqe,
1282 bool force_nonblock)
1289 ret = io_prep_sfr(req, sqe);
1293 /* sync_file_range always requires a blocking context */
1297 sqe_off = READ_ONCE(sqe->off);
1298 sqe_len = READ_ONCE(sqe->len);
1299 flags = READ_ONCE(sqe->sync_range_flags);
1301 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1303 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1308 static void io_poll_remove_one(struct io_kiocb *req)
1310 struct io_poll_iocb *poll = &req->poll;
1312 spin_lock(&poll->head->lock);
1313 WRITE_ONCE(poll->canceled, true);
1314 if (!list_empty(&poll->wait.entry)) {
1315 list_del_init(&poll->wait.entry);
1316 queue_work(req->ctx->sqo_wq, &req->work);
1318 spin_unlock(&poll->head->lock);
1320 list_del_init(&req->list);
1323 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1325 struct io_kiocb *req;
1327 spin_lock_irq(&ctx->completion_lock);
1328 while (!list_empty(&ctx->cancel_list)) {
1329 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1330 io_poll_remove_one(req);
1332 spin_unlock_irq(&ctx->completion_lock);
1336 * Find a running poll command that matches one specified in sqe->addr,
1337 * and remove it if found.
1339 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1341 struct io_ring_ctx *ctx = req->ctx;
1342 struct io_kiocb *poll_req, *next;
1345 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1347 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1351 spin_lock_irq(&ctx->completion_lock);
1352 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1353 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1354 io_poll_remove_one(poll_req);
1359 spin_unlock_irq(&ctx->completion_lock);
1361 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1366 static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1369 req->poll.done = true;
1370 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
1371 io_commit_cqring(ctx);
1374 static void io_poll_complete_work(struct work_struct *work)
1376 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1377 struct io_poll_iocb *poll = &req->poll;
1378 struct poll_table_struct pt = { ._key = poll->events };
1379 struct io_ring_ctx *ctx = req->ctx;
1382 if (!READ_ONCE(poll->canceled))
1383 mask = vfs_poll(poll->file, &pt) & poll->events;
1386 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1387 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1388 * synchronize with them. In the cancellation case the list_del_init
1389 * itself is not actually needed, but harmless so we keep it in to
1390 * avoid further branches in the fast path.
1392 spin_lock_irq(&ctx->completion_lock);
1393 if (!mask && !READ_ONCE(poll->canceled)) {
1394 add_wait_queue(poll->head, &poll->wait);
1395 spin_unlock_irq(&ctx->completion_lock);
1398 list_del_init(&req->list);
1399 io_poll_complete(ctx, req, mask);
1400 spin_unlock_irq(&ctx->completion_lock);
1402 io_cqring_ev_posted(ctx);
1406 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1409 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1411 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1412 struct io_ring_ctx *ctx = req->ctx;
1413 __poll_t mask = key_to_poll(key);
1414 unsigned long flags;
1416 /* for instances that support it check for an event match first: */
1417 if (mask && !(mask & poll->events))
1420 list_del_init(&poll->wait.entry);
1422 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1423 list_del(&req->list);
1424 io_poll_complete(ctx, req, mask);
1425 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1427 io_cqring_ev_posted(ctx);
1430 queue_work(ctx->sqo_wq, &req->work);
1436 struct io_poll_table {
1437 struct poll_table_struct pt;
1438 struct io_kiocb *req;
1442 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1443 struct poll_table_struct *p)
1445 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1447 if (unlikely(pt->req->poll.head)) {
1448 pt->error = -EINVAL;
1453 pt->req->poll.head = head;
1454 add_wait_queue(head, &pt->req->poll.wait);
1457 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1459 struct io_poll_iocb *poll = &req->poll;
1460 struct io_ring_ctx *ctx = req->ctx;
1461 struct io_poll_table ipt;
1462 bool cancel = false;
1466 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1468 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1473 INIT_WORK(&req->work, io_poll_complete_work);
1474 events = READ_ONCE(sqe->poll_events);
1475 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1479 poll->canceled = false;
1481 ipt.pt._qproc = io_poll_queue_proc;
1482 ipt.pt._key = poll->events;
1484 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1486 /* initialized the list so that we can do list_empty checks */
1487 INIT_LIST_HEAD(&poll->wait.entry);
1488 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1490 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1492 spin_lock_irq(&ctx->completion_lock);
1493 if (likely(poll->head)) {
1494 spin_lock(&poll->head->lock);
1495 if (unlikely(list_empty(&poll->wait.entry))) {
1501 if (mask || ipt.error)
1502 list_del_init(&poll->wait.entry);
1504 WRITE_ONCE(poll->canceled, true);
1505 else if (!poll->done) /* actually waiting for an event */
1506 list_add_tail(&req->list, &ctx->cancel_list);
1507 spin_unlock(&poll->head->lock);
1509 if (mask) { /* no async, we'd stolen it */
1511 io_poll_complete(ctx, req, mask);
1513 spin_unlock_irq(&ctx->completion_lock);
1516 io_cqring_ev_posted(ctx);
1522 static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1523 const struct io_uring_sqe *sqe)
1525 struct io_uring_sqe *sqe_copy;
1527 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1530 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1534 spin_lock_irq(&ctx->completion_lock);
1535 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1536 spin_unlock_irq(&ctx->completion_lock);
1541 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1542 req->submit.sqe = sqe_copy;
1544 INIT_WORK(&req->work, io_sq_wq_submit_work);
1545 list_add_tail(&req->list, &ctx->defer_list);
1546 spin_unlock_irq(&ctx->completion_lock);
1547 return -EIOCBQUEUED;
1550 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1551 const struct sqe_submit *s, bool force_nonblock)
1555 if (unlikely(s->index >= ctx->sq_entries))
1557 req->user_data = READ_ONCE(s->sqe->user_data);
1559 opcode = READ_ONCE(s->sqe->opcode);
1562 ret = io_nop(req, req->user_data);
1564 case IORING_OP_READV:
1565 if (unlikely(s->sqe->buf_index))
1567 ret = io_read(req, s, force_nonblock);
1569 case IORING_OP_WRITEV:
1570 if (unlikely(s->sqe->buf_index))
1572 ret = io_write(req, s, force_nonblock);
1574 case IORING_OP_READ_FIXED:
1575 ret = io_read(req, s, force_nonblock);
1577 case IORING_OP_WRITE_FIXED:
1578 ret = io_write(req, s, force_nonblock);
1580 case IORING_OP_FSYNC:
1581 ret = io_fsync(req, s->sqe, force_nonblock);
1583 case IORING_OP_POLL_ADD:
1584 ret = io_poll_add(req, s->sqe);
1586 case IORING_OP_POLL_REMOVE:
1587 ret = io_poll_remove(req, s->sqe);
1589 case IORING_OP_SYNC_FILE_RANGE:
1590 ret = io_sync_file_range(req, s->sqe, force_nonblock);
1600 if (ctx->flags & IORING_SETUP_IOPOLL) {
1601 if (req->error == -EAGAIN)
1604 /* workqueue context doesn't hold uring_lock, grab it now */
1606 mutex_lock(&ctx->uring_lock);
1607 io_iopoll_req_issued(req);
1609 mutex_unlock(&ctx->uring_lock);
1615 static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1616 const struct io_uring_sqe *sqe)
1618 switch (sqe->opcode) {
1619 case IORING_OP_READV:
1620 case IORING_OP_READ_FIXED:
1621 return &ctx->pending_async[READ];
1622 case IORING_OP_WRITEV:
1623 case IORING_OP_WRITE_FIXED:
1624 return &ctx->pending_async[WRITE];
1630 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1632 u8 opcode = READ_ONCE(sqe->opcode);
1634 return !(opcode == IORING_OP_READ_FIXED ||
1635 opcode == IORING_OP_WRITE_FIXED);
1638 static void io_sq_wq_submit_work(struct work_struct *work)
1640 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1641 struct io_ring_ctx *ctx = req->ctx;
1642 struct mm_struct *cur_mm = NULL;
1643 struct async_list *async_list;
1644 LIST_HEAD(req_list);
1645 mm_segment_t old_fs;
1648 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1651 struct sqe_submit *s = &req->submit;
1652 const struct io_uring_sqe *sqe = s->sqe;
1654 /* Ensure we clear previously set non-block flag */
1655 req->rw.ki_flags &= ~IOCB_NOWAIT;
1658 if (io_sqe_needs_user(sqe) && !cur_mm) {
1659 if (!mmget_not_zero(ctx->sqo_mm)) {
1662 cur_mm = ctx->sqo_mm;
1670 s->has_user = cur_mm != NULL;
1671 s->needs_lock = true;
1673 ret = __io_submit_sqe(ctx, req, s, false);
1675 * We can get EAGAIN for polled IO even though
1676 * we're forcing a sync submission from here,
1677 * since we can't wait for request slots on the
1686 /* drop submission reference */
1690 io_cqring_add_event(ctx, sqe->user_data, ret);
1694 /* async context always use a copy of the sqe */
1699 if (!list_empty(&req_list)) {
1700 req = list_first_entry(&req_list, struct io_kiocb,
1702 list_del(&req->list);
1705 if (list_empty(&async_list->list))
1709 spin_lock(&async_list->lock);
1710 if (list_empty(&async_list->list)) {
1711 spin_unlock(&async_list->lock);
1714 list_splice_init(&async_list->list, &req_list);
1715 spin_unlock(&async_list->lock);
1717 req = list_first_entry(&req_list, struct io_kiocb, list);
1718 list_del(&req->list);
1722 * Rare case of racing with a submitter. If we find the count has
1723 * dropped to zero AND we have pending work items, then restart
1724 * the processing. This is a tiny race window.
1727 ret = atomic_dec_return(&async_list->cnt);
1728 while (!ret && !list_empty(&async_list->list)) {
1729 spin_lock(&async_list->lock);
1730 atomic_inc(&async_list->cnt);
1731 list_splice_init(&async_list->list, &req_list);
1732 spin_unlock(&async_list->lock);
1734 if (!list_empty(&req_list)) {
1735 req = list_first_entry(&req_list,
1736 struct io_kiocb, list);
1737 list_del(&req->list);
1740 ret = atomic_dec_return(&async_list->cnt);
1752 * See if we can piggy back onto previously submitted work, that is still
1753 * running. We currently only allow this if the new request is sequential
1754 * to the previous one we punted.
1756 static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1762 if (!(req->flags & REQ_F_SEQ_PREV))
1764 if (!atomic_read(&list->cnt))
1768 spin_lock(&list->lock);
1769 list_add_tail(&req->list, &list->list);
1770 if (!atomic_read(&list->cnt)) {
1771 list_del_init(&req->list);
1774 spin_unlock(&list->lock);
1778 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
1780 int op = READ_ONCE(sqe->opcode);
1784 case IORING_OP_POLL_REMOVE:
1791 static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
1792 struct io_submit_state *state, struct io_kiocb *req)
1797 flags = READ_ONCE(s->sqe->flags);
1798 fd = READ_ONCE(s->sqe->fd);
1800 if (flags & IOSQE_IO_DRAIN) {
1801 req->flags |= REQ_F_IO_DRAIN;
1802 req->sequence = ctx->cached_sq_head - 1;
1805 if (!io_op_needs_file(s->sqe)) {
1810 if (flags & IOSQE_FIXED_FILE) {
1811 if (unlikely(!ctx->user_files ||
1812 (unsigned) fd >= ctx->nr_user_files))
1814 req->file = ctx->user_files[fd];
1815 req->flags |= REQ_F_FIXED_FILE;
1817 if (s->needs_fixed_file)
1819 req->file = io_file_get(state, fd);
1820 if (unlikely(!req->file))
1827 static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1828 struct io_submit_state *state)
1830 struct io_kiocb *req;
1833 /* enforce forwards compatibility on users */
1834 if (unlikely(s->sqe->flags & ~(IOSQE_FIXED_FILE | IOSQE_IO_DRAIN)))
1837 req = io_get_req(ctx, state);
1841 ret = io_req_set_file(ctx, s, state, req);
1845 ret = io_req_defer(ctx, req, s->sqe);
1847 if (ret == -EIOCBQUEUED)
1852 ret = __io_submit_sqe(ctx, req, s, true);
1853 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
1854 struct io_uring_sqe *sqe_copy;
1856 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1858 struct async_list *list;
1860 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1863 memcpy(&req->submit, s, sizeof(*s));
1864 list = io_async_list_from_sqe(ctx, s->sqe);
1865 if (!io_add_to_prev_work(list, req)) {
1867 atomic_inc(&list->cnt);
1868 INIT_WORK(&req->work, io_sq_wq_submit_work);
1869 queue_work(ctx->sqo_wq, &req->work);
1873 * Queued up for async execution, worker will release
1874 * submit reference when the iocb is actually
1882 /* drop submission reference */
1885 /* and drop final reference, if we failed */
1893 * Batched submission is done, ensure local IO is flushed out.
1895 static void io_submit_state_end(struct io_submit_state *state)
1897 blk_finish_plug(&state->plug);
1899 if (state->free_reqs)
1900 kmem_cache_free_bulk(req_cachep, state->free_reqs,
1901 &state->reqs[state->cur_req]);
1905 * Start submission side cache.
1907 static void io_submit_state_start(struct io_submit_state *state,
1908 struct io_ring_ctx *ctx, unsigned max_ios)
1910 blk_start_plug(&state->plug);
1911 state->free_reqs = 0;
1913 state->ios_left = max_ios;
1916 static void io_commit_sqring(struct io_ring_ctx *ctx)
1918 struct io_sq_ring *ring = ctx->sq_ring;
1920 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1922 * Ensure any loads from the SQEs are done at this point,
1923 * since once we write the new head, the application could
1924 * write new data to them.
1926 smp_store_release(&ring->r.head, ctx->cached_sq_head);
1931 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1932 * that is mapped by userspace. This means that care needs to be taken to
1933 * ensure that reads are stable, as we cannot rely on userspace always
1934 * being a good citizen. If members of the sqe are validated and then later
1935 * used, it's important that those reads are done through READ_ONCE() to
1936 * prevent a re-load down the line.
1938 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1940 struct io_sq_ring *ring = ctx->sq_ring;
1944 * The cached sq head (or cq tail) serves two purposes:
1946 * 1) allows us to batch the cost of updating the user visible
1948 * 2) allows the kernel side to track the head on its own, even
1949 * though the application is the one updating it.
1951 head = ctx->cached_sq_head;
1952 /* make sure SQ entry isn't read before tail */
1953 if (head == smp_load_acquire(&ring->r.tail))
1956 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1957 if (head < ctx->sq_entries) {
1959 s->sqe = &ctx->sq_sqes[head];
1960 ctx->cached_sq_head++;
1964 /* drop invalid entries */
1965 ctx->cached_sq_head++;
1970 static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
1971 unsigned int nr, bool has_user, bool mm_fault)
1973 struct io_submit_state state, *statep = NULL;
1974 int ret, i, submitted = 0;
1976 if (nr > IO_PLUG_THRESHOLD) {
1977 io_submit_state_start(&state, ctx, nr);
1981 for (i = 0; i < nr; i++) {
1982 if (unlikely(mm_fault)) {
1985 sqes[i].has_user = has_user;
1986 sqes[i].needs_lock = true;
1987 sqes[i].needs_fixed_file = true;
1988 ret = io_submit_sqe(ctx, &sqes[i], statep);
1995 io_cqring_add_event(ctx, sqes[i].sqe->user_data, ret);
1999 io_submit_state_end(&state);
2004 static int io_sq_thread(void *data)
2006 struct sqe_submit sqes[IO_IOPOLL_BATCH];
2007 struct io_ring_ctx *ctx = data;
2008 struct mm_struct *cur_mm = NULL;
2009 mm_segment_t old_fs;
2012 unsigned long timeout;
2017 timeout = inflight = 0;
2018 while (!kthread_should_stop() && !ctx->sqo_stop) {
2019 bool all_fixed, mm_fault = false;
2023 unsigned nr_events = 0;
2025 if (ctx->flags & IORING_SETUP_IOPOLL) {
2027 * We disallow the app entering submit/complete
2028 * with polling, but we still need to lock the
2029 * ring to prevent racing with polled issue
2030 * that got punted to a workqueue.
2032 mutex_lock(&ctx->uring_lock);
2033 io_iopoll_check(ctx, &nr_events, 0);
2034 mutex_unlock(&ctx->uring_lock);
2037 * Normal IO, just pretend everything completed.
2038 * We don't have to poll completions for that.
2040 nr_events = inflight;
2043 inflight -= nr_events;
2045 timeout = jiffies + ctx->sq_thread_idle;
2048 if (!io_get_sqring(ctx, &sqes[0])) {
2050 * We're polling. If we're within the defined idle
2051 * period, then let us spin without work before going
2054 if (inflight || !time_after(jiffies, timeout)) {
2060 * Drop cur_mm before scheduling, we can't hold it for
2061 * long periods (or over schedule()). Do this before
2062 * adding ourselves to the waitqueue, as the unuse/drop
2071 prepare_to_wait(&ctx->sqo_wait, &wait,
2072 TASK_INTERRUPTIBLE);
2074 /* Tell userspace we may need a wakeup call */
2075 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
2076 /* make sure to read SQ tail after writing flags */
2079 if (!io_get_sqring(ctx, &sqes[0])) {
2080 if (kthread_should_stop()) {
2081 finish_wait(&ctx->sqo_wait, &wait);
2084 if (signal_pending(current))
2085 flush_signals(current);
2087 finish_wait(&ctx->sqo_wait, &wait);
2089 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
2092 finish_wait(&ctx->sqo_wait, &wait);
2094 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
2100 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2104 if (i == ARRAY_SIZE(sqes))
2106 } while (io_get_sqring(ctx, &sqes[i]));
2108 /* Unless all new commands are FIXED regions, grab mm */
2109 if (!all_fixed && !cur_mm) {
2110 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2112 use_mm(ctx->sqo_mm);
2113 cur_mm = ctx->sqo_mm;
2117 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2120 /* Commit SQ ring head once we've consumed all SQEs */
2121 io_commit_sqring(ctx);
2130 if (kthread_should_park())
2136 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2138 struct io_submit_state state, *statep = NULL;
2141 if (to_submit > IO_PLUG_THRESHOLD) {
2142 io_submit_state_start(&state, ctx, to_submit);
2146 for (i = 0; i < to_submit; i++) {
2147 struct sqe_submit s;
2150 if (!io_get_sqring(ctx, &s))
2154 s.needs_lock = false;
2155 s.needs_fixed_file = false;
2158 ret = io_submit_sqe(ctx, &s, statep);
2160 io_cqring_add_event(ctx, s.sqe->user_data, ret);
2162 io_commit_sqring(ctx);
2165 io_submit_state_end(statep);
2170 static unsigned io_cqring_events(struct io_cq_ring *ring)
2172 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
2176 * Wait until events become available, if we don't already have some. The
2177 * application must reap them itself, as they reside on the shared cq ring.
2179 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2180 const sigset_t __user *sig, size_t sigsz)
2182 struct io_cq_ring *ring = ctx->cq_ring;
2183 sigset_t ksigmask, sigsaved;
2187 /* See comment at the top of this file */
2189 if (io_cqring_events(ring) >= min_events)
2193 #ifdef CONFIG_COMPAT
2194 if (in_compat_syscall())
2195 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2196 &ksigmask, &sigsaved, sigsz);
2199 ret = set_user_sigmask(sig, &ksigmask,
2207 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
2210 /* See comment at the top of this file */
2212 if (io_cqring_events(ring) >= min_events)
2218 if (signal_pending(current))
2222 finish_wait(&ctx->wait, &wait);
2225 restore_user_sigmask(sig, &sigsaved);
2227 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2230 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2232 #if defined(CONFIG_UNIX)
2233 if (ctx->ring_sock) {
2234 struct sock *sock = ctx->ring_sock->sk;
2235 struct sk_buff *skb;
2237 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2243 for (i = 0; i < ctx->nr_user_files; i++)
2244 fput(ctx->user_files[i]);
2248 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2250 if (!ctx->user_files)
2253 __io_sqe_files_unregister(ctx);
2254 kfree(ctx->user_files);
2255 ctx->user_files = NULL;
2256 ctx->nr_user_files = 0;
2260 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2262 if (ctx->sqo_thread) {
2265 kthread_park(ctx->sqo_thread);
2266 kthread_stop(ctx->sqo_thread);
2267 ctx->sqo_thread = NULL;
2271 static void io_finish_async(struct io_ring_ctx *ctx)
2273 io_sq_thread_stop(ctx);
2276 destroy_workqueue(ctx->sqo_wq);
2281 #if defined(CONFIG_UNIX)
2282 static void io_destruct_skb(struct sk_buff *skb)
2284 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2286 io_finish_async(ctx);
2287 unix_destruct_scm(skb);
2291 * Ensure the UNIX gc is aware of our file set, so we are certain that
2292 * the io_uring can be safely unregistered on process exit, even if we have
2293 * loops in the file referencing.
2295 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2297 struct sock *sk = ctx->ring_sock->sk;
2298 struct scm_fp_list *fpl;
2299 struct sk_buff *skb;
2302 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2303 unsigned long inflight = ctx->user->unix_inflight + nr;
2305 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2309 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2313 skb = alloc_skb(0, GFP_KERNEL);
2320 skb->destructor = io_destruct_skb;
2322 fpl->user = get_uid(ctx->user);
2323 for (i = 0; i < nr; i++) {
2324 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2325 unix_inflight(fpl->user, fpl->fp[i]);
2328 fpl->max = fpl->count = nr;
2329 UNIXCB(skb).fp = fpl;
2330 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2331 skb_queue_head(&sk->sk_receive_queue, skb);
2333 for (i = 0; i < nr; i++)
2340 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2341 * causes regular reference counting to break down. We rely on the UNIX
2342 * garbage collection to take care of this problem for us.
2344 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2346 unsigned left, total;
2350 left = ctx->nr_user_files;
2352 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2354 ret = __io_sqe_files_scm(ctx, this_files, total);
2358 total += this_files;
2364 while (total < ctx->nr_user_files) {
2365 fput(ctx->user_files[total]);
2372 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2378 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2381 __s32 __user *fds = (__s32 __user *) arg;
2385 if (ctx->user_files)
2389 if (nr_args > IORING_MAX_FIXED_FILES)
2392 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2393 if (!ctx->user_files)
2396 for (i = 0; i < nr_args; i++) {
2398 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2401 ctx->user_files[i] = fget(fd);
2404 if (!ctx->user_files[i])
2407 * Don't allow io_uring instances to be registered. If UNIX
2408 * isn't enabled, then this causes a reference cycle and this
2409 * instance can never get freed. If UNIX is enabled we'll
2410 * handle it just fine, but there's still no point in allowing
2411 * a ring fd as it doesn't support regular read/write anyway.
2413 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2414 fput(ctx->user_files[i]);
2417 ctx->nr_user_files++;
2422 for (i = 0; i < ctx->nr_user_files; i++)
2423 fput(ctx->user_files[i]);
2425 kfree(ctx->user_files);
2426 ctx->user_files = NULL;
2427 ctx->nr_user_files = 0;
2431 ret = io_sqe_files_scm(ctx);
2433 io_sqe_files_unregister(ctx);
2438 static int io_sq_offload_start(struct io_ring_ctx *ctx,
2439 struct io_uring_params *p)
2443 init_waitqueue_head(&ctx->sqo_wait);
2444 mmgrab(current->mm);
2445 ctx->sqo_mm = current->mm;
2447 if (ctx->flags & IORING_SETUP_SQPOLL) {
2449 if (!capable(CAP_SYS_ADMIN))
2452 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2453 if (!ctx->sq_thread_idle)
2454 ctx->sq_thread_idle = HZ;
2456 if (p->flags & IORING_SETUP_SQ_AFF) {
2457 int cpu = p->sq_thread_cpu;
2460 if (cpu >= nr_cpu_ids)
2462 if (!cpu_online(cpu))
2465 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2469 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2472 if (IS_ERR(ctx->sqo_thread)) {
2473 ret = PTR_ERR(ctx->sqo_thread);
2474 ctx->sqo_thread = NULL;
2477 wake_up_process(ctx->sqo_thread);
2478 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2479 /* Can't have SQ_AFF without SQPOLL */
2484 /* Do QD, or 2 * CPUS, whatever is smallest */
2485 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2486 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2494 io_sq_thread_stop(ctx);
2495 mmdrop(ctx->sqo_mm);
2500 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2502 atomic_long_sub(nr_pages, &user->locked_vm);
2505 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2507 unsigned long page_limit, cur_pages, new_pages;
2509 /* Don't allow more pages than we can safely lock */
2510 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2513 cur_pages = atomic_long_read(&user->locked_vm);
2514 new_pages = cur_pages + nr_pages;
2515 if (new_pages > page_limit)
2517 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2518 new_pages) != cur_pages);
2523 static void io_mem_free(void *ptr)
2530 page = virt_to_head_page(ptr);
2531 if (put_page_testzero(page))
2532 free_compound_page(page);
2535 static void *io_mem_alloc(size_t size)
2537 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2540 return (void *) __get_free_pages(gfp_flags, get_order(size));
2543 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2545 struct io_sq_ring *sq_ring;
2546 struct io_cq_ring *cq_ring;
2549 bytes = struct_size(sq_ring, array, sq_entries);
2550 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2551 bytes += struct_size(cq_ring, cqes, cq_entries);
2553 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2556 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2560 if (!ctx->user_bufs)
2563 for (i = 0; i < ctx->nr_user_bufs; i++) {
2564 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2566 for (j = 0; j < imu->nr_bvecs; j++)
2567 put_page(imu->bvec[j].bv_page);
2569 if (ctx->account_mem)
2570 io_unaccount_mem(ctx->user, imu->nr_bvecs);
2575 kfree(ctx->user_bufs);
2576 ctx->user_bufs = NULL;
2577 ctx->nr_user_bufs = 0;
2581 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2582 void __user *arg, unsigned index)
2584 struct iovec __user *src;
2586 #ifdef CONFIG_COMPAT
2588 struct compat_iovec __user *ciovs;
2589 struct compat_iovec ciov;
2591 ciovs = (struct compat_iovec __user *) arg;
2592 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2595 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2596 dst->iov_len = ciov.iov_len;
2600 src = (struct iovec __user *) arg;
2601 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2606 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2609 struct vm_area_struct **vmas = NULL;
2610 struct page **pages = NULL;
2611 int i, j, got_pages = 0;
2616 if (!nr_args || nr_args > UIO_MAXIOV)
2619 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2621 if (!ctx->user_bufs)
2624 for (i = 0; i < nr_args; i++) {
2625 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2626 unsigned long off, start, end, ubuf;
2631 ret = io_copy_iov(ctx, &iov, arg, i);
2636 * Don't impose further limits on the size and buffer
2637 * constraints here, we'll -EINVAL later when IO is
2638 * submitted if they are wrong.
2641 if (!iov.iov_base || !iov.iov_len)
2644 /* arbitrary limit, but we need something */
2645 if (iov.iov_len > SZ_1G)
2648 ubuf = (unsigned long) iov.iov_base;
2649 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2650 start = ubuf >> PAGE_SHIFT;
2651 nr_pages = end - start;
2653 if (ctx->account_mem) {
2654 ret = io_account_mem(ctx->user, nr_pages);
2660 if (!pages || nr_pages > got_pages) {
2663 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
2665 vmas = kvmalloc_array(nr_pages,
2666 sizeof(struct vm_area_struct *),
2668 if (!pages || !vmas) {
2670 if (ctx->account_mem)
2671 io_unaccount_mem(ctx->user, nr_pages);
2674 got_pages = nr_pages;
2677 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
2681 if (ctx->account_mem)
2682 io_unaccount_mem(ctx->user, nr_pages);
2687 down_read(¤t->mm->mmap_sem);
2688 pret = get_user_pages_longterm(ubuf, nr_pages, FOLL_WRITE,
2690 if (pret == nr_pages) {
2691 /* don't support file backed memory */
2692 for (j = 0; j < nr_pages; j++) {
2693 struct vm_area_struct *vma = vmas[j];
2696 !is_file_hugepages(vma->vm_file)) {
2702 ret = pret < 0 ? pret : -EFAULT;
2704 up_read(¤t->mm->mmap_sem);
2707 * if we did partial map, or found file backed vmas,
2708 * release any pages we did get
2711 for (j = 0; j < pret; j++)
2714 if (ctx->account_mem)
2715 io_unaccount_mem(ctx->user, nr_pages);
2720 off = ubuf & ~PAGE_MASK;
2722 for (j = 0; j < nr_pages; j++) {
2725 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2726 imu->bvec[j].bv_page = pages[j];
2727 imu->bvec[j].bv_len = vec_len;
2728 imu->bvec[j].bv_offset = off;
2732 /* store original address for later verification */
2734 imu->len = iov.iov_len;
2735 imu->nr_bvecs = nr_pages;
2737 ctx->nr_user_bufs++;
2745 io_sqe_buffer_unregister(ctx);
2749 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
2751 __s32 __user *fds = arg;
2757 if (copy_from_user(&fd, fds, sizeof(*fds)))
2760 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
2761 if (IS_ERR(ctx->cq_ev_fd)) {
2762 int ret = PTR_ERR(ctx->cq_ev_fd);
2763 ctx->cq_ev_fd = NULL;
2770 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2772 if (ctx->cq_ev_fd) {
2773 eventfd_ctx_put(ctx->cq_ev_fd);
2774 ctx->cq_ev_fd = NULL;
2781 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2783 io_finish_async(ctx);
2785 mmdrop(ctx->sqo_mm);
2787 io_iopoll_reap_events(ctx);
2788 io_sqe_buffer_unregister(ctx);
2789 io_sqe_files_unregister(ctx);
2790 io_eventfd_unregister(ctx);
2792 #if defined(CONFIG_UNIX)
2794 sock_release(ctx->ring_sock);
2797 io_mem_free(ctx->sq_ring);
2798 io_mem_free(ctx->sq_sqes);
2799 io_mem_free(ctx->cq_ring);
2801 percpu_ref_exit(&ctx->refs);
2802 if (ctx->account_mem)
2803 io_unaccount_mem(ctx->user,
2804 ring_pages(ctx->sq_entries, ctx->cq_entries));
2805 free_uid(ctx->user);
2809 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2811 struct io_ring_ctx *ctx = file->private_data;
2814 poll_wait(file, &ctx->cq_wait, wait);
2816 * synchronizes with barrier from wq_has_sleeper call in
2820 if (READ_ONCE(ctx->sq_ring->r.tail) - ctx->cached_sq_head !=
2821 ctx->sq_ring->ring_entries)
2822 mask |= EPOLLOUT | EPOLLWRNORM;
2823 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2824 mask |= EPOLLIN | EPOLLRDNORM;
2829 static int io_uring_fasync(int fd, struct file *file, int on)
2831 struct io_ring_ctx *ctx = file->private_data;
2833 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2836 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2838 mutex_lock(&ctx->uring_lock);
2839 percpu_ref_kill(&ctx->refs);
2840 mutex_unlock(&ctx->uring_lock);
2842 io_poll_remove_all(ctx);
2843 io_iopoll_reap_events(ctx);
2844 wait_for_completion(&ctx->ctx_done);
2845 io_ring_ctx_free(ctx);
2848 static int io_uring_release(struct inode *inode, struct file *file)
2850 struct io_ring_ctx *ctx = file->private_data;
2852 file->private_data = NULL;
2853 io_ring_ctx_wait_and_kill(ctx);
2857 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2859 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
2860 unsigned long sz = vma->vm_end - vma->vm_start;
2861 struct io_ring_ctx *ctx = file->private_data;
2867 case IORING_OFF_SQ_RING:
2870 case IORING_OFF_SQES:
2873 case IORING_OFF_CQ_RING:
2880 page = virt_to_head_page(ptr);
2881 if (sz > (PAGE_SIZE << compound_order(page)))
2884 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2885 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2888 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2889 u32, min_complete, u32, flags, const sigset_t __user *, sig,
2892 struct io_ring_ctx *ctx;
2897 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2905 if (f.file->f_op != &io_uring_fops)
2909 ctx = f.file->private_data;
2910 if (!percpu_ref_tryget(&ctx->refs))
2914 * For SQ polling, the thread will do all submissions and completions.
2915 * Just return the requested submit count, and wake the thread if
2918 if (ctx->flags & IORING_SETUP_SQPOLL) {
2919 if (flags & IORING_ENTER_SQ_WAKEUP)
2920 wake_up(&ctx->sqo_wait);
2921 submitted = to_submit;
2927 to_submit = min(to_submit, ctx->sq_entries);
2929 mutex_lock(&ctx->uring_lock);
2930 submitted = io_ring_submit(ctx, to_submit);
2931 mutex_unlock(&ctx->uring_lock);
2933 if (flags & IORING_ENTER_GETEVENTS) {
2934 unsigned nr_events = 0;
2936 min_complete = min(min_complete, ctx->cq_entries);
2938 if (ctx->flags & IORING_SETUP_IOPOLL) {
2939 mutex_lock(&ctx->uring_lock);
2940 ret = io_iopoll_check(ctx, &nr_events, min_complete);
2941 mutex_unlock(&ctx->uring_lock);
2943 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
2948 io_ring_drop_ctx_refs(ctx, 1);
2951 return submitted ? submitted : ret;
2954 static const struct file_operations io_uring_fops = {
2955 .release = io_uring_release,
2956 .mmap = io_uring_mmap,
2957 .poll = io_uring_poll,
2958 .fasync = io_uring_fasync,
2961 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2962 struct io_uring_params *p)
2964 struct io_sq_ring *sq_ring;
2965 struct io_cq_ring *cq_ring;
2968 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
2972 ctx->sq_ring = sq_ring;
2973 sq_ring->ring_mask = p->sq_entries - 1;
2974 sq_ring->ring_entries = p->sq_entries;
2975 ctx->sq_mask = sq_ring->ring_mask;
2976 ctx->sq_entries = sq_ring->ring_entries;
2978 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
2979 if (size == SIZE_MAX)
2982 ctx->sq_sqes = io_mem_alloc(size);
2986 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
2990 ctx->cq_ring = cq_ring;
2991 cq_ring->ring_mask = p->cq_entries - 1;
2992 cq_ring->ring_entries = p->cq_entries;
2993 ctx->cq_mask = cq_ring->ring_mask;
2994 ctx->cq_entries = cq_ring->ring_entries;
2999 * Allocate an anonymous fd, this is what constitutes the application
3000 * visible backing of an io_uring instance. The application mmaps this
3001 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3002 * we have to tie this fd to a socket for file garbage collection purposes.
3004 static int io_uring_get_fd(struct io_ring_ctx *ctx)
3009 #if defined(CONFIG_UNIX)
3010 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3016 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3020 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3021 O_RDWR | O_CLOEXEC);
3024 ret = PTR_ERR(file);
3028 #if defined(CONFIG_UNIX)
3029 ctx->ring_sock->file = file;
3030 ctx->ring_sock->sk->sk_user_data = ctx;
3032 fd_install(ret, file);
3035 #if defined(CONFIG_UNIX)
3036 sock_release(ctx->ring_sock);
3037 ctx->ring_sock = NULL;
3042 static int io_uring_create(unsigned entries, struct io_uring_params *p)
3044 struct user_struct *user = NULL;
3045 struct io_ring_ctx *ctx;
3049 if (!entries || entries > IORING_MAX_ENTRIES)
3053 * Use twice as many entries for the CQ ring. It's possible for the
3054 * application to drive a higher depth than the size of the SQ ring,
3055 * since the sqes are only used at submission time. This allows for
3056 * some flexibility in overcommitting a bit.
3058 p->sq_entries = roundup_pow_of_two(entries);
3059 p->cq_entries = 2 * p->sq_entries;
3061 user = get_uid(current_user());
3062 account_mem = !capable(CAP_IPC_LOCK);
3065 ret = io_account_mem(user,
3066 ring_pages(p->sq_entries, p->cq_entries));
3073 ctx = io_ring_ctx_alloc(p);
3076 io_unaccount_mem(user, ring_pages(p->sq_entries,
3081 ctx->compat = in_compat_syscall();
3082 ctx->account_mem = account_mem;
3085 ret = io_allocate_scq_urings(ctx, p);
3089 ret = io_sq_offload_start(ctx, p);
3093 ret = io_uring_get_fd(ctx);
3097 memset(&p->sq_off, 0, sizeof(p->sq_off));
3098 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
3099 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
3100 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
3101 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
3102 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
3103 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
3104 p->sq_off.array = offsetof(struct io_sq_ring, array);
3106 memset(&p->cq_off, 0, sizeof(p->cq_off));
3107 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
3108 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
3109 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
3110 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
3111 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
3112 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
3115 io_ring_ctx_wait_and_kill(ctx);
3120 * Sets up an aio uring context, and returns the fd. Applications asks for a
3121 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3122 * params structure passed in.
3124 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3126 struct io_uring_params p;
3130 if (copy_from_user(&p, params, sizeof(p)))
3132 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3137 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3138 IORING_SETUP_SQ_AFF))
3141 ret = io_uring_create(entries, &p);
3145 if (copy_to_user(params, &p, sizeof(p)))
3151 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3152 struct io_uring_params __user *, params)
3154 return io_uring_setup(entries, params);
3157 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3158 void __user *arg, unsigned nr_args)
3159 __releases(ctx->uring_lock)
3160 __acquires(ctx->uring_lock)
3165 * We're inside the ring mutex, if the ref is already dying, then
3166 * someone else killed the ctx or is already going through
3167 * io_uring_register().
3169 if (percpu_ref_is_dying(&ctx->refs))
3172 percpu_ref_kill(&ctx->refs);
3175 * Drop uring mutex before waiting for references to exit. If another
3176 * thread is currently inside io_uring_enter() it might need to grab
3177 * the uring_lock to make progress. If we hold it here across the drain
3178 * wait, then we can deadlock. It's safe to drop the mutex here, since
3179 * no new references will come in after we've killed the percpu ref.
3181 mutex_unlock(&ctx->uring_lock);
3182 wait_for_completion(&ctx->ctx_done);
3183 mutex_lock(&ctx->uring_lock);
3186 case IORING_REGISTER_BUFFERS:
3187 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3189 case IORING_UNREGISTER_BUFFERS:
3193 ret = io_sqe_buffer_unregister(ctx);
3195 case IORING_REGISTER_FILES:
3196 ret = io_sqe_files_register(ctx, arg, nr_args);
3198 case IORING_UNREGISTER_FILES:
3202 ret = io_sqe_files_unregister(ctx);
3204 case IORING_REGISTER_EVENTFD:
3208 ret = io_eventfd_register(ctx, arg);
3210 case IORING_UNREGISTER_EVENTFD:
3214 ret = io_eventfd_unregister(ctx);
3221 /* bring the ctx back to life */
3222 reinit_completion(&ctx->ctx_done);
3223 percpu_ref_reinit(&ctx->refs);
3227 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3228 void __user *, arg, unsigned int, nr_args)
3230 struct io_ring_ctx *ctx;
3239 if (f.file->f_op != &io_uring_fops)
3242 ctx = f.file->private_data;
3244 mutex_lock(&ctx->uring_lock);
3245 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3246 mutex_unlock(&ctx->uring_lock);
3252 static int __init io_uring_init(void)
3254 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3257 __initcall(io_uring_init);