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>
73 #include <linux/highmem.h>
74 #include <linux/fs_struct.h>
76 #include <uapi/linux/io_uring.h>
80 #define IORING_MAX_ENTRIES 32768
81 #define IORING_MAX_FIXED_FILES 1024
84 u32 head ____cacheline_aligned_in_smp;
85 u32 tail ____cacheline_aligned_in_smp;
89 * This data is shared with the application through the mmap at offsets
90 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
92 * The offsets to the member fields are published through struct
93 * io_sqring_offsets when calling io_uring_setup.
97 * Head and tail offsets into the ring; the offsets need to be
98 * masked to get valid indices.
100 * The kernel controls head of the sq ring and the tail of the cq ring,
101 * and the application controls tail of the sq ring and the head of the
104 struct io_uring sq, cq;
106 * Bitmasks to apply to head and tail offsets (constant, equals
109 u32 sq_ring_mask, cq_ring_mask;
110 /* Ring sizes (constant, power of 2) */
111 u32 sq_ring_entries, cq_ring_entries;
113 * Number of invalid entries dropped by the kernel due to
114 * invalid index stored in array
116 * Written by the kernel, shouldn't be modified by the
117 * application (i.e. get number of "new events" by comparing to
120 * After a new SQ head value was read by the application this
121 * counter includes all submissions that were dropped reaching
122 * the new SQ head (and possibly more).
128 * Written by the kernel, shouldn't be modified by the
131 * The application needs a full memory barrier before checking
132 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
136 * Number of completion events lost because the queue was full;
137 * this should be avoided by the application by making sure
138 * there are not more requests pending thatn there is space in
139 * the completion queue.
141 * Written by the kernel, shouldn't be modified by the
142 * application (i.e. get number of "new events" by comparing to
145 * As completion events come in out of order this counter is not
146 * ordered with any other data.
150 * Ring buffer of completion events.
152 * The kernel writes completion events fresh every time they are
153 * produced, so the application is allowed to modify pending
156 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
159 struct io_mapped_ubuf {
162 struct bio_vec *bvec;
163 unsigned int nr_bvecs;
169 struct list_head list;
178 struct percpu_ref refs;
179 } ____cacheline_aligned_in_smp;
187 * Ring buffer of indices into array of io_uring_sqe, which is
188 * mmapped by the application using the IORING_OFF_SQES offset.
190 * This indirection could e.g. be used to assign fixed
191 * io_uring_sqe entries to operations and only submit them to
192 * the queue when needed.
194 * The kernel modifies neither the indices array nor the entries
198 unsigned cached_sq_head;
201 unsigned sq_thread_idle;
202 unsigned cached_sq_dropped;
203 struct io_uring_sqe *sq_sqes;
205 struct list_head defer_list;
206 struct list_head timeout_list;
207 } ____cacheline_aligned_in_smp;
210 struct workqueue_struct *sqo_wq[2];
211 struct task_struct *sqo_thread; /* if using sq thread polling */
212 struct mm_struct *sqo_mm;
213 wait_queue_head_t sqo_wait;
214 struct completion sqo_thread_started;
217 unsigned cached_cq_tail;
218 atomic_t cached_cq_overflow;
221 struct wait_queue_head cq_wait;
222 struct fasync_struct *cq_fasync;
223 struct eventfd_ctx *cq_ev_fd;
224 atomic_t cq_timeouts;
225 } ____cacheline_aligned_in_smp;
227 struct io_rings *rings;
230 * If used, fixed file set. Writers must ensure that ->refs is dead,
231 * readers must ensure that ->refs is alive as long as the file* is
232 * used. Only updated through io_uring_register(2).
234 struct file **user_files;
235 unsigned nr_user_files;
237 /* if used, fixed mapped user buffers */
238 unsigned nr_user_bufs;
239 struct io_mapped_ubuf *user_bufs;
241 struct user_struct *user;
243 const struct cred *creds;
245 struct completion ctx_done;
248 struct mutex uring_lock;
249 wait_queue_head_t wait;
250 } ____cacheline_aligned_in_smp;
253 spinlock_t completion_lock;
254 bool poll_multi_file;
256 * ->poll_list is protected by the ctx->uring_lock for
257 * io_uring instances that don't use IORING_SETUP_SQPOLL.
258 * For SQPOLL, only the single threaded io_sq_thread() will
259 * manipulate the list, hence no extra locking is needed there.
261 struct list_head poll_list;
262 struct list_head cancel_list;
263 } ____cacheline_aligned_in_smp;
265 struct async_list pending_async[2];
267 #if defined(CONFIG_UNIX)
268 struct socket *ring_sock;
273 const struct io_uring_sqe *sqe;
274 unsigned short index;
278 bool needs_fixed_file;
282 * First field must be the file pointer in all the
283 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
285 struct io_poll_iocb {
287 struct wait_queue_head *head;
291 struct wait_queue_entry wait;
296 struct hrtimer timer;
300 * NOTE! Each of the iocb union members has the file pointer
301 * as the first entry in their struct definition. So you can
302 * access the file pointer through any of the sub-structs,
303 * or directly as just 'ki_filp' in this struct.
309 struct io_poll_iocb poll;
310 struct io_timeout timeout;
313 struct sqe_submit submit;
315 struct io_ring_ctx *ctx;
316 struct list_head list;
317 struct list_head link_list;
320 #define REQ_F_NOWAIT 1 /* must not punt to workers */
321 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
322 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
323 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
324 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
325 #define REQ_F_IO_DRAINED 32 /* drain done */
326 #define REQ_F_LINK 64 /* linked sqes */
327 #define REQ_F_LINK_DONE 128 /* linked sqes done */
328 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
329 #define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
330 #define REQ_F_TIMEOUT 1024 /* timeout request */
331 #define REQ_F_ISREG 2048 /* regular file */
332 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
333 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
339 struct fs_struct *fs;
341 struct work_struct work;
344 #define IO_PLUG_THRESHOLD 2
345 #define IO_IOPOLL_BATCH 8
347 struct io_submit_state {
348 struct blk_plug plug;
351 * io_kiocb alloc cache
353 void *reqs[IO_IOPOLL_BATCH];
354 unsigned int free_reqs;
355 unsigned int cur_req;
358 * File reference cache
362 unsigned int has_refs;
363 unsigned int used_refs;
364 unsigned int ios_left;
367 static void io_sq_wq_submit_work(struct work_struct *work);
368 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
370 static void __io_free_req(struct io_kiocb *req);
372 static struct kmem_cache *req_cachep;
374 static const struct file_operations io_uring_fops;
376 struct sock *io_uring_get_socket(struct file *file)
378 #if defined(CONFIG_UNIX)
379 if (file->f_op == &io_uring_fops) {
380 struct io_ring_ctx *ctx = file->private_data;
382 return ctx->ring_sock->sk;
387 EXPORT_SYMBOL(io_uring_get_socket);
389 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
391 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
393 complete(&ctx->ctx_done);
396 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
398 struct io_ring_ctx *ctx;
401 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
405 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
406 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
411 ctx->flags = p->flags;
412 init_waitqueue_head(&ctx->cq_wait);
413 init_completion(&ctx->ctx_done);
414 init_completion(&ctx->sqo_thread_started);
415 mutex_init(&ctx->uring_lock);
416 init_waitqueue_head(&ctx->wait);
417 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
418 spin_lock_init(&ctx->pending_async[i].lock);
419 INIT_LIST_HEAD(&ctx->pending_async[i].list);
420 atomic_set(&ctx->pending_async[i].cnt, 0);
422 spin_lock_init(&ctx->completion_lock);
423 INIT_LIST_HEAD(&ctx->poll_list);
424 INIT_LIST_HEAD(&ctx->cancel_list);
425 INIT_LIST_HEAD(&ctx->defer_list);
426 INIT_LIST_HEAD(&ctx->timeout_list);
430 static inline bool __io_sequence_defer(struct io_ring_ctx *ctx,
431 struct io_kiocb *req)
433 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
434 + atomic_read(&ctx->cached_cq_overflow);
437 static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
438 struct io_kiocb *req)
440 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
443 return __io_sequence_defer(ctx, req);
446 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
448 struct io_kiocb *req;
450 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
451 if (req && !io_sequence_defer(ctx, req)) {
452 list_del_init(&req->list);
459 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
461 struct io_kiocb *req;
463 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
465 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
467 if (!__io_sequence_defer(ctx, req)) {
468 list_del_init(&req->list);
476 static void __io_commit_cqring(struct io_ring_ctx *ctx)
478 struct io_rings *rings = ctx->rings;
480 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
481 /* order cqe stores with ring update */
482 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
484 if (wq_has_sleeper(&ctx->cq_wait)) {
485 wake_up_interruptible(&ctx->cq_wait);
486 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
491 static inline void io_queue_async_work(struct io_ring_ctx *ctx,
492 struct io_kiocb *req)
496 if (req->submit.sqe) {
497 switch (req->submit.sqe->opcode) {
498 case IORING_OP_WRITEV:
499 case IORING_OP_WRITE_FIXED:
500 rw = !(req->rw.ki_flags & IOCB_DIRECT);
505 queue_work(ctx->sqo_wq[rw], &req->work);
508 static void io_kill_timeout(struct io_kiocb *req)
512 ret = hrtimer_try_to_cancel(&req->timeout.timer);
514 atomic_inc(&req->ctx->cq_timeouts);
515 list_del(&req->list);
516 io_cqring_fill_event(req->ctx, req->user_data, 0);
521 static void io_kill_timeouts(struct io_ring_ctx *ctx)
523 struct io_kiocb *req, *tmp;
525 spin_lock_irq(&ctx->completion_lock);
526 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
527 io_kill_timeout(req);
528 spin_unlock_irq(&ctx->completion_lock);
531 static void io_commit_cqring(struct io_ring_ctx *ctx)
533 struct io_kiocb *req;
535 while ((req = io_get_timeout_req(ctx)) != NULL)
536 io_kill_timeout(req);
538 __io_commit_cqring(ctx);
540 while ((req = io_get_deferred_req(ctx)) != NULL) {
541 if (req->flags & REQ_F_SHADOW_DRAIN) {
542 /* Just for drain, free it. */
546 req->flags |= REQ_F_IO_DRAINED;
547 io_queue_async_work(ctx, req);
551 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
553 struct io_rings *rings = ctx->rings;
556 tail = ctx->cached_cq_tail;
558 * writes to the cq entry need to come after reading head; the
559 * control dependency is enough as we're using WRITE_ONCE to
562 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
565 ctx->cached_cq_tail++;
566 return &rings->cqes[tail & ctx->cq_mask];
569 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
572 struct io_uring_cqe *cqe;
575 * If we can't get a cq entry, userspace overflowed the
576 * submission (by quite a lot). Increment the overflow count in
579 cqe = io_get_cqring(ctx);
581 WRITE_ONCE(cqe->user_data, ki_user_data);
582 WRITE_ONCE(cqe->res, res);
583 WRITE_ONCE(cqe->flags, 0);
585 WRITE_ONCE(ctx->rings->cq_overflow,
586 atomic_inc_return(&ctx->cached_cq_overflow));
590 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
592 if (waitqueue_active(&ctx->wait))
594 if (waitqueue_active(&ctx->sqo_wait))
595 wake_up(&ctx->sqo_wait);
597 eventfd_signal(ctx->cq_ev_fd, 1);
600 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
605 spin_lock_irqsave(&ctx->completion_lock, flags);
606 io_cqring_fill_event(ctx, user_data, res);
607 io_commit_cqring(ctx);
608 spin_unlock_irqrestore(&ctx->completion_lock, flags);
610 io_cqring_ev_posted(ctx);
613 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
614 struct io_submit_state *state)
616 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
617 struct io_kiocb *req;
619 if (!percpu_ref_tryget(&ctx->refs))
623 req = kmem_cache_alloc(req_cachep, gfp);
626 } else if (!state->free_reqs) {
630 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
631 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
634 * Bulk alloc is all-or-nothing. If we fail to get a batch,
635 * retry single alloc to be on the safe side.
637 if (unlikely(ret <= 0)) {
638 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
643 state->free_reqs = ret - 1;
645 req = state->reqs[0];
647 req = state->reqs[state->cur_req];
655 /* one is dropped after submission, the other at completion */
656 refcount_set(&req->refs, 2);
661 percpu_ref_put(&ctx->refs);
665 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
668 kmem_cache_free_bulk(req_cachep, *nr, reqs);
669 percpu_ref_put_many(&ctx->refs, *nr);
674 static void __io_free_req(struct io_kiocb *req)
676 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
678 percpu_ref_put(&req->ctx->refs);
679 kmem_cache_free(req_cachep, req);
682 static void io_req_link_next(struct io_kiocb *req)
684 struct io_kiocb *nxt;
687 * The list should never be empty when we are called here. But could
688 * potentially happen if the chain is messed up, check to be on the
691 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
693 list_del(&nxt->list);
694 if (!list_empty(&req->link_list)) {
695 INIT_LIST_HEAD(&nxt->link_list);
696 list_splice(&req->link_list, &nxt->link_list);
697 nxt->flags |= REQ_F_LINK;
700 nxt->flags |= REQ_F_LINK_DONE;
701 INIT_WORK(&nxt->work, io_sq_wq_submit_work);
702 io_queue_async_work(req->ctx, nxt);
707 * Called if REQ_F_LINK is set, and we fail the head request
709 static void io_fail_links(struct io_kiocb *req)
711 struct io_kiocb *link;
713 while (!list_empty(&req->link_list)) {
714 link = list_first_entry(&req->link_list, struct io_kiocb, list);
715 list_del(&link->list);
717 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
722 static void io_free_req(struct io_kiocb *req)
725 * If LINK is set, we have dependent requests in this chain. If we
726 * didn't fail this request, queue the first one up, moving any other
727 * dependencies to the next request. In case of failure, fail the rest
730 if (req->flags & REQ_F_LINK) {
731 if (req->flags & REQ_F_FAIL_LINK)
734 io_req_link_next(req);
740 static void io_put_req(struct io_kiocb *req)
742 if (refcount_dec_and_test(&req->refs))
746 static unsigned io_cqring_events(struct io_rings *rings)
748 /* See comment at the top of this file */
750 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
753 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
755 struct io_rings *rings = ctx->rings;
757 /* make sure SQ entry isn't read before tail */
758 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
762 * Find and free completed poll iocbs
764 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
765 struct list_head *done)
767 void *reqs[IO_IOPOLL_BATCH];
768 struct io_kiocb *req;
772 while (!list_empty(done)) {
773 req = list_first_entry(done, struct io_kiocb, list);
774 list_del(&req->list);
776 io_cqring_fill_event(ctx, req->user_data, req->result);
779 if (refcount_dec_and_test(&req->refs)) {
780 /* If we're not using fixed files, we have to pair the
781 * completion part with the file put. Use regular
782 * completions for those, only batch free for fixed
783 * file and non-linked commands.
785 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
787 reqs[to_free++] = req;
788 if (to_free == ARRAY_SIZE(reqs))
789 io_free_req_many(ctx, reqs, &to_free);
796 io_commit_cqring(ctx);
797 io_free_req_many(ctx, reqs, &to_free);
800 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
803 struct io_kiocb *req, *tmp;
809 * Only spin for completions if we don't have multiple devices hanging
810 * off our complete list, and we're under the requested amount.
812 spin = !ctx->poll_multi_file && *nr_events < min;
815 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
816 struct kiocb *kiocb = &req->rw;
819 * Move completed entries to our local list. If we find a
820 * request that requires polling, break out and complete
821 * the done list first, if we have entries there.
823 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
824 list_move_tail(&req->list, &done);
827 if (!list_empty(&done))
830 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
839 if (!list_empty(&done))
840 io_iopoll_complete(ctx, nr_events, &done);
846 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
847 * non-spinning poll check - we'll still enter the driver poll loop, but only
848 * as a non-spinning completion check.
850 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
853 while (!list_empty(&ctx->poll_list) && !need_resched()) {
856 ret = io_do_iopoll(ctx, nr_events, min);
859 if (!min || *nr_events >= min)
867 * We can't just wait for polled events to come to us, we have to actively
868 * find and complete them.
870 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
872 if (!(ctx->flags & IORING_SETUP_IOPOLL))
875 mutex_lock(&ctx->uring_lock);
876 while (!list_empty(&ctx->poll_list)) {
877 unsigned int nr_events = 0;
879 io_iopoll_getevents(ctx, &nr_events, 1);
882 * Ensure we allow local-to-the-cpu processing to take place,
883 * in this case we need to ensure that we reap all events.
887 mutex_unlock(&ctx->uring_lock);
890 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
893 int iters = 0, ret = 0;
896 * We disallow the app entering submit/complete with polling, but we
897 * still need to lock the ring to prevent racing with polled issue
898 * that got punted to a workqueue.
900 mutex_lock(&ctx->uring_lock);
905 * Don't enter poll loop if we already have events pending.
906 * If we do, we can potentially be spinning for commands that
907 * already triggered a CQE (eg in error).
909 if (io_cqring_events(ctx->rings))
913 * If a submit got punted to a workqueue, we can have the
914 * application entering polling for a command before it gets
915 * issued. That app will hold the uring_lock for the duration
916 * of the poll right here, so we need to take a breather every
917 * now and then to ensure that the issue has a chance to add
918 * the poll to the issued list. Otherwise we can spin here
919 * forever, while the workqueue is stuck trying to acquire the
922 if (!(++iters & 7)) {
923 mutex_unlock(&ctx->uring_lock);
924 mutex_lock(&ctx->uring_lock);
927 if (*nr_events < min)
928 tmin = min - *nr_events;
930 ret = io_iopoll_getevents(ctx, nr_events, tmin);
934 } while (min && !*nr_events && !need_resched());
936 mutex_unlock(&ctx->uring_lock);
940 static void kiocb_end_write(struct io_kiocb *req)
943 * Tell lockdep we inherited freeze protection from submission
946 if (req->flags & REQ_F_ISREG) {
947 struct inode *inode = file_inode(req->file);
949 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
951 file_end_write(req->file);
954 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
956 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
958 if (kiocb->ki_flags & IOCB_WRITE)
959 kiocb_end_write(req);
961 if ((req->flags & REQ_F_LINK) && res != req->result)
962 req->flags |= REQ_F_FAIL_LINK;
963 io_cqring_add_event(req->ctx, req->user_data, res);
967 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
969 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
971 if (kiocb->ki_flags & IOCB_WRITE)
972 kiocb_end_write(req);
974 if ((req->flags & REQ_F_LINK) && res != req->result)
975 req->flags |= REQ_F_FAIL_LINK;
978 req->flags |= REQ_F_IOPOLL_COMPLETED;
982 * After the iocb has been issued, it's safe to be found on the poll list.
983 * Adding the kiocb to the list AFTER submission ensures that we don't
984 * find it from a io_iopoll_getevents() thread before the issuer is done
985 * accessing the kiocb cookie.
987 static void io_iopoll_req_issued(struct io_kiocb *req)
989 struct io_ring_ctx *ctx = req->ctx;
992 * Track whether we have multiple files in our lists. This will impact
993 * how we do polling eventually, not spinning if we're on potentially
996 if (list_empty(&ctx->poll_list)) {
997 ctx->poll_multi_file = false;
998 } else if (!ctx->poll_multi_file) {
999 struct io_kiocb *list_req;
1001 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1003 if (list_req->rw.ki_filp != req->rw.ki_filp)
1004 ctx->poll_multi_file = true;
1008 * For fast devices, IO may have already completed. If it has, add
1009 * it to the front so we find it first.
1011 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1012 list_add(&req->list, &ctx->poll_list);
1014 list_add_tail(&req->list, &ctx->poll_list);
1017 static void io_file_put(struct io_submit_state *state)
1020 int diff = state->has_refs - state->used_refs;
1023 fput_many(state->file, diff);
1029 * Get as many references to a file as we have IOs left in this submission,
1030 * assuming most submissions are for one file, or at least that each file
1031 * has more than one submission.
1033 static struct file *io_file_get(struct io_submit_state *state, int fd)
1039 if (state->fd == fd) {
1046 state->file = fget_many(fd, state->ios_left);
1051 state->has_refs = state->ios_left;
1052 state->used_refs = 1;
1058 * If we tracked the file through the SCM inflight mechanism, we could support
1059 * any file. For now, just ensure that anything potentially problematic is done
1062 static bool io_file_supports_async(struct file *file)
1064 umode_t mode = file_inode(file)->i_mode;
1066 if (S_ISBLK(mode) || S_ISCHR(mode))
1068 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1074 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
1075 bool force_nonblock)
1077 const struct io_uring_sqe *sqe = s->sqe;
1078 struct io_ring_ctx *ctx = req->ctx;
1079 struct kiocb *kiocb = &req->rw;
1086 if (S_ISREG(file_inode(req->file)->i_mode))
1087 req->flags |= REQ_F_ISREG;
1090 req->fsize = rlimit(RLIMIT_FSIZE);
1093 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1094 * we know to async punt it even if it was opened O_NONBLOCK
1096 if (force_nonblock && !io_file_supports_async(req->file)) {
1097 req->flags |= REQ_F_MUST_PUNT;
1101 kiocb->ki_pos = READ_ONCE(sqe->off);
1102 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1103 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1105 ioprio = READ_ONCE(sqe->ioprio);
1107 ret = ioprio_check_cap(ioprio);
1111 kiocb->ki_ioprio = ioprio;
1113 kiocb->ki_ioprio = get_current_ioprio();
1115 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1119 /* don't allow async punt if RWF_NOWAIT was requested */
1120 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1121 (req->file->f_flags & O_NONBLOCK))
1122 req->flags |= REQ_F_NOWAIT;
1125 kiocb->ki_flags |= IOCB_NOWAIT;
1127 if (ctx->flags & IORING_SETUP_IOPOLL) {
1128 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1129 !kiocb->ki_filp->f_op->iopoll)
1132 kiocb->ki_flags |= IOCB_HIPRI;
1133 kiocb->ki_complete = io_complete_rw_iopoll;
1136 if (kiocb->ki_flags & IOCB_HIPRI)
1138 kiocb->ki_complete = io_complete_rw;
1143 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1149 case -ERESTARTNOINTR:
1150 case -ERESTARTNOHAND:
1151 case -ERESTART_RESTARTBLOCK:
1153 * We can't just restart the syscall, since previously
1154 * submitted sqes may already be in progress. Just fail this
1160 kiocb->ki_complete(kiocb, ret, 0);
1164 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1165 const struct io_uring_sqe *sqe,
1166 struct iov_iter *iter)
1168 size_t len = READ_ONCE(sqe->len);
1169 struct io_mapped_ubuf *imu;
1170 unsigned index, buf_index;
1174 /* attempt to use fixed buffers without having provided iovecs */
1175 if (unlikely(!ctx->user_bufs))
1178 buf_index = READ_ONCE(sqe->buf_index);
1179 if (unlikely(buf_index >= ctx->nr_user_bufs))
1182 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1183 imu = &ctx->user_bufs[index];
1184 buf_addr = READ_ONCE(sqe->addr);
1187 if (buf_addr + len < buf_addr)
1189 /* not inside the mapped region */
1190 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1194 * May not be a start of buffer, set size appropriately
1195 * and advance us to the beginning.
1197 offset = buf_addr - imu->ubuf;
1198 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1202 * Don't use iov_iter_advance() here, as it's really slow for
1203 * using the latter parts of a big fixed buffer - it iterates
1204 * over each segment manually. We can cheat a bit here, because
1207 * 1) it's a BVEC iter, we set it up
1208 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1209 * first and last bvec
1211 * So just find our index, and adjust the iterator afterwards.
1212 * If the offset is within the first bvec (or the whole first
1213 * bvec, just use iov_iter_advance(). This makes it easier
1214 * since we can just skip the first segment, which may not
1215 * be PAGE_SIZE aligned.
1217 const struct bio_vec *bvec = imu->bvec;
1219 if (offset <= bvec->bv_len) {
1220 iov_iter_advance(iter, offset);
1222 unsigned long seg_skip;
1224 /* skip first vec */
1225 offset -= bvec->bv_len;
1226 seg_skip = 1 + (offset >> PAGE_SHIFT);
1228 iter->bvec = bvec + seg_skip;
1229 iter->nr_segs -= seg_skip;
1230 iter->count -= bvec->bv_len + offset;
1231 iter->iov_offset = offset & ~PAGE_MASK;
1238 static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1239 const struct sqe_submit *s, struct iovec **iovec,
1240 struct iov_iter *iter)
1242 const struct io_uring_sqe *sqe = s->sqe;
1243 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1244 size_t sqe_len = READ_ONCE(sqe->len);
1248 * We're reading ->opcode for the second time, but the first read
1249 * doesn't care whether it's _FIXED or not, so it doesn't matter
1250 * whether ->opcode changes concurrently. The first read does care
1251 * about whether it is a READ or a WRITE, so we don't trust this read
1252 * for that purpose and instead let the caller pass in the read/write
1255 opcode = READ_ONCE(sqe->opcode);
1256 if (opcode == IORING_OP_READ_FIXED ||
1257 opcode == IORING_OP_WRITE_FIXED) {
1258 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
1266 #ifdef CONFIG_COMPAT
1268 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1272 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1275 static inline bool io_should_merge(struct async_list *al, struct kiocb *kiocb)
1277 if (al->file == kiocb->ki_filp) {
1281 * Allow merging if we're anywhere in the range of the same
1282 * page. Generally this happens for sub-page reads or writes,
1283 * and it's beneficial to allow the first worker to bring the
1284 * page in and the piggy backed work can then work on the
1287 start = al->io_start & PAGE_MASK;
1288 end = (al->io_start + al->io_len + PAGE_SIZE - 1) & PAGE_MASK;
1289 if (kiocb->ki_pos >= start && kiocb->ki_pos <= end)
1298 * Make a note of the last file/offset/direction we punted to async
1299 * context. We'll use this information to see if we can piggy back a
1300 * sequential request onto the previous one, if it's still hasn't been
1301 * completed by the async worker.
1303 static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1305 struct async_list *async_list = &req->ctx->pending_async[rw];
1306 struct kiocb *kiocb = &req->rw;
1307 struct file *filp = kiocb->ki_filp;
1309 if (io_should_merge(async_list, kiocb)) {
1310 unsigned long max_bytes;
1312 /* Use 8x RA size as a decent limiter for both reads/writes */
1313 max_bytes = filp->f_ra.ra_pages << (PAGE_SHIFT + 3);
1315 max_bytes = VM_READAHEAD_PAGES << (PAGE_SHIFT + 3);
1317 /* If max len are exceeded, reset the state */
1318 if (async_list->io_len + len <= max_bytes) {
1319 req->flags |= REQ_F_SEQ_PREV;
1320 async_list->io_len += len;
1322 async_list->file = NULL;
1326 /* New file? Reset state. */
1327 if (async_list->file != filp) {
1328 async_list->io_start = kiocb->ki_pos;
1329 async_list->io_len = len;
1330 async_list->file = filp;
1335 * For files that don't have ->read_iter() and ->write_iter(), handle them
1336 * by looping over ->read() or ->write() manually.
1338 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1339 struct iov_iter *iter)
1344 * Don't support polled IO through this interface, and we can't
1345 * support non-blocking either. For the latter, this just causes
1346 * the kiocb to be handled from an async context.
1348 if (kiocb->ki_flags & IOCB_HIPRI)
1350 if (kiocb->ki_flags & IOCB_NOWAIT)
1353 while (iov_iter_count(iter)) {
1357 if (!iov_iter_is_bvec(iter)) {
1358 iovec = iov_iter_iovec(iter);
1360 /* fixed buffers import bvec */
1361 iovec.iov_base = kmap(iter->bvec->bv_page)
1363 iovec.iov_len = min(iter->count,
1364 iter->bvec->bv_len - iter->iov_offset);
1368 nr = file->f_op->read(file, iovec.iov_base,
1369 iovec.iov_len, &kiocb->ki_pos);
1371 nr = file->f_op->write(file, iovec.iov_base,
1372 iovec.iov_len, &kiocb->ki_pos);
1375 if (iov_iter_is_bvec(iter))
1376 kunmap(iter->bvec->bv_page);
1384 if (nr != iovec.iov_len)
1386 iov_iter_advance(iter, nr);
1392 static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1393 bool force_nonblock)
1395 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1396 struct kiocb *kiocb = &req->rw;
1397 struct iov_iter iter;
1400 ssize_t read_size, ret;
1402 ret = io_prep_rw(req, s, force_nonblock);
1405 file = kiocb->ki_filp;
1407 if (unlikely(!(file->f_mode & FMODE_READ)))
1410 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
1415 if (req->flags & REQ_F_LINK)
1416 req->result = read_size;
1418 iov_count = iov_iter_count(&iter);
1419 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1423 if (file->f_op->read_iter)
1424 ret2 = call_read_iter(file, kiocb, &iter);
1426 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1429 * In case of a short read, punt to async. This can happen
1430 * if we have data partially cached. Alternatively we can
1431 * return the short read, in which case the application will
1432 * need to issue another SQE and wait for it. That SQE will
1433 * need async punt anyway, so it's more efficient to do it
1436 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1437 (req->flags & REQ_F_ISREG) &&
1438 ret2 > 0 && ret2 < read_size)
1440 /* Catch -EAGAIN return for forced non-blocking submission */
1441 if (!force_nonblock || ret2 != -EAGAIN) {
1442 io_rw_done(kiocb, ret2);
1445 * If ->needs_lock is true, we're already in async
1449 io_async_list_note(READ, req, iov_count);
1457 static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1458 bool force_nonblock)
1460 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1461 struct kiocb *kiocb = &req->rw;
1462 struct iov_iter iter;
1467 ret = io_prep_rw(req, s, force_nonblock);
1471 file = kiocb->ki_filp;
1472 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1475 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1479 if (req->flags & REQ_F_LINK)
1482 iov_count = iov_iter_count(&iter);
1485 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1486 /* If ->needs_lock is true, we're already in async context. */
1488 io_async_list_note(WRITE, req, iov_count);
1492 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1497 * Open-code file_start_write here to grab freeze protection,
1498 * which will be released by another thread in
1499 * io_complete_rw(). Fool lockdep by telling it the lock got
1500 * released so that it doesn't complain about the held lock when
1501 * we return to userspace.
1503 if (req->flags & REQ_F_ISREG) {
1504 __sb_start_write(file_inode(file)->i_sb,
1505 SB_FREEZE_WRITE, true);
1506 __sb_writers_release(file_inode(file)->i_sb,
1509 kiocb->ki_flags |= IOCB_WRITE;
1511 if (!force_nonblock)
1512 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
1514 if (file->f_op->write_iter)
1515 ret2 = call_write_iter(file, kiocb, &iter);
1517 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1519 if (!force_nonblock)
1520 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
1522 if (!force_nonblock || ret2 != -EAGAIN) {
1523 io_rw_done(kiocb, ret2);
1526 * If ->needs_lock is true, we're already in async
1530 io_async_list_note(WRITE, req, iov_count);
1540 * IORING_OP_NOP just posts a completion event, nothing else.
1542 static int io_nop(struct io_kiocb *req, u64 user_data)
1544 struct io_ring_ctx *ctx = req->ctx;
1547 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1550 io_cqring_add_event(ctx, user_data, err);
1555 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1557 struct io_ring_ctx *ctx = req->ctx;
1562 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1564 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1570 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1571 bool force_nonblock)
1573 loff_t sqe_off = READ_ONCE(sqe->off);
1574 loff_t sqe_len = READ_ONCE(sqe->len);
1575 loff_t end = sqe_off + sqe_len;
1576 unsigned fsync_flags;
1579 fsync_flags = READ_ONCE(sqe->fsync_flags);
1580 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1583 ret = io_prep_fsync(req, sqe);
1587 /* fsync always requires a blocking context */
1591 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1592 end > 0 ? end : LLONG_MAX,
1593 fsync_flags & IORING_FSYNC_DATASYNC);
1595 if (ret < 0 && (req->flags & REQ_F_LINK))
1596 req->flags |= REQ_F_FAIL_LINK;
1597 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1602 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1604 struct io_ring_ctx *ctx = req->ctx;
1610 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1612 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1618 static int io_sync_file_range(struct io_kiocb *req,
1619 const struct io_uring_sqe *sqe,
1620 bool force_nonblock)
1627 ret = io_prep_sfr(req, sqe);
1631 /* sync_file_range always requires a blocking context */
1635 sqe_off = READ_ONCE(sqe->off);
1636 sqe_len = READ_ONCE(sqe->len);
1637 flags = READ_ONCE(sqe->sync_range_flags);
1639 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1641 if (ret < 0 && (req->flags & REQ_F_LINK))
1642 req->flags |= REQ_F_FAIL_LINK;
1643 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1648 #if defined(CONFIG_NET)
1649 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1650 bool force_nonblock,
1651 long (*fn)(struct socket *, struct user_msghdr __user *,
1654 struct socket *sock;
1657 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1660 sock = sock_from_file(req->file, &ret);
1662 struct user_msghdr __user *msg;
1665 flags = READ_ONCE(sqe->msg_flags);
1666 if (flags & MSG_DONTWAIT)
1667 req->flags |= REQ_F_NOWAIT;
1668 else if (force_nonblock)
1669 flags |= MSG_DONTWAIT;
1671 #ifdef CONFIG_COMPAT
1672 if (req->ctx->compat)
1673 flags |= MSG_CMSG_COMPAT;
1676 msg = (struct user_msghdr __user *) (unsigned long)
1677 READ_ONCE(sqe->addr);
1679 ret = fn(sock, msg, flags);
1680 if (force_nonblock && ret == -EAGAIN)
1682 if (ret == -ERESTARTSYS)
1687 struct fs_struct *fs = req->fs;
1689 spin_lock(&req->fs->lock);
1692 spin_unlock(&req->fs->lock);
1696 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1702 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1703 bool force_nonblock)
1705 #if defined(CONFIG_NET)
1706 return io_send_recvmsg(req, sqe, force_nonblock, __sys_sendmsg_sock);
1712 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1713 bool force_nonblock)
1715 #if defined(CONFIG_NET)
1716 return io_send_recvmsg(req, sqe, force_nonblock, __sys_recvmsg_sock);
1722 static void io_poll_remove_one(struct io_kiocb *req)
1724 struct io_poll_iocb *poll = &req->poll;
1726 spin_lock(&poll->head->lock);
1727 WRITE_ONCE(poll->canceled, true);
1728 if (!list_empty(&poll->wait.entry)) {
1729 list_del_init(&poll->wait.entry);
1730 io_queue_async_work(req->ctx, req);
1732 spin_unlock(&poll->head->lock);
1734 list_del_init(&req->list);
1737 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1739 struct io_kiocb *req;
1741 spin_lock_irq(&ctx->completion_lock);
1742 while (!list_empty(&ctx->cancel_list)) {
1743 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1744 io_poll_remove_one(req);
1746 spin_unlock_irq(&ctx->completion_lock);
1750 * Find a running poll command that matches one specified in sqe->addr,
1751 * and remove it if found.
1753 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1755 struct io_ring_ctx *ctx = req->ctx;
1756 struct io_kiocb *poll_req, *next;
1759 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1761 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1765 spin_lock_irq(&ctx->completion_lock);
1766 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1767 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1768 io_poll_remove_one(poll_req);
1773 spin_unlock_irq(&ctx->completion_lock);
1775 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1780 static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1783 req->poll.done = true;
1784 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
1785 io_commit_cqring(ctx);
1788 static void io_poll_complete_work(struct work_struct *work)
1790 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1791 struct io_poll_iocb *poll = &req->poll;
1792 struct poll_table_struct pt = { ._key = poll->events };
1793 struct io_ring_ctx *ctx = req->ctx;
1794 const struct cred *old_cred;
1797 old_cred = override_creds(ctx->creds);
1799 if (!READ_ONCE(poll->canceled))
1800 mask = vfs_poll(poll->file, &pt) & poll->events;
1803 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1804 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1805 * synchronize with them. In the cancellation case the list_del_init
1806 * itself is not actually needed, but harmless so we keep it in to
1807 * avoid further branches in the fast path.
1809 spin_lock_irq(&ctx->completion_lock);
1810 if (!mask && !READ_ONCE(poll->canceled)) {
1811 add_wait_queue(poll->head, &poll->wait);
1812 spin_unlock_irq(&ctx->completion_lock);
1815 list_del_init(&req->list);
1816 io_poll_complete(ctx, req, mask);
1817 spin_unlock_irq(&ctx->completion_lock);
1819 io_cqring_ev_posted(ctx);
1822 revert_creds(old_cred);
1825 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1828 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1830 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1831 struct io_ring_ctx *ctx = req->ctx;
1832 __poll_t mask = key_to_poll(key);
1833 unsigned long flags;
1835 /* for instances that support it check for an event match first: */
1836 if (mask && !(mask & poll->events))
1839 list_del_init(&poll->wait.entry);
1841 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1842 list_del(&req->list);
1843 io_poll_complete(ctx, req, mask);
1844 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1846 io_cqring_ev_posted(ctx);
1849 io_queue_async_work(ctx, req);
1855 struct io_poll_table {
1856 struct poll_table_struct pt;
1857 struct io_kiocb *req;
1861 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1862 struct poll_table_struct *p)
1864 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1866 if (unlikely(pt->req->poll.head)) {
1867 pt->error = -EINVAL;
1872 pt->req->poll.head = head;
1873 add_wait_queue(head, &pt->req->poll.wait);
1876 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1878 struct io_poll_iocb *poll = &req->poll;
1879 struct io_ring_ctx *ctx = req->ctx;
1880 struct io_poll_table ipt;
1881 bool cancel = false;
1885 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1887 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1892 req->submit.sqe = NULL;
1893 INIT_WORK(&req->work, io_poll_complete_work);
1894 events = READ_ONCE(sqe->poll_events);
1895 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1899 poll->canceled = false;
1901 ipt.pt._qproc = io_poll_queue_proc;
1902 ipt.pt._key = poll->events;
1904 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1906 /* initialized the list so that we can do list_empty checks */
1907 INIT_LIST_HEAD(&poll->wait.entry);
1908 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1910 INIT_LIST_HEAD(&req->list);
1912 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1914 spin_lock_irq(&ctx->completion_lock);
1915 if (likely(poll->head)) {
1916 spin_lock(&poll->head->lock);
1917 if (unlikely(list_empty(&poll->wait.entry))) {
1923 if (mask || ipt.error)
1924 list_del_init(&poll->wait.entry);
1926 WRITE_ONCE(poll->canceled, true);
1927 else if (!poll->done) /* actually waiting for an event */
1928 list_add_tail(&req->list, &ctx->cancel_list);
1929 spin_unlock(&poll->head->lock);
1931 if (mask) { /* no async, we'd stolen it */
1933 io_poll_complete(ctx, req, mask);
1935 spin_unlock_irq(&ctx->completion_lock);
1938 io_cqring_ev_posted(ctx);
1944 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
1946 struct io_ring_ctx *ctx;
1947 struct io_kiocb *req, *prev;
1948 unsigned long flags;
1950 req = container_of(timer, struct io_kiocb, timeout.timer);
1952 atomic_inc(&ctx->cq_timeouts);
1954 spin_lock_irqsave(&ctx->completion_lock, flags);
1956 * Adjust the reqs sequence before the current one because it
1957 * will consume a slot in the cq_ring and the the cq_tail pointer
1958 * will be increased, otherwise other timeout reqs may return in
1959 * advance without waiting for enough wait_nr.
1962 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
1964 list_del(&req->list);
1966 io_cqring_fill_event(ctx, req->user_data, -ETIME);
1967 io_commit_cqring(ctx);
1968 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1970 io_cqring_ev_posted(ctx);
1973 return HRTIMER_NORESTART;
1976 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1979 struct io_ring_ctx *ctx = req->ctx;
1980 struct list_head *entry;
1981 struct timespec64 ts;
1984 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1986 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->timeout_flags ||
1990 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
1993 req->flags |= REQ_F_TIMEOUT;
1996 * sqe->off holds how many events that need to occur for this
1997 * timeout event to be satisfied. If it isn't set, then this is
1998 * a pure timeout request, sequence isn't used.
2000 count = READ_ONCE(sqe->off);
2002 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2003 spin_lock_irq(&ctx->completion_lock);
2004 entry = ctx->timeout_list.prev;
2008 req->sequence = ctx->cached_sq_head + count - 1;
2009 /* reuse it to store the count */
2010 req->submit.sequence = count;
2013 * Insertion sort, ensuring the first entry in the list is always
2014 * the one we need first.
2016 spin_lock_irq(&ctx->completion_lock);
2017 list_for_each_prev(entry, &ctx->timeout_list) {
2018 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2019 unsigned nxt_sq_head;
2020 long long tmp, tmp_nxt;
2022 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2026 * Since cached_sq_head + count - 1 can overflow, use type long
2029 tmp = (long long)ctx->cached_sq_head + count - 1;
2030 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
2031 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
2034 * cached_sq_head may overflow, and it will never overflow twice
2035 * once there is some timeout req still be valid.
2037 if (ctx->cached_sq_head < nxt_sq_head)
2044 * Sequence of reqs after the insert one and itself should
2045 * be adjusted because each timeout req consumes a slot.
2050 req->sequence -= span;
2052 list_add(&req->list, entry);
2053 spin_unlock_irq(&ctx->completion_lock);
2055 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2056 req->timeout.timer.function = io_timeout_fn;
2057 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts),
2062 static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
2063 struct sqe_submit *s)
2065 struct io_uring_sqe *sqe_copy;
2067 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
2070 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2074 spin_lock_irq(&ctx->completion_lock);
2075 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
2076 spin_unlock_irq(&ctx->completion_lock);
2081 memcpy(&req->submit, s, sizeof(*s));
2082 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
2083 req->submit.sqe = sqe_copy;
2085 INIT_WORK(&req->work, io_sq_wq_submit_work);
2086 list_add_tail(&req->list, &ctx->defer_list);
2087 spin_unlock_irq(&ctx->completion_lock);
2088 return -EIOCBQUEUED;
2091 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2092 const struct sqe_submit *s, bool force_nonblock)
2096 req->user_data = READ_ONCE(s->sqe->user_data);
2098 if (unlikely(s->index >= ctx->sq_entries))
2101 opcode = READ_ONCE(s->sqe->opcode);
2104 ret = io_nop(req, req->user_data);
2106 case IORING_OP_READV:
2107 if (unlikely(s->sqe->buf_index))
2109 ret = io_read(req, s, force_nonblock);
2111 case IORING_OP_WRITEV:
2112 if (unlikely(s->sqe->buf_index))
2114 ret = io_write(req, s, force_nonblock);
2116 case IORING_OP_READ_FIXED:
2117 ret = io_read(req, s, force_nonblock);
2119 case IORING_OP_WRITE_FIXED:
2120 ret = io_write(req, s, force_nonblock);
2122 case IORING_OP_FSYNC:
2123 ret = io_fsync(req, s->sqe, force_nonblock);
2125 case IORING_OP_POLL_ADD:
2126 ret = io_poll_add(req, s->sqe);
2128 case IORING_OP_POLL_REMOVE:
2129 ret = io_poll_remove(req, s->sqe);
2131 case IORING_OP_SYNC_FILE_RANGE:
2132 ret = io_sync_file_range(req, s->sqe, force_nonblock);
2134 case IORING_OP_SENDMSG:
2135 ret = io_sendmsg(req, s->sqe, force_nonblock);
2137 case IORING_OP_RECVMSG:
2138 ret = io_recvmsg(req, s->sqe, force_nonblock);
2140 case IORING_OP_TIMEOUT:
2141 ret = io_timeout(req, s->sqe);
2151 if (ctx->flags & IORING_SETUP_IOPOLL) {
2152 if (req->result == -EAGAIN)
2155 /* workqueue context doesn't hold uring_lock, grab it now */
2157 mutex_lock(&ctx->uring_lock);
2158 io_iopoll_req_issued(req);
2160 mutex_unlock(&ctx->uring_lock);
2166 static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
2167 const struct io_uring_sqe *sqe)
2169 switch (sqe->opcode) {
2170 case IORING_OP_READV:
2171 case IORING_OP_READ_FIXED:
2172 return &ctx->pending_async[READ];
2173 case IORING_OP_WRITEV:
2174 case IORING_OP_WRITE_FIXED:
2175 return &ctx->pending_async[WRITE];
2181 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
2183 u8 opcode = READ_ONCE(sqe->opcode);
2185 return !(opcode == IORING_OP_READ_FIXED ||
2186 opcode == IORING_OP_WRITE_FIXED);
2189 static void io_sq_wq_submit_work(struct work_struct *work)
2191 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2192 struct fs_struct *old_fs_struct = current->fs;
2193 struct io_ring_ctx *ctx = req->ctx;
2194 struct mm_struct *cur_mm = NULL;
2195 struct async_list *async_list;
2196 const struct cred *old_cred;
2197 LIST_HEAD(req_list);
2198 mm_segment_t old_fs;
2201 old_cred = override_creds(ctx->creds);
2202 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
2205 struct sqe_submit *s = &req->submit;
2206 const struct io_uring_sqe *sqe = s->sqe;
2207 unsigned int flags = req->flags;
2209 /* Ensure we clear previously set non-block flag */
2210 req->rw.ki_flags &= ~IOCB_NOWAIT;
2212 if (req->fs != current->fs && current->fs != old_fs_struct) {
2215 current->fs = req->fs;
2217 current->fs = old_fs_struct;
2218 task_unlock(current);
2222 if (io_sqe_needs_user(sqe) && !cur_mm) {
2223 if (!mmget_not_zero(ctx->sqo_mm)) {
2226 cur_mm = ctx->sqo_mm;
2234 s->has_user = cur_mm != NULL;
2235 s->needs_lock = true;
2237 ret = __io_submit_sqe(ctx, req, s, false);
2239 * We can get EAGAIN for polled IO even though
2240 * we're forcing a sync submission from here,
2241 * since we can't wait for request slots on the
2250 /* drop submission reference */
2254 io_cqring_add_event(ctx, sqe->user_data, ret);
2258 /* async context always use a copy of the sqe */
2261 /* req from defer and link list needn't decrease async cnt */
2262 if (flags & (REQ_F_IO_DRAINED | REQ_F_LINK_DONE))
2267 if (!list_empty(&req_list)) {
2268 req = list_first_entry(&req_list, struct io_kiocb,
2270 list_del(&req->list);
2273 if (list_empty(&async_list->list))
2277 spin_lock(&async_list->lock);
2278 if (list_empty(&async_list->list)) {
2279 spin_unlock(&async_list->lock);
2282 list_splice_init(&async_list->list, &req_list);
2283 spin_unlock(&async_list->lock);
2285 req = list_first_entry(&req_list, struct io_kiocb, list);
2286 list_del(&req->list);
2290 * Rare case of racing with a submitter. If we find the count has
2291 * dropped to zero AND we have pending work items, then restart
2292 * the processing. This is a tiny race window.
2295 ret = atomic_dec_return(&async_list->cnt);
2296 while (!ret && !list_empty(&async_list->list)) {
2297 spin_lock(&async_list->lock);
2298 atomic_inc(&async_list->cnt);
2299 list_splice_init(&async_list->list, &req_list);
2300 spin_unlock(&async_list->lock);
2302 if (!list_empty(&req_list)) {
2303 req = list_first_entry(&req_list,
2304 struct io_kiocb, list);
2305 list_del(&req->list);
2308 ret = atomic_dec_return(&async_list->cnt);
2318 revert_creds(old_cred);
2319 if (old_fs_struct) {
2321 current->fs = old_fs_struct;
2322 task_unlock(current);
2327 * See if we can piggy back onto previously submitted work, that is still
2328 * running. We currently only allow this if the new request is sequential
2329 * to the previous one we punted.
2331 static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
2337 if (!(req->flags & REQ_F_SEQ_PREV))
2339 if (!atomic_read(&list->cnt))
2343 spin_lock(&list->lock);
2344 list_add_tail(&req->list, &list->list);
2346 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2349 if (!atomic_read(&list->cnt)) {
2350 list_del_init(&req->list);
2353 spin_unlock(&list->lock);
2357 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2359 int op = READ_ONCE(sqe->opcode);
2363 case IORING_OP_POLL_REMOVE:
2364 case IORING_OP_TIMEOUT:
2371 static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
2372 struct io_submit_state *state, struct io_kiocb *req)
2377 flags = READ_ONCE(s->sqe->flags);
2378 fd = READ_ONCE(s->sqe->fd);
2380 if (flags & IOSQE_IO_DRAIN)
2381 req->flags |= REQ_F_IO_DRAIN;
2383 * All io need record the previous position, if LINK vs DARIN,
2384 * it can be used to mark the position of the first IO in the
2387 req->sequence = s->sequence;
2389 if (!io_op_needs_file(s->sqe))
2392 if (flags & IOSQE_FIXED_FILE) {
2393 if (unlikely(!ctx->user_files ||
2394 (unsigned) fd >= ctx->nr_user_files))
2396 req->file = ctx->user_files[fd];
2397 req->flags |= REQ_F_FIXED_FILE;
2399 if (s->needs_fixed_file)
2401 req->file = io_file_get(state, fd);
2402 if (unlikely(!req->file))
2409 static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2410 struct sqe_submit *s)
2414 ret = __io_submit_sqe(ctx, req, s, true);
2417 * We async punt it if the file wasn't marked NOWAIT, or if the file
2418 * doesn't support non-blocking read/write attempts
2420 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2421 (req->flags & REQ_F_MUST_PUNT))) {
2422 struct io_uring_sqe *sqe_copy;
2424 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2426 struct async_list *list;
2429 memcpy(&req->submit, s, sizeof(*s));
2430 list = io_async_list_from_sqe(ctx, s->sqe);
2431 if (!io_add_to_prev_work(list, req)) {
2433 atomic_inc(&list->cnt);
2434 INIT_WORK(&req->work, io_sq_wq_submit_work);
2435 io_queue_async_work(ctx, req);
2439 * Queued up for async execution, worker will release
2440 * submit reference when the iocb is actually submitted.
2446 /* drop submission reference */
2449 /* and drop final reference, if we failed */
2451 io_cqring_add_event(ctx, req->user_data, ret);
2452 if (req->flags & REQ_F_LINK)
2453 req->flags |= REQ_F_FAIL_LINK;
2460 static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2461 struct sqe_submit *s)
2465 ret = io_req_defer(ctx, req, s);
2467 if (ret != -EIOCBQUEUED) {
2469 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2474 return __io_queue_sqe(ctx, req, s);
2477 static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
2478 struct sqe_submit *s, struct io_kiocb *shadow)
2481 int need_submit = false;
2484 return io_queue_sqe(ctx, req, s);
2487 * Mark the first IO in link list as DRAIN, let all the following
2488 * IOs enter the defer list. all IO needs to be completed before link
2491 req->flags |= REQ_F_IO_DRAIN;
2492 ret = io_req_defer(ctx, req, s);
2494 if (ret != -EIOCBQUEUED) {
2496 __io_free_req(shadow);
2497 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2502 * If ret == 0 means that all IOs in front of link io are
2503 * running done. let's queue link head.
2508 /* Insert shadow req to defer_list, blocking next IOs */
2509 spin_lock_irq(&ctx->completion_lock);
2510 list_add_tail(&shadow->list, &ctx->defer_list);
2511 spin_unlock_irq(&ctx->completion_lock);
2514 return __io_queue_sqe(ctx, req, s);
2519 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2521 static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
2522 struct io_submit_state *state, struct io_kiocb **link)
2524 struct io_uring_sqe *sqe_copy;
2525 struct io_kiocb *req;
2528 /* enforce forwards compatibility on users */
2529 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2534 req = io_get_req(ctx, state);
2535 if (unlikely(!req)) {
2540 ret = io_req_set_file(ctx, s, state, req);
2541 if (unlikely(ret)) {
2545 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2549 req->user_data = s->sqe->user_data;
2551 #if defined(CONFIG_NET)
2552 switch (READ_ONCE(s->sqe->opcode)) {
2553 case IORING_OP_SENDMSG:
2554 case IORING_OP_RECVMSG:
2555 spin_lock(¤t->fs->lock);
2556 if (!current->fs->in_exec) {
2557 req->fs = current->fs;
2560 spin_unlock(¤t->fs->lock);
2569 * If we already have a head request, queue this one for async
2570 * submittal once the head completes. If we don't have a head but
2571 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2572 * submitted sync once the chain is complete. If none of those
2573 * conditions are true (normal request), then just queue it.
2576 struct io_kiocb *prev = *link;
2578 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2585 memcpy(&req->submit, s, sizeof(*s));
2586 list_add_tail(&req->list, &prev->link_list);
2587 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2588 req->flags |= REQ_F_LINK;
2590 memcpy(&req->submit, s, sizeof(*s));
2591 INIT_LIST_HEAD(&req->link_list);
2594 io_queue_sqe(ctx, req, s);
2599 * Batched submission is done, ensure local IO is flushed out.
2601 static void io_submit_state_end(struct io_submit_state *state)
2603 blk_finish_plug(&state->plug);
2605 if (state->free_reqs)
2606 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2607 &state->reqs[state->cur_req]);
2611 * Start submission side cache.
2613 static void io_submit_state_start(struct io_submit_state *state,
2614 struct io_ring_ctx *ctx, unsigned max_ios)
2616 blk_start_plug(&state->plug);
2617 state->free_reqs = 0;
2619 state->ios_left = max_ios;
2622 static void io_commit_sqring(struct io_ring_ctx *ctx)
2624 struct io_rings *rings = ctx->rings;
2626 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2628 * Ensure any loads from the SQEs are done at this point,
2629 * since once we write the new head, the application could
2630 * write new data to them.
2632 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2637 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2638 * that is mapped by userspace. This means that care needs to be taken to
2639 * ensure that reads are stable, as we cannot rely on userspace always
2640 * being a good citizen. If members of the sqe are validated and then later
2641 * used, it's important that those reads are done through READ_ONCE() to
2642 * prevent a re-load down the line.
2644 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2646 struct io_rings *rings = ctx->rings;
2647 u32 *sq_array = ctx->sq_array;
2651 * The cached sq head (or cq tail) serves two purposes:
2653 * 1) allows us to batch the cost of updating the user visible
2655 * 2) allows the kernel side to track the head on its own, even
2656 * though the application is the one updating it.
2658 head = ctx->cached_sq_head;
2659 /* make sure SQ entry isn't read before tail */
2660 if (head == smp_load_acquire(&rings->sq.tail))
2663 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2664 if (head < ctx->sq_entries) {
2666 s->sqe = &ctx->sq_sqes[head];
2667 s->sequence = ctx->cached_sq_head;
2668 ctx->cached_sq_head++;
2672 /* drop invalid entries */
2673 ctx->cached_sq_head++;
2674 ctx->cached_sq_dropped++;
2675 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
2679 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
2680 bool has_user, bool mm_fault)
2682 struct io_submit_state state, *statep = NULL;
2683 struct io_kiocb *link = NULL;
2684 struct io_kiocb *shadow_req = NULL;
2685 bool prev_was_link = false;
2686 int i, submitted = 0;
2688 if (nr > IO_PLUG_THRESHOLD) {
2689 io_submit_state_start(&state, ctx, nr);
2693 for (i = 0; i < nr; i++) {
2694 struct sqe_submit s;
2696 if (!io_get_sqring(ctx, &s))
2700 * If previous wasn't linked and we have a linked command,
2701 * that's the end of the chain. Submit the previous link.
2703 if (!prev_was_link && link) {
2704 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2708 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2710 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2712 shadow_req = io_get_req(ctx, NULL);
2713 if (unlikely(!shadow_req))
2715 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2716 refcount_dec(&shadow_req->refs);
2718 shadow_req->sequence = s.sequence;
2722 if (unlikely(mm_fault)) {
2723 io_cqring_add_event(ctx, s.sqe->user_data,
2726 s.has_user = has_user;
2727 s.needs_lock = true;
2728 s.needs_fixed_file = true;
2729 io_submit_sqe(ctx, &s, statep, &link);
2735 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2737 io_submit_state_end(&state);
2742 static int io_sq_thread(void *data)
2744 struct io_ring_ctx *ctx = data;
2745 struct mm_struct *cur_mm = NULL;
2746 const struct cred *old_cred;
2747 mm_segment_t old_fs;
2750 unsigned long timeout;
2752 complete(&ctx->sqo_thread_started);
2756 old_cred = override_creds(ctx->creds);
2758 timeout = inflight = 0;
2759 while (!kthread_should_park()) {
2760 bool mm_fault = false;
2761 unsigned int to_submit;
2764 unsigned nr_events = 0;
2766 if (ctx->flags & IORING_SETUP_IOPOLL) {
2768 * inflight is the count of the maximum possible
2769 * entries we submitted, but it can be smaller
2770 * if we dropped some of them. If we don't have
2771 * poll entries available, then we know that we
2772 * have nothing left to poll for. Reset the
2773 * inflight count to zero in that case.
2775 mutex_lock(&ctx->uring_lock);
2776 if (!list_empty(&ctx->poll_list))
2777 io_iopoll_getevents(ctx, &nr_events, 0);
2780 mutex_unlock(&ctx->uring_lock);
2783 * Normal IO, just pretend everything completed.
2784 * We don't have to poll completions for that.
2786 nr_events = inflight;
2789 inflight -= nr_events;
2791 timeout = jiffies + ctx->sq_thread_idle;
2794 to_submit = io_sqring_entries(ctx);
2797 * Drop cur_mm before scheduling, we can't hold it for
2798 * long periods (or over schedule()). Do this before
2799 * adding ourselves to the waitqueue, as the unuse/drop
2809 * We're polling. If we're within the defined idle
2810 * period, then let us spin without work before going
2813 if (inflight || !time_after(jiffies, timeout)) {
2818 prepare_to_wait(&ctx->sqo_wait, &wait,
2819 TASK_INTERRUPTIBLE);
2821 /* Tell userspace we may need a wakeup call */
2822 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
2823 /* make sure to read SQ tail after writing flags */
2826 to_submit = io_sqring_entries(ctx);
2828 if (kthread_should_park()) {
2829 finish_wait(&ctx->sqo_wait, &wait);
2832 if (signal_pending(current))
2833 flush_signals(current);
2835 finish_wait(&ctx->sqo_wait, &wait);
2837 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2840 finish_wait(&ctx->sqo_wait, &wait);
2842 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2845 /* Unless all new commands are FIXED regions, grab mm */
2847 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2849 use_mm(ctx->sqo_mm);
2850 cur_mm = ctx->sqo_mm;
2854 to_submit = min(to_submit, ctx->sq_entries);
2855 inflight += io_submit_sqes(ctx, to_submit, cur_mm != NULL,
2858 /* Commit SQ ring head once we've consumed all SQEs */
2859 io_commit_sqring(ctx);
2867 revert_creds(old_cred);
2874 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2876 struct io_submit_state state, *statep = NULL;
2877 struct io_kiocb *link = NULL;
2878 struct io_kiocb *shadow_req = NULL;
2879 bool prev_was_link = false;
2882 if (to_submit > IO_PLUG_THRESHOLD) {
2883 io_submit_state_start(&state, ctx, to_submit);
2887 for (i = 0; i < to_submit; i++) {
2888 struct sqe_submit s;
2890 if (!io_get_sqring(ctx, &s))
2894 * If previous wasn't linked and we have a linked command,
2895 * that's the end of the chain. Submit the previous link.
2897 if (!prev_was_link && link) {
2898 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2902 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2904 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2906 shadow_req = io_get_req(ctx, NULL);
2907 if (unlikely(!shadow_req))
2909 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2910 refcount_dec(&shadow_req->refs);
2912 shadow_req->sequence = s.sequence;
2917 s.needs_lock = false;
2918 s.needs_fixed_file = false;
2920 io_submit_sqe(ctx, &s, statep, &link);
2924 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2926 io_submit_state_end(statep);
2928 io_commit_sqring(ctx);
2933 struct io_wait_queue {
2934 struct wait_queue_entry wq;
2935 struct io_ring_ctx *ctx;
2937 unsigned nr_timeouts;
2940 static inline bool io_should_wake(struct io_wait_queue *iowq)
2942 struct io_ring_ctx *ctx = iowq->ctx;
2945 * Wake up if we have enough events, or if a timeout occured since we
2946 * started waiting. For timeouts, we always want to return to userspace,
2947 * regardless of event count.
2949 return io_cqring_events(ctx->rings) >= iowq->to_wait ||
2950 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2953 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2954 int wake_flags, void *key)
2956 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
2959 if (!io_should_wake(iowq))
2962 return autoremove_wake_function(curr, mode, wake_flags, key);
2966 * Wait until events become available, if we don't already have some. The
2967 * application must reap them itself, as they reside on the shared cq ring.
2969 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2970 const sigset_t __user *sig, size_t sigsz)
2972 struct io_wait_queue iowq = {
2975 .func = io_wake_function,
2976 .entry = LIST_HEAD_INIT(iowq.wq.entry),
2979 .to_wait = min_events,
2981 struct io_rings *rings = ctx->rings;
2984 if (io_cqring_events(rings) >= min_events)
2988 #ifdef CONFIG_COMPAT
2989 if (in_compat_syscall())
2990 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2994 ret = set_user_sigmask(sig, sigsz);
3001 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3003 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3004 TASK_INTERRUPTIBLE);
3005 if (io_should_wake(&iowq))
3008 if (signal_pending(current)) {
3013 finish_wait(&ctx->wait, &iowq.wq);
3015 restore_saved_sigmask_unless(ret == -ERESTARTSYS);
3016 if (ret == -ERESTARTSYS)
3019 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3022 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3024 #if defined(CONFIG_UNIX)
3025 if (ctx->ring_sock) {
3026 struct sock *sock = ctx->ring_sock->sk;
3027 struct sk_buff *skb;
3029 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3035 for (i = 0; i < ctx->nr_user_files; i++)
3036 fput(ctx->user_files[i]);
3040 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3042 if (!ctx->user_files)
3045 __io_sqe_files_unregister(ctx);
3046 kfree(ctx->user_files);
3047 ctx->user_files = NULL;
3048 ctx->nr_user_files = 0;
3052 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3054 if (ctx->sqo_thread) {
3055 wait_for_completion(&ctx->sqo_thread_started);
3057 * The park is a bit of a work-around, without it we get
3058 * warning spews on shutdown with SQPOLL set and affinity
3059 * set to a single CPU.
3061 kthread_park(ctx->sqo_thread);
3062 kthread_stop(ctx->sqo_thread);
3063 ctx->sqo_thread = NULL;
3067 static void io_finish_async(struct io_ring_ctx *ctx)
3071 io_sq_thread_stop(ctx);
3073 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++) {
3074 if (ctx->sqo_wq[i]) {
3075 destroy_workqueue(ctx->sqo_wq[i]);
3076 ctx->sqo_wq[i] = NULL;
3081 #if defined(CONFIG_UNIX)
3082 static void io_destruct_skb(struct sk_buff *skb)
3084 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
3087 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++)
3089 flush_workqueue(ctx->sqo_wq[i]);
3091 unix_destruct_scm(skb);
3095 * Ensure the UNIX gc is aware of our file set, so we are certain that
3096 * the io_uring can be safely unregistered on process exit, even if we have
3097 * loops in the file referencing.
3099 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3101 struct sock *sk = ctx->ring_sock->sk;
3102 struct scm_fp_list *fpl;
3103 struct sk_buff *skb;
3106 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3110 skb = alloc_skb(0, GFP_KERNEL);
3117 skb->destructor = io_destruct_skb;
3119 fpl->user = get_uid(ctx->user);
3120 for (i = 0; i < nr; i++) {
3121 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
3122 unix_inflight(fpl->user, fpl->fp[i]);
3125 fpl->max = fpl->count = nr;
3126 UNIXCB(skb).fp = fpl;
3127 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3128 skb_queue_head(&sk->sk_receive_queue, skb);
3130 for (i = 0; i < nr; i++)
3137 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3138 * causes regular reference counting to break down. We rely on the UNIX
3139 * garbage collection to take care of this problem for us.
3141 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3143 unsigned left, total;
3147 left = ctx->nr_user_files;
3149 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
3151 ret = __io_sqe_files_scm(ctx, this_files, total);
3155 total += this_files;
3161 while (total < ctx->nr_user_files) {
3162 fput(ctx->user_files[total]);
3169 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3175 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3178 __s32 __user *fds = (__s32 __user *) arg;
3182 if (ctx->user_files)
3186 if (nr_args > IORING_MAX_FIXED_FILES)
3189 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
3190 if (!ctx->user_files)
3193 for (i = 0; i < nr_args; i++) {
3195 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3198 ctx->user_files[i] = fget(fd);
3201 if (!ctx->user_files[i])
3204 * Don't allow io_uring instances to be registered. If UNIX
3205 * isn't enabled, then this causes a reference cycle and this
3206 * instance can never get freed. If UNIX is enabled we'll
3207 * handle it just fine, but there's still no point in allowing
3208 * a ring fd as it doesn't support regular read/write anyway.
3210 if (ctx->user_files[i]->f_op == &io_uring_fops) {
3211 fput(ctx->user_files[i]);
3214 ctx->nr_user_files++;
3219 for (i = 0; i < ctx->nr_user_files; i++)
3220 fput(ctx->user_files[i]);
3222 kfree(ctx->user_files);
3223 ctx->user_files = NULL;
3224 ctx->nr_user_files = 0;
3228 ret = io_sqe_files_scm(ctx);
3230 io_sqe_files_unregister(ctx);
3235 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3236 struct io_uring_params *p)
3240 init_waitqueue_head(&ctx->sqo_wait);
3241 mmgrab(current->mm);
3242 ctx->sqo_mm = current->mm;
3244 if (ctx->flags & IORING_SETUP_SQPOLL) {
3246 if (!capable(CAP_SYS_ADMIN))
3249 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3250 if (!ctx->sq_thread_idle)
3251 ctx->sq_thread_idle = HZ;
3253 if (p->flags & IORING_SETUP_SQ_AFF) {
3254 int cpu = p->sq_thread_cpu;
3257 if (cpu >= nr_cpu_ids)
3259 if (!cpu_online(cpu))
3262 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3266 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3269 if (IS_ERR(ctx->sqo_thread)) {
3270 ret = PTR_ERR(ctx->sqo_thread);
3271 ctx->sqo_thread = NULL;
3274 wake_up_process(ctx->sqo_thread);
3275 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3276 /* Can't have SQ_AFF without SQPOLL */
3281 /* Do QD, or 2 * CPUS, whatever is smallest */
3282 ctx->sqo_wq[0] = alloc_workqueue("io_ring-wq",
3283 WQ_UNBOUND | WQ_FREEZABLE,
3284 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
3285 if (!ctx->sqo_wq[0]) {
3291 * This is for buffered writes, where we want to limit the parallelism
3292 * due to file locking in file systems. As "normal" buffered writes
3293 * should parellelize on writeout quite nicely, limit us to having 2
3294 * pending. This avoids massive contention on the inode when doing
3295 * buffered async writes.
3297 ctx->sqo_wq[1] = alloc_workqueue("io_ring-write-wq",
3298 WQ_UNBOUND | WQ_FREEZABLE, 2);
3299 if (!ctx->sqo_wq[1]) {
3306 io_finish_async(ctx);
3307 mmdrop(ctx->sqo_mm);
3312 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3314 atomic_long_sub(nr_pages, &user->locked_vm);
3317 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3319 unsigned long page_limit, cur_pages, new_pages;
3321 /* Don't allow more pages than we can safely lock */
3322 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3325 cur_pages = atomic_long_read(&user->locked_vm);
3326 new_pages = cur_pages + nr_pages;
3327 if (new_pages > page_limit)
3329 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3330 new_pages) != cur_pages);
3335 static void io_mem_free(void *ptr)
3342 page = virt_to_head_page(ptr);
3343 if (put_page_testzero(page))
3344 free_compound_page(page);
3347 static void *io_mem_alloc(size_t size)
3349 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3352 return (void *) __get_free_pages(gfp_flags, get_order(size));
3355 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3358 struct io_rings *rings;
3359 size_t off, sq_array_size;
3361 off = struct_size(rings, cqes, cq_entries);
3362 if (off == SIZE_MAX)
3366 off = ALIGN(off, SMP_CACHE_BYTES);
3371 sq_array_size = array_size(sizeof(u32), sq_entries);
3372 if (sq_array_size == SIZE_MAX)
3375 if (check_add_overflow(off, sq_array_size, &off))
3384 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3388 pages = (size_t)1 << get_order(
3389 rings_size(sq_entries, cq_entries, NULL));
3390 pages += (size_t)1 << get_order(
3391 array_size(sizeof(struct io_uring_sqe), sq_entries));
3396 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3400 if (!ctx->user_bufs)
3403 for (i = 0; i < ctx->nr_user_bufs; i++) {
3404 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3406 for (j = 0; j < imu->nr_bvecs; j++)
3407 put_user_page(imu->bvec[j].bv_page);
3409 if (ctx->account_mem)
3410 io_unaccount_mem(ctx->user, imu->nr_bvecs);
3415 kfree(ctx->user_bufs);
3416 ctx->user_bufs = NULL;
3417 ctx->nr_user_bufs = 0;
3421 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3422 void __user *arg, unsigned index)
3424 struct iovec __user *src;
3426 #ifdef CONFIG_COMPAT
3428 struct compat_iovec __user *ciovs;
3429 struct compat_iovec ciov;
3431 ciovs = (struct compat_iovec __user *) arg;
3432 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3435 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3436 dst->iov_len = ciov.iov_len;
3440 src = (struct iovec __user *) arg;
3441 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3446 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3449 struct vm_area_struct **vmas = NULL;
3450 struct page **pages = NULL;
3451 int i, j, got_pages = 0;
3456 if (!nr_args || nr_args > UIO_MAXIOV)
3459 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3461 if (!ctx->user_bufs)
3464 for (i = 0; i < nr_args; i++) {
3465 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3466 unsigned long off, start, end, ubuf;
3471 ret = io_copy_iov(ctx, &iov, arg, i);
3476 * Don't impose further limits on the size and buffer
3477 * constraints here, we'll -EINVAL later when IO is
3478 * submitted if they are wrong.
3481 if (!iov.iov_base || !iov.iov_len)
3484 /* arbitrary limit, but we need something */
3485 if (iov.iov_len > SZ_1G)
3488 ubuf = (unsigned long) iov.iov_base;
3489 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3490 start = ubuf >> PAGE_SHIFT;
3491 nr_pages = end - start;
3493 if (ctx->account_mem) {
3494 ret = io_account_mem(ctx->user, nr_pages);
3500 if (!pages || nr_pages > got_pages) {
3503 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
3505 vmas = kvmalloc_array(nr_pages,
3506 sizeof(struct vm_area_struct *),
3508 if (!pages || !vmas) {
3510 if (ctx->account_mem)
3511 io_unaccount_mem(ctx->user, nr_pages);
3514 got_pages = nr_pages;
3517 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
3521 if (ctx->account_mem)
3522 io_unaccount_mem(ctx->user, nr_pages);
3527 down_read(¤t->mm->mmap_sem);
3528 pret = get_user_pages(ubuf, nr_pages,
3529 FOLL_WRITE | FOLL_LONGTERM,
3531 if (pret == nr_pages) {
3532 /* don't support file backed memory */
3533 for (j = 0; j < nr_pages; j++) {
3534 struct vm_area_struct *vma = vmas[j];
3537 !is_file_hugepages(vma->vm_file)) {
3543 ret = pret < 0 ? pret : -EFAULT;
3545 up_read(¤t->mm->mmap_sem);
3548 * if we did partial map, or found file backed vmas,
3549 * release any pages we did get
3552 put_user_pages(pages, pret);
3553 if (ctx->account_mem)
3554 io_unaccount_mem(ctx->user, nr_pages);
3559 off = ubuf & ~PAGE_MASK;
3561 for (j = 0; j < nr_pages; j++) {
3564 vec_len = min_t(size_t, size, PAGE_SIZE - off);
3565 imu->bvec[j].bv_page = pages[j];
3566 imu->bvec[j].bv_len = vec_len;
3567 imu->bvec[j].bv_offset = off;
3571 /* store original address for later verification */
3573 imu->len = iov.iov_len;
3574 imu->nr_bvecs = nr_pages;
3576 ctx->nr_user_bufs++;
3584 io_sqe_buffer_unregister(ctx);
3588 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
3590 __s32 __user *fds = arg;
3596 if (copy_from_user(&fd, fds, sizeof(*fds)))
3599 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
3600 if (IS_ERR(ctx->cq_ev_fd)) {
3601 int ret = PTR_ERR(ctx->cq_ev_fd);
3602 ctx->cq_ev_fd = NULL;
3609 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
3611 if (ctx->cq_ev_fd) {
3612 eventfd_ctx_put(ctx->cq_ev_fd);
3613 ctx->cq_ev_fd = NULL;
3620 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
3622 io_finish_async(ctx);
3624 mmdrop(ctx->sqo_mm);
3626 io_iopoll_reap_events(ctx);
3627 io_sqe_buffer_unregister(ctx);
3628 io_sqe_files_unregister(ctx);
3629 io_eventfd_unregister(ctx);
3631 #if defined(CONFIG_UNIX)
3632 if (ctx->ring_sock) {
3633 ctx->ring_sock->file = NULL; /* so that iput() is called */
3634 sock_release(ctx->ring_sock);
3638 io_mem_free(ctx->rings);
3639 io_mem_free(ctx->sq_sqes);
3641 percpu_ref_exit(&ctx->refs);
3642 if (ctx->account_mem)
3643 io_unaccount_mem(ctx->user,
3644 ring_pages(ctx->sq_entries, ctx->cq_entries));
3645 free_uid(ctx->user);
3647 put_cred(ctx->creds);
3651 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3653 struct io_ring_ctx *ctx = file->private_data;
3656 poll_wait(file, &ctx->cq_wait, wait);
3658 * synchronizes with barrier from wq_has_sleeper call in
3662 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
3663 ctx->rings->sq_ring_entries)
3664 mask |= EPOLLOUT | EPOLLWRNORM;
3665 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
3666 mask |= EPOLLIN | EPOLLRDNORM;
3671 static int io_uring_fasync(int fd, struct file *file, int on)
3673 struct io_ring_ctx *ctx = file->private_data;
3675 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3678 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3680 mutex_lock(&ctx->uring_lock);
3681 percpu_ref_kill(&ctx->refs);
3682 mutex_unlock(&ctx->uring_lock);
3684 io_kill_timeouts(ctx);
3685 io_poll_remove_all(ctx);
3686 io_iopoll_reap_events(ctx);
3687 wait_for_completion(&ctx->ctx_done);
3688 io_ring_ctx_free(ctx);
3691 static int io_uring_release(struct inode *inode, struct file *file)
3693 struct io_ring_ctx *ctx = file->private_data;
3695 file->private_data = NULL;
3696 io_ring_ctx_wait_and_kill(ctx);
3700 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3702 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3703 unsigned long sz = vma->vm_end - vma->vm_start;
3704 struct io_ring_ctx *ctx = file->private_data;
3710 case IORING_OFF_SQ_RING:
3711 case IORING_OFF_CQ_RING:
3714 case IORING_OFF_SQES:
3721 page = virt_to_head_page(ptr);
3722 if (sz > page_size(page))
3725 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3726 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3729 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3730 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3733 struct io_ring_ctx *ctx;
3738 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
3746 if (f.file->f_op != &io_uring_fops)
3750 ctx = f.file->private_data;
3751 if (!percpu_ref_tryget(&ctx->refs))
3755 * For SQ polling, the thread will do all submissions and completions.
3756 * Just return the requested submit count, and wake the thread if
3760 if (ctx->flags & IORING_SETUP_SQPOLL) {
3761 if (flags & IORING_ENTER_SQ_WAKEUP)
3762 wake_up(&ctx->sqo_wait);
3763 submitted = to_submit;
3764 } else if (to_submit) {
3765 to_submit = min(to_submit, ctx->sq_entries);
3767 mutex_lock(&ctx->uring_lock);
3768 submitted = io_ring_submit(ctx, to_submit);
3769 mutex_unlock(&ctx->uring_lock);
3771 if (submitted != to_submit)
3774 if (flags & IORING_ENTER_GETEVENTS) {
3775 unsigned nr_events = 0;
3777 min_complete = min(min_complete, ctx->cq_entries);
3779 if (ctx->flags & IORING_SETUP_IOPOLL) {
3780 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3782 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3787 percpu_ref_put(&ctx->refs);
3790 return submitted ? submitted : ret;
3793 static const struct file_operations io_uring_fops = {
3794 .release = io_uring_release,
3795 .mmap = io_uring_mmap,
3796 .poll = io_uring_poll,
3797 .fasync = io_uring_fasync,
3800 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3801 struct io_uring_params *p)
3803 struct io_rings *rings;
3804 size_t size, sq_array_offset;
3806 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
3807 if (size == SIZE_MAX)
3810 rings = io_mem_alloc(size);
3815 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3816 rings->sq_ring_mask = p->sq_entries - 1;
3817 rings->cq_ring_mask = p->cq_entries - 1;
3818 rings->sq_ring_entries = p->sq_entries;
3819 rings->cq_ring_entries = p->cq_entries;
3820 ctx->sq_mask = rings->sq_ring_mask;
3821 ctx->cq_mask = rings->cq_ring_mask;
3822 ctx->sq_entries = rings->sq_ring_entries;
3823 ctx->cq_entries = rings->cq_ring_entries;
3825 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3826 if (size == SIZE_MAX) {
3827 io_mem_free(ctx->rings);
3832 ctx->sq_sqes = io_mem_alloc(size);
3833 if (!ctx->sq_sqes) {
3834 io_mem_free(ctx->rings);
3843 * Allocate an anonymous fd, this is what constitutes the application
3844 * visible backing of an io_uring instance. The application mmaps this
3845 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3846 * we have to tie this fd to a socket for file garbage collection purposes.
3848 static int io_uring_get_fd(struct io_ring_ctx *ctx)
3853 #if defined(CONFIG_UNIX)
3854 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3860 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3864 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3865 O_RDWR | O_CLOEXEC);
3868 ret = PTR_ERR(file);
3872 #if defined(CONFIG_UNIX)
3873 ctx->ring_sock->file = file;
3874 ctx->ring_sock->sk->sk_user_data = ctx;
3876 fd_install(ret, file);
3879 #if defined(CONFIG_UNIX)
3880 sock_release(ctx->ring_sock);
3881 ctx->ring_sock = NULL;
3886 static int io_uring_create(unsigned entries, struct io_uring_params *p)
3888 struct user_struct *user = NULL;
3889 struct io_ring_ctx *ctx;
3893 if (!entries || entries > IORING_MAX_ENTRIES)
3897 * Use twice as many entries for the CQ ring. It's possible for the
3898 * application to drive a higher depth than the size of the SQ ring,
3899 * since the sqes are only used at submission time. This allows for
3900 * some flexibility in overcommitting a bit.
3902 p->sq_entries = roundup_pow_of_two(entries);
3903 p->cq_entries = 2 * p->sq_entries;
3905 user = get_uid(current_user());
3906 account_mem = !capable(CAP_IPC_LOCK);
3909 ret = io_account_mem(user,
3910 ring_pages(p->sq_entries, p->cq_entries));
3917 ctx = io_ring_ctx_alloc(p);
3920 io_unaccount_mem(user, ring_pages(p->sq_entries,
3925 ctx->compat = in_compat_syscall();
3926 ctx->account_mem = account_mem;
3929 ctx->creds = get_current_cred();
3935 ret = io_allocate_scq_urings(ctx, p);
3939 ret = io_sq_offload_start(ctx, p);
3943 memset(&p->sq_off, 0, sizeof(p->sq_off));
3944 p->sq_off.head = offsetof(struct io_rings, sq.head);
3945 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3946 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3947 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3948 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3949 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3950 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3952 memset(&p->cq_off, 0, sizeof(p->cq_off));
3953 p->cq_off.head = offsetof(struct io_rings, cq.head);
3954 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3955 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3956 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3957 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3958 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3961 * Install ring fd as the very last thing, so we don't risk someone
3962 * having closed it before we finish setup
3964 ret = io_uring_get_fd(ctx);
3968 p->features = IORING_FEAT_SINGLE_MMAP;
3971 io_ring_ctx_wait_and_kill(ctx);
3976 * Sets up an aio uring context, and returns the fd. Applications asks for a
3977 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3978 * params structure passed in.
3980 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3982 struct io_uring_params p;
3986 if (copy_from_user(&p, params, sizeof(p)))
3988 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3993 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3994 IORING_SETUP_SQ_AFF))
3997 ret = io_uring_create(entries, &p);
4001 if (copy_to_user(params, &p, sizeof(p)))
4007 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4008 struct io_uring_params __user *, params)
4010 return io_uring_setup(entries, params);
4013 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4014 void __user *arg, unsigned nr_args)
4015 __releases(ctx->uring_lock)
4016 __acquires(ctx->uring_lock)
4021 * We're inside the ring mutex, if the ref is already dying, then
4022 * someone else killed the ctx or is already going through
4023 * io_uring_register().
4025 if (percpu_ref_is_dying(&ctx->refs))
4028 percpu_ref_kill(&ctx->refs);
4031 * Drop uring mutex before waiting for references to exit. If another
4032 * thread is currently inside io_uring_enter() it might need to grab
4033 * the uring_lock to make progress. If we hold it here across the drain
4034 * wait, then we can deadlock. It's safe to drop the mutex here, since
4035 * no new references will come in after we've killed the percpu ref.
4037 mutex_unlock(&ctx->uring_lock);
4038 wait_for_completion(&ctx->ctx_done);
4039 mutex_lock(&ctx->uring_lock);
4042 case IORING_REGISTER_BUFFERS:
4043 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4045 case IORING_UNREGISTER_BUFFERS:
4049 ret = io_sqe_buffer_unregister(ctx);
4051 case IORING_REGISTER_FILES:
4052 ret = io_sqe_files_register(ctx, arg, nr_args);
4054 case IORING_UNREGISTER_FILES:
4058 ret = io_sqe_files_unregister(ctx);
4060 case IORING_REGISTER_EVENTFD:
4064 ret = io_eventfd_register(ctx, arg);
4066 case IORING_UNREGISTER_EVENTFD:
4070 ret = io_eventfd_unregister(ctx);
4077 /* bring the ctx back to life */
4078 reinit_completion(&ctx->ctx_done);
4079 percpu_ref_reinit(&ctx->refs);
4083 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4084 void __user *, arg, unsigned int, nr_args)
4086 struct io_ring_ctx *ctx;
4095 if (f.file->f_op != &io_uring_fops)
4098 ctx = f.file->private_data;
4100 mutex_lock(&ctx->uring_lock);
4101 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4102 mutex_unlock(&ctx->uring_lock);
4108 static int __init io_uring_init(void)
4110 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4113 __initcall(io_uring_init);