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;
271 struct list_head task_list;
272 spinlock_t task_lock;
276 const struct io_uring_sqe *sqe;
277 unsigned short index;
281 bool needs_fixed_file;
286 * First field must be the file pointer in all the
287 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
289 struct io_poll_iocb {
291 struct wait_queue_head *head;
295 struct wait_queue_entry wait;
300 struct hrtimer timer;
304 * NOTE! Each of the iocb union members has the file pointer
305 * as the first entry in their struct definition. So you can
306 * access the file pointer through any of the sub-structs,
307 * or directly as just 'ki_filp' in this struct.
313 struct io_poll_iocb poll;
314 struct io_timeout timeout;
317 struct sqe_submit submit;
319 struct io_ring_ctx *ctx;
320 struct list_head list;
321 struct list_head link_list;
324 #define REQ_F_NOWAIT 1 /* must not punt to workers */
325 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
326 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
327 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
328 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
329 #define REQ_F_IO_DRAINED 32 /* drain done */
330 #define REQ_F_LINK 64 /* linked sqes */
331 #define REQ_F_LINK_DONE 128 /* linked sqes done */
332 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
333 #define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
334 #define REQ_F_TIMEOUT 1024 /* timeout request */
335 #define REQ_F_ISREG 2048 /* regular file */
336 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
337 #define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
338 #define REQ_F_CANCEL 16384 /* cancel request */
343 struct files_struct *files;
345 struct fs_struct *fs;
347 struct work_struct work;
348 struct task_struct *work_task;
349 struct list_head task_list;
352 #define IO_PLUG_THRESHOLD 2
353 #define IO_IOPOLL_BATCH 8
355 struct io_submit_state {
356 struct blk_plug plug;
359 * io_kiocb alloc cache
361 void *reqs[IO_IOPOLL_BATCH];
362 unsigned int free_reqs;
363 unsigned int cur_req;
366 * File reference cache
370 unsigned int has_refs;
371 unsigned int used_refs;
372 unsigned int ios_left;
375 static void io_sq_wq_submit_work(struct work_struct *work);
376 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
378 static void __io_free_req(struct io_kiocb *req);
380 static struct kmem_cache *req_cachep;
382 static const struct file_operations io_uring_fops;
384 struct sock *io_uring_get_socket(struct file *file)
386 #if defined(CONFIG_UNIX)
387 if (file->f_op == &io_uring_fops) {
388 struct io_ring_ctx *ctx = file->private_data;
390 return ctx->ring_sock->sk;
395 EXPORT_SYMBOL(io_uring_get_socket);
397 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
399 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
401 complete(&ctx->ctx_done);
404 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
406 struct io_ring_ctx *ctx;
409 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
413 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
414 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
419 ctx->flags = p->flags;
420 init_waitqueue_head(&ctx->sqo_wait);
421 init_waitqueue_head(&ctx->cq_wait);
422 init_completion(&ctx->ctx_done);
423 init_completion(&ctx->sqo_thread_started);
424 mutex_init(&ctx->uring_lock);
425 init_waitqueue_head(&ctx->wait);
426 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
427 spin_lock_init(&ctx->pending_async[i].lock);
428 INIT_LIST_HEAD(&ctx->pending_async[i].list);
429 atomic_set(&ctx->pending_async[i].cnt, 0);
431 spin_lock_init(&ctx->completion_lock);
432 INIT_LIST_HEAD(&ctx->poll_list);
433 INIT_LIST_HEAD(&ctx->cancel_list);
434 INIT_LIST_HEAD(&ctx->defer_list);
435 INIT_LIST_HEAD(&ctx->timeout_list);
436 INIT_LIST_HEAD(&ctx->task_list);
437 spin_lock_init(&ctx->task_lock);
441 static void io_req_put_fs(struct io_kiocb *req)
443 struct fs_struct *fs = req->fs;
448 spin_lock(&req->fs->lock);
451 spin_unlock(&req->fs->lock);
457 static inline bool __io_sequence_defer(struct io_ring_ctx *ctx,
458 struct io_kiocb *req)
460 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
461 + atomic_read(&ctx->cached_cq_overflow);
464 static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
465 struct io_kiocb *req)
467 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
470 return __io_sequence_defer(ctx, req);
473 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
475 struct io_kiocb *req;
477 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
478 if (req && !io_sequence_defer(ctx, req)) {
479 list_del_init(&req->list);
486 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
488 struct io_kiocb *req;
490 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
492 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
494 if (!__io_sequence_defer(ctx, req)) {
495 list_del_init(&req->list);
503 static void __io_commit_cqring(struct io_ring_ctx *ctx)
505 struct io_rings *rings = ctx->rings;
507 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
508 /* order cqe stores with ring update */
509 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
511 if (wq_has_sleeper(&ctx->cq_wait)) {
512 wake_up_interruptible(&ctx->cq_wait);
513 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
518 static inline void io_queue_async_work(struct io_ring_ctx *ctx,
519 struct io_kiocb *req)
524 if (req->submit.sqe) {
525 switch (req->submit.opcode) {
526 case IORING_OP_WRITEV:
527 case IORING_OP_WRITE_FIXED:
528 rw = !(req->rw.ki_flags & IOCB_DIRECT);
533 if (req->work.func == io_sq_wq_submit_work) {
534 req->files = current->files;
536 spin_lock_irqsave(&ctx->task_lock, flags);
537 list_add(&req->task_list, &ctx->task_list);
538 req->work_task = NULL;
539 spin_unlock_irqrestore(&ctx->task_lock, flags);
542 queue_work(ctx->sqo_wq[rw], &req->work);
545 static void io_kill_timeout(struct io_kiocb *req)
549 ret = hrtimer_try_to_cancel(&req->timeout.timer);
551 atomic_inc(&req->ctx->cq_timeouts);
552 list_del(&req->list);
553 io_cqring_fill_event(req->ctx, req->user_data, 0);
554 if (refcount_dec_and_test(&req->refs))
559 static void io_kill_timeouts(struct io_ring_ctx *ctx)
561 struct io_kiocb *req, *tmp;
563 spin_lock_irq(&ctx->completion_lock);
564 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
565 io_kill_timeout(req);
566 spin_unlock_irq(&ctx->completion_lock);
569 static void io_commit_cqring(struct io_ring_ctx *ctx)
571 struct io_kiocb *req;
573 while ((req = io_get_timeout_req(ctx)) != NULL)
574 io_kill_timeout(req);
576 __io_commit_cqring(ctx);
578 while ((req = io_get_deferred_req(ctx)) != NULL) {
579 if (req->flags & REQ_F_SHADOW_DRAIN) {
580 /* Just for drain, free it. */
584 req->flags |= REQ_F_IO_DRAINED;
585 io_queue_async_work(ctx, req);
589 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
591 struct io_rings *rings = ctx->rings;
594 tail = ctx->cached_cq_tail;
596 * writes to the cq entry need to come after reading head; the
597 * control dependency is enough as we're using WRITE_ONCE to
600 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
603 ctx->cached_cq_tail++;
604 return &rings->cqes[tail & ctx->cq_mask];
607 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
610 struct io_uring_cqe *cqe;
613 * If we can't get a cq entry, userspace overflowed the
614 * submission (by quite a lot). Increment the overflow count in
617 cqe = io_get_cqring(ctx);
619 WRITE_ONCE(cqe->user_data, ki_user_data);
620 WRITE_ONCE(cqe->res, res);
621 WRITE_ONCE(cqe->flags, 0);
623 WRITE_ONCE(ctx->rings->cq_overflow,
624 atomic_inc_return(&ctx->cached_cq_overflow));
628 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
630 if (waitqueue_active(&ctx->wait))
632 if (waitqueue_active(&ctx->sqo_wait))
633 wake_up(&ctx->sqo_wait);
635 eventfd_signal(ctx->cq_ev_fd, 1);
638 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
643 spin_lock_irqsave(&ctx->completion_lock, flags);
644 io_cqring_fill_event(ctx, user_data, res);
645 io_commit_cqring(ctx);
646 spin_unlock_irqrestore(&ctx->completion_lock, flags);
648 io_cqring_ev_posted(ctx);
651 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
652 struct io_submit_state *state)
654 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
655 struct io_kiocb *req;
657 if (!percpu_ref_tryget(&ctx->refs))
661 req = kmem_cache_alloc(req_cachep, gfp);
664 } else if (!state->free_reqs) {
668 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
669 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
672 * Bulk alloc is all-or-nothing. If we fail to get a batch,
673 * retry single alloc to be on the safe side.
675 if (unlikely(ret <= 0)) {
676 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
681 state->free_reqs = ret - 1;
683 req = state->reqs[0];
685 req = state->reqs[state->cur_req];
690 INIT_LIST_HEAD(&req->task_list);
694 /* one is dropped after submission, the other at completion */
695 refcount_set(&req->refs, 2);
700 percpu_ref_put(&ctx->refs);
704 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
707 kmem_cache_free_bulk(req_cachep, *nr, reqs);
708 percpu_ref_put_many(&ctx->refs, *nr);
713 static void __io_free_req(struct io_kiocb *req)
716 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
718 percpu_ref_put(&req->ctx->refs);
719 kmem_cache_free(req_cachep, req);
722 static void io_req_link_next(struct io_kiocb *req)
724 struct io_kiocb *nxt;
727 * The list should never be empty when we are called here. But could
728 * potentially happen if the chain is messed up, check to be on the
731 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
733 list_del(&nxt->list);
734 if (!list_empty(&req->link_list)) {
735 INIT_LIST_HEAD(&nxt->link_list);
736 list_splice(&req->link_list, &nxt->link_list);
737 nxt->flags |= REQ_F_LINK;
740 nxt->flags |= REQ_F_LINK_DONE;
741 INIT_WORK(&nxt->work, io_sq_wq_submit_work);
742 io_queue_async_work(req->ctx, nxt);
747 * Called if REQ_F_LINK is set, and we fail the head request
749 static void io_fail_links(struct io_kiocb *req)
751 struct io_kiocb *link;
753 while (!list_empty(&req->link_list)) {
754 link = list_first_entry(&req->link_list, struct io_kiocb, list);
755 list_del(&link->list);
757 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
762 static void io_free_req(struct io_kiocb *req)
765 * If LINK is set, we have dependent requests in this chain. If we
766 * didn't fail this request, queue the first one up, moving any other
767 * dependencies to the next request. In case of failure, fail the rest
770 if (req->flags & REQ_F_LINK) {
771 if (req->flags & REQ_F_FAIL_LINK)
774 io_req_link_next(req);
780 static void io_put_req(struct io_kiocb *req)
782 if (refcount_dec_and_test(&req->refs))
786 static unsigned io_cqring_events(struct io_rings *rings)
788 /* See comment at the top of this file */
790 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
793 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
795 struct io_rings *rings = ctx->rings;
797 /* make sure SQ entry isn't read before tail */
798 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
802 * Find and free completed poll iocbs
804 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
805 struct list_head *done)
807 void *reqs[IO_IOPOLL_BATCH];
808 struct io_kiocb *req;
812 while (!list_empty(done)) {
813 req = list_first_entry(done, struct io_kiocb, list);
814 list_del(&req->list);
816 io_cqring_fill_event(ctx, req->user_data, req->result);
819 if (refcount_dec_and_test(&req->refs)) {
820 /* If we're not using fixed files, we have to pair the
821 * completion part with the file put. Use regular
822 * completions for those, only batch free for fixed
823 * file and non-linked commands.
825 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
827 reqs[to_free++] = req;
828 if (to_free == ARRAY_SIZE(reqs))
829 io_free_req_many(ctx, reqs, &to_free);
836 io_commit_cqring(ctx);
837 io_free_req_many(ctx, reqs, &to_free);
840 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
843 struct io_kiocb *req, *tmp;
849 * Only spin for completions if we don't have multiple devices hanging
850 * off our complete list, and we're under the requested amount.
852 spin = !ctx->poll_multi_file && *nr_events < min;
855 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
856 struct kiocb *kiocb = &req->rw;
859 * Move completed entries to our local list. If we find a
860 * request that requires polling, break out and complete
861 * the done list first, if we have entries there.
863 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
864 list_move_tail(&req->list, &done);
867 if (!list_empty(&done))
870 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
879 if (!list_empty(&done))
880 io_iopoll_complete(ctx, nr_events, &done);
886 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
887 * non-spinning poll check - we'll still enter the driver poll loop, but only
888 * as a non-spinning completion check.
890 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
893 while (!list_empty(&ctx->poll_list) && !need_resched()) {
896 ret = io_do_iopoll(ctx, nr_events, min);
899 if (!min || *nr_events >= min)
907 * We can't just wait for polled events to come to us, we have to actively
908 * find and complete them.
910 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
912 if (!(ctx->flags & IORING_SETUP_IOPOLL))
915 mutex_lock(&ctx->uring_lock);
916 while (!list_empty(&ctx->poll_list)) {
917 unsigned int nr_events = 0;
919 io_iopoll_getevents(ctx, &nr_events, 1);
922 * Ensure we allow local-to-the-cpu processing to take place,
923 * in this case we need to ensure that we reap all events.
927 mutex_unlock(&ctx->uring_lock);
930 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
933 int iters = 0, ret = 0;
936 * We disallow the app entering submit/complete with polling, but we
937 * still need to lock the ring to prevent racing with polled issue
938 * that got punted to a workqueue.
940 mutex_lock(&ctx->uring_lock);
945 * Don't enter poll loop if we already have events pending.
946 * If we do, we can potentially be spinning for commands that
947 * already triggered a CQE (eg in error).
949 if (io_cqring_events(ctx->rings))
953 * If a submit got punted to a workqueue, we can have the
954 * application entering polling for a command before it gets
955 * issued. That app will hold the uring_lock for the duration
956 * of the poll right here, so we need to take a breather every
957 * now and then to ensure that the issue has a chance to add
958 * the poll to the issued list. Otherwise we can spin here
959 * forever, while the workqueue is stuck trying to acquire the
962 if (!(++iters & 7)) {
963 mutex_unlock(&ctx->uring_lock);
964 mutex_lock(&ctx->uring_lock);
967 if (*nr_events < min)
968 tmin = min - *nr_events;
970 ret = io_iopoll_getevents(ctx, nr_events, tmin);
974 } while (min && !*nr_events && !need_resched());
976 mutex_unlock(&ctx->uring_lock);
980 static void kiocb_end_write(struct io_kiocb *req)
983 * Tell lockdep we inherited freeze protection from submission
986 if (req->flags & REQ_F_ISREG) {
987 struct inode *inode = file_inode(req->file);
989 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
991 file_end_write(req->file);
994 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
996 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
998 if (kiocb->ki_flags & IOCB_WRITE)
999 kiocb_end_write(req);
1001 if ((req->flags & REQ_F_LINK) && res != req->result)
1002 req->flags |= REQ_F_FAIL_LINK;
1003 io_cqring_add_event(req->ctx, req->user_data, res);
1007 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1009 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1011 if (kiocb->ki_flags & IOCB_WRITE)
1012 kiocb_end_write(req);
1014 if ((req->flags & REQ_F_LINK) && res != req->result)
1015 req->flags |= REQ_F_FAIL_LINK;
1018 req->flags |= REQ_F_IOPOLL_COMPLETED;
1022 * After the iocb has been issued, it's safe to be found on the poll list.
1023 * Adding the kiocb to the list AFTER submission ensures that we don't
1024 * find it from a io_iopoll_getevents() thread before the issuer is done
1025 * accessing the kiocb cookie.
1027 static void io_iopoll_req_issued(struct io_kiocb *req)
1029 struct io_ring_ctx *ctx = req->ctx;
1032 * Track whether we have multiple files in our lists. This will impact
1033 * how we do polling eventually, not spinning if we're on potentially
1034 * different devices.
1036 if (list_empty(&ctx->poll_list)) {
1037 ctx->poll_multi_file = false;
1038 } else if (!ctx->poll_multi_file) {
1039 struct io_kiocb *list_req;
1041 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1043 if (list_req->rw.ki_filp != req->rw.ki_filp)
1044 ctx->poll_multi_file = true;
1048 * For fast devices, IO may have already completed. If it has, add
1049 * it to the front so we find it first.
1051 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1052 list_add(&req->list, &ctx->poll_list);
1054 list_add_tail(&req->list, &ctx->poll_list);
1057 static void io_file_put(struct io_submit_state *state)
1060 int diff = state->has_refs - state->used_refs;
1063 fput_many(state->file, diff);
1069 * Get as many references to a file as we have IOs left in this submission,
1070 * assuming most submissions are for one file, or at least that each file
1071 * has more than one submission.
1073 static struct file *io_file_get(struct io_submit_state *state, int fd)
1079 if (state->fd == fd) {
1086 state->file = fget_many(fd, state->ios_left);
1091 state->has_refs = state->ios_left;
1092 state->used_refs = 1;
1098 * If we tracked the file through the SCM inflight mechanism, we could support
1099 * any file. For now, just ensure that anything potentially problematic is done
1102 static bool io_file_supports_async(struct file *file)
1104 umode_t mode = file_inode(file)->i_mode;
1106 if (S_ISBLK(mode) || S_ISCHR(mode))
1108 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1114 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
1115 bool force_nonblock)
1117 const struct io_uring_sqe *sqe = s->sqe;
1118 struct io_ring_ctx *ctx = req->ctx;
1119 struct kiocb *kiocb = &req->rw;
1126 if (S_ISREG(file_inode(req->file)->i_mode))
1127 req->flags |= REQ_F_ISREG;
1130 req->fsize = rlimit(RLIMIT_FSIZE);
1133 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1134 * we know to async punt it even if it was opened O_NONBLOCK
1136 if (force_nonblock && !io_file_supports_async(req->file)) {
1137 req->flags |= REQ_F_MUST_PUNT;
1141 kiocb->ki_pos = READ_ONCE(sqe->off);
1142 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1143 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1145 ioprio = READ_ONCE(sqe->ioprio);
1147 ret = ioprio_check_cap(ioprio);
1151 kiocb->ki_ioprio = ioprio;
1153 kiocb->ki_ioprio = get_current_ioprio();
1155 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1159 /* don't allow async punt if RWF_NOWAIT was requested */
1160 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1161 (req->file->f_flags & O_NONBLOCK))
1162 req->flags |= REQ_F_NOWAIT;
1165 kiocb->ki_flags |= IOCB_NOWAIT;
1167 if (ctx->flags & IORING_SETUP_IOPOLL) {
1168 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1169 !kiocb->ki_filp->f_op->iopoll)
1172 kiocb->ki_flags |= IOCB_HIPRI;
1173 kiocb->ki_complete = io_complete_rw_iopoll;
1176 if (kiocb->ki_flags & IOCB_HIPRI)
1178 kiocb->ki_complete = io_complete_rw;
1183 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1189 case -ERESTARTNOINTR:
1190 case -ERESTARTNOHAND:
1191 case -ERESTART_RESTARTBLOCK:
1193 * We can't just restart the syscall, since previously
1194 * submitted sqes may already be in progress. Just fail this
1200 kiocb->ki_complete(kiocb, ret, 0);
1204 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1205 const struct io_uring_sqe *sqe,
1206 struct iov_iter *iter)
1208 size_t len = READ_ONCE(sqe->len);
1209 struct io_mapped_ubuf *imu;
1210 unsigned index, buf_index;
1214 /* attempt to use fixed buffers without having provided iovecs */
1215 if (unlikely(!ctx->user_bufs))
1218 buf_index = READ_ONCE(sqe->buf_index);
1219 if (unlikely(buf_index >= ctx->nr_user_bufs))
1222 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1223 imu = &ctx->user_bufs[index];
1224 buf_addr = READ_ONCE(sqe->addr);
1227 if (buf_addr + len < buf_addr)
1229 /* not inside the mapped region */
1230 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1234 * May not be a start of buffer, set size appropriately
1235 * and advance us to the beginning.
1237 offset = buf_addr - imu->ubuf;
1238 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1242 * Don't use iov_iter_advance() here, as it's really slow for
1243 * using the latter parts of a big fixed buffer - it iterates
1244 * over each segment manually. We can cheat a bit here, because
1247 * 1) it's a BVEC iter, we set it up
1248 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1249 * first and last bvec
1251 * So just find our index, and adjust the iterator afterwards.
1252 * If the offset is within the first bvec (or the whole first
1253 * bvec, just use iov_iter_advance(). This makes it easier
1254 * since we can just skip the first segment, which may not
1255 * be PAGE_SIZE aligned.
1257 const struct bio_vec *bvec = imu->bvec;
1259 if (offset <= bvec->bv_len) {
1260 iov_iter_advance(iter, offset);
1262 unsigned long seg_skip;
1264 /* skip first vec */
1265 offset -= bvec->bv_len;
1266 seg_skip = 1 + (offset >> PAGE_SHIFT);
1268 iter->bvec = bvec + seg_skip;
1269 iter->nr_segs -= seg_skip;
1270 iter->count -= bvec->bv_len + offset;
1271 iter->iov_offset = offset & ~PAGE_MASK;
1278 static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1279 struct io_kiocb *req, struct iovec **iovec,
1280 struct iov_iter *iter)
1282 const struct io_uring_sqe *sqe = req->submit.sqe;
1283 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1284 size_t sqe_len = READ_ONCE(sqe->len);
1287 opcode = req->submit.opcode;
1288 if (opcode == IORING_OP_READ_FIXED ||
1289 opcode == IORING_OP_WRITE_FIXED) {
1290 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
1295 if (!req->submit.has_user)
1298 #ifdef CONFIG_COMPAT
1300 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1304 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1307 static inline bool io_should_merge(struct async_list *al, struct kiocb *kiocb)
1309 if (al->file == kiocb->ki_filp) {
1313 * Allow merging if we're anywhere in the range of the same
1314 * page. Generally this happens for sub-page reads or writes,
1315 * and it's beneficial to allow the first worker to bring the
1316 * page in and the piggy backed work can then work on the
1319 start = al->io_start & PAGE_MASK;
1320 end = (al->io_start + al->io_len + PAGE_SIZE - 1) & PAGE_MASK;
1321 if (kiocb->ki_pos >= start && kiocb->ki_pos <= end)
1330 * Make a note of the last file/offset/direction we punted to async
1331 * context. We'll use this information to see if we can piggy back a
1332 * sequential request onto the previous one, if it's still hasn't been
1333 * completed by the async worker.
1335 static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1337 struct async_list *async_list = &req->ctx->pending_async[rw];
1338 struct kiocb *kiocb = &req->rw;
1339 struct file *filp = kiocb->ki_filp;
1341 if (io_should_merge(async_list, kiocb)) {
1342 unsigned long max_bytes;
1344 /* Use 8x RA size as a decent limiter for both reads/writes */
1345 max_bytes = filp->f_ra.ra_pages << (PAGE_SHIFT + 3);
1347 max_bytes = VM_READAHEAD_PAGES << (PAGE_SHIFT + 3);
1349 /* If max len are exceeded, reset the state */
1350 if (async_list->io_len + len <= max_bytes) {
1351 req->flags |= REQ_F_SEQ_PREV;
1352 async_list->io_len += len;
1354 async_list->file = NULL;
1358 /* New file? Reset state. */
1359 if (async_list->file != filp) {
1360 async_list->io_start = kiocb->ki_pos;
1361 async_list->io_len = len;
1362 async_list->file = filp;
1367 * For files that don't have ->read_iter() and ->write_iter(), handle them
1368 * by looping over ->read() or ->write() manually.
1370 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1371 struct iov_iter *iter)
1376 * Don't support polled IO through this interface, and we can't
1377 * support non-blocking either. For the latter, this just causes
1378 * the kiocb to be handled from an async context.
1380 if (kiocb->ki_flags & IOCB_HIPRI)
1382 if (kiocb->ki_flags & IOCB_NOWAIT)
1385 while (iov_iter_count(iter)) {
1389 if (!iov_iter_is_bvec(iter)) {
1390 iovec = iov_iter_iovec(iter);
1392 /* fixed buffers import bvec */
1393 iovec.iov_base = kmap(iter->bvec->bv_page)
1395 iovec.iov_len = min(iter->count,
1396 iter->bvec->bv_len - iter->iov_offset);
1400 nr = file->f_op->read(file, iovec.iov_base,
1401 iovec.iov_len, &kiocb->ki_pos);
1403 nr = file->f_op->write(file, iovec.iov_base,
1404 iovec.iov_len, &kiocb->ki_pos);
1407 if (iov_iter_is_bvec(iter))
1408 kunmap(iter->bvec->bv_page);
1416 if (nr != iovec.iov_len)
1418 iov_iter_advance(iter, nr);
1424 static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1425 bool force_nonblock)
1427 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1428 struct kiocb *kiocb = &req->rw;
1429 struct iov_iter iter;
1432 ssize_t read_size, ret;
1434 ret = io_prep_rw(req, s, force_nonblock);
1437 file = kiocb->ki_filp;
1439 if (unlikely(!(file->f_mode & FMODE_READ)))
1442 ret = io_import_iovec(req->ctx, READ, req, &iovec, &iter);
1447 if (req->flags & REQ_F_LINK)
1448 req->result = read_size;
1450 iov_count = iov_iter_count(&iter);
1451 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1455 if (file->f_op->read_iter)
1456 ret2 = call_read_iter(file, kiocb, &iter);
1457 else if (req->file->f_op->read)
1458 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1463 * In case of a short read, punt to async. This can happen
1464 * if we have data partially cached. Alternatively we can
1465 * return the short read, in which case the application will
1466 * need to issue another SQE and wait for it. That SQE will
1467 * need async punt anyway, so it's more efficient to do it
1470 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1471 (req->flags & REQ_F_ISREG) &&
1472 ret2 > 0 && ret2 < read_size)
1474 /* Catch -EAGAIN return for forced non-blocking submission */
1475 if (!force_nonblock || ret2 != -EAGAIN) {
1476 io_rw_done(kiocb, ret2);
1479 * If ->needs_lock is true, we're already in async
1483 io_async_list_note(READ, req, iov_count);
1491 static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1492 bool force_nonblock)
1494 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1495 struct kiocb *kiocb = &req->rw;
1496 struct iov_iter iter;
1501 ret = io_prep_rw(req, s, force_nonblock);
1505 file = kiocb->ki_filp;
1506 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1509 ret = io_import_iovec(req->ctx, WRITE, req, &iovec, &iter);
1513 if (req->flags & REQ_F_LINK)
1516 iov_count = iov_iter_count(&iter);
1519 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1520 /* If ->needs_lock is true, we're already in async context. */
1522 io_async_list_note(WRITE, req, iov_count);
1526 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1531 * Open-code file_start_write here to grab freeze protection,
1532 * which will be released by another thread in
1533 * io_complete_rw(). Fool lockdep by telling it the lock got
1534 * released so that it doesn't complain about the held lock when
1535 * we return to userspace.
1537 if (req->flags & REQ_F_ISREG) {
1538 __sb_start_write(file_inode(file)->i_sb,
1539 SB_FREEZE_WRITE, true);
1540 __sb_writers_release(file_inode(file)->i_sb,
1543 kiocb->ki_flags |= IOCB_WRITE;
1545 if (!force_nonblock)
1546 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
1548 if (file->f_op->write_iter)
1549 ret2 = call_write_iter(file, kiocb, &iter);
1550 else if (req->file->f_op->write)
1551 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1555 if (!force_nonblock)
1556 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
1558 if (!force_nonblock || ret2 != -EAGAIN) {
1559 io_rw_done(kiocb, ret2);
1562 * If ->needs_lock is true, we're already in async
1566 io_async_list_note(WRITE, req, iov_count);
1576 * IORING_OP_NOP just posts a completion event, nothing else.
1578 static int io_nop(struct io_kiocb *req, u64 user_data)
1580 struct io_ring_ctx *ctx = req->ctx;
1583 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1586 io_cqring_add_event(ctx, user_data, err);
1591 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1593 struct io_ring_ctx *ctx = req->ctx;
1598 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1600 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1606 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1607 bool force_nonblock)
1609 loff_t sqe_off = READ_ONCE(sqe->off);
1610 loff_t sqe_len = READ_ONCE(sqe->len);
1611 loff_t end = sqe_off + sqe_len;
1612 unsigned fsync_flags;
1615 fsync_flags = READ_ONCE(sqe->fsync_flags);
1616 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1619 ret = io_prep_fsync(req, sqe);
1623 /* fsync always requires a blocking context */
1627 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1628 end > 0 ? end : LLONG_MAX,
1629 fsync_flags & IORING_FSYNC_DATASYNC);
1631 if (ret < 0 && (req->flags & REQ_F_LINK))
1632 req->flags |= REQ_F_FAIL_LINK;
1633 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1638 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1640 struct io_ring_ctx *ctx = req->ctx;
1646 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1648 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1654 static int io_sync_file_range(struct io_kiocb *req,
1655 const struct io_uring_sqe *sqe,
1656 bool force_nonblock)
1663 ret = io_prep_sfr(req, sqe);
1667 /* sync_file_range always requires a blocking context */
1671 sqe_off = READ_ONCE(sqe->off);
1672 sqe_len = READ_ONCE(sqe->len);
1673 flags = READ_ONCE(sqe->sync_range_flags);
1675 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1677 if (ret < 0 && (req->flags & REQ_F_LINK))
1678 req->flags |= REQ_F_FAIL_LINK;
1679 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1684 #if defined(CONFIG_NET)
1685 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1686 bool force_nonblock,
1687 long (*fn)(struct socket *, struct user_msghdr __user *,
1690 struct socket *sock;
1693 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1696 sock = sock_from_file(req->file, &ret);
1698 struct user_msghdr __user *msg;
1701 flags = READ_ONCE(sqe->msg_flags);
1702 if (flags & MSG_DONTWAIT)
1703 req->flags |= REQ_F_NOWAIT;
1704 else if (force_nonblock)
1705 flags |= MSG_DONTWAIT;
1707 #ifdef CONFIG_COMPAT
1708 if (req->ctx->compat)
1709 flags |= MSG_CMSG_COMPAT;
1712 msg = (struct user_msghdr __user *) (unsigned long)
1713 READ_ONCE(sqe->addr);
1715 ret = fn(sock, msg, flags);
1716 if (force_nonblock && ret == -EAGAIN)
1718 if (ret == -ERESTARTSYS)
1723 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1729 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1730 bool force_nonblock)
1732 #if defined(CONFIG_NET)
1733 return io_send_recvmsg(req, sqe, force_nonblock, __sys_sendmsg_sock);
1739 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1740 bool force_nonblock)
1742 #if defined(CONFIG_NET)
1743 return io_send_recvmsg(req, sqe, force_nonblock, __sys_recvmsg_sock);
1749 static void io_poll_remove_one(struct io_kiocb *req)
1751 struct io_poll_iocb *poll = &req->poll;
1753 spin_lock(&poll->head->lock);
1754 WRITE_ONCE(poll->canceled, true);
1755 if (!list_empty(&poll->wait.entry)) {
1756 list_del_init(&poll->wait.entry);
1757 io_queue_async_work(req->ctx, req);
1759 spin_unlock(&poll->head->lock);
1761 list_del_init(&req->list);
1764 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1766 struct io_kiocb *req;
1768 spin_lock_irq(&ctx->completion_lock);
1769 while (!list_empty(&ctx->cancel_list)) {
1770 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1771 io_poll_remove_one(req);
1773 spin_unlock_irq(&ctx->completion_lock);
1777 * Find a running poll command that matches one specified in sqe->addr,
1778 * and remove it if found.
1780 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1782 struct io_ring_ctx *ctx = req->ctx;
1783 struct io_kiocb *poll_req, *next;
1786 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1788 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1792 spin_lock_irq(&ctx->completion_lock);
1793 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1794 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1795 io_poll_remove_one(poll_req);
1800 spin_unlock_irq(&ctx->completion_lock);
1802 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1807 static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1810 req->poll.done = true;
1811 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
1812 io_commit_cqring(ctx);
1815 static void io_poll_complete_work(struct work_struct *work)
1817 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1818 struct io_poll_iocb *poll = &req->poll;
1819 struct poll_table_struct pt = { ._key = poll->events };
1820 struct io_ring_ctx *ctx = req->ctx;
1821 const struct cred *old_cred;
1824 old_cred = override_creds(ctx->creds);
1826 if (!READ_ONCE(poll->canceled))
1827 mask = vfs_poll(poll->file, &pt) & poll->events;
1830 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1831 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1832 * synchronize with them. In the cancellation case the list_del_init
1833 * itself is not actually needed, but harmless so we keep it in to
1834 * avoid further branches in the fast path.
1836 spin_lock_irq(&ctx->completion_lock);
1837 if (!mask && !READ_ONCE(poll->canceled)) {
1838 add_wait_queue(poll->head, &poll->wait);
1839 spin_unlock_irq(&ctx->completion_lock);
1842 list_del_init(&req->list);
1843 io_poll_complete(ctx, req, mask);
1844 spin_unlock_irq(&ctx->completion_lock);
1846 io_cqring_ev_posted(ctx);
1849 revert_creds(old_cred);
1852 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1855 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1857 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1858 struct io_ring_ctx *ctx = req->ctx;
1859 __poll_t mask = key_to_poll(key);
1860 unsigned long flags;
1862 /* for instances that support it check for an event match first: */
1863 if (mask && !(mask & poll->events))
1866 list_del_init(&poll->wait.entry);
1868 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1869 list_del(&req->list);
1870 io_poll_complete(ctx, req, mask);
1871 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1873 io_cqring_ev_posted(ctx);
1876 io_queue_async_work(ctx, req);
1882 struct io_poll_table {
1883 struct poll_table_struct pt;
1884 struct io_kiocb *req;
1888 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1889 struct poll_table_struct *p)
1891 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1893 if (unlikely(pt->req->poll.head)) {
1894 pt->error = -EINVAL;
1899 pt->req->poll.head = head;
1900 add_wait_queue(head, &pt->req->poll.wait);
1903 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1905 struct io_poll_iocb *poll = &req->poll;
1906 struct io_ring_ctx *ctx = req->ctx;
1907 struct io_poll_table ipt;
1908 bool cancel = false;
1912 if (req->file->f_op->may_pollfree)
1915 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1917 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1922 req->submit.sqe = NULL;
1923 INIT_WORK(&req->work, io_poll_complete_work);
1924 events = READ_ONCE(sqe->poll_events);
1925 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1929 poll->canceled = false;
1931 ipt.pt._qproc = io_poll_queue_proc;
1932 ipt.pt._key = poll->events;
1934 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1936 /* initialized the list so that we can do list_empty checks */
1937 INIT_LIST_HEAD(&poll->wait.entry);
1938 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1940 INIT_LIST_HEAD(&req->list);
1942 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1944 spin_lock_irq(&ctx->completion_lock);
1945 if (likely(poll->head)) {
1946 spin_lock(&poll->head->lock);
1947 if (unlikely(list_empty(&poll->wait.entry))) {
1953 if (mask || ipt.error)
1954 list_del_init(&poll->wait.entry);
1956 WRITE_ONCE(poll->canceled, true);
1957 else if (!poll->done) /* actually waiting for an event */
1958 list_add_tail(&req->list, &ctx->cancel_list);
1959 spin_unlock(&poll->head->lock);
1961 if (mask) { /* no async, we'd stolen it */
1963 io_poll_complete(ctx, req, mask);
1965 spin_unlock_irq(&ctx->completion_lock);
1968 io_cqring_ev_posted(ctx);
1974 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
1976 struct io_ring_ctx *ctx;
1977 struct io_kiocb *req, *prev;
1978 unsigned long flags;
1980 req = container_of(timer, struct io_kiocb, timeout.timer);
1982 atomic_inc(&ctx->cq_timeouts);
1984 spin_lock_irqsave(&ctx->completion_lock, flags);
1986 * Adjust the reqs sequence before the current one because it
1987 * will consume a slot in the cq_ring and the the cq_tail pointer
1988 * will be increased, otherwise other timeout reqs may return in
1989 * advance without waiting for enough wait_nr.
1992 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
1994 list_del(&req->list);
1996 io_cqring_fill_event(ctx, req->user_data, -ETIME);
1997 io_commit_cqring(ctx);
1998 spin_unlock_irqrestore(&ctx->completion_lock, flags);
2000 io_cqring_ev_posted(ctx);
2003 return HRTIMER_NORESTART;
2006 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2009 struct io_ring_ctx *ctx = req->ctx;
2010 struct list_head *entry;
2011 struct timespec64 ts;
2014 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2016 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->timeout_flags ||
2020 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
2023 req->flags |= REQ_F_TIMEOUT;
2026 * sqe->off holds how many events that need to occur for this
2027 * timeout event to be satisfied. If it isn't set, then this is
2028 * a pure timeout request, sequence isn't used.
2030 count = READ_ONCE(sqe->off);
2032 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2033 spin_lock_irq(&ctx->completion_lock);
2034 entry = ctx->timeout_list.prev;
2038 req->sequence = ctx->cached_sq_head + count - 1;
2039 /* reuse it to store the count */
2040 req->submit.sequence = count;
2043 * Insertion sort, ensuring the first entry in the list is always
2044 * the one we need first.
2046 spin_lock_irq(&ctx->completion_lock);
2047 list_for_each_prev(entry, &ctx->timeout_list) {
2048 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2049 unsigned nxt_sq_head;
2050 long long tmp, tmp_nxt;
2052 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2056 * Since cached_sq_head + count - 1 can overflow, use type long
2059 tmp = (long long)ctx->cached_sq_head + count - 1;
2060 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
2061 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
2064 * cached_sq_head may overflow, and it will never overflow twice
2065 * once there is some timeout req still be valid.
2067 if (ctx->cached_sq_head < nxt_sq_head)
2074 * Sequence of reqs after the insert one and itself should
2075 * be adjusted because each timeout req consumes a slot.
2080 req->sequence -= span;
2082 list_add(&req->list, entry);
2084 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2085 req->timeout.timer.function = io_timeout_fn;
2086 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts),
2088 spin_unlock_irq(&ctx->completion_lock);
2092 static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
2093 struct sqe_submit *s)
2095 struct io_uring_sqe *sqe_copy;
2097 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
2100 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2104 spin_lock_irq(&ctx->completion_lock);
2105 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
2106 spin_unlock_irq(&ctx->completion_lock);
2111 memcpy(&req->submit, s, sizeof(*s));
2112 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
2113 req->submit.sqe = sqe_copy;
2115 INIT_WORK(&req->work, io_sq_wq_submit_work);
2116 list_add_tail(&req->list, &ctx->defer_list);
2117 spin_unlock_irq(&ctx->completion_lock);
2118 return -EIOCBQUEUED;
2121 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2122 const struct sqe_submit *s, bool force_nonblock)
2126 req->user_data = READ_ONCE(s->sqe->user_data);
2128 if (unlikely(s->index >= ctx->sq_entries))
2131 switch (req->submit.opcode) {
2133 ret = io_nop(req, req->user_data);
2135 case IORING_OP_READV:
2136 if (unlikely(s->sqe->buf_index))
2138 ret = io_read(req, s, force_nonblock);
2140 case IORING_OP_WRITEV:
2141 if (unlikely(s->sqe->buf_index))
2143 ret = io_write(req, s, force_nonblock);
2145 case IORING_OP_READ_FIXED:
2146 ret = io_read(req, s, force_nonblock);
2148 case IORING_OP_WRITE_FIXED:
2149 ret = io_write(req, s, force_nonblock);
2151 case IORING_OP_FSYNC:
2152 ret = io_fsync(req, s->sqe, force_nonblock);
2154 case IORING_OP_POLL_ADD:
2155 ret = io_poll_add(req, s->sqe);
2157 case IORING_OP_POLL_REMOVE:
2158 ret = io_poll_remove(req, s->sqe);
2160 case IORING_OP_SYNC_FILE_RANGE:
2161 ret = io_sync_file_range(req, s->sqe, force_nonblock);
2163 case IORING_OP_SENDMSG:
2164 ret = io_sendmsg(req, s->sqe, force_nonblock);
2166 case IORING_OP_RECVMSG:
2167 ret = io_recvmsg(req, s->sqe, force_nonblock);
2169 case IORING_OP_TIMEOUT:
2170 ret = io_timeout(req, s->sqe);
2180 if (ctx->flags & IORING_SETUP_IOPOLL) {
2181 if (req->result == -EAGAIN)
2184 /* workqueue context doesn't hold uring_lock, grab it now */
2186 mutex_lock(&ctx->uring_lock);
2187 io_iopoll_req_issued(req);
2189 mutex_unlock(&ctx->uring_lock);
2195 static struct async_list *io_async_list_from_req(struct io_ring_ctx *ctx,
2196 struct io_kiocb *req)
2198 switch (req->submit.opcode) {
2199 case IORING_OP_READV:
2200 case IORING_OP_READ_FIXED:
2201 return &ctx->pending_async[READ];
2202 case IORING_OP_WRITEV:
2203 case IORING_OP_WRITE_FIXED:
2204 return &ctx->pending_async[WRITE];
2210 static inline bool io_req_needs_user(struct io_kiocb *req)
2212 return !(req->submit.opcode == IORING_OP_READ_FIXED ||
2213 req->submit.opcode == IORING_OP_WRITE_FIXED);
2216 static void io_sq_wq_submit_work(struct work_struct *work)
2218 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2219 struct fs_struct *old_fs_struct = current->fs;
2220 struct io_ring_ctx *ctx = req->ctx;
2221 struct mm_struct *cur_mm = NULL;
2222 struct async_list *async_list;
2223 const struct cred *old_cred;
2224 LIST_HEAD(req_list);
2225 mm_segment_t old_fs;
2228 old_cred = override_creds(ctx->creds);
2229 async_list = io_async_list_from_req(ctx, req);
2231 allow_kernel_signal(SIGINT);
2234 struct sqe_submit *s = &req->submit;
2235 const struct io_uring_sqe *sqe = s->sqe;
2236 unsigned int flags = req->flags;
2238 /* Ensure we clear previously set non-block flag */
2239 req->rw.ki_flags &= ~IOCB_NOWAIT;
2241 if ((req->fs && req->fs != current->fs) ||
2242 (!req->fs && current->fs != old_fs_struct)) {
2245 current->fs = req->fs;
2247 current->fs = old_fs_struct;
2248 task_unlock(current);
2252 if (io_req_needs_user(req) && !cur_mm) {
2253 if (!mmget_not_zero(ctx->sqo_mm)) {
2257 cur_mm = ctx->sqo_mm;
2265 req->work_task = current;
2268 * Pairs with the smp_store_mb() (B) in
2269 * io_cancel_async_work().
2272 if (req->flags & REQ_F_CANCEL) {
2277 s->has_user = cur_mm != NULL;
2278 s->needs_lock = true;
2280 ret = __io_submit_sqe(ctx, req, s, false);
2282 * We can get EAGAIN for polled IO even though
2283 * we're forcing a sync submission from here,
2284 * since we can't wait for request slots on the
2293 spin_lock_irq(&ctx->task_lock);
2294 list_del_init(&req->task_list);
2295 spin_unlock_irq(&ctx->task_lock);
2297 /* drop submission reference */
2301 io_cqring_add_event(ctx, sqe->user_data, ret);
2305 /* async context always use a copy of the sqe */
2308 /* req from defer and link list needn't decrease async cnt */
2309 if (flags & (REQ_F_IO_DRAINED | REQ_F_LINK_DONE))
2314 if (!list_empty(&req_list)) {
2315 req = list_first_entry(&req_list, struct io_kiocb,
2317 list_del(&req->list);
2320 if (list_empty(&async_list->list))
2324 spin_lock(&async_list->lock);
2325 if (list_empty(&async_list->list)) {
2326 spin_unlock(&async_list->lock);
2329 list_splice_init(&async_list->list, &req_list);
2330 spin_unlock(&async_list->lock);
2332 req = list_first_entry(&req_list, struct io_kiocb, list);
2333 list_del(&req->list);
2337 * Rare case of racing with a submitter. If we find the count has
2338 * dropped to zero AND we have pending work items, then restart
2339 * the processing. This is a tiny race window.
2342 ret = atomic_dec_return(&async_list->cnt);
2343 while (!ret && !list_empty(&async_list->list)) {
2344 spin_lock(&async_list->lock);
2345 atomic_inc(&async_list->cnt);
2346 list_splice_init(&async_list->list, &req_list);
2347 spin_unlock(&async_list->lock);
2349 if (!list_empty(&req_list)) {
2350 req = list_first_entry(&req_list,
2351 struct io_kiocb, list);
2352 list_del(&req->list);
2355 ret = atomic_dec_return(&async_list->cnt);
2360 disallow_signal(SIGINT);
2366 revert_creds(old_cred);
2367 if (old_fs_struct != current->fs) {
2369 current->fs = old_fs_struct;
2370 task_unlock(current);
2375 * See if we can piggy back onto previously submitted work, that is still
2376 * running. We currently only allow this if the new request is sequential
2377 * to the previous one we punted.
2379 static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
2385 if (!(req->flags & REQ_F_SEQ_PREV))
2387 if (!atomic_read(&list->cnt))
2391 spin_lock(&list->lock);
2392 list_add_tail(&req->list, &list->list);
2394 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2397 if (!atomic_read(&list->cnt)) {
2398 list_del_init(&req->list);
2403 struct io_ring_ctx *ctx = req->ctx;
2405 req->files = current->files;
2407 spin_lock_irq(&ctx->task_lock);
2408 list_add(&req->task_list, &ctx->task_list);
2409 req->work_task = NULL;
2410 spin_unlock_irq(&ctx->task_lock);
2412 spin_unlock(&list->lock);
2416 static bool io_op_needs_file(struct io_kiocb *req)
2418 switch (req->submit.opcode) {
2420 case IORING_OP_POLL_REMOVE:
2421 case IORING_OP_TIMEOUT:
2428 static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
2429 struct io_submit_state *state, struct io_kiocb *req)
2434 flags = READ_ONCE(s->sqe->flags);
2435 fd = READ_ONCE(s->sqe->fd);
2437 if (flags & IOSQE_IO_DRAIN)
2438 req->flags |= REQ_F_IO_DRAIN;
2440 * All io need record the previous position, if LINK vs DARIN,
2441 * it can be used to mark the position of the first IO in the
2444 req->sequence = s->sequence;
2446 if (!io_op_needs_file(req))
2449 if (flags & IOSQE_FIXED_FILE) {
2450 if (unlikely(!ctx->user_files ||
2451 (unsigned) fd >= ctx->nr_user_files))
2453 req->file = ctx->user_files[fd];
2454 req->flags |= REQ_F_FIXED_FILE;
2456 if (s->needs_fixed_file)
2458 req->file = io_file_get(state, fd);
2459 if (unlikely(!req->file))
2466 static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2467 struct sqe_submit *s)
2471 ret = __io_submit_sqe(ctx, req, s, true);
2474 * We async punt it if the file wasn't marked NOWAIT, or if the file
2475 * doesn't support non-blocking read/write attempts
2477 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2478 (req->flags & REQ_F_MUST_PUNT))) {
2479 struct io_uring_sqe *sqe_copy;
2481 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2483 struct async_list *list;
2486 memcpy(&req->submit, s, sizeof(*s));
2487 list = io_async_list_from_req(ctx, req);
2488 if (!io_add_to_prev_work(list, req)) {
2490 atomic_inc(&list->cnt);
2491 INIT_WORK(&req->work, io_sq_wq_submit_work);
2492 io_queue_async_work(ctx, req);
2496 * Queued up for async execution, worker will release
2497 * submit reference when the iocb is actually submitted.
2503 /* drop submission reference */
2506 /* and drop final reference, if we failed */
2508 io_cqring_add_event(ctx, req->user_data, ret);
2509 if (req->flags & REQ_F_LINK)
2510 req->flags |= REQ_F_FAIL_LINK;
2517 static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2518 struct sqe_submit *s)
2522 ret = io_req_defer(ctx, req, s);
2524 if (ret != -EIOCBQUEUED) {
2526 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2531 return __io_queue_sqe(ctx, req, s);
2534 static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
2535 struct sqe_submit *s, struct io_kiocb *shadow)
2538 int need_submit = false;
2541 return io_queue_sqe(ctx, req, s);
2544 * Mark the first IO in link list as DRAIN, let all the following
2545 * IOs enter the defer list. all IO needs to be completed before link
2548 req->flags |= REQ_F_IO_DRAIN;
2549 ret = io_req_defer(ctx, req, s);
2551 if (ret != -EIOCBQUEUED) {
2553 __io_free_req(shadow);
2554 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2559 * If ret == 0 means that all IOs in front of link io are
2560 * running done. let's queue link head.
2565 /* Insert shadow req to defer_list, blocking next IOs */
2566 spin_lock_irq(&ctx->completion_lock);
2567 list_add_tail(&shadow->list, &ctx->defer_list);
2568 spin_unlock_irq(&ctx->completion_lock);
2571 return __io_queue_sqe(ctx, req, s);
2576 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2578 static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
2579 struct io_submit_state *state, struct io_kiocb **link)
2581 struct io_uring_sqe *sqe_copy;
2582 struct io_kiocb *req;
2585 /* enforce forwards compatibility on users */
2586 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2591 req = io_get_req(ctx, state);
2592 if (unlikely(!req)) {
2597 memcpy(&req->submit, s, sizeof(*s));
2598 ret = io_req_set_file(ctx, s, state, req);
2599 if (unlikely(ret)) {
2603 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2607 req->user_data = s->sqe->user_data;
2609 #if defined(CONFIG_NET)
2610 switch (req->submit.opcode) {
2611 case IORING_OP_SENDMSG:
2612 case IORING_OP_RECVMSG:
2613 spin_lock(¤t->fs->lock);
2614 if (!current->fs->in_exec) {
2615 req->fs = current->fs;
2618 spin_unlock(¤t->fs->lock);
2627 * If we already have a head request, queue this one for async
2628 * submittal once the head completes. If we don't have a head but
2629 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2630 * submitted sync once the chain is complete. If none of those
2631 * conditions are true (normal request), then just queue it.
2634 struct io_kiocb *prev = *link;
2636 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2643 memcpy(&req->submit, s, sizeof(*s));
2644 list_add_tail(&req->list, &prev->link_list);
2645 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2646 req->flags |= REQ_F_LINK;
2648 memcpy(&req->submit, s, sizeof(*s));
2649 INIT_LIST_HEAD(&req->link_list);
2652 io_queue_sqe(ctx, req, s);
2657 * Batched submission is done, ensure local IO is flushed out.
2659 static void io_submit_state_end(struct io_submit_state *state)
2661 blk_finish_plug(&state->plug);
2663 if (state->free_reqs)
2664 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2665 &state->reqs[state->cur_req]);
2669 * Start submission side cache.
2671 static void io_submit_state_start(struct io_submit_state *state,
2672 struct io_ring_ctx *ctx, unsigned max_ios)
2674 blk_start_plug(&state->plug);
2675 state->free_reqs = 0;
2677 state->ios_left = max_ios;
2680 static void io_commit_sqring(struct io_ring_ctx *ctx)
2682 struct io_rings *rings = ctx->rings;
2684 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2686 * Ensure any loads from the SQEs are done at this point,
2687 * since once we write the new head, the application could
2688 * write new data to them.
2690 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2695 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2696 * that is mapped by userspace. This means that care needs to be taken to
2697 * ensure that reads are stable, as we cannot rely on userspace always
2698 * being a good citizen. If members of the sqe are validated and then later
2699 * used, it's important that those reads are done through READ_ONCE() to
2700 * prevent a re-load down the line.
2702 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2704 struct io_rings *rings = ctx->rings;
2705 u32 *sq_array = ctx->sq_array;
2709 * The cached sq head (or cq tail) serves two purposes:
2711 * 1) allows us to batch the cost of updating the user visible
2713 * 2) allows the kernel side to track the head on its own, even
2714 * though the application is the one updating it.
2716 head = ctx->cached_sq_head;
2717 /* make sure SQ entry isn't read before tail */
2718 if (head == smp_load_acquire(&rings->sq.tail))
2721 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2722 if (head < ctx->sq_entries) {
2724 s->sqe = &ctx->sq_sqes[head];
2725 s->opcode = READ_ONCE(s->sqe->opcode);
2726 s->sequence = ctx->cached_sq_head;
2727 ctx->cached_sq_head++;
2731 /* drop invalid entries */
2732 ctx->cached_sq_head++;
2733 ctx->cached_sq_dropped++;
2734 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
2738 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
2739 bool has_user, bool mm_fault)
2741 struct io_submit_state state, *statep = NULL;
2742 struct io_kiocb *link = NULL;
2743 struct io_kiocb *shadow_req = NULL;
2744 bool prev_was_link = false;
2745 int i, submitted = 0;
2747 if (nr > IO_PLUG_THRESHOLD) {
2748 io_submit_state_start(&state, ctx, nr);
2752 for (i = 0; i < nr; i++) {
2753 struct sqe_submit s;
2755 if (!io_get_sqring(ctx, &s))
2759 * If previous wasn't linked and we have a linked command,
2760 * that's the end of the chain. Submit the previous link.
2762 if (!prev_was_link && link) {
2763 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2767 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2769 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2771 shadow_req = io_get_req(ctx, NULL);
2772 if (unlikely(!shadow_req))
2774 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2775 refcount_dec(&shadow_req->refs);
2777 shadow_req->sequence = s.sequence;
2781 if (unlikely(mm_fault)) {
2782 io_cqring_add_event(ctx, s.sqe->user_data,
2785 s.has_user = has_user;
2786 s.needs_lock = true;
2787 s.needs_fixed_file = true;
2788 io_submit_sqe(ctx, &s, statep, &link);
2794 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2796 io_submit_state_end(&state);
2801 static int io_sq_thread(void *data)
2803 struct io_ring_ctx *ctx = data;
2804 struct mm_struct *cur_mm = NULL;
2805 const struct cred *old_cred;
2806 mm_segment_t old_fs;
2809 unsigned long timeout;
2811 complete(&ctx->sqo_thread_started);
2815 old_cred = override_creds(ctx->creds);
2817 timeout = inflight = 0;
2818 while (!kthread_should_park()) {
2819 bool mm_fault = false;
2820 unsigned int to_submit;
2823 unsigned nr_events = 0;
2825 if (ctx->flags & IORING_SETUP_IOPOLL) {
2827 * inflight is the count of the maximum possible
2828 * entries we submitted, but it can be smaller
2829 * if we dropped some of them. If we don't have
2830 * poll entries available, then we know that we
2831 * have nothing left to poll for. Reset the
2832 * inflight count to zero in that case.
2834 mutex_lock(&ctx->uring_lock);
2835 if (!list_empty(&ctx->poll_list))
2836 io_iopoll_getevents(ctx, &nr_events, 0);
2839 mutex_unlock(&ctx->uring_lock);
2842 * Normal IO, just pretend everything completed.
2843 * We don't have to poll completions for that.
2845 nr_events = inflight;
2848 inflight -= nr_events;
2850 timeout = jiffies + ctx->sq_thread_idle;
2853 to_submit = io_sqring_entries(ctx);
2856 * Drop cur_mm before scheduling, we can't hold it for
2857 * long periods (or over schedule()). Do this before
2858 * adding ourselves to the waitqueue, as the unuse/drop
2868 * We're polling. If we're within the defined idle
2869 * period, then let us spin without work before going
2872 if (inflight || !time_after(jiffies, timeout)) {
2877 prepare_to_wait(&ctx->sqo_wait, &wait,
2878 TASK_INTERRUPTIBLE);
2880 /* Tell userspace we may need a wakeup call */
2881 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
2882 /* make sure to read SQ tail after writing flags */
2885 to_submit = io_sqring_entries(ctx);
2887 if (kthread_should_park()) {
2888 finish_wait(&ctx->sqo_wait, &wait);
2891 if (signal_pending(current))
2892 flush_signals(current);
2894 finish_wait(&ctx->sqo_wait, &wait);
2896 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2899 finish_wait(&ctx->sqo_wait, &wait);
2901 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2904 /* Unless all new commands are FIXED regions, grab mm */
2906 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2908 use_mm(ctx->sqo_mm);
2909 cur_mm = ctx->sqo_mm;
2913 to_submit = min(to_submit, ctx->sq_entries);
2914 inflight += io_submit_sqes(ctx, to_submit, cur_mm != NULL,
2917 /* Commit SQ ring head once we've consumed all SQEs */
2918 io_commit_sqring(ctx);
2926 revert_creds(old_cred);
2933 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2935 struct io_submit_state state, *statep = NULL;
2936 struct io_kiocb *link = NULL;
2937 struct io_kiocb *shadow_req = NULL;
2938 bool prev_was_link = false;
2941 if (to_submit > IO_PLUG_THRESHOLD) {
2942 io_submit_state_start(&state, ctx, to_submit);
2946 for (i = 0; i < to_submit; i++) {
2947 struct sqe_submit s;
2949 if (!io_get_sqring(ctx, &s))
2953 * If previous wasn't linked and we have a linked command,
2954 * that's the end of the chain. Submit the previous link.
2956 if (!prev_was_link && link) {
2957 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2961 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2963 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2965 shadow_req = io_get_req(ctx, NULL);
2966 if (unlikely(!shadow_req))
2968 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2969 refcount_dec(&shadow_req->refs);
2971 shadow_req->sequence = s.sequence;
2976 s.needs_lock = false;
2977 s.needs_fixed_file = false;
2979 io_submit_sqe(ctx, &s, statep, &link);
2983 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2985 io_submit_state_end(statep);
2987 io_commit_sqring(ctx);
2992 struct io_wait_queue {
2993 struct wait_queue_entry wq;
2994 struct io_ring_ctx *ctx;
2996 unsigned nr_timeouts;
2999 static inline bool io_should_wake(struct io_wait_queue *iowq)
3001 struct io_ring_ctx *ctx = iowq->ctx;
3004 * Wake up if we have enough events, or if a timeout occured since we
3005 * started waiting. For timeouts, we always want to return to userspace,
3006 * regardless of event count.
3008 return io_cqring_events(ctx->rings) >= iowq->to_wait ||
3009 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
3012 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
3013 int wake_flags, void *key)
3015 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3018 if (!io_should_wake(iowq))
3021 return autoremove_wake_function(curr, mode, wake_flags, key);
3025 * Wait until events become available, if we don't already have some. The
3026 * application must reap them itself, as they reside on the shared cq ring.
3028 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3029 const sigset_t __user *sig, size_t sigsz)
3031 struct io_wait_queue iowq = {
3034 .func = io_wake_function,
3035 .entry = LIST_HEAD_INIT(iowq.wq.entry),
3038 .to_wait = min_events,
3040 struct io_rings *rings = ctx->rings;
3043 if (io_cqring_events(rings) >= min_events)
3047 #ifdef CONFIG_COMPAT
3048 if (in_compat_syscall())
3049 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3053 ret = set_user_sigmask(sig, sigsz);
3060 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3062 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3063 TASK_INTERRUPTIBLE);
3064 if (io_should_wake(&iowq))
3067 if (signal_pending(current)) {
3072 finish_wait(&ctx->wait, &iowq.wq);
3074 restore_saved_sigmask_unless(ret == -ERESTARTSYS);
3075 if (ret == -ERESTARTSYS)
3078 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3081 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3083 #if defined(CONFIG_UNIX)
3084 if (ctx->ring_sock) {
3085 struct sock *sock = ctx->ring_sock->sk;
3086 struct sk_buff *skb;
3088 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3094 for (i = 0; i < ctx->nr_user_files; i++)
3095 fput(ctx->user_files[i]);
3099 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3101 if (!ctx->user_files)
3104 __io_sqe_files_unregister(ctx);
3105 kfree(ctx->user_files);
3106 ctx->user_files = NULL;
3107 ctx->nr_user_files = 0;
3111 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3113 if (ctx->sqo_thread) {
3114 wait_for_completion(&ctx->sqo_thread_started);
3116 * The park is a bit of a work-around, without it we get
3117 * warning spews on shutdown with SQPOLL set and affinity
3118 * set to a single CPU.
3120 kthread_park(ctx->sqo_thread);
3121 kthread_stop(ctx->sqo_thread);
3122 ctx->sqo_thread = NULL;
3126 static void io_finish_async(struct io_ring_ctx *ctx)
3130 io_sq_thread_stop(ctx);
3132 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++) {
3133 if (ctx->sqo_wq[i]) {
3134 destroy_workqueue(ctx->sqo_wq[i]);
3135 ctx->sqo_wq[i] = NULL;
3140 #if defined(CONFIG_UNIX)
3141 static void io_destruct_skb(struct sk_buff *skb)
3143 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
3146 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++)
3148 flush_workqueue(ctx->sqo_wq[i]);
3150 unix_destruct_scm(skb);
3154 * Ensure the UNIX gc is aware of our file set, so we are certain that
3155 * the io_uring can be safely unregistered on process exit, even if we have
3156 * loops in the file referencing.
3158 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3160 struct sock *sk = ctx->ring_sock->sk;
3161 struct scm_fp_list *fpl;
3162 struct sk_buff *skb;
3165 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3169 skb = alloc_skb(0, GFP_KERNEL);
3176 skb->scm_io_uring = 1;
3177 skb->destructor = io_destruct_skb;
3179 fpl->user = get_uid(ctx->user);
3180 for (i = 0; i < nr; i++) {
3181 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
3182 unix_inflight(fpl->user, fpl->fp[i]);
3185 fpl->max = fpl->count = nr;
3186 UNIXCB(skb).fp = fpl;
3187 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3188 skb_queue_head(&sk->sk_receive_queue, skb);
3190 for (i = 0; i < nr; i++)
3197 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3198 * causes regular reference counting to break down. We rely on the UNIX
3199 * garbage collection to take care of this problem for us.
3201 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3203 unsigned left, total;
3207 left = ctx->nr_user_files;
3209 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
3211 ret = __io_sqe_files_scm(ctx, this_files, total);
3215 total += this_files;
3221 while (total < ctx->nr_user_files) {
3222 fput(ctx->user_files[total]);
3229 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3235 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3238 __s32 __user *fds = (__s32 __user *) arg;
3242 if (ctx->user_files)
3246 if (nr_args > IORING_MAX_FIXED_FILES)
3249 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
3250 if (!ctx->user_files)
3253 for (i = 0; i < nr_args; i++) {
3255 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3258 ctx->user_files[i] = fget(fd);
3261 if (!ctx->user_files[i])
3264 * Don't allow io_uring instances to be registered. If UNIX
3265 * isn't enabled, then this causes a reference cycle and this
3266 * instance can never get freed. If UNIX is enabled we'll
3267 * handle it just fine, but there's still no point in allowing
3268 * a ring fd as it doesn't support regular read/write anyway.
3270 if (ctx->user_files[i]->f_op == &io_uring_fops) {
3271 fput(ctx->user_files[i]);
3274 ctx->nr_user_files++;
3279 for (i = 0; i < ctx->nr_user_files; i++)
3280 fput(ctx->user_files[i]);
3282 kfree(ctx->user_files);
3283 ctx->user_files = NULL;
3284 ctx->nr_user_files = 0;
3288 ret = io_sqe_files_scm(ctx);
3290 io_sqe_files_unregister(ctx);
3295 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3296 struct io_uring_params *p)
3300 mmgrab(current->mm);
3301 ctx->sqo_mm = current->mm;
3303 if (ctx->flags & IORING_SETUP_SQPOLL) {
3305 if (!capable(CAP_SYS_ADMIN))
3308 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3309 if (!ctx->sq_thread_idle)
3310 ctx->sq_thread_idle = HZ;
3312 if (p->flags & IORING_SETUP_SQ_AFF) {
3313 int cpu = p->sq_thread_cpu;
3316 if (cpu >= nr_cpu_ids)
3318 if (!cpu_online(cpu))
3321 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3325 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3328 if (IS_ERR(ctx->sqo_thread)) {
3329 ret = PTR_ERR(ctx->sqo_thread);
3330 ctx->sqo_thread = NULL;
3333 wake_up_process(ctx->sqo_thread);
3334 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3335 /* Can't have SQ_AFF without SQPOLL */
3340 /* Do QD, or 2 * CPUS, whatever is smallest */
3341 ctx->sqo_wq[0] = alloc_workqueue("io_ring-wq",
3342 WQ_UNBOUND | WQ_FREEZABLE,
3343 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
3344 if (!ctx->sqo_wq[0]) {
3350 * This is for buffered writes, where we want to limit the parallelism
3351 * due to file locking in file systems. As "normal" buffered writes
3352 * should parellelize on writeout quite nicely, limit us to having 2
3353 * pending. This avoids massive contention on the inode when doing
3354 * buffered async writes.
3356 ctx->sqo_wq[1] = alloc_workqueue("io_ring-write-wq",
3357 WQ_UNBOUND | WQ_FREEZABLE, 2);
3358 if (!ctx->sqo_wq[1]) {
3365 io_finish_async(ctx);
3366 mmdrop(ctx->sqo_mm);
3371 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3373 atomic_long_sub(nr_pages, &user->locked_vm);
3376 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3378 unsigned long page_limit, cur_pages, new_pages;
3380 /* Don't allow more pages than we can safely lock */
3381 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3384 cur_pages = atomic_long_read(&user->locked_vm);
3385 new_pages = cur_pages + nr_pages;
3386 if (new_pages > page_limit)
3388 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3389 new_pages) != cur_pages);
3394 static void io_mem_free(void *ptr)
3401 page = virt_to_head_page(ptr);
3402 if (put_page_testzero(page))
3403 free_compound_page(page);
3406 static void *io_mem_alloc(size_t size)
3408 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3411 return (void *) __get_free_pages(gfp_flags, get_order(size));
3414 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3417 struct io_rings *rings;
3418 size_t off, sq_array_size;
3420 off = struct_size(rings, cqes, cq_entries);
3421 if (off == SIZE_MAX)
3425 off = ALIGN(off, SMP_CACHE_BYTES);
3433 sq_array_size = array_size(sizeof(u32), sq_entries);
3434 if (sq_array_size == SIZE_MAX)
3437 if (check_add_overflow(off, sq_array_size, &off))
3443 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3447 pages = (size_t)1 << get_order(
3448 rings_size(sq_entries, cq_entries, NULL));
3449 pages += (size_t)1 << get_order(
3450 array_size(sizeof(struct io_uring_sqe), sq_entries));
3455 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3459 if (!ctx->user_bufs)
3462 for (i = 0; i < ctx->nr_user_bufs; i++) {
3463 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3465 for (j = 0; j < imu->nr_bvecs; j++)
3466 put_user_page(imu->bvec[j].bv_page);
3468 if (ctx->account_mem)
3469 io_unaccount_mem(ctx->user, imu->nr_bvecs);
3474 kfree(ctx->user_bufs);
3475 ctx->user_bufs = NULL;
3476 ctx->nr_user_bufs = 0;
3480 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3481 void __user *arg, unsigned index)
3483 struct iovec __user *src;
3485 #ifdef CONFIG_COMPAT
3487 struct compat_iovec __user *ciovs;
3488 struct compat_iovec ciov;
3490 ciovs = (struct compat_iovec __user *) arg;
3491 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3494 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3495 dst->iov_len = ciov.iov_len;
3499 src = (struct iovec __user *) arg;
3500 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3505 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3508 struct vm_area_struct **vmas = NULL;
3509 struct page **pages = NULL;
3510 int i, j, got_pages = 0;
3515 if (!nr_args || nr_args > UIO_MAXIOV)
3518 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3520 if (!ctx->user_bufs)
3523 for (i = 0; i < nr_args; i++) {
3524 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3525 unsigned long off, start, end, ubuf;
3530 ret = io_copy_iov(ctx, &iov, arg, i);
3535 * Don't impose further limits on the size and buffer
3536 * constraints here, we'll -EINVAL later when IO is
3537 * submitted if they are wrong.
3540 if (!iov.iov_base || !iov.iov_len)
3543 /* arbitrary limit, but we need something */
3544 if (iov.iov_len > SZ_1G)
3547 ubuf = (unsigned long) iov.iov_base;
3548 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3549 start = ubuf >> PAGE_SHIFT;
3550 nr_pages = end - start;
3552 if (ctx->account_mem) {
3553 ret = io_account_mem(ctx->user, nr_pages);
3559 if (!pages || nr_pages > got_pages) {
3562 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
3564 vmas = kvmalloc_array(nr_pages,
3565 sizeof(struct vm_area_struct *),
3567 if (!pages || !vmas) {
3569 if (ctx->account_mem)
3570 io_unaccount_mem(ctx->user, nr_pages);
3573 got_pages = nr_pages;
3576 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
3580 if (ctx->account_mem)
3581 io_unaccount_mem(ctx->user, nr_pages);
3586 down_read(¤t->mm->mmap_sem);
3587 pret = get_user_pages(ubuf, nr_pages,
3588 FOLL_WRITE | FOLL_LONGTERM,
3590 if (pret == nr_pages) {
3591 /* don't support file backed memory */
3592 for (j = 0; j < nr_pages; j++) {
3593 struct vm_area_struct *vma = vmas[j];
3596 !is_file_hugepages(vma->vm_file)) {
3602 ret = pret < 0 ? pret : -EFAULT;
3604 up_read(¤t->mm->mmap_sem);
3607 * if we did partial map, or found file backed vmas,
3608 * release any pages we did get
3611 put_user_pages(pages, pret);
3612 if (ctx->account_mem)
3613 io_unaccount_mem(ctx->user, nr_pages);
3618 off = ubuf & ~PAGE_MASK;
3620 for (j = 0; j < nr_pages; j++) {
3623 vec_len = min_t(size_t, size, PAGE_SIZE - off);
3624 imu->bvec[j].bv_page = pages[j];
3625 imu->bvec[j].bv_len = vec_len;
3626 imu->bvec[j].bv_offset = off;
3630 /* store original address for later verification */
3632 imu->len = iov.iov_len;
3633 imu->nr_bvecs = nr_pages;
3635 ctx->nr_user_bufs++;
3643 io_sqe_buffer_unregister(ctx);
3647 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
3649 __s32 __user *fds = arg;
3655 if (copy_from_user(&fd, fds, sizeof(*fds)))
3658 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
3659 if (IS_ERR(ctx->cq_ev_fd)) {
3660 int ret = PTR_ERR(ctx->cq_ev_fd);
3661 ctx->cq_ev_fd = NULL;
3668 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
3670 if (ctx->cq_ev_fd) {
3671 eventfd_ctx_put(ctx->cq_ev_fd);
3672 ctx->cq_ev_fd = NULL;
3679 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
3681 io_finish_async(ctx);
3683 mmdrop(ctx->sqo_mm);
3685 io_iopoll_reap_events(ctx);
3686 io_sqe_buffer_unregister(ctx);
3687 io_sqe_files_unregister(ctx);
3688 io_eventfd_unregister(ctx);
3690 #if defined(CONFIG_UNIX)
3691 if (ctx->ring_sock) {
3692 ctx->ring_sock->file = NULL; /* so that iput() is called */
3693 sock_release(ctx->ring_sock);
3697 io_mem_free(ctx->rings);
3698 io_mem_free(ctx->sq_sqes);
3700 percpu_ref_exit(&ctx->refs);
3701 if (ctx->account_mem)
3702 io_unaccount_mem(ctx->user,
3703 ring_pages(ctx->sq_entries, ctx->cq_entries));
3704 free_uid(ctx->user);
3706 put_cred(ctx->creds);
3710 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3712 struct io_ring_ctx *ctx = file->private_data;
3715 poll_wait(file, &ctx->cq_wait, wait);
3717 * synchronizes with barrier from wq_has_sleeper call in
3721 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
3722 ctx->rings->sq_ring_entries)
3723 mask |= EPOLLOUT | EPOLLWRNORM;
3724 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
3725 mask |= EPOLLIN | EPOLLRDNORM;
3730 static int io_uring_fasync(int fd, struct file *file, int on)
3732 struct io_ring_ctx *ctx = file->private_data;
3734 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3737 static void io_cancel_async_work(struct io_ring_ctx *ctx,
3738 struct files_struct *files)
3740 struct io_kiocb *req;
3742 spin_lock_irq(&ctx->task_lock);
3744 list_for_each_entry(req, &ctx->task_list, task_list) {
3745 if (files && req->files != files)
3749 * The below executes an smp_mb(), which matches with the
3750 * smp_mb() (A) in io_sq_wq_submit_work() such that either
3751 * we store REQ_F_CANCEL flag to req->flags or we see the
3752 * req->work_task setted in io_sq_wq_submit_work().
3754 smp_store_mb(req->flags, req->flags | REQ_F_CANCEL); /* B */
3757 send_sig(SIGINT, req->work_task, 1);
3759 spin_unlock_irq(&ctx->task_lock);
3762 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3764 mutex_lock(&ctx->uring_lock);
3765 percpu_ref_kill(&ctx->refs);
3766 mutex_unlock(&ctx->uring_lock);
3768 io_cancel_async_work(ctx, NULL);
3769 io_kill_timeouts(ctx);
3770 io_poll_remove_all(ctx);
3771 io_iopoll_reap_events(ctx);
3772 wait_for_completion(&ctx->ctx_done);
3773 io_ring_ctx_free(ctx);
3776 static int io_uring_flush(struct file *file, void *data)
3778 struct io_ring_ctx *ctx = file->private_data;
3780 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
3781 io_cancel_async_work(ctx, data);
3786 static int io_uring_release(struct inode *inode, struct file *file)
3788 struct io_ring_ctx *ctx = file->private_data;
3790 file->private_data = NULL;
3791 io_ring_ctx_wait_and_kill(ctx);
3795 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3797 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3798 unsigned long sz = vma->vm_end - vma->vm_start;
3799 struct io_ring_ctx *ctx = file->private_data;
3805 case IORING_OFF_SQ_RING:
3806 case IORING_OFF_CQ_RING:
3809 case IORING_OFF_SQES:
3816 page = virt_to_head_page(ptr);
3817 if (sz > page_size(page))
3820 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3821 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3824 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3825 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3828 struct io_ring_ctx *ctx;
3833 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
3841 if (f.file->f_op != &io_uring_fops)
3845 ctx = f.file->private_data;
3846 if (!percpu_ref_tryget(&ctx->refs))
3850 * For SQ polling, the thread will do all submissions and completions.
3851 * Just return the requested submit count, and wake the thread if
3855 if (ctx->flags & IORING_SETUP_SQPOLL) {
3856 if (flags & IORING_ENTER_SQ_WAKEUP)
3857 wake_up(&ctx->sqo_wait);
3858 submitted = to_submit;
3859 } else if (to_submit) {
3860 to_submit = min(to_submit, ctx->sq_entries);
3862 mutex_lock(&ctx->uring_lock);
3863 submitted = io_ring_submit(ctx, to_submit);
3864 mutex_unlock(&ctx->uring_lock);
3866 if (submitted != to_submit)
3869 if (flags & IORING_ENTER_GETEVENTS) {
3870 unsigned nr_events = 0;
3872 min_complete = min(min_complete, ctx->cq_entries);
3874 if (ctx->flags & IORING_SETUP_IOPOLL) {
3875 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3877 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3882 percpu_ref_put(&ctx->refs);
3885 return submitted ? submitted : ret;
3888 static const struct file_operations io_uring_fops = {
3889 .release = io_uring_release,
3890 .flush = io_uring_flush,
3891 .mmap = io_uring_mmap,
3892 .poll = io_uring_poll,
3893 .fasync = io_uring_fasync,
3896 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3897 struct io_uring_params *p)
3899 struct io_rings *rings;
3900 size_t size, sq_array_offset;
3902 /* make sure these are sane, as we already accounted them */
3903 ctx->sq_entries = p->sq_entries;
3904 ctx->cq_entries = p->cq_entries;
3906 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
3907 if (size == SIZE_MAX)
3910 rings = io_mem_alloc(size);
3915 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3916 rings->sq_ring_mask = p->sq_entries - 1;
3917 rings->cq_ring_mask = p->cq_entries - 1;
3918 rings->sq_ring_entries = p->sq_entries;
3919 rings->cq_ring_entries = p->cq_entries;
3920 ctx->sq_mask = rings->sq_ring_mask;
3921 ctx->cq_mask = rings->cq_ring_mask;
3923 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3924 if (size == SIZE_MAX) {
3925 io_mem_free(ctx->rings);
3930 ctx->sq_sqes = io_mem_alloc(size);
3931 if (!ctx->sq_sqes) {
3932 io_mem_free(ctx->rings);
3941 * Allocate an anonymous fd, this is what constitutes the application
3942 * visible backing of an io_uring instance. The application mmaps this
3943 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3944 * we have to tie this fd to a socket for file garbage collection purposes.
3946 static int io_uring_get_fd(struct io_ring_ctx *ctx)
3951 #if defined(CONFIG_UNIX)
3952 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3958 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3962 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3963 O_RDWR | O_CLOEXEC);
3966 ret = PTR_ERR(file);
3970 #if defined(CONFIG_UNIX)
3971 ctx->ring_sock->file = file;
3972 ctx->ring_sock->sk->sk_user_data = ctx;
3974 fd_install(ret, file);
3977 #if defined(CONFIG_UNIX)
3978 sock_release(ctx->ring_sock);
3979 ctx->ring_sock = NULL;
3984 static int io_uring_create(unsigned entries, struct io_uring_params *p)
3986 struct user_struct *user = NULL;
3987 struct io_ring_ctx *ctx;
3991 if (!entries || entries > IORING_MAX_ENTRIES)
3995 * Use twice as many entries for the CQ ring. It's possible for the
3996 * application to drive a higher depth than the size of the SQ ring,
3997 * since the sqes are only used at submission time. This allows for
3998 * some flexibility in overcommitting a bit.
4000 p->sq_entries = roundup_pow_of_two(entries);
4001 p->cq_entries = 2 * p->sq_entries;
4003 user = get_uid(current_user());
4004 account_mem = !capable(CAP_IPC_LOCK);
4007 ret = io_account_mem(user,
4008 ring_pages(p->sq_entries, p->cq_entries));
4015 ctx = io_ring_ctx_alloc(p);
4018 io_unaccount_mem(user, ring_pages(p->sq_entries,
4023 ctx->compat = in_compat_syscall();
4024 ctx->account_mem = account_mem;
4027 ctx->creds = get_current_cred();
4033 ret = io_allocate_scq_urings(ctx, p);
4037 ret = io_sq_offload_start(ctx, p);
4041 memset(&p->sq_off, 0, sizeof(p->sq_off));
4042 p->sq_off.head = offsetof(struct io_rings, sq.head);
4043 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4044 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4045 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4046 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4047 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4048 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
4050 memset(&p->cq_off, 0, sizeof(p->cq_off));
4051 p->cq_off.head = offsetof(struct io_rings, cq.head);
4052 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4053 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4054 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4055 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4056 p->cq_off.cqes = offsetof(struct io_rings, cqes);
4059 * Install ring fd as the very last thing, so we don't risk someone
4060 * having closed it before we finish setup
4062 ret = io_uring_get_fd(ctx);
4066 p->features = IORING_FEAT_SINGLE_MMAP;
4069 io_ring_ctx_wait_and_kill(ctx);
4074 * Sets up an aio uring context, and returns the fd. Applications asks for a
4075 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4076 * params structure passed in.
4078 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4080 struct io_uring_params p;
4084 if (copy_from_user(&p, params, sizeof(p)))
4086 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4091 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4092 IORING_SETUP_SQ_AFF))
4095 ret = io_uring_create(entries, &p);
4099 if (copy_to_user(params, &p, sizeof(p)))
4105 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4106 struct io_uring_params __user *, params)
4108 return io_uring_setup(entries, params);
4111 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4112 void __user *arg, unsigned nr_args)
4113 __releases(ctx->uring_lock)
4114 __acquires(ctx->uring_lock)
4119 * We're inside the ring mutex, if the ref is already dying, then
4120 * someone else killed the ctx or is already going through
4121 * io_uring_register().
4123 if (percpu_ref_is_dying(&ctx->refs))
4126 percpu_ref_kill(&ctx->refs);
4129 * Drop uring mutex before waiting for references to exit. If another
4130 * thread is currently inside io_uring_enter() it might need to grab
4131 * the uring_lock to make progress. If we hold it here across the drain
4132 * wait, then we can deadlock. It's safe to drop the mutex here, since
4133 * no new references will come in after we've killed the percpu ref.
4135 mutex_unlock(&ctx->uring_lock);
4136 wait_for_completion(&ctx->ctx_done);
4137 mutex_lock(&ctx->uring_lock);
4140 case IORING_REGISTER_BUFFERS:
4141 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4143 case IORING_UNREGISTER_BUFFERS:
4147 ret = io_sqe_buffer_unregister(ctx);
4149 case IORING_REGISTER_FILES:
4150 ret = io_sqe_files_register(ctx, arg, nr_args);
4152 case IORING_UNREGISTER_FILES:
4156 ret = io_sqe_files_unregister(ctx);
4158 case IORING_REGISTER_EVENTFD:
4162 ret = io_eventfd_register(ctx, arg);
4164 case IORING_UNREGISTER_EVENTFD:
4168 ret = io_eventfd_unregister(ctx);
4175 /* bring the ctx back to life */
4176 reinit_completion(&ctx->ctx_done);
4177 percpu_ref_reinit(&ctx->refs);
4181 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4182 void __user *, arg, unsigned int, nr_args)
4184 struct io_ring_ctx *ctx;
4193 if (f.file->f_op != &io_uring_fops)
4196 ctx = f.file->private_data;
4198 mutex_lock(&ctx->uring_lock);
4199 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4200 mutex_unlock(&ctx->uring_lock);
4206 static int __init io_uring_init(void)
4208 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4211 __initcall(io_uring_init);