1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <linux/refcount.h>
48 #include <linux/uio.h>
50 #include <linux/sched/signal.h>
52 #include <linux/file.h>
53 #include <linux/fdtable.h>
55 #include <linux/mman.h>
56 #include <linux/mmu_context.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/workqueue.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
65 #include <net/af_unix.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
74 #include <uapi/linux/io_uring.h>
78 #define IORING_MAX_ENTRIES 32768
79 #define IORING_MAX_FIXED_FILES 1024
82 u32 head ____cacheline_aligned_in_smp;
83 u32 tail ____cacheline_aligned_in_smp;
87 * This data is shared with the application through the mmap at offsets
88 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
90 * The offsets to the member fields are published through struct
91 * io_sqring_offsets when calling io_uring_setup.
95 * Head and tail offsets into the ring; the offsets need to be
96 * masked to get valid indices.
98 * The kernel controls head of the sq ring and the tail of the cq ring,
99 * and the application controls tail of the sq ring and the head of the
102 struct io_uring sq, cq;
104 * Bitmasks to apply to head and tail offsets (constant, equals
107 u32 sq_ring_mask, cq_ring_mask;
108 /* Ring sizes (constant, power of 2) */
109 u32 sq_ring_entries, cq_ring_entries;
111 * Number of invalid entries dropped by the kernel due to
112 * invalid index stored in array
114 * Written by the kernel, shouldn't be modified by the
115 * application (i.e. get number of "new events" by comparing to
118 * After a new SQ head value was read by the application this
119 * counter includes all submissions that were dropped reaching
120 * the new SQ head (and possibly more).
126 * Written by the kernel, shouldn't be modified by the
129 * The application needs a full memory barrier before checking
130 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
134 * Number of completion events lost because the queue was full;
135 * this should be avoided by the application by making sure
136 * there are not more requests pending thatn there is space in
137 * the completion queue.
139 * Written by the kernel, shouldn't be modified by the
140 * application (i.e. get number of "new events" by comparing to
143 * As completion events come in out of order this counter is not
144 * ordered with any other data.
148 * Ring buffer of completion events.
150 * The kernel writes completion events fresh every time they are
151 * produced, so the application is allowed to modify pending
154 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
157 struct io_mapped_ubuf {
160 struct bio_vec *bvec;
161 unsigned int nr_bvecs;
167 struct list_head list;
176 struct percpu_ref refs;
177 } ____cacheline_aligned_in_smp;
185 * Ring buffer of indices into array of io_uring_sqe, which is
186 * mmapped by the application using the IORING_OFF_SQES offset.
188 * This indirection could e.g. be used to assign fixed
189 * io_uring_sqe entries to operations and only submit them to
190 * the queue when needed.
192 * The kernel modifies neither the indices array nor the entries
196 unsigned cached_sq_head;
199 unsigned sq_thread_idle;
200 struct io_uring_sqe *sq_sqes;
202 struct list_head defer_list;
203 struct list_head timeout_list;
204 } ____cacheline_aligned_in_smp;
207 struct workqueue_struct *sqo_wq[2];
208 struct task_struct *sqo_thread; /* if using sq thread polling */
209 struct mm_struct *sqo_mm;
210 wait_queue_head_t sqo_wait;
211 struct completion sqo_thread_started;
214 unsigned cached_cq_tail;
217 struct wait_queue_head cq_wait;
218 struct fasync_struct *cq_fasync;
219 struct eventfd_ctx *cq_ev_fd;
220 atomic_t cq_timeouts;
221 } ____cacheline_aligned_in_smp;
223 struct io_rings *rings;
226 * If used, fixed file set. Writers must ensure that ->refs is dead,
227 * readers must ensure that ->refs is alive as long as the file* is
228 * used. Only updated through io_uring_register(2).
230 struct file **user_files;
231 unsigned nr_user_files;
233 /* if used, fixed mapped user buffers */
234 unsigned nr_user_bufs;
235 struct io_mapped_ubuf *user_bufs;
237 struct user_struct *user;
239 struct completion ctx_done;
242 struct mutex uring_lock;
243 wait_queue_head_t wait;
244 } ____cacheline_aligned_in_smp;
247 spinlock_t completion_lock;
248 bool poll_multi_file;
250 * ->poll_list is protected by the ctx->uring_lock for
251 * io_uring instances that don't use IORING_SETUP_SQPOLL.
252 * For SQPOLL, only the single threaded io_sq_thread() will
253 * manipulate the list, hence no extra locking is needed there.
255 struct list_head poll_list;
256 struct list_head cancel_list;
257 } ____cacheline_aligned_in_smp;
259 struct async_list pending_async[2];
261 #if defined(CONFIG_UNIX)
262 struct socket *ring_sock;
267 const struct io_uring_sqe *sqe;
268 unsigned short index;
272 bool needs_fixed_file;
276 * First field must be the file pointer in all the
277 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
279 struct io_poll_iocb {
281 struct wait_queue_head *head;
285 struct wait_queue_entry wait;
290 struct hrtimer timer;
294 * NOTE! Each of the iocb union members has the file pointer
295 * as the first entry in their struct definition. So you can
296 * access the file pointer through any of the sub-structs,
297 * or directly as just 'ki_filp' in this struct.
303 struct io_poll_iocb poll;
304 struct io_timeout timeout;
307 struct sqe_submit submit;
309 struct io_ring_ctx *ctx;
310 struct list_head list;
311 struct list_head link_list;
314 #define REQ_F_NOWAIT 1 /* must not punt to workers */
315 #define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
316 #define REQ_F_FIXED_FILE 4 /* ctx owns file */
317 #define REQ_F_SEQ_PREV 8 /* sequential with previous */
318 #define REQ_F_IO_DRAIN 16 /* drain existing IO first */
319 #define REQ_F_IO_DRAINED 32 /* drain done */
320 #define REQ_F_LINK 64 /* linked sqes */
321 #define REQ_F_LINK_DONE 128 /* linked sqes done */
322 #define REQ_F_FAIL_LINK 256 /* fail rest of links */
323 #define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
324 #define REQ_F_TIMEOUT 1024 /* timeout request */
325 #define REQ_F_ISREG 2048 /* regular file */
326 #define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
331 struct work_struct work;
334 #define IO_PLUG_THRESHOLD 2
335 #define IO_IOPOLL_BATCH 8
337 struct io_submit_state {
338 struct blk_plug plug;
341 * io_kiocb alloc cache
343 void *reqs[IO_IOPOLL_BATCH];
344 unsigned int free_reqs;
345 unsigned int cur_req;
348 * File reference cache
352 unsigned int has_refs;
353 unsigned int used_refs;
354 unsigned int ios_left;
357 static void io_sq_wq_submit_work(struct work_struct *work);
358 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
360 static void __io_free_req(struct io_kiocb *req);
362 static struct kmem_cache *req_cachep;
364 static const struct file_operations io_uring_fops;
366 struct sock *io_uring_get_socket(struct file *file)
368 #if defined(CONFIG_UNIX)
369 if (file->f_op == &io_uring_fops) {
370 struct io_ring_ctx *ctx = file->private_data;
372 return ctx->ring_sock->sk;
377 EXPORT_SYMBOL(io_uring_get_socket);
379 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
381 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
383 complete(&ctx->ctx_done);
386 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
388 struct io_ring_ctx *ctx;
391 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
395 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
396 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
401 ctx->flags = p->flags;
402 init_waitqueue_head(&ctx->cq_wait);
403 init_completion(&ctx->ctx_done);
404 init_completion(&ctx->sqo_thread_started);
405 mutex_init(&ctx->uring_lock);
406 init_waitqueue_head(&ctx->wait);
407 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
408 spin_lock_init(&ctx->pending_async[i].lock);
409 INIT_LIST_HEAD(&ctx->pending_async[i].list);
410 atomic_set(&ctx->pending_async[i].cnt, 0);
412 spin_lock_init(&ctx->completion_lock);
413 INIT_LIST_HEAD(&ctx->poll_list);
414 INIT_LIST_HEAD(&ctx->cancel_list);
415 INIT_LIST_HEAD(&ctx->defer_list);
416 INIT_LIST_HEAD(&ctx->timeout_list);
420 static inline bool __io_sequence_defer(struct io_ring_ctx *ctx,
421 struct io_kiocb *req)
423 return req->sequence != ctx->cached_cq_tail + ctx->rings->sq_dropped;
426 static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
427 struct io_kiocb *req)
429 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
432 return __io_sequence_defer(ctx, req);
435 static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
437 struct io_kiocb *req;
439 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
440 if (req && !io_sequence_defer(ctx, req)) {
441 list_del_init(&req->list);
448 static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
450 struct io_kiocb *req;
452 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
453 if (req && !__io_sequence_defer(ctx, req)) {
454 list_del_init(&req->list);
461 static void __io_commit_cqring(struct io_ring_ctx *ctx)
463 struct io_rings *rings = ctx->rings;
465 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
466 /* order cqe stores with ring update */
467 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
469 if (wq_has_sleeper(&ctx->cq_wait)) {
470 wake_up_interruptible(&ctx->cq_wait);
471 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
476 static inline void io_queue_async_work(struct io_ring_ctx *ctx,
477 struct io_kiocb *req)
481 if (req->submit.sqe) {
482 switch (req->submit.sqe->opcode) {
483 case IORING_OP_WRITEV:
484 case IORING_OP_WRITE_FIXED:
485 rw = !(req->rw.ki_flags & IOCB_DIRECT);
490 queue_work(ctx->sqo_wq[rw], &req->work);
493 static void io_kill_timeout(struct io_kiocb *req)
497 ret = hrtimer_try_to_cancel(&req->timeout.timer);
499 atomic_inc(&req->ctx->cq_timeouts);
500 list_del(&req->list);
501 io_cqring_fill_event(req->ctx, req->user_data, 0);
506 static void io_kill_timeouts(struct io_ring_ctx *ctx)
508 struct io_kiocb *req, *tmp;
510 spin_lock_irq(&ctx->completion_lock);
511 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
512 io_kill_timeout(req);
513 spin_unlock_irq(&ctx->completion_lock);
516 static void io_commit_cqring(struct io_ring_ctx *ctx)
518 struct io_kiocb *req;
520 while ((req = io_get_timeout_req(ctx)) != NULL)
521 io_kill_timeout(req);
523 __io_commit_cqring(ctx);
525 while ((req = io_get_deferred_req(ctx)) != NULL) {
526 if (req->flags & REQ_F_SHADOW_DRAIN) {
527 /* Just for drain, free it. */
531 req->flags |= REQ_F_IO_DRAINED;
532 io_queue_async_work(ctx, req);
536 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
538 struct io_rings *rings = ctx->rings;
541 tail = ctx->cached_cq_tail;
543 * writes to the cq entry need to come after reading head; the
544 * control dependency is enough as we're using WRITE_ONCE to
547 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
550 ctx->cached_cq_tail++;
551 return &rings->cqes[tail & ctx->cq_mask];
554 static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
557 struct io_uring_cqe *cqe;
560 * If we can't get a cq entry, userspace overflowed the
561 * submission (by quite a lot). Increment the overflow count in
564 cqe = io_get_cqring(ctx);
566 WRITE_ONCE(cqe->user_data, ki_user_data);
567 WRITE_ONCE(cqe->res, res);
568 WRITE_ONCE(cqe->flags, 0);
570 unsigned overflow = READ_ONCE(ctx->rings->cq_overflow);
572 WRITE_ONCE(ctx->rings->cq_overflow, overflow + 1);
576 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
578 if (waitqueue_active(&ctx->wait))
580 if (waitqueue_active(&ctx->sqo_wait))
581 wake_up(&ctx->sqo_wait);
583 eventfd_signal(ctx->cq_ev_fd, 1);
586 static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
591 spin_lock_irqsave(&ctx->completion_lock, flags);
592 io_cqring_fill_event(ctx, user_data, res);
593 io_commit_cqring(ctx);
594 spin_unlock_irqrestore(&ctx->completion_lock, flags);
596 io_cqring_ev_posted(ctx);
599 static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
600 struct io_submit_state *state)
602 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
603 struct io_kiocb *req;
605 if (!percpu_ref_tryget(&ctx->refs))
609 req = kmem_cache_alloc(req_cachep, gfp);
612 } else if (!state->free_reqs) {
616 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
617 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
620 * Bulk alloc is all-or-nothing. If we fail to get a batch,
621 * retry single alloc to be on the safe side.
623 if (unlikely(ret <= 0)) {
624 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
629 state->free_reqs = ret - 1;
631 req = state->reqs[0];
633 req = state->reqs[state->cur_req];
641 /* one is dropped after submission, the other at completion */
642 refcount_set(&req->refs, 2);
646 percpu_ref_put(&ctx->refs);
650 static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
653 kmem_cache_free_bulk(req_cachep, *nr, reqs);
654 percpu_ref_put_many(&ctx->refs, *nr);
659 static void __io_free_req(struct io_kiocb *req)
661 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
663 percpu_ref_put(&req->ctx->refs);
664 kmem_cache_free(req_cachep, req);
667 static void io_req_link_next(struct io_kiocb *req)
669 struct io_kiocb *nxt;
672 * The list should never be empty when we are called here. But could
673 * potentially happen if the chain is messed up, check to be on the
676 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
678 list_del(&nxt->list);
679 if (!list_empty(&req->link_list)) {
680 INIT_LIST_HEAD(&nxt->link_list);
681 list_splice(&req->link_list, &nxt->link_list);
682 nxt->flags |= REQ_F_LINK;
685 nxt->flags |= REQ_F_LINK_DONE;
686 INIT_WORK(&nxt->work, io_sq_wq_submit_work);
687 io_queue_async_work(req->ctx, nxt);
692 * Called if REQ_F_LINK is set, and we fail the head request
694 static void io_fail_links(struct io_kiocb *req)
696 struct io_kiocb *link;
698 while (!list_empty(&req->link_list)) {
699 link = list_first_entry(&req->link_list, struct io_kiocb, list);
700 list_del(&link->list);
702 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
707 static void io_free_req(struct io_kiocb *req)
710 * If LINK is set, we have dependent requests in this chain. If we
711 * didn't fail this request, queue the first one up, moving any other
712 * dependencies to the next request. In case of failure, fail the rest
715 if (req->flags & REQ_F_LINK) {
716 if (req->flags & REQ_F_FAIL_LINK)
719 io_req_link_next(req);
725 static void io_put_req(struct io_kiocb *req)
727 if (refcount_dec_and_test(&req->refs))
731 static unsigned io_cqring_events(struct io_rings *rings)
733 /* See comment at the top of this file */
735 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
739 * Find and free completed poll iocbs
741 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
742 struct list_head *done)
744 void *reqs[IO_IOPOLL_BATCH];
745 struct io_kiocb *req;
749 while (!list_empty(done)) {
750 req = list_first_entry(done, struct io_kiocb, list);
751 list_del(&req->list);
753 io_cqring_fill_event(ctx, req->user_data, req->result);
756 if (refcount_dec_and_test(&req->refs)) {
757 /* If we're not using fixed files, we have to pair the
758 * completion part with the file put. Use regular
759 * completions for those, only batch free for fixed
760 * file and non-linked commands.
762 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
764 reqs[to_free++] = req;
765 if (to_free == ARRAY_SIZE(reqs))
766 io_free_req_many(ctx, reqs, &to_free);
773 io_commit_cqring(ctx);
774 io_free_req_many(ctx, reqs, &to_free);
777 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
780 struct io_kiocb *req, *tmp;
786 * Only spin for completions if we don't have multiple devices hanging
787 * off our complete list, and we're under the requested amount.
789 spin = !ctx->poll_multi_file && *nr_events < min;
792 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
793 struct kiocb *kiocb = &req->rw;
796 * Move completed entries to our local list. If we find a
797 * request that requires polling, break out and complete
798 * the done list first, if we have entries there.
800 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
801 list_move_tail(&req->list, &done);
804 if (!list_empty(&done))
807 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
816 if (!list_empty(&done))
817 io_iopoll_complete(ctx, nr_events, &done);
823 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
824 * non-spinning poll check - we'll still enter the driver poll loop, but only
825 * as a non-spinning completion check.
827 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
830 while (!list_empty(&ctx->poll_list) && !need_resched()) {
833 ret = io_do_iopoll(ctx, nr_events, min);
836 if (!min || *nr_events >= min)
844 * We can't just wait for polled events to come to us, we have to actively
845 * find and complete them.
847 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
849 if (!(ctx->flags & IORING_SETUP_IOPOLL))
852 mutex_lock(&ctx->uring_lock);
853 while (!list_empty(&ctx->poll_list)) {
854 unsigned int nr_events = 0;
856 io_iopoll_getevents(ctx, &nr_events, 1);
859 * Ensure we allow local-to-the-cpu processing to take place,
860 * in this case we need to ensure that we reap all events.
864 mutex_unlock(&ctx->uring_lock);
867 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
873 * We disallow the app entering submit/complete with polling, but we
874 * still need to lock the ring to prevent racing with polled issue
875 * that got punted to a workqueue.
877 mutex_lock(&ctx->uring_lock);
884 * Don't enter poll loop if we already have events pending.
885 * If we do, we can potentially be spinning for commands that
886 * already triggered a CQE (eg in error).
888 if (io_cqring_events(ctx->rings))
892 * If a submit got punted to a workqueue, we can have the
893 * application entering polling for a command before it gets
894 * issued. That app will hold the uring_lock for the duration
895 * of the poll right here, so we need to take a breather every
896 * now and then to ensure that the issue has a chance to add
897 * the poll to the issued list. Otherwise we can spin here
898 * forever, while the workqueue is stuck trying to acquire the
901 if (!(++iters & 7)) {
902 mutex_unlock(&ctx->uring_lock);
903 mutex_lock(&ctx->uring_lock);
906 if (*nr_events < min)
907 tmin = min - *nr_events;
909 ret = io_iopoll_getevents(ctx, nr_events, tmin);
913 } while (min && !*nr_events && !need_resched());
915 mutex_unlock(&ctx->uring_lock);
919 static void kiocb_end_write(struct io_kiocb *req)
922 * Tell lockdep we inherited freeze protection from submission
925 if (req->flags & REQ_F_ISREG) {
926 struct inode *inode = file_inode(req->file);
928 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
930 file_end_write(req->file);
933 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
935 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
937 if (kiocb->ki_flags & IOCB_WRITE)
938 kiocb_end_write(req);
940 if ((req->flags & REQ_F_LINK) && res != req->result)
941 req->flags |= REQ_F_FAIL_LINK;
942 io_cqring_add_event(req->ctx, req->user_data, res);
946 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
948 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
950 if (kiocb->ki_flags & IOCB_WRITE)
951 kiocb_end_write(req);
953 if ((req->flags & REQ_F_LINK) && res != req->result)
954 req->flags |= REQ_F_FAIL_LINK;
957 req->flags |= REQ_F_IOPOLL_COMPLETED;
961 * After the iocb has been issued, it's safe to be found on the poll list.
962 * Adding the kiocb to the list AFTER submission ensures that we don't
963 * find it from a io_iopoll_getevents() thread before the issuer is done
964 * accessing the kiocb cookie.
966 static void io_iopoll_req_issued(struct io_kiocb *req)
968 struct io_ring_ctx *ctx = req->ctx;
971 * Track whether we have multiple files in our lists. This will impact
972 * how we do polling eventually, not spinning if we're on potentially
975 if (list_empty(&ctx->poll_list)) {
976 ctx->poll_multi_file = false;
977 } else if (!ctx->poll_multi_file) {
978 struct io_kiocb *list_req;
980 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
982 if (list_req->rw.ki_filp != req->rw.ki_filp)
983 ctx->poll_multi_file = true;
987 * For fast devices, IO may have already completed. If it has, add
988 * it to the front so we find it first.
990 if (req->flags & REQ_F_IOPOLL_COMPLETED)
991 list_add(&req->list, &ctx->poll_list);
993 list_add_tail(&req->list, &ctx->poll_list);
996 static void io_file_put(struct io_submit_state *state)
999 int diff = state->has_refs - state->used_refs;
1002 fput_many(state->file, diff);
1008 * Get as many references to a file as we have IOs left in this submission,
1009 * assuming most submissions are for one file, or at least that each file
1010 * has more than one submission.
1012 static struct file *io_file_get(struct io_submit_state *state, int fd)
1018 if (state->fd == fd) {
1025 state->file = fget_many(fd, state->ios_left);
1030 state->has_refs = state->ios_left;
1031 state->used_refs = 1;
1037 * If we tracked the file through the SCM inflight mechanism, we could support
1038 * any file. For now, just ensure that anything potentially problematic is done
1041 static bool io_file_supports_async(struct file *file)
1043 umode_t mode = file_inode(file)->i_mode;
1045 if (S_ISBLK(mode) || S_ISCHR(mode))
1047 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1053 static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
1054 bool force_nonblock)
1056 const struct io_uring_sqe *sqe = s->sqe;
1057 struct io_ring_ctx *ctx = req->ctx;
1058 struct kiocb *kiocb = &req->rw;
1065 if (S_ISREG(file_inode(req->file)->i_mode))
1066 req->flags |= REQ_F_ISREG;
1069 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1070 * we know to async punt it even if it was opened O_NONBLOCK
1072 if (force_nonblock && !io_file_supports_async(req->file)) {
1073 req->flags |= REQ_F_MUST_PUNT;
1077 kiocb->ki_pos = READ_ONCE(sqe->off);
1078 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1079 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1081 ioprio = READ_ONCE(sqe->ioprio);
1083 ret = ioprio_check_cap(ioprio);
1087 kiocb->ki_ioprio = ioprio;
1089 kiocb->ki_ioprio = get_current_ioprio();
1091 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1095 /* don't allow async punt if RWF_NOWAIT was requested */
1096 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1097 (req->file->f_flags & O_NONBLOCK))
1098 req->flags |= REQ_F_NOWAIT;
1101 kiocb->ki_flags |= IOCB_NOWAIT;
1103 if (ctx->flags & IORING_SETUP_IOPOLL) {
1104 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1105 !kiocb->ki_filp->f_op->iopoll)
1108 kiocb->ki_flags |= IOCB_HIPRI;
1109 kiocb->ki_complete = io_complete_rw_iopoll;
1111 if (kiocb->ki_flags & IOCB_HIPRI)
1113 kiocb->ki_complete = io_complete_rw;
1118 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1124 case -ERESTARTNOINTR:
1125 case -ERESTARTNOHAND:
1126 case -ERESTART_RESTARTBLOCK:
1128 * We can't just restart the syscall, since previously
1129 * submitted sqes may already be in progress. Just fail this
1135 kiocb->ki_complete(kiocb, ret, 0);
1139 static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1140 const struct io_uring_sqe *sqe,
1141 struct iov_iter *iter)
1143 size_t len = READ_ONCE(sqe->len);
1144 struct io_mapped_ubuf *imu;
1145 unsigned index, buf_index;
1149 /* attempt to use fixed buffers without having provided iovecs */
1150 if (unlikely(!ctx->user_bufs))
1153 buf_index = READ_ONCE(sqe->buf_index);
1154 if (unlikely(buf_index >= ctx->nr_user_bufs))
1157 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1158 imu = &ctx->user_bufs[index];
1159 buf_addr = READ_ONCE(sqe->addr);
1162 if (buf_addr + len < buf_addr)
1164 /* not inside the mapped region */
1165 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1169 * May not be a start of buffer, set size appropriately
1170 * and advance us to the beginning.
1172 offset = buf_addr - imu->ubuf;
1173 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1177 * Don't use iov_iter_advance() here, as it's really slow for
1178 * using the latter parts of a big fixed buffer - it iterates
1179 * over each segment manually. We can cheat a bit here, because
1182 * 1) it's a BVEC iter, we set it up
1183 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1184 * first and last bvec
1186 * So just find our index, and adjust the iterator afterwards.
1187 * If the offset is within the first bvec (or the whole first
1188 * bvec, just use iov_iter_advance(). This makes it easier
1189 * since we can just skip the first segment, which may not
1190 * be PAGE_SIZE aligned.
1192 const struct bio_vec *bvec = imu->bvec;
1194 if (offset <= bvec->bv_len) {
1195 iov_iter_advance(iter, offset);
1197 unsigned long seg_skip;
1199 /* skip first vec */
1200 offset -= bvec->bv_len;
1201 seg_skip = 1 + (offset >> PAGE_SHIFT);
1203 iter->bvec = bvec + seg_skip;
1204 iter->nr_segs -= seg_skip;
1205 iter->count -= bvec->bv_len + offset;
1206 iter->iov_offset = offset & ~PAGE_MASK;
1213 static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1214 const struct sqe_submit *s, struct iovec **iovec,
1215 struct iov_iter *iter)
1217 const struct io_uring_sqe *sqe = s->sqe;
1218 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1219 size_t sqe_len = READ_ONCE(sqe->len);
1223 * We're reading ->opcode for the second time, but the first read
1224 * doesn't care whether it's _FIXED or not, so it doesn't matter
1225 * whether ->opcode changes concurrently. The first read does care
1226 * about whether it is a READ or a WRITE, so we don't trust this read
1227 * for that purpose and instead let the caller pass in the read/write
1230 opcode = READ_ONCE(sqe->opcode);
1231 if (opcode == IORING_OP_READ_FIXED ||
1232 opcode == IORING_OP_WRITE_FIXED) {
1233 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
1241 #ifdef CONFIG_COMPAT
1243 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1247 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1250 static inline bool io_should_merge(struct async_list *al, struct kiocb *kiocb)
1252 if (al->file == kiocb->ki_filp) {
1256 * Allow merging if we're anywhere in the range of the same
1257 * page. Generally this happens for sub-page reads or writes,
1258 * and it's beneficial to allow the first worker to bring the
1259 * page in and the piggy backed work can then work on the
1262 start = al->io_start & PAGE_MASK;
1263 end = (al->io_start + al->io_len + PAGE_SIZE - 1) & PAGE_MASK;
1264 if (kiocb->ki_pos >= start && kiocb->ki_pos <= end)
1273 * Make a note of the last file/offset/direction we punted to async
1274 * context. We'll use this information to see if we can piggy back a
1275 * sequential request onto the previous one, if it's still hasn't been
1276 * completed by the async worker.
1278 static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1280 struct async_list *async_list = &req->ctx->pending_async[rw];
1281 struct kiocb *kiocb = &req->rw;
1282 struct file *filp = kiocb->ki_filp;
1284 if (io_should_merge(async_list, kiocb)) {
1285 unsigned long max_bytes;
1287 /* Use 8x RA size as a decent limiter for both reads/writes */
1288 max_bytes = filp->f_ra.ra_pages << (PAGE_SHIFT + 3);
1290 max_bytes = VM_READAHEAD_PAGES << (PAGE_SHIFT + 3);
1292 /* If max len are exceeded, reset the state */
1293 if (async_list->io_len + len <= max_bytes) {
1294 req->flags |= REQ_F_SEQ_PREV;
1295 async_list->io_len += len;
1297 async_list->file = NULL;
1301 /* New file? Reset state. */
1302 if (async_list->file != filp) {
1303 async_list->io_start = kiocb->ki_pos;
1304 async_list->io_len = len;
1305 async_list->file = filp;
1310 * For files that don't have ->read_iter() and ->write_iter(), handle them
1311 * by looping over ->read() or ->write() manually.
1313 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1314 struct iov_iter *iter)
1319 * Don't support polled IO through this interface, and we can't
1320 * support non-blocking either. For the latter, this just causes
1321 * the kiocb to be handled from an async context.
1323 if (kiocb->ki_flags & IOCB_HIPRI)
1325 if (kiocb->ki_flags & IOCB_NOWAIT)
1328 while (iov_iter_count(iter)) {
1329 struct iovec iovec = iov_iter_iovec(iter);
1333 nr = file->f_op->read(file, iovec.iov_base,
1334 iovec.iov_len, &kiocb->ki_pos);
1336 nr = file->f_op->write(file, iovec.iov_base,
1337 iovec.iov_len, &kiocb->ki_pos);
1346 if (nr != iovec.iov_len)
1348 iov_iter_advance(iter, nr);
1354 static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1355 bool force_nonblock)
1357 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1358 struct kiocb *kiocb = &req->rw;
1359 struct iov_iter iter;
1362 ssize_t read_size, ret;
1364 ret = io_prep_rw(req, s, force_nonblock);
1367 file = kiocb->ki_filp;
1369 if (unlikely(!(file->f_mode & FMODE_READ)))
1372 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
1377 if (req->flags & REQ_F_LINK)
1378 req->result = read_size;
1380 iov_count = iov_iter_count(&iter);
1381 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1385 if (file->f_op->read_iter)
1386 ret2 = call_read_iter(file, kiocb, &iter);
1388 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1391 * In case of a short read, punt to async. This can happen
1392 * if we have data partially cached. Alternatively we can
1393 * return the short read, in which case the application will
1394 * need to issue another SQE and wait for it. That SQE will
1395 * need async punt anyway, so it's more efficient to do it
1398 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1399 (req->flags & REQ_F_ISREG) &&
1400 ret2 > 0 && ret2 < read_size)
1402 /* Catch -EAGAIN return for forced non-blocking submission */
1403 if (!force_nonblock || ret2 != -EAGAIN) {
1404 io_rw_done(kiocb, ret2);
1407 * If ->needs_lock is true, we're already in async
1411 io_async_list_note(READ, req, iov_count);
1419 static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1420 bool force_nonblock)
1422 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1423 struct kiocb *kiocb = &req->rw;
1424 struct iov_iter iter;
1429 ret = io_prep_rw(req, s, force_nonblock);
1433 file = kiocb->ki_filp;
1434 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1437 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
1441 if (req->flags & REQ_F_LINK)
1444 iov_count = iov_iter_count(&iter);
1447 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1448 /* If ->needs_lock is true, we're already in async context. */
1450 io_async_list_note(WRITE, req, iov_count);
1454 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1459 * Open-code file_start_write here to grab freeze protection,
1460 * which will be released by another thread in
1461 * io_complete_rw(). Fool lockdep by telling it the lock got
1462 * released so that it doesn't complain about the held lock when
1463 * we return to userspace.
1465 if (req->flags & REQ_F_ISREG) {
1466 __sb_start_write(file_inode(file)->i_sb,
1467 SB_FREEZE_WRITE, true);
1468 __sb_writers_release(file_inode(file)->i_sb,
1471 kiocb->ki_flags |= IOCB_WRITE;
1473 if (file->f_op->write_iter)
1474 ret2 = call_write_iter(file, kiocb, &iter);
1476 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1477 if (!force_nonblock || ret2 != -EAGAIN) {
1478 io_rw_done(kiocb, ret2);
1481 * If ->needs_lock is true, we're already in async
1485 io_async_list_note(WRITE, req, iov_count);
1495 * IORING_OP_NOP just posts a completion event, nothing else.
1497 static int io_nop(struct io_kiocb *req, u64 user_data)
1499 struct io_ring_ctx *ctx = req->ctx;
1502 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1505 io_cqring_add_event(ctx, user_data, err);
1510 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1512 struct io_ring_ctx *ctx = req->ctx;
1517 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1519 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1525 static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1526 bool force_nonblock)
1528 loff_t sqe_off = READ_ONCE(sqe->off);
1529 loff_t sqe_len = READ_ONCE(sqe->len);
1530 loff_t end = sqe_off + sqe_len;
1531 unsigned fsync_flags;
1534 fsync_flags = READ_ONCE(sqe->fsync_flags);
1535 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1538 ret = io_prep_fsync(req, sqe);
1542 /* fsync always requires a blocking context */
1546 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1547 end > 0 ? end : LLONG_MAX,
1548 fsync_flags & IORING_FSYNC_DATASYNC);
1550 if (ret < 0 && (req->flags & REQ_F_LINK))
1551 req->flags |= REQ_F_FAIL_LINK;
1552 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1557 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1559 struct io_ring_ctx *ctx = req->ctx;
1565 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1567 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1573 static int io_sync_file_range(struct io_kiocb *req,
1574 const struct io_uring_sqe *sqe,
1575 bool force_nonblock)
1582 ret = io_prep_sfr(req, sqe);
1586 /* sync_file_range always requires a blocking context */
1590 sqe_off = READ_ONCE(sqe->off);
1591 sqe_len = READ_ONCE(sqe->len);
1592 flags = READ_ONCE(sqe->sync_range_flags);
1594 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1596 if (ret < 0 && (req->flags & REQ_F_LINK))
1597 req->flags |= REQ_F_FAIL_LINK;
1598 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1603 #if defined(CONFIG_NET)
1604 static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1605 bool force_nonblock,
1606 long (*fn)(struct socket *, struct user_msghdr __user *,
1609 struct socket *sock;
1612 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1615 sock = sock_from_file(req->file, &ret);
1617 struct user_msghdr __user *msg;
1620 flags = READ_ONCE(sqe->msg_flags);
1621 if (flags & MSG_DONTWAIT)
1622 req->flags |= REQ_F_NOWAIT;
1623 else if (force_nonblock)
1624 flags |= MSG_DONTWAIT;
1626 msg = (struct user_msghdr __user *) (unsigned long)
1627 READ_ONCE(sqe->addr);
1629 ret = fn(sock, msg, flags);
1630 if (force_nonblock && ret == -EAGAIN)
1634 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1640 static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1641 bool force_nonblock)
1643 #if defined(CONFIG_NET)
1644 return io_send_recvmsg(req, sqe, force_nonblock, __sys_sendmsg_sock);
1650 static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1651 bool force_nonblock)
1653 #if defined(CONFIG_NET)
1654 return io_send_recvmsg(req, sqe, force_nonblock, __sys_recvmsg_sock);
1660 static void io_poll_remove_one(struct io_kiocb *req)
1662 struct io_poll_iocb *poll = &req->poll;
1664 spin_lock(&poll->head->lock);
1665 WRITE_ONCE(poll->canceled, true);
1666 if (!list_empty(&poll->wait.entry)) {
1667 list_del_init(&poll->wait.entry);
1668 io_queue_async_work(req->ctx, req);
1670 spin_unlock(&poll->head->lock);
1672 list_del_init(&req->list);
1675 static void io_poll_remove_all(struct io_ring_ctx *ctx)
1677 struct io_kiocb *req;
1679 spin_lock_irq(&ctx->completion_lock);
1680 while (!list_empty(&ctx->cancel_list)) {
1681 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1682 io_poll_remove_one(req);
1684 spin_unlock_irq(&ctx->completion_lock);
1688 * Find a running poll command that matches one specified in sqe->addr,
1689 * and remove it if found.
1691 static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1693 struct io_ring_ctx *ctx = req->ctx;
1694 struct io_kiocb *poll_req, *next;
1697 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1699 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1703 spin_lock_irq(&ctx->completion_lock);
1704 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1705 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1706 io_poll_remove_one(poll_req);
1711 spin_unlock_irq(&ctx->completion_lock);
1713 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1718 static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1721 req->poll.done = true;
1722 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
1723 io_commit_cqring(ctx);
1726 static void io_poll_complete_work(struct work_struct *work)
1728 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1729 struct io_poll_iocb *poll = &req->poll;
1730 struct poll_table_struct pt = { ._key = poll->events };
1731 struct io_ring_ctx *ctx = req->ctx;
1734 if (!READ_ONCE(poll->canceled))
1735 mask = vfs_poll(poll->file, &pt) & poll->events;
1738 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1739 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1740 * synchronize with them. In the cancellation case the list_del_init
1741 * itself is not actually needed, but harmless so we keep it in to
1742 * avoid further branches in the fast path.
1744 spin_lock_irq(&ctx->completion_lock);
1745 if (!mask && !READ_ONCE(poll->canceled)) {
1746 add_wait_queue(poll->head, &poll->wait);
1747 spin_unlock_irq(&ctx->completion_lock);
1750 list_del_init(&req->list);
1751 io_poll_complete(ctx, req, mask);
1752 spin_unlock_irq(&ctx->completion_lock);
1754 io_cqring_ev_posted(ctx);
1758 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1761 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1763 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1764 struct io_ring_ctx *ctx = req->ctx;
1765 __poll_t mask = key_to_poll(key);
1766 unsigned long flags;
1768 /* for instances that support it check for an event match first: */
1769 if (mask && !(mask & poll->events))
1772 list_del_init(&poll->wait.entry);
1774 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1775 list_del(&req->list);
1776 io_poll_complete(ctx, req, mask);
1777 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1779 io_cqring_ev_posted(ctx);
1782 io_queue_async_work(ctx, req);
1788 struct io_poll_table {
1789 struct poll_table_struct pt;
1790 struct io_kiocb *req;
1794 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1795 struct poll_table_struct *p)
1797 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1799 if (unlikely(pt->req->poll.head)) {
1800 pt->error = -EINVAL;
1805 pt->req->poll.head = head;
1806 add_wait_queue(head, &pt->req->poll.wait);
1809 static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1811 struct io_poll_iocb *poll = &req->poll;
1812 struct io_ring_ctx *ctx = req->ctx;
1813 struct io_poll_table ipt;
1814 bool cancel = false;
1818 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1820 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1825 req->submit.sqe = NULL;
1826 INIT_WORK(&req->work, io_poll_complete_work);
1827 events = READ_ONCE(sqe->poll_events);
1828 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1832 poll->canceled = false;
1834 ipt.pt._qproc = io_poll_queue_proc;
1835 ipt.pt._key = poll->events;
1837 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1839 /* initialized the list so that we can do list_empty checks */
1840 INIT_LIST_HEAD(&poll->wait.entry);
1841 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1843 INIT_LIST_HEAD(&req->list);
1845 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1847 spin_lock_irq(&ctx->completion_lock);
1848 if (likely(poll->head)) {
1849 spin_lock(&poll->head->lock);
1850 if (unlikely(list_empty(&poll->wait.entry))) {
1856 if (mask || ipt.error)
1857 list_del_init(&poll->wait.entry);
1859 WRITE_ONCE(poll->canceled, true);
1860 else if (!poll->done) /* actually waiting for an event */
1861 list_add_tail(&req->list, &ctx->cancel_list);
1862 spin_unlock(&poll->head->lock);
1864 if (mask) { /* no async, we'd stolen it */
1866 io_poll_complete(ctx, req, mask);
1868 spin_unlock_irq(&ctx->completion_lock);
1871 io_cqring_ev_posted(ctx);
1877 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
1879 struct io_ring_ctx *ctx;
1880 struct io_kiocb *req;
1881 unsigned long flags;
1883 req = container_of(timer, struct io_kiocb, timeout.timer);
1885 atomic_inc(&ctx->cq_timeouts);
1887 spin_lock_irqsave(&ctx->completion_lock, flags);
1888 list_del(&req->list);
1890 io_cqring_fill_event(ctx, req->user_data, -ETIME);
1891 io_commit_cqring(ctx);
1892 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1894 io_cqring_ev_posted(ctx);
1897 return HRTIMER_NORESTART;
1900 static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1903 struct io_ring_ctx *ctx = req->ctx;
1904 struct list_head *entry;
1905 struct timespec64 ts;
1907 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1909 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->timeout_flags ||
1913 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
1917 * sqe->off holds how many events that need to occur for this
1918 * timeout event to be satisfied.
1920 count = READ_ONCE(sqe->off);
1924 req->sequence = ctx->cached_sq_head + count - 1;
1925 /* reuse it to store the count */
1926 req->submit.sequence = count;
1927 req->flags |= REQ_F_TIMEOUT;
1930 * Insertion sort, ensuring the first entry in the list is always
1931 * the one we need first.
1933 spin_lock_irq(&ctx->completion_lock);
1934 list_for_each_prev(entry, &ctx->timeout_list) {
1935 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
1936 unsigned nxt_sq_head;
1937 long long tmp, tmp_nxt;
1940 * Since cached_sq_head + count - 1 can overflow, use type long
1943 tmp = (long long)ctx->cached_sq_head + count - 1;
1944 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
1945 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
1948 * cached_sq_head may overflow, and it will never overflow twice
1949 * once there is some timeout req still be valid.
1951 if (ctx->cached_sq_head < nxt_sq_head)
1957 list_add(&req->list, entry);
1958 spin_unlock_irq(&ctx->completion_lock);
1960 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1961 req->timeout.timer.function = io_timeout_fn;
1962 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts),
1967 static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1968 const struct io_uring_sqe *sqe)
1970 struct io_uring_sqe *sqe_copy;
1972 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1975 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1979 spin_lock_irq(&ctx->completion_lock);
1980 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1981 spin_unlock_irq(&ctx->completion_lock);
1986 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1987 req->submit.sqe = sqe_copy;
1989 INIT_WORK(&req->work, io_sq_wq_submit_work);
1990 list_add_tail(&req->list, &ctx->defer_list);
1991 spin_unlock_irq(&ctx->completion_lock);
1992 return -EIOCBQUEUED;
1995 static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1996 const struct sqe_submit *s, bool force_nonblock)
2000 req->user_data = READ_ONCE(s->sqe->user_data);
2002 if (unlikely(s->index >= ctx->sq_entries))
2005 opcode = READ_ONCE(s->sqe->opcode);
2008 ret = io_nop(req, req->user_data);
2010 case IORING_OP_READV:
2011 if (unlikely(s->sqe->buf_index))
2013 ret = io_read(req, s, force_nonblock);
2015 case IORING_OP_WRITEV:
2016 if (unlikely(s->sqe->buf_index))
2018 ret = io_write(req, s, force_nonblock);
2020 case IORING_OP_READ_FIXED:
2021 ret = io_read(req, s, force_nonblock);
2023 case IORING_OP_WRITE_FIXED:
2024 ret = io_write(req, s, force_nonblock);
2026 case IORING_OP_FSYNC:
2027 ret = io_fsync(req, s->sqe, force_nonblock);
2029 case IORING_OP_POLL_ADD:
2030 ret = io_poll_add(req, s->sqe);
2032 case IORING_OP_POLL_REMOVE:
2033 ret = io_poll_remove(req, s->sqe);
2035 case IORING_OP_SYNC_FILE_RANGE:
2036 ret = io_sync_file_range(req, s->sqe, force_nonblock);
2038 case IORING_OP_SENDMSG:
2039 ret = io_sendmsg(req, s->sqe, force_nonblock);
2041 case IORING_OP_RECVMSG:
2042 ret = io_recvmsg(req, s->sqe, force_nonblock);
2044 case IORING_OP_TIMEOUT:
2045 ret = io_timeout(req, s->sqe);
2055 if (ctx->flags & IORING_SETUP_IOPOLL) {
2056 if (req->result == -EAGAIN)
2059 /* workqueue context doesn't hold uring_lock, grab it now */
2061 mutex_lock(&ctx->uring_lock);
2062 io_iopoll_req_issued(req);
2064 mutex_unlock(&ctx->uring_lock);
2070 static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
2071 const struct io_uring_sqe *sqe)
2073 switch (sqe->opcode) {
2074 case IORING_OP_READV:
2075 case IORING_OP_READ_FIXED:
2076 return &ctx->pending_async[READ];
2077 case IORING_OP_WRITEV:
2078 case IORING_OP_WRITE_FIXED:
2079 return &ctx->pending_async[WRITE];
2085 static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
2087 u8 opcode = READ_ONCE(sqe->opcode);
2089 return !(opcode == IORING_OP_READ_FIXED ||
2090 opcode == IORING_OP_WRITE_FIXED);
2093 static void io_sq_wq_submit_work(struct work_struct *work)
2095 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2096 struct io_ring_ctx *ctx = req->ctx;
2097 struct mm_struct *cur_mm = NULL;
2098 struct async_list *async_list;
2099 LIST_HEAD(req_list);
2100 mm_segment_t old_fs;
2103 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
2106 struct sqe_submit *s = &req->submit;
2107 const struct io_uring_sqe *sqe = s->sqe;
2108 unsigned int flags = req->flags;
2110 /* Ensure we clear previously set non-block flag */
2111 req->rw.ki_flags &= ~IOCB_NOWAIT;
2114 if (io_sqe_needs_user(sqe) && !cur_mm) {
2115 if (!mmget_not_zero(ctx->sqo_mm)) {
2118 cur_mm = ctx->sqo_mm;
2126 s->has_user = cur_mm != NULL;
2127 s->needs_lock = true;
2129 ret = __io_submit_sqe(ctx, req, s, false);
2131 * We can get EAGAIN for polled IO even though
2132 * we're forcing a sync submission from here,
2133 * since we can't wait for request slots on the
2142 /* drop submission reference */
2146 io_cqring_add_event(ctx, sqe->user_data, ret);
2150 /* async context always use a copy of the sqe */
2153 /* req from defer and link list needn't decrease async cnt */
2154 if (flags & (REQ_F_IO_DRAINED | REQ_F_LINK_DONE))
2159 if (!list_empty(&req_list)) {
2160 req = list_first_entry(&req_list, struct io_kiocb,
2162 list_del(&req->list);
2165 if (list_empty(&async_list->list))
2169 spin_lock(&async_list->lock);
2170 if (list_empty(&async_list->list)) {
2171 spin_unlock(&async_list->lock);
2174 list_splice_init(&async_list->list, &req_list);
2175 spin_unlock(&async_list->lock);
2177 req = list_first_entry(&req_list, struct io_kiocb, list);
2178 list_del(&req->list);
2182 * Rare case of racing with a submitter. If we find the count has
2183 * dropped to zero AND we have pending work items, then restart
2184 * the processing. This is a tiny race window.
2187 ret = atomic_dec_return(&async_list->cnt);
2188 while (!ret && !list_empty(&async_list->list)) {
2189 spin_lock(&async_list->lock);
2190 atomic_inc(&async_list->cnt);
2191 list_splice_init(&async_list->list, &req_list);
2192 spin_unlock(&async_list->lock);
2194 if (!list_empty(&req_list)) {
2195 req = list_first_entry(&req_list,
2196 struct io_kiocb, list);
2197 list_del(&req->list);
2200 ret = atomic_dec_return(&async_list->cnt);
2213 * See if we can piggy back onto previously submitted work, that is still
2214 * running. We currently only allow this if the new request is sequential
2215 * to the previous one we punted.
2217 static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
2223 if (!(req->flags & REQ_F_SEQ_PREV))
2225 if (!atomic_read(&list->cnt))
2229 spin_lock(&list->lock);
2230 list_add_tail(&req->list, &list->list);
2232 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2235 if (!atomic_read(&list->cnt)) {
2236 list_del_init(&req->list);
2239 spin_unlock(&list->lock);
2243 static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2245 int op = READ_ONCE(sqe->opcode);
2249 case IORING_OP_POLL_REMOVE:
2256 static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
2257 struct io_submit_state *state, struct io_kiocb *req)
2262 flags = READ_ONCE(s->sqe->flags);
2263 fd = READ_ONCE(s->sqe->fd);
2265 if (flags & IOSQE_IO_DRAIN)
2266 req->flags |= REQ_F_IO_DRAIN;
2268 * All io need record the previous position, if LINK vs DARIN,
2269 * it can be used to mark the position of the first IO in the
2272 req->sequence = s->sequence;
2274 if (!io_op_needs_file(s->sqe))
2277 if (flags & IOSQE_FIXED_FILE) {
2278 if (unlikely(!ctx->user_files ||
2279 (unsigned) fd >= ctx->nr_user_files))
2281 req->file = ctx->user_files[fd];
2282 req->flags |= REQ_F_FIXED_FILE;
2284 if (s->needs_fixed_file)
2286 req->file = io_file_get(state, fd);
2287 if (unlikely(!req->file))
2294 static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2295 struct sqe_submit *s, bool force_nonblock)
2299 ret = __io_submit_sqe(ctx, req, s, force_nonblock);
2302 * We async punt it if the file wasn't marked NOWAIT, or if the file
2303 * doesn't support non-blocking read/write attempts
2305 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2306 (req->flags & REQ_F_MUST_PUNT))) {
2307 struct io_uring_sqe *sqe_copy;
2309 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2311 struct async_list *list;
2314 memcpy(&req->submit, s, sizeof(*s));
2315 list = io_async_list_from_sqe(ctx, s->sqe);
2316 if (!io_add_to_prev_work(list, req)) {
2318 atomic_inc(&list->cnt);
2319 INIT_WORK(&req->work, io_sq_wq_submit_work);
2320 io_queue_async_work(ctx, req);
2324 * Queued up for async execution, worker will release
2325 * submit reference when the iocb is actually submitted.
2331 /* drop submission reference */
2334 /* and drop final reference, if we failed */
2336 io_cqring_add_event(ctx, req->user_data, ret);
2337 if (req->flags & REQ_F_LINK)
2338 req->flags |= REQ_F_FAIL_LINK;
2345 static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2346 struct sqe_submit *s, bool force_nonblock)
2350 ret = io_req_defer(ctx, req, s->sqe);
2352 if (ret != -EIOCBQUEUED) {
2354 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2359 return __io_queue_sqe(ctx, req, s, force_nonblock);
2362 static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
2363 struct sqe_submit *s, struct io_kiocb *shadow,
2364 bool force_nonblock)
2367 int need_submit = false;
2370 return io_queue_sqe(ctx, req, s, force_nonblock);
2373 * Mark the first IO in link list as DRAIN, let all the following
2374 * IOs enter the defer list. all IO needs to be completed before link
2377 req->flags |= REQ_F_IO_DRAIN;
2378 ret = io_req_defer(ctx, req, s->sqe);
2380 if (ret != -EIOCBQUEUED) {
2382 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2387 * If ret == 0 means that all IOs in front of link io are
2388 * running done. let's queue link head.
2393 /* Insert shadow req to defer_list, blocking next IOs */
2394 spin_lock_irq(&ctx->completion_lock);
2395 list_add_tail(&shadow->list, &ctx->defer_list);
2396 spin_unlock_irq(&ctx->completion_lock);
2399 return __io_queue_sqe(ctx, req, s, force_nonblock);
2404 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2406 static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
2407 struct io_submit_state *state, struct io_kiocb **link,
2408 bool force_nonblock)
2410 struct io_uring_sqe *sqe_copy;
2411 struct io_kiocb *req;
2414 /* enforce forwards compatibility on users */
2415 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2420 req = io_get_req(ctx, state);
2421 if (unlikely(!req)) {
2426 ret = io_req_set_file(ctx, s, state, req);
2427 if (unlikely(ret)) {
2431 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2436 * If we already have a head request, queue this one for async
2437 * submittal once the head completes. If we don't have a head but
2438 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2439 * submitted sync once the chain is complete. If none of those
2440 * conditions are true (normal request), then just queue it.
2443 struct io_kiocb *prev = *link;
2445 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2452 memcpy(&req->submit, s, sizeof(*s));
2453 list_add_tail(&req->list, &prev->link_list);
2454 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2455 req->flags |= REQ_F_LINK;
2457 memcpy(&req->submit, s, sizeof(*s));
2458 INIT_LIST_HEAD(&req->link_list);
2461 io_queue_sqe(ctx, req, s, force_nonblock);
2466 * Batched submission is done, ensure local IO is flushed out.
2468 static void io_submit_state_end(struct io_submit_state *state)
2470 blk_finish_plug(&state->plug);
2472 if (state->free_reqs)
2473 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2474 &state->reqs[state->cur_req]);
2478 * Start submission side cache.
2480 static void io_submit_state_start(struct io_submit_state *state,
2481 struct io_ring_ctx *ctx, unsigned max_ios)
2483 blk_start_plug(&state->plug);
2484 state->free_reqs = 0;
2486 state->ios_left = max_ios;
2489 static void io_commit_sqring(struct io_ring_ctx *ctx)
2491 struct io_rings *rings = ctx->rings;
2493 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2495 * Ensure any loads from the SQEs are done at this point,
2496 * since once we write the new head, the application could
2497 * write new data to them.
2499 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2504 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2505 * that is mapped by userspace. This means that care needs to be taken to
2506 * ensure that reads are stable, as we cannot rely on userspace always
2507 * being a good citizen. If members of the sqe are validated and then later
2508 * used, it's important that those reads are done through READ_ONCE() to
2509 * prevent a re-load down the line.
2511 static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2513 struct io_rings *rings = ctx->rings;
2514 u32 *sq_array = ctx->sq_array;
2518 * The cached sq head (or cq tail) serves two purposes:
2520 * 1) allows us to batch the cost of updating the user visible
2522 * 2) allows the kernel side to track the head on its own, even
2523 * though the application is the one updating it.
2525 head = ctx->cached_sq_head;
2526 /* make sure SQ entry isn't read before tail */
2527 if (head == smp_load_acquire(&rings->sq.tail))
2530 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2531 if (head < ctx->sq_entries) {
2533 s->sqe = &ctx->sq_sqes[head];
2534 s->sequence = ctx->cached_sq_head;
2535 ctx->cached_sq_head++;
2539 /* drop invalid entries */
2540 ctx->cached_sq_head++;
2541 rings->sq_dropped++;
2545 static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
2546 unsigned int nr, bool has_user, bool mm_fault)
2548 struct io_submit_state state, *statep = NULL;
2549 struct io_kiocb *link = NULL;
2550 struct io_kiocb *shadow_req = NULL;
2551 bool prev_was_link = false;
2552 int i, submitted = 0;
2554 if (nr > IO_PLUG_THRESHOLD) {
2555 io_submit_state_start(&state, ctx, nr);
2559 for (i = 0; i < nr; i++) {
2561 * If previous wasn't linked and we have a linked command,
2562 * that's the end of the chain. Submit the previous link.
2564 if (!prev_was_link && link) {
2565 io_queue_link_head(ctx, link, &link->submit, shadow_req,
2570 prev_was_link = (sqes[i].sqe->flags & IOSQE_IO_LINK) != 0;
2572 if (link && (sqes[i].sqe->flags & IOSQE_IO_DRAIN)) {
2574 shadow_req = io_get_req(ctx, NULL);
2575 if (unlikely(!shadow_req))
2577 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2578 refcount_dec(&shadow_req->refs);
2580 shadow_req->sequence = sqes[i].sequence;
2584 if (unlikely(mm_fault)) {
2585 io_cqring_add_event(ctx, sqes[i].sqe->user_data,
2588 sqes[i].has_user = has_user;
2589 sqes[i].needs_lock = true;
2590 sqes[i].needs_fixed_file = true;
2591 io_submit_sqe(ctx, &sqes[i], statep, &link, true);
2597 io_queue_link_head(ctx, link, &link->submit, shadow_req, true);
2599 io_submit_state_end(&state);
2604 static int io_sq_thread(void *data)
2606 struct sqe_submit sqes[IO_IOPOLL_BATCH];
2607 struct io_ring_ctx *ctx = data;
2608 struct mm_struct *cur_mm = NULL;
2609 mm_segment_t old_fs;
2612 unsigned long timeout;
2614 complete(&ctx->sqo_thread_started);
2619 timeout = inflight = 0;
2620 while (!kthread_should_park()) {
2621 bool all_fixed, mm_fault = false;
2625 unsigned nr_events = 0;
2627 if (ctx->flags & IORING_SETUP_IOPOLL) {
2628 io_iopoll_check(ctx, &nr_events, 0);
2631 * Normal IO, just pretend everything completed.
2632 * We don't have to poll completions for that.
2634 nr_events = inflight;
2637 inflight -= nr_events;
2639 timeout = jiffies + ctx->sq_thread_idle;
2642 if (!io_get_sqring(ctx, &sqes[0])) {
2644 * We're polling. If we're within the defined idle
2645 * period, then let us spin without work before going
2648 if (inflight || !time_after(jiffies, timeout)) {
2654 * Drop cur_mm before scheduling, we can't hold it for
2655 * long periods (or over schedule()). Do this before
2656 * adding ourselves to the waitqueue, as the unuse/drop
2665 prepare_to_wait(&ctx->sqo_wait, &wait,
2666 TASK_INTERRUPTIBLE);
2668 /* Tell userspace we may need a wakeup call */
2669 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
2670 /* make sure to read SQ tail after writing flags */
2673 if (!io_get_sqring(ctx, &sqes[0])) {
2674 if (kthread_should_park()) {
2675 finish_wait(&ctx->sqo_wait, &wait);
2678 if (signal_pending(current))
2679 flush_signals(current);
2681 finish_wait(&ctx->sqo_wait, &wait);
2683 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2686 finish_wait(&ctx->sqo_wait, &wait);
2688 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2694 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2698 if (i == ARRAY_SIZE(sqes))
2700 } while (io_get_sqring(ctx, &sqes[i]));
2702 /* Unless all new commands are FIXED regions, grab mm */
2703 if (!all_fixed && !cur_mm) {
2704 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2706 use_mm(ctx->sqo_mm);
2707 cur_mm = ctx->sqo_mm;
2711 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2714 /* Commit SQ ring head once we've consumed all SQEs */
2715 io_commit_sqring(ctx);
2729 static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit,
2730 bool block_for_last)
2732 struct io_submit_state state, *statep = NULL;
2733 struct io_kiocb *link = NULL;
2734 struct io_kiocb *shadow_req = NULL;
2735 bool prev_was_link = false;
2738 if (to_submit > IO_PLUG_THRESHOLD) {
2739 io_submit_state_start(&state, ctx, to_submit);
2743 for (i = 0; i < to_submit; i++) {
2744 bool force_nonblock = true;
2745 struct sqe_submit s;
2747 if (!io_get_sqring(ctx, &s))
2751 * If previous wasn't linked and we have a linked command,
2752 * that's the end of the chain. Submit the previous link.
2754 if (!prev_was_link && link) {
2755 io_queue_link_head(ctx, link, &link->submit, shadow_req,
2760 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2762 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2764 shadow_req = io_get_req(ctx, NULL);
2765 if (unlikely(!shadow_req))
2767 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2768 refcount_dec(&shadow_req->refs);
2770 shadow_req->sequence = s.sequence;
2775 s.needs_lock = false;
2776 s.needs_fixed_file = false;
2780 * The caller will block for events after submit, submit the
2781 * last IO non-blocking. This is either the only IO it's
2782 * submitting, or it already submitted the previous ones. This
2783 * improves performance by avoiding an async punt that we don't
2786 if (block_for_last && submit == to_submit)
2787 force_nonblock = false;
2789 io_submit_sqe(ctx, &s, statep, &link, force_nonblock);
2791 io_commit_sqring(ctx);
2794 io_queue_link_head(ctx, link, &link->submit, shadow_req,
2797 io_submit_state_end(statep);
2803 * Wait until events become available, if we don't already have some. The
2804 * application must reap them itself, as they reside on the shared cq ring.
2806 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2807 const sigset_t __user *sig, size_t sigsz)
2809 struct io_rings *rings = ctx->rings;
2810 unsigned nr_timeouts;
2813 if (io_cqring_events(rings) >= min_events)
2817 #ifdef CONFIG_COMPAT
2818 if (in_compat_syscall())
2819 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2823 ret = set_user_sigmask(sig, sigsz);
2829 nr_timeouts = atomic_read(&ctx->cq_timeouts);
2831 * Return if we have enough events, or if a timeout occured since
2832 * we started waiting. For timeouts, we always want to return to
2835 ret = wait_event_interruptible(ctx->wait,
2836 io_cqring_events(rings) >= min_events ||
2837 atomic_read(&ctx->cq_timeouts) != nr_timeouts);
2838 restore_saved_sigmask_unless(ret == -ERESTARTSYS);
2839 if (ret == -ERESTARTSYS)
2842 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2845 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2847 #if defined(CONFIG_UNIX)
2848 if (ctx->ring_sock) {
2849 struct sock *sock = ctx->ring_sock->sk;
2850 struct sk_buff *skb;
2852 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2858 for (i = 0; i < ctx->nr_user_files; i++)
2859 fput(ctx->user_files[i]);
2863 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2865 if (!ctx->user_files)
2868 __io_sqe_files_unregister(ctx);
2869 kfree(ctx->user_files);
2870 ctx->user_files = NULL;
2871 ctx->nr_user_files = 0;
2875 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2877 if (ctx->sqo_thread) {
2878 wait_for_completion(&ctx->sqo_thread_started);
2880 * The park is a bit of a work-around, without it we get
2881 * warning spews on shutdown with SQPOLL set and affinity
2882 * set to a single CPU.
2884 kthread_park(ctx->sqo_thread);
2885 kthread_stop(ctx->sqo_thread);
2886 ctx->sqo_thread = NULL;
2890 static void io_finish_async(struct io_ring_ctx *ctx)
2894 io_sq_thread_stop(ctx);
2896 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++) {
2897 if (ctx->sqo_wq[i]) {
2898 destroy_workqueue(ctx->sqo_wq[i]);
2899 ctx->sqo_wq[i] = NULL;
2904 #if defined(CONFIG_UNIX)
2905 static void io_destruct_skb(struct sk_buff *skb)
2907 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2910 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++)
2912 flush_workqueue(ctx->sqo_wq[i]);
2914 unix_destruct_scm(skb);
2918 * Ensure the UNIX gc is aware of our file set, so we are certain that
2919 * the io_uring can be safely unregistered on process exit, even if we have
2920 * loops in the file referencing.
2922 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2924 struct sock *sk = ctx->ring_sock->sk;
2925 struct scm_fp_list *fpl;
2926 struct sk_buff *skb;
2929 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2930 unsigned long inflight = ctx->user->unix_inflight + nr;
2932 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2936 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2940 skb = alloc_skb(0, GFP_KERNEL);
2947 skb->destructor = io_destruct_skb;
2949 fpl->user = get_uid(ctx->user);
2950 for (i = 0; i < nr; i++) {
2951 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2952 unix_inflight(fpl->user, fpl->fp[i]);
2955 fpl->max = fpl->count = nr;
2956 UNIXCB(skb).fp = fpl;
2957 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2958 skb_queue_head(&sk->sk_receive_queue, skb);
2960 for (i = 0; i < nr; i++)
2967 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2968 * causes regular reference counting to break down. We rely on the UNIX
2969 * garbage collection to take care of this problem for us.
2971 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2973 unsigned left, total;
2977 left = ctx->nr_user_files;
2979 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2981 ret = __io_sqe_files_scm(ctx, this_files, total);
2985 total += this_files;
2991 while (total < ctx->nr_user_files) {
2992 fput(ctx->user_files[total]);
2999 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3005 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3008 __s32 __user *fds = (__s32 __user *) arg;
3012 if (ctx->user_files)
3016 if (nr_args > IORING_MAX_FIXED_FILES)
3019 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
3020 if (!ctx->user_files)
3023 for (i = 0; i < nr_args; i++) {
3025 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3028 ctx->user_files[i] = fget(fd);
3031 if (!ctx->user_files[i])
3034 * Don't allow io_uring instances to be registered. If UNIX
3035 * isn't enabled, then this causes a reference cycle and this
3036 * instance can never get freed. If UNIX is enabled we'll
3037 * handle it just fine, but there's still no point in allowing
3038 * a ring fd as it doesn't support regular read/write anyway.
3040 if (ctx->user_files[i]->f_op == &io_uring_fops) {
3041 fput(ctx->user_files[i]);
3044 ctx->nr_user_files++;
3049 for (i = 0; i < ctx->nr_user_files; i++)
3050 fput(ctx->user_files[i]);
3052 kfree(ctx->user_files);
3053 ctx->user_files = NULL;
3054 ctx->nr_user_files = 0;
3058 ret = io_sqe_files_scm(ctx);
3060 io_sqe_files_unregister(ctx);
3065 static int io_sq_offload_start(struct io_ring_ctx *ctx,
3066 struct io_uring_params *p)
3070 init_waitqueue_head(&ctx->sqo_wait);
3071 mmgrab(current->mm);
3072 ctx->sqo_mm = current->mm;
3074 if (ctx->flags & IORING_SETUP_SQPOLL) {
3076 if (!capable(CAP_SYS_ADMIN))
3079 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3080 if (!ctx->sq_thread_idle)
3081 ctx->sq_thread_idle = HZ;
3083 if (p->flags & IORING_SETUP_SQ_AFF) {
3084 int cpu = p->sq_thread_cpu;
3087 if (cpu >= nr_cpu_ids)
3089 if (!cpu_online(cpu))
3092 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3096 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3099 if (IS_ERR(ctx->sqo_thread)) {
3100 ret = PTR_ERR(ctx->sqo_thread);
3101 ctx->sqo_thread = NULL;
3104 wake_up_process(ctx->sqo_thread);
3105 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3106 /* Can't have SQ_AFF without SQPOLL */
3111 /* Do QD, or 2 * CPUS, whatever is smallest */
3112 ctx->sqo_wq[0] = alloc_workqueue("io_ring-wq",
3113 WQ_UNBOUND | WQ_FREEZABLE,
3114 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
3115 if (!ctx->sqo_wq[0]) {
3121 * This is for buffered writes, where we want to limit the parallelism
3122 * due to file locking in file systems. As "normal" buffered writes
3123 * should parellelize on writeout quite nicely, limit us to having 2
3124 * pending. This avoids massive contention on the inode when doing
3125 * buffered async writes.
3127 ctx->sqo_wq[1] = alloc_workqueue("io_ring-write-wq",
3128 WQ_UNBOUND | WQ_FREEZABLE, 2);
3129 if (!ctx->sqo_wq[1]) {
3136 io_finish_async(ctx);
3137 mmdrop(ctx->sqo_mm);
3142 static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3144 atomic_long_sub(nr_pages, &user->locked_vm);
3147 static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3149 unsigned long page_limit, cur_pages, new_pages;
3151 /* Don't allow more pages than we can safely lock */
3152 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3155 cur_pages = atomic_long_read(&user->locked_vm);
3156 new_pages = cur_pages + nr_pages;
3157 if (new_pages > page_limit)
3159 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3160 new_pages) != cur_pages);
3165 static void io_mem_free(void *ptr)
3172 page = virt_to_head_page(ptr);
3173 if (put_page_testzero(page))
3174 free_compound_page(page);
3177 static void *io_mem_alloc(size_t size)
3179 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3182 return (void *) __get_free_pages(gfp_flags, get_order(size));
3185 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3188 struct io_rings *rings;
3189 size_t off, sq_array_size;
3191 off = struct_size(rings, cqes, cq_entries);
3192 if (off == SIZE_MAX)
3196 off = ALIGN(off, SMP_CACHE_BYTES);
3201 sq_array_size = array_size(sizeof(u32), sq_entries);
3202 if (sq_array_size == SIZE_MAX)
3205 if (check_add_overflow(off, sq_array_size, &off))
3214 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3218 pages = (size_t)1 << get_order(
3219 rings_size(sq_entries, cq_entries, NULL));
3220 pages += (size_t)1 << get_order(
3221 array_size(sizeof(struct io_uring_sqe), sq_entries));
3226 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3230 if (!ctx->user_bufs)
3233 for (i = 0; i < ctx->nr_user_bufs; i++) {
3234 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3236 for (j = 0; j < imu->nr_bvecs; j++)
3237 put_user_page(imu->bvec[j].bv_page);
3239 if (ctx->account_mem)
3240 io_unaccount_mem(ctx->user, imu->nr_bvecs);
3245 kfree(ctx->user_bufs);
3246 ctx->user_bufs = NULL;
3247 ctx->nr_user_bufs = 0;
3251 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3252 void __user *arg, unsigned index)
3254 struct iovec __user *src;
3256 #ifdef CONFIG_COMPAT
3258 struct compat_iovec __user *ciovs;
3259 struct compat_iovec ciov;
3261 ciovs = (struct compat_iovec __user *) arg;
3262 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3265 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3266 dst->iov_len = ciov.iov_len;
3270 src = (struct iovec __user *) arg;
3271 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3276 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3279 struct vm_area_struct **vmas = NULL;
3280 struct page **pages = NULL;
3281 int i, j, got_pages = 0;
3286 if (!nr_args || nr_args > UIO_MAXIOV)
3289 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3291 if (!ctx->user_bufs)
3294 for (i = 0; i < nr_args; i++) {
3295 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3296 unsigned long off, start, end, ubuf;
3301 ret = io_copy_iov(ctx, &iov, arg, i);
3306 * Don't impose further limits on the size and buffer
3307 * constraints here, we'll -EINVAL later when IO is
3308 * submitted if they are wrong.
3311 if (!iov.iov_base || !iov.iov_len)
3314 /* arbitrary limit, but we need something */
3315 if (iov.iov_len > SZ_1G)
3318 ubuf = (unsigned long) iov.iov_base;
3319 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3320 start = ubuf >> PAGE_SHIFT;
3321 nr_pages = end - start;
3323 if (ctx->account_mem) {
3324 ret = io_account_mem(ctx->user, nr_pages);
3330 if (!pages || nr_pages > got_pages) {
3333 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
3335 vmas = kvmalloc_array(nr_pages,
3336 sizeof(struct vm_area_struct *),
3338 if (!pages || !vmas) {
3340 if (ctx->account_mem)
3341 io_unaccount_mem(ctx->user, nr_pages);
3344 got_pages = nr_pages;
3347 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
3351 if (ctx->account_mem)
3352 io_unaccount_mem(ctx->user, nr_pages);
3357 down_read(¤t->mm->mmap_sem);
3358 pret = get_user_pages(ubuf, nr_pages,
3359 FOLL_WRITE | FOLL_LONGTERM,
3361 if (pret == nr_pages) {
3362 /* don't support file backed memory */
3363 for (j = 0; j < nr_pages; j++) {
3364 struct vm_area_struct *vma = vmas[j];
3367 !is_file_hugepages(vma->vm_file)) {
3373 ret = pret < 0 ? pret : -EFAULT;
3375 up_read(¤t->mm->mmap_sem);
3378 * if we did partial map, or found file backed vmas,
3379 * release any pages we did get
3382 put_user_pages(pages, pret);
3383 if (ctx->account_mem)
3384 io_unaccount_mem(ctx->user, nr_pages);
3389 off = ubuf & ~PAGE_MASK;
3391 for (j = 0; j < nr_pages; j++) {
3394 vec_len = min_t(size_t, size, PAGE_SIZE - off);
3395 imu->bvec[j].bv_page = pages[j];
3396 imu->bvec[j].bv_len = vec_len;
3397 imu->bvec[j].bv_offset = off;
3401 /* store original address for later verification */
3403 imu->len = iov.iov_len;
3404 imu->nr_bvecs = nr_pages;
3406 ctx->nr_user_bufs++;
3414 io_sqe_buffer_unregister(ctx);
3418 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
3420 __s32 __user *fds = arg;
3426 if (copy_from_user(&fd, fds, sizeof(*fds)))
3429 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
3430 if (IS_ERR(ctx->cq_ev_fd)) {
3431 int ret = PTR_ERR(ctx->cq_ev_fd);
3432 ctx->cq_ev_fd = NULL;
3439 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
3441 if (ctx->cq_ev_fd) {
3442 eventfd_ctx_put(ctx->cq_ev_fd);
3443 ctx->cq_ev_fd = NULL;
3450 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
3452 io_finish_async(ctx);
3454 mmdrop(ctx->sqo_mm);
3456 io_iopoll_reap_events(ctx);
3457 io_sqe_buffer_unregister(ctx);
3458 io_sqe_files_unregister(ctx);
3459 io_eventfd_unregister(ctx);
3461 #if defined(CONFIG_UNIX)
3462 if (ctx->ring_sock) {
3463 ctx->ring_sock->file = NULL; /* so that iput() is called */
3464 sock_release(ctx->ring_sock);
3468 io_mem_free(ctx->rings);
3469 io_mem_free(ctx->sq_sqes);
3471 percpu_ref_exit(&ctx->refs);
3472 if (ctx->account_mem)
3473 io_unaccount_mem(ctx->user,
3474 ring_pages(ctx->sq_entries, ctx->cq_entries));
3475 free_uid(ctx->user);
3479 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3481 struct io_ring_ctx *ctx = file->private_data;
3484 poll_wait(file, &ctx->cq_wait, wait);
3486 * synchronizes with barrier from wq_has_sleeper call in
3490 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
3491 ctx->rings->sq_ring_entries)
3492 mask |= EPOLLOUT | EPOLLWRNORM;
3493 if (READ_ONCE(ctx->rings->sq.head) != ctx->cached_cq_tail)
3494 mask |= EPOLLIN | EPOLLRDNORM;
3499 static int io_uring_fasync(int fd, struct file *file, int on)
3501 struct io_ring_ctx *ctx = file->private_data;
3503 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3506 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3508 mutex_lock(&ctx->uring_lock);
3509 percpu_ref_kill(&ctx->refs);
3510 mutex_unlock(&ctx->uring_lock);
3512 io_kill_timeouts(ctx);
3513 io_poll_remove_all(ctx);
3514 io_iopoll_reap_events(ctx);
3515 wait_for_completion(&ctx->ctx_done);
3516 io_ring_ctx_free(ctx);
3519 static int io_uring_release(struct inode *inode, struct file *file)
3521 struct io_ring_ctx *ctx = file->private_data;
3523 file->private_data = NULL;
3524 io_ring_ctx_wait_and_kill(ctx);
3528 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3530 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3531 unsigned long sz = vma->vm_end - vma->vm_start;
3532 struct io_ring_ctx *ctx = file->private_data;
3538 case IORING_OFF_SQ_RING:
3539 case IORING_OFF_CQ_RING:
3542 case IORING_OFF_SQES:
3549 page = virt_to_head_page(ptr);
3550 if (sz > page_size(page))
3553 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3554 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3557 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3558 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3561 struct io_ring_ctx *ctx;
3566 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
3574 if (f.file->f_op != &io_uring_fops)
3578 ctx = f.file->private_data;
3579 if (!percpu_ref_tryget(&ctx->refs))
3583 * For SQ polling, the thread will do all submissions and completions.
3584 * Just return the requested submit count, and wake the thread if
3588 if (ctx->flags & IORING_SETUP_SQPOLL) {
3589 if (flags & IORING_ENTER_SQ_WAKEUP)
3590 wake_up(&ctx->sqo_wait);
3591 submitted = to_submit;
3592 } else if (to_submit) {
3593 bool block_for_last = false;
3595 to_submit = min(to_submit, ctx->sq_entries);
3598 * Allow last submission to block in a series, IFF the caller
3599 * asked to wait for events and we don't currently have
3600 * enough. This potentially avoids an async punt.
3602 if (to_submit == min_complete &&
3603 io_cqring_events(ctx->rings) < min_complete)
3604 block_for_last = true;
3606 mutex_lock(&ctx->uring_lock);
3607 submitted = io_ring_submit(ctx, to_submit, block_for_last);
3608 mutex_unlock(&ctx->uring_lock);
3610 if (flags & IORING_ENTER_GETEVENTS) {
3611 unsigned nr_events = 0;
3613 min_complete = min(min_complete, ctx->cq_entries);
3615 if (ctx->flags & IORING_SETUP_IOPOLL) {
3616 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3618 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3622 percpu_ref_put(&ctx->refs);
3625 return submitted ? submitted : ret;
3628 static const struct file_operations io_uring_fops = {
3629 .release = io_uring_release,
3630 .mmap = io_uring_mmap,
3631 .poll = io_uring_poll,
3632 .fasync = io_uring_fasync,
3635 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3636 struct io_uring_params *p)
3638 struct io_rings *rings;
3639 size_t size, sq_array_offset;
3641 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
3642 if (size == SIZE_MAX)
3645 rings = io_mem_alloc(size);
3650 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3651 rings->sq_ring_mask = p->sq_entries - 1;
3652 rings->cq_ring_mask = p->cq_entries - 1;
3653 rings->sq_ring_entries = p->sq_entries;
3654 rings->cq_ring_entries = p->cq_entries;
3655 ctx->sq_mask = rings->sq_ring_mask;
3656 ctx->cq_mask = rings->cq_ring_mask;
3657 ctx->sq_entries = rings->sq_ring_entries;
3658 ctx->cq_entries = rings->cq_ring_entries;
3660 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3661 if (size == SIZE_MAX)
3664 ctx->sq_sqes = io_mem_alloc(size);
3672 * Allocate an anonymous fd, this is what constitutes the application
3673 * visible backing of an io_uring instance. The application mmaps this
3674 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3675 * we have to tie this fd to a socket for file garbage collection purposes.
3677 static int io_uring_get_fd(struct io_ring_ctx *ctx)
3682 #if defined(CONFIG_UNIX)
3683 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3689 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3693 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3694 O_RDWR | O_CLOEXEC);
3697 ret = PTR_ERR(file);
3701 #if defined(CONFIG_UNIX)
3702 ctx->ring_sock->file = file;
3703 ctx->ring_sock->sk->sk_user_data = ctx;
3705 fd_install(ret, file);
3708 #if defined(CONFIG_UNIX)
3709 sock_release(ctx->ring_sock);
3710 ctx->ring_sock = NULL;
3715 static int io_uring_create(unsigned entries, struct io_uring_params *p)
3717 struct user_struct *user = NULL;
3718 struct io_ring_ctx *ctx;
3722 if (!entries || entries > IORING_MAX_ENTRIES)
3726 * Use twice as many entries for the CQ ring. It's possible for the
3727 * application to drive a higher depth than the size of the SQ ring,
3728 * since the sqes are only used at submission time. This allows for
3729 * some flexibility in overcommitting a bit.
3731 p->sq_entries = roundup_pow_of_two(entries);
3732 p->cq_entries = 2 * p->sq_entries;
3734 user = get_uid(current_user());
3735 account_mem = !capable(CAP_IPC_LOCK);
3738 ret = io_account_mem(user,
3739 ring_pages(p->sq_entries, p->cq_entries));
3746 ctx = io_ring_ctx_alloc(p);
3749 io_unaccount_mem(user, ring_pages(p->sq_entries,
3754 ctx->compat = in_compat_syscall();
3755 ctx->account_mem = account_mem;
3758 ret = io_allocate_scq_urings(ctx, p);
3762 ret = io_sq_offload_start(ctx, p);
3766 ret = io_uring_get_fd(ctx);
3770 memset(&p->sq_off, 0, sizeof(p->sq_off));
3771 p->sq_off.head = offsetof(struct io_rings, sq.head);
3772 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3773 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3774 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3775 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3776 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3777 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3779 memset(&p->cq_off, 0, sizeof(p->cq_off));
3780 p->cq_off.head = offsetof(struct io_rings, cq.head);
3781 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3782 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3783 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3784 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3785 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3787 p->features = IORING_FEAT_SINGLE_MMAP;
3790 io_ring_ctx_wait_and_kill(ctx);
3795 * Sets up an aio uring context, and returns the fd. Applications asks for a
3796 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3797 * params structure passed in.
3799 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3801 struct io_uring_params p;
3805 if (copy_from_user(&p, params, sizeof(p)))
3807 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3812 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3813 IORING_SETUP_SQ_AFF))
3816 ret = io_uring_create(entries, &p);
3820 if (copy_to_user(params, &p, sizeof(p)))
3826 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3827 struct io_uring_params __user *, params)
3829 return io_uring_setup(entries, params);
3832 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3833 void __user *arg, unsigned nr_args)
3834 __releases(ctx->uring_lock)
3835 __acquires(ctx->uring_lock)
3840 * We're inside the ring mutex, if the ref is already dying, then
3841 * someone else killed the ctx or is already going through
3842 * io_uring_register().
3844 if (percpu_ref_is_dying(&ctx->refs))
3847 percpu_ref_kill(&ctx->refs);
3850 * Drop uring mutex before waiting for references to exit. If another
3851 * thread is currently inside io_uring_enter() it might need to grab
3852 * the uring_lock to make progress. If we hold it here across the drain
3853 * wait, then we can deadlock. It's safe to drop the mutex here, since
3854 * no new references will come in after we've killed the percpu ref.
3856 mutex_unlock(&ctx->uring_lock);
3857 wait_for_completion(&ctx->ctx_done);
3858 mutex_lock(&ctx->uring_lock);
3861 case IORING_REGISTER_BUFFERS:
3862 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3864 case IORING_UNREGISTER_BUFFERS:
3868 ret = io_sqe_buffer_unregister(ctx);
3870 case IORING_REGISTER_FILES:
3871 ret = io_sqe_files_register(ctx, arg, nr_args);
3873 case IORING_UNREGISTER_FILES:
3877 ret = io_sqe_files_unregister(ctx);
3879 case IORING_REGISTER_EVENTFD:
3883 ret = io_eventfd_register(ctx, arg);
3885 case IORING_UNREGISTER_EVENTFD:
3889 ret = io_eventfd_unregister(ctx);
3896 /* bring the ctx back to life */
3897 reinit_completion(&ctx->ctx_done);
3898 percpu_ref_reinit(&ctx->refs);
3902 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3903 void __user *, arg, unsigned int, nr_args)
3905 struct io_ring_ctx *ctx;
3914 if (f.file->f_op != &io_uring_fops)
3917 ctx = f.file->private_data;
3919 mutex_lock(&ctx->uring_lock);
3920 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3921 mutex_unlock(&ctx->uring_lock);
3927 static int __init io_uring_init(void)
3929 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3932 __initcall(io_uring_init);