]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/io_uring.c
io_uring: add support for recvmsg()
[mirror_ubuntu-jammy-kernel.git] / fs / io_uring.c
CommitLineData
2b188cc1
JA
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
1e84b97b
SB
7 * the application and kernel side.
8 *
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
16 * CQ entries.
17 *
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
23 * head will do).
24 *
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
28 * between.
2b188cc1
JA
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
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.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
c992fe29 40 * Copyright (c) 2018-2019 Christoph Hellwig
2b188cc1
JA
41 */
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>
49
50#include <linux/sched/signal.h>
51#include <linux/fs.h>
52#include <linux/file.h>
53#include <linux/fdtable.h>
54#include <linux/mm.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>
6c271ce2 60#include <linux/kthread.h>
2b188cc1 61#include <linux/blkdev.h>
edafccee 62#include <linux/bvec.h>
2b188cc1
JA
63#include <linux/net.h>
64#include <net/sock.h>
65#include <net/af_unix.h>
6b06314c 66#include <net/scm.h>
2b188cc1
JA
67#include <linux/anon_inodes.h>
68#include <linux/sched/mm.h>
69#include <linux/uaccess.h>
70#include <linux/nospec.h>
edafccee
JA
71#include <linux/sizes.h>
72#include <linux/hugetlb.h>
2b188cc1
JA
73
74#include <uapi/linux/io_uring.h>
75
76#include "internal.h"
77
78#define IORING_MAX_ENTRIES 4096
6b06314c 79#define IORING_MAX_FIXED_FILES 1024
2b188cc1
JA
80
81struct io_uring {
82 u32 head ____cacheline_aligned_in_smp;
83 u32 tail ____cacheline_aligned_in_smp;
84};
85
1e84b97b
SB
86/*
87 * This data is shared with the application through the mmap at offset
88 * IORING_OFF_SQ_RING.
89 *
90 * The offsets to the member fields are published through struct
91 * io_sqring_offsets when calling io_uring_setup.
92 */
2b188cc1 93struct io_sq_ring {
1e84b97b
SB
94 /*
95 * Head and tail offsets into the ring; the offsets need to be
96 * masked to get valid indices.
97 *
98 * The kernel controls head and the application controls tail.
99 */
2b188cc1 100 struct io_uring r;
1e84b97b
SB
101 /*
102 * Bitmask to apply to head and tail offsets (constant, equals
103 * ring_entries - 1)
104 */
2b188cc1 105 u32 ring_mask;
1e84b97b 106 /* Ring size (constant, power of 2) */
2b188cc1 107 u32 ring_entries;
1e84b97b
SB
108 /*
109 * Number of invalid entries dropped by the kernel due to
110 * invalid index stored in array
111 *
112 * Written by the kernel, shouldn't be modified by the
113 * application (i.e. get number of "new events" by comparing to
114 * cached value).
115 *
116 * After a new SQ head value was read by the application this
117 * counter includes all submissions that were dropped reaching
118 * the new SQ head (and possibly more).
119 */
2b188cc1 120 u32 dropped;
1e84b97b
SB
121 /*
122 * Runtime flags
123 *
124 * Written by the kernel, shouldn't be modified by the
125 * application.
126 *
127 * The application needs a full memory barrier before checking
128 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
129 */
2b188cc1 130 u32 flags;
1e84b97b
SB
131 /*
132 * Ring buffer of indices into array of io_uring_sqe, which is
133 * mmapped by the application using the IORING_OFF_SQES offset.
134 *
135 * This indirection could e.g. be used to assign fixed
136 * io_uring_sqe entries to operations and only submit them to
137 * the queue when needed.
138 *
139 * The kernel modifies neither the indices array nor the entries
140 * array.
141 */
2b188cc1
JA
142 u32 array[];
143};
144
1e84b97b
SB
145/*
146 * This data is shared with the application through the mmap at offset
147 * IORING_OFF_CQ_RING.
148 *
149 * The offsets to the member fields are published through struct
150 * io_cqring_offsets when calling io_uring_setup.
151 */
2b188cc1 152struct io_cq_ring {
1e84b97b
SB
153 /*
154 * Head and tail offsets into the ring; the offsets need to be
155 * masked to get valid indices.
156 *
157 * The application controls head and the kernel tail.
158 */
2b188cc1 159 struct io_uring r;
1e84b97b
SB
160 /*
161 * Bitmask to apply to head and tail offsets (constant, equals
162 * ring_entries - 1)
163 */
2b188cc1 164 u32 ring_mask;
1e84b97b 165 /* Ring size (constant, power of 2) */
2b188cc1 166 u32 ring_entries;
1e84b97b
SB
167 /*
168 * Number of completion events lost because the queue was full;
169 * this should be avoided by the application by making sure
170 * there are not more requests pending thatn there is space in
171 * the completion queue.
172 *
173 * Written by the kernel, shouldn't be modified by the
174 * application (i.e. get number of "new events" by comparing to
175 * cached value).
176 *
177 * As completion events come in out of order this counter is not
178 * ordered with any other data.
179 */
2b188cc1 180 u32 overflow;
1e84b97b
SB
181 /*
182 * Ring buffer of completion events.
183 *
184 * The kernel writes completion events fresh every time they are
185 * produced, so the application is allowed to modify pending
186 * entries.
187 */
2b188cc1
JA
188 struct io_uring_cqe cqes[];
189};
190
edafccee
JA
191struct io_mapped_ubuf {
192 u64 ubuf;
193 size_t len;
194 struct bio_vec *bvec;
195 unsigned int nr_bvecs;
196};
197
31b51510
JA
198struct async_list {
199 spinlock_t lock;
200 atomic_t cnt;
201 struct list_head list;
202
203 struct file *file;
204 off_t io_end;
205 size_t io_pages;
206};
207
2b188cc1
JA
208struct io_ring_ctx {
209 struct {
210 struct percpu_ref refs;
211 } ____cacheline_aligned_in_smp;
212
213 struct {
214 unsigned int flags;
215 bool compat;
216 bool account_mem;
217
218 /* SQ ring */
219 struct io_sq_ring *sq_ring;
220 unsigned cached_sq_head;
221 unsigned sq_entries;
222 unsigned sq_mask;
6c271ce2 223 unsigned sq_thread_idle;
2b188cc1 224 struct io_uring_sqe *sq_sqes;
de0617e4
JA
225
226 struct list_head defer_list;
2b188cc1
JA
227 } ____cacheline_aligned_in_smp;
228
229 /* IO offload */
230 struct workqueue_struct *sqo_wq;
6c271ce2 231 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 232 struct mm_struct *sqo_mm;
6c271ce2 233 wait_queue_head_t sqo_wait;
2b188cc1
JA
234
235 struct {
236 /* CQ ring */
237 struct io_cq_ring *cq_ring;
238 unsigned cached_cq_tail;
239 unsigned cq_entries;
240 unsigned cq_mask;
241 struct wait_queue_head cq_wait;
242 struct fasync_struct *cq_fasync;
9b402849 243 struct eventfd_ctx *cq_ev_fd;
2b188cc1
JA
244 } ____cacheline_aligned_in_smp;
245
6b06314c
JA
246 /*
247 * If used, fixed file set. Writers must ensure that ->refs is dead,
248 * readers must ensure that ->refs is alive as long as the file* is
249 * used. Only updated through io_uring_register(2).
250 */
251 struct file **user_files;
252 unsigned nr_user_files;
253
edafccee
JA
254 /* if used, fixed mapped user buffers */
255 unsigned nr_user_bufs;
256 struct io_mapped_ubuf *user_bufs;
257
2b188cc1
JA
258 struct user_struct *user;
259
260 struct completion ctx_done;
261
262 struct {
263 struct mutex uring_lock;
264 wait_queue_head_t wait;
265 } ____cacheline_aligned_in_smp;
266
267 struct {
268 spinlock_t completion_lock;
def596e9
JA
269 bool poll_multi_file;
270 /*
271 * ->poll_list is protected by the ctx->uring_lock for
272 * io_uring instances that don't use IORING_SETUP_SQPOLL.
273 * For SQPOLL, only the single threaded io_sq_thread() will
274 * manipulate the list, hence no extra locking is needed there.
275 */
276 struct list_head poll_list;
221c5eb2 277 struct list_head cancel_list;
2b188cc1
JA
278 } ____cacheline_aligned_in_smp;
279
31b51510
JA
280 struct async_list pending_async[2];
281
2b188cc1
JA
282#if defined(CONFIG_UNIX)
283 struct socket *ring_sock;
284#endif
285};
286
287struct sqe_submit {
288 const struct io_uring_sqe *sqe;
289 unsigned short index;
290 bool has_user;
def596e9 291 bool needs_lock;
6c271ce2 292 bool needs_fixed_file;
2b188cc1
JA
293};
294
09bb8394
JA
295/*
296 * First field must be the file pointer in all the
297 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
298 */
221c5eb2
JA
299struct io_poll_iocb {
300 struct file *file;
301 struct wait_queue_head *head;
302 __poll_t events;
8c838788 303 bool done;
221c5eb2
JA
304 bool canceled;
305 struct wait_queue_entry wait;
306};
307
09bb8394
JA
308/*
309 * NOTE! Each of the iocb union members has the file pointer
310 * as the first entry in their struct definition. So you can
311 * access the file pointer through any of the sub-structs,
312 * or directly as just 'ki_filp' in this struct.
313 */
2b188cc1 314struct io_kiocb {
221c5eb2 315 union {
09bb8394 316 struct file *file;
221c5eb2
JA
317 struct kiocb rw;
318 struct io_poll_iocb poll;
319 };
2b188cc1
JA
320
321 struct sqe_submit submit;
322
323 struct io_ring_ctx *ctx;
324 struct list_head list;
9e645e11 325 struct list_head link_list;
2b188cc1 326 unsigned int flags;
c16361c1 327 refcount_t refs;
8449eeda 328#define REQ_F_NOWAIT 1 /* must not punt to workers */
def596e9 329#define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
6b06314c 330#define REQ_F_FIXED_FILE 4 /* ctx owns file */
31b51510 331#define REQ_F_SEQ_PREV 8 /* sequential with previous */
e2033e33
SB
332#define REQ_F_IO_DRAIN 16 /* drain existing IO first */
333#define REQ_F_IO_DRAINED 32 /* drain done */
9e645e11
JA
334#define REQ_F_LINK 64 /* linked sqes */
335#define REQ_F_FAIL_LINK 128 /* fail rest of links */
2b188cc1 336 u64 user_data;
9e645e11 337 u32 result;
de0617e4 338 u32 sequence;
2b188cc1
JA
339
340 struct work_struct work;
341};
342
343#define IO_PLUG_THRESHOLD 2
def596e9 344#define IO_IOPOLL_BATCH 8
2b188cc1 345
9a56a232
JA
346struct io_submit_state {
347 struct blk_plug plug;
348
2579f913
JA
349 /*
350 * io_kiocb alloc cache
351 */
352 void *reqs[IO_IOPOLL_BATCH];
353 unsigned int free_reqs;
354 unsigned int cur_req;
355
9a56a232
JA
356 /*
357 * File reference cache
358 */
359 struct file *file;
360 unsigned int fd;
361 unsigned int has_refs;
362 unsigned int used_refs;
363 unsigned int ios_left;
364};
365
de0617e4
JA
366static void io_sq_wq_submit_work(struct work_struct *work);
367
2b188cc1
JA
368static struct kmem_cache *req_cachep;
369
370static const struct file_operations io_uring_fops;
371
372struct sock *io_uring_get_socket(struct file *file)
373{
374#if defined(CONFIG_UNIX)
375 if (file->f_op == &io_uring_fops) {
376 struct io_ring_ctx *ctx = file->private_data;
377
378 return ctx->ring_sock->sk;
379 }
380#endif
381 return NULL;
382}
383EXPORT_SYMBOL(io_uring_get_socket);
384
385static void io_ring_ctx_ref_free(struct percpu_ref *ref)
386{
387 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
388
389 complete(&ctx->ctx_done);
390}
391
392static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
393{
394 struct io_ring_ctx *ctx;
31b51510 395 int i;
2b188cc1
JA
396
397 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
398 if (!ctx)
399 return NULL;
400
401 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, 0, GFP_KERNEL)) {
402 kfree(ctx);
403 return NULL;
404 }
405
406 ctx->flags = p->flags;
407 init_waitqueue_head(&ctx->cq_wait);
408 init_completion(&ctx->ctx_done);
409 mutex_init(&ctx->uring_lock);
410 init_waitqueue_head(&ctx->wait);
31b51510
JA
411 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
412 spin_lock_init(&ctx->pending_async[i].lock);
413 INIT_LIST_HEAD(&ctx->pending_async[i].list);
414 atomic_set(&ctx->pending_async[i].cnt, 0);
415 }
2b188cc1 416 spin_lock_init(&ctx->completion_lock);
def596e9 417 INIT_LIST_HEAD(&ctx->poll_list);
221c5eb2 418 INIT_LIST_HEAD(&ctx->cancel_list);
de0617e4 419 INIT_LIST_HEAD(&ctx->defer_list);
2b188cc1
JA
420 return ctx;
421}
422
de0617e4
JA
423static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
424 struct io_kiocb *req)
425{
426 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
427 return false;
428
429 return req->sequence > ctx->cached_cq_tail + ctx->sq_ring->dropped;
430}
431
432static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
433{
434 struct io_kiocb *req;
435
436 if (list_empty(&ctx->defer_list))
437 return NULL;
438
439 req = list_first_entry(&ctx->defer_list, struct io_kiocb, list);
440 if (!io_sequence_defer(ctx, req)) {
441 list_del_init(&req->list);
442 return req;
443 }
444
445 return NULL;
446}
447
448static void __io_commit_cqring(struct io_ring_ctx *ctx)
2b188cc1
JA
449{
450 struct io_cq_ring *ring = ctx->cq_ring;
451
452 if (ctx->cached_cq_tail != READ_ONCE(ring->r.tail)) {
453 /* order cqe stores with ring update */
454 smp_store_release(&ring->r.tail, ctx->cached_cq_tail);
455
2b188cc1
JA
456 if (wq_has_sleeper(&ctx->cq_wait)) {
457 wake_up_interruptible(&ctx->cq_wait);
458 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
459 }
460 }
461}
462
de0617e4
JA
463static void io_commit_cqring(struct io_ring_ctx *ctx)
464{
465 struct io_kiocb *req;
466
467 __io_commit_cqring(ctx);
468
469 while ((req = io_get_deferred_req(ctx)) != NULL) {
470 req->flags |= REQ_F_IO_DRAINED;
471 queue_work(ctx->sqo_wq, &req->work);
472 }
473}
474
2b188cc1
JA
475static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
476{
477 struct io_cq_ring *ring = ctx->cq_ring;
478 unsigned tail;
479
480 tail = ctx->cached_cq_tail;
115e12e5
SB
481 /*
482 * writes to the cq entry need to come after reading head; the
483 * control dependency is enough as we're using WRITE_ONCE to
484 * fill the cq entry
485 */
74f464e9 486 if (tail - READ_ONCE(ring->r.head) == ring->ring_entries)
2b188cc1
JA
487 return NULL;
488
489 ctx->cached_cq_tail++;
490 return &ring->cqes[tail & ctx->cq_mask];
491}
492
493static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
c71ffb67 494 long res)
2b188cc1
JA
495{
496 struct io_uring_cqe *cqe;
497
498 /*
499 * If we can't get a cq entry, userspace overflowed the
500 * submission (by quite a lot). Increment the overflow count in
501 * the ring.
502 */
503 cqe = io_get_cqring(ctx);
504 if (cqe) {
505 WRITE_ONCE(cqe->user_data, ki_user_data);
506 WRITE_ONCE(cqe->res, res);
c71ffb67 507 WRITE_ONCE(cqe->flags, 0);
2b188cc1
JA
508 } else {
509 unsigned overflow = READ_ONCE(ctx->cq_ring->overflow);
510
511 WRITE_ONCE(ctx->cq_ring->overflow, overflow + 1);
512 }
513}
514
8c838788
JA
515static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
516{
517 if (waitqueue_active(&ctx->wait))
518 wake_up(&ctx->wait);
519 if (waitqueue_active(&ctx->sqo_wait))
520 wake_up(&ctx->sqo_wait);
9b402849
JA
521 if (ctx->cq_ev_fd)
522 eventfd_signal(ctx->cq_ev_fd, 1);
8c838788
JA
523}
524
525static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
c71ffb67 526 long res)
2b188cc1
JA
527{
528 unsigned long flags;
529
530 spin_lock_irqsave(&ctx->completion_lock, flags);
c71ffb67 531 io_cqring_fill_event(ctx, user_data, res);
2b188cc1
JA
532 io_commit_cqring(ctx);
533 spin_unlock_irqrestore(&ctx->completion_lock, flags);
534
8c838788 535 io_cqring_ev_posted(ctx);
2b188cc1
JA
536}
537
538static void io_ring_drop_ctx_refs(struct io_ring_ctx *ctx, unsigned refs)
539{
540 percpu_ref_put_many(&ctx->refs, refs);
541
542 if (waitqueue_active(&ctx->wait))
543 wake_up(&ctx->wait);
544}
545
2579f913
JA
546static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
547 struct io_submit_state *state)
2b188cc1 548{
fd6fab2c 549 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
550 struct io_kiocb *req;
551
552 if (!percpu_ref_tryget(&ctx->refs))
553 return NULL;
554
2579f913 555 if (!state) {
fd6fab2c 556 req = kmem_cache_alloc(req_cachep, gfp);
2579f913
JA
557 if (unlikely(!req))
558 goto out;
559 } else if (!state->free_reqs) {
560 size_t sz;
561 int ret;
562
563 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
564 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
565
566 /*
567 * Bulk alloc is all-or-nothing. If we fail to get a batch,
568 * retry single alloc to be on the safe side.
569 */
570 if (unlikely(ret <= 0)) {
571 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
572 if (!state->reqs[0])
573 goto out;
574 ret = 1;
575 }
2579f913
JA
576 state->free_reqs = ret - 1;
577 state->cur_req = 1;
578 req = state->reqs[0];
579 } else {
580 req = state->reqs[state->cur_req];
581 state->free_reqs--;
582 state->cur_req++;
2b188cc1
JA
583 }
584
2579f913
JA
585 req->ctx = ctx;
586 req->flags = 0;
e65ef56d
JA
587 /* one is dropped after submission, the other at completion */
588 refcount_set(&req->refs, 2);
9e645e11 589 req->result = 0;
2579f913
JA
590 return req;
591out:
2b188cc1
JA
592 io_ring_drop_ctx_refs(ctx, 1);
593 return NULL;
594}
595
def596e9
JA
596static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
597{
598 if (*nr) {
599 kmem_cache_free_bulk(req_cachep, *nr, reqs);
600 io_ring_drop_ctx_refs(ctx, *nr);
601 *nr = 0;
602 }
603}
604
9e645e11 605static void __io_free_req(struct io_kiocb *req)
2b188cc1 606{
09bb8394
JA
607 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
608 fput(req->file);
e65ef56d
JA
609 io_ring_drop_ctx_refs(req->ctx, 1);
610 kmem_cache_free(req_cachep, req);
611}
612
9e645e11
JA
613static void io_req_link_next(struct io_kiocb *req)
614{
615 struct io_kiocb *nxt;
616
617 /*
618 * The list should never be empty when we are called here. But could
619 * potentially happen if the chain is messed up, check to be on the
620 * safe side.
621 */
622 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
623 if (nxt) {
624 list_del(&nxt->list);
625 if (!list_empty(&req->link_list)) {
626 INIT_LIST_HEAD(&nxt->link_list);
627 list_splice(&req->link_list, &nxt->link_list);
628 nxt->flags |= REQ_F_LINK;
629 }
630
631 INIT_WORK(&nxt->work, io_sq_wq_submit_work);
632 queue_work(req->ctx->sqo_wq, &nxt->work);
633 }
634}
635
636/*
637 * Called if REQ_F_LINK is set, and we fail the head request
638 */
639static void io_fail_links(struct io_kiocb *req)
640{
641 struct io_kiocb *link;
642
643 while (!list_empty(&req->link_list)) {
644 link = list_first_entry(&req->link_list, struct io_kiocb, list);
645 list_del(&link->list);
646
647 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
648 __io_free_req(link);
649 }
650}
651
652static void io_free_req(struct io_kiocb *req)
653{
654 /*
655 * If LINK is set, we have dependent requests in this chain. If we
656 * didn't fail this request, queue the first one up, moving any other
657 * dependencies to the next request. In case of failure, fail the rest
658 * of the chain.
659 */
660 if (req->flags & REQ_F_LINK) {
661 if (req->flags & REQ_F_FAIL_LINK)
662 io_fail_links(req);
663 else
664 io_req_link_next(req);
665 }
666
667 __io_free_req(req);
668}
669
e65ef56d
JA
670static void io_put_req(struct io_kiocb *req)
671{
672 if (refcount_dec_and_test(&req->refs))
673 io_free_req(req);
2b188cc1
JA
674}
675
def596e9
JA
676/*
677 * Find and free completed poll iocbs
678 */
679static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
680 struct list_head *done)
681{
682 void *reqs[IO_IOPOLL_BATCH];
683 struct io_kiocb *req;
09bb8394 684 int to_free;
def596e9 685
09bb8394 686 to_free = 0;
def596e9
JA
687 while (!list_empty(done)) {
688 req = list_first_entry(done, struct io_kiocb, list);
689 list_del(&req->list);
690
9e645e11 691 io_cqring_fill_event(ctx, req->user_data, req->result);
def596e9
JA
692 (*nr_events)++;
693
09bb8394
JA
694 if (refcount_dec_and_test(&req->refs)) {
695 /* If we're not using fixed files, we have to pair the
696 * completion part with the file put. Use regular
697 * completions for those, only batch free for fixed
9e645e11 698 * file and non-linked commands.
09bb8394 699 */
9e645e11
JA
700 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
701 REQ_F_FIXED_FILE) {
09bb8394
JA
702 reqs[to_free++] = req;
703 if (to_free == ARRAY_SIZE(reqs))
704 io_free_req_many(ctx, reqs, &to_free);
6b06314c 705 } else {
09bb8394 706 io_free_req(req);
6b06314c 707 }
9a56a232 708 }
def596e9 709 }
def596e9 710
09bb8394 711 io_commit_cqring(ctx);
def596e9
JA
712 io_free_req_many(ctx, reqs, &to_free);
713}
714
715static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
716 long min)
717{
718 struct io_kiocb *req, *tmp;
719 LIST_HEAD(done);
720 bool spin;
721 int ret;
722
723 /*
724 * Only spin for completions if we don't have multiple devices hanging
725 * off our complete list, and we're under the requested amount.
726 */
727 spin = !ctx->poll_multi_file && *nr_events < min;
728
729 ret = 0;
730 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
731 struct kiocb *kiocb = &req->rw;
732
733 /*
734 * Move completed entries to our local list. If we find a
735 * request that requires polling, break out and complete
736 * the done list first, if we have entries there.
737 */
738 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
739 list_move_tail(&req->list, &done);
740 continue;
741 }
742 if (!list_empty(&done))
743 break;
744
745 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
746 if (ret < 0)
747 break;
748
749 if (ret && spin)
750 spin = false;
751 ret = 0;
752 }
753
754 if (!list_empty(&done))
755 io_iopoll_complete(ctx, nr_events, &done);
756
757 return ret;
758}
759
760/*
761 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
762 * non-spinning poll check - we'll still enter the driver poll loop, but only
763 * as a non-spinning completion check.
764 */
765static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
766 long min)
767{
768 while (!list_empty(&ctx->poll_list)) {
769 int ret;
770
771 ret = io_do_iopoll(ctx, nr_events, min);
772 if (ret < 0)
773 return ret;
774 if (!min || *nr_events >= min)
775 return 0;
776 }
777
778 return 1;
779}
780
781/*
782 * We can't just wait for polled events to come to us, we have to actively
783 * find and complete them.
784 */
785static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
786{
787 if (!(ctx->flags & IORING_SETUP_IOPOLL))
788 return;
789
790 mutex_lock(&ctx->uring_lock);
791 while (!list_empty(&ctx->poll_list)) {
792 unsigned int nr_events = 0;
793
794 io_iopoll_getevents(ctx, &nr_events, 1);
795 }
796 mutex_unlock(&ctx->uring_lock);
797}
798
799static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
800 long min)
801{
802 int ret = 0;
803
804 do {
805 int tmin = 0;
806
807 if (*nr_events < min)
808 tmin = min - *nr_events;
809
810 ret = io_iopoll_getevents(ctx, nr_events, tmin);
811 if (ret <= 0)
812 break;
813 ret = 0;
814 } while (min && !*nr_events && !need_resched());
815
816 return ret;
817}
818
2b188cc1
JA
819static void kiocb_end_write(struct kiocb *kiocb)
820{
821 if (kiocb->ki_flags & IOCB_WRITE) {
822 struct inode *inode = file_inode(kiocb->ki_filp);
823
824 /*
825 * Tell lockdep we inherited freeze protection from submission
826 * thread.
827 */
828 if (S_ISREG(inode->i_mode))
829 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
830 file_end_write(kiocb->ki_filp);
831 }
832}
833
834static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
835{
836 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
837
838 kiocb_end_write(kiocb);
839
9e645e11
JA
840 if ((req->flags & REQ_F_LINK) && res != req->result)
841 req->flags |= REQ_F_FAIL_LINK;
c71ffb67 842 io_cqring_add_event(req->ctx, req->user_data, res);
e65ef56d 843 io_put_req(req);
2b188cc1
JA
844}
845
def596e9
JA
846static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
847{
848 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
849
850 kiocb_end_write(kiocb);
851
9e645e11
JA
852 if ((req->flags & REQ_F_LINK) && res != req->result)
853 req->flags |= REQ_F_FAIL_LINK;
854 req->result = res;
def596e9
JA
855 if (res != -EAGAIN)
856 req->flags |= REQ_F_IOPOLL_COMPLETED;
857}
858
859/*
860 * After the iocb has been issued, it's safe to be found on the poll list.
861 * Adding the kiocb to the list AFTER submission ensures that we don't
862 * find it from a io_iopoll_getevents() thread before the issuer is done
863 * accessing the kiocb cookie.
864 */
865static void io_iopoll_req_issued(struct io_kiocb *req)
866{
867 struct io_ring_ctx *ctx = req->ctx;
868
869 /*
870 * Track whether we have multiple files in our lists. This will impact
871 * how we do polling eventually, not spinning if we're on potentially
872 * different devices.
873 */
874 if (list_empty(&ctx->poll_list)) {
875 ctx->poll_multi_file = false;
876 } else if (!ctx->poll_multi_file) {
877 struct io_kiocb *list_req;
878
879 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
880 list);
881 if (list_req->rw.ki_filp != req->rw.ki_filp)
882 ctx->poll_multi_file = true;
883 }
884
885 /*
886 * For fast devices, IO may have already completed. If it has, add
887 * it to the front so we find it first.
888 */
889 if (req->flags & REQ_F_IOPOLL_COMPLETED)
890 list_add(&req->list, &ctx->poll_list);
891 else
892 list_add_tail(&req->list, &ctx->poll_list);
893}
894
3d6770fb 895static void io_file_put(struct io_submit_state *state)
9a56a232 896{
3d6770fb 897 if (state->file) {
9a56a232
JA
898 int diff = state->has_refs - state->used_refs;
899
900 if (diff)
901 fput_many(state->file, diff);
902 state->file = NULL;
903 }
904}
905
906/*
907 * Get as many references to a file as we have IOs left in this submission,
908 * assuming most submissions are for one file, or at least that each file
909 * has more than one submission.
910 */
911static struct file *io_file_get(struct io_submit_state *state, int fd)
912{
913 if (!state)
914 return fget(fd);
915
916 if (state->file) {
917 if (state->fd == fd) {
918 state->used_refs++;
919 state->ios_left--;
920 return state->file;
921 }
3d6770fb 922 io_file_put(state);
9a56a232
JA
923 }
924 state->file = fget_many(fd, state->ios_left);
925 if (!state->file)
926 return NULL;
927
928 state->fd = fd;
929 state->has_refs = state->ios_left;
930 state->used_refs = 1;
931 state->ios_left--;
932 return state->file;
933}
934
2b188cc1
JA
935/*
936 * If we tracked the file through the SCM inflight mechanism, we could support
937 * any file. For now, just ensure that anything potentially problematic is done
938 * inline.
939 */
940static bool io_file_supports_async(struct file *file)
941{
942 umode_t mode = file_inode(file)->i_mode;
943
944 if (S_ISBLK(mode) || S_ISCHR(mode))
945 return true;
946 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
947 return true;
948
949 return false;
950}
951
6c271ce2 952static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 953 bool force_nonblock)
2b188cc1 954{
6c271ce2 955 const struct io_uring_sqe *sqe = s->sqe;
def596e9 956 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 957 struct kiocb *kiocb = &req->rw;
09bb8394
JA
958 unsigned ioprio;
959 int ret;
2b188cc1 960
09bb8394
JA
961 if (!req->file)
962 return -EBADF;
2b188cc1 963
09bb8394
JA
964 if (force_nonblock && !io_file_supports_async(req->file))
965 force_nonblock = false;
6b06314c 966
2b188cc1
JA
967 kiocb->ki_pos = READ_ONCE(sqe->off);
968 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
969 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
970
971 ioprio = READ_ONCE(sqe->ioprio);
972 if (ioprio) {
973 ret = ioprio_check_cap(ioprio);
974 if (ret)
09bb8394 975 return ret;
2b188cc1
JA
976
977 kiocb->ki_ioprio = ioprio;
978 } else
979 kiocb->ki_ioprio = get_current_ioprio();
980
981 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
982 if (unlikely(ret))
09bb8394 983 return ret;
8449eeda
SB
984
985 /* don't allow async punt if RWF_NOWAIT was requested */
986 if (kiocb->ki_flags & IOCB_NOWAIT)
987 req->flags |= REQ_F_NOWAIT;
988
989 if (force_nonblock)
2b188cc1 990 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 991
def596e9 992 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
993 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
994 !kiocb->ki_filp->f_op->iopoll)
09bb8394 995 return -EOPNOTSUPP;
2b188cc1 996
def596e9
JA
997 kiocb->ki_flags |= IOCB_HIPRI;
998 kiocb->ki_complete = io_complete_rw_iopoll;
999 } else {
09bb8394
JA
1000 if (kiocb->ki_flags & IOCB_HIPRI)
1001 return -EINVAL;
def596e9
JA
1002 kiocb->ki_complete = io_complete_rw;
1003 }
2b188cc1 1004 return 0;
2b188cc1
JA
1005}
1006
1007static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1008{
1009 switch (ret) {
1010 case -EIOCBQUEUED:
1011 break;
1012 case -ERESTARTSYS:
1013 case -ERESTARTNOINTR:
1014 case -ERESTARTNOHAND:
1015 case -ERESTART_RESTARTBLOCK:
1016 /*
1017 * We can't just restart the syscall, since previously
1018 * submitted sqes may already be in progress. Just fail this
1019 * IO with EINTR.
1020 */
1021 ret = -EINTR;
1022 /* fall through */
1023 default:
1024 kiocb->ki_complete(kiocb, ret, 0);
1025 }
1026}
1027
edafccee
JA
1028static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1029 const struct io_uring_sqe *sqe,
1030 struct iov_iter *iter)
1031{
1032 size_t len = READ_ONCE(sqe->len);
1033 struct io_mapped_ubuf *imu;
1034 unsigned index, buf_index;
1035 size_t offset;
1036 u64 buf_addr;
1037
1038 /* attempt to use fixed buffers without having provided iovecs */
1039 if (unlikely(!ctx->user_bufs))
1040 return -EFAULT;
1041
1042 buf_index = READ_ONCE(sqe->buf_index);
1043 if (unlikely(buf_index >= ctx->nr_user_bufs))
1044 return -EFAULT;
1045
1046 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1047 imu = &ctx->user_bufs[index];
1048 buf_addr = READ_ONCE(sqe->addr);
1049
1050 /* overflow */
1051 if (buf_addr + len < buf_addr)
1052 return -EFAULT;
1053 /* not inside the mapped region */
1054 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1055 return -EFAULT;
1056
1057 /*
1058 * May not be a start of buffer, set size appropriately
1059 * and advance us to the beginning.
1060 */
1061 offset = buf_addr - imu->ubuf;
1062 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1063 if (offset)
1064 iov_iter_advance(iter, offset);
875f1d07
JA
1065
1066 /* don't drop a reference to these pages */
1067 iter->type |= ITER_BVEC_FLAG_NO_REF;
edafccee
JA
1068 return 0;
1069}
1070
87e5e6da
JA
1071static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1072 const struct sqe_submit *s, struct iovec **iovec,
1073 struct iov_iter *iter)
2b188cc1
JA
1074{
1075 const struct io_uring_sqe *sqe = s->sqe;
1076 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1077 size_t sqe_len = READ_ONCE(sqe->len);
edafccee
JA
1078 u8 opcode;
1079
1080 /*
1081 * We're reading ->opcode for the second time, but the first read
1082 * doesn't care whether it's _FIXED or not, so it doesn't matter
1083 * whether ->opcode changes concurrently. The first read does care
1084 * about whether it is a READ or a WRITE, so we don't trust this read
1085 * for that purpose and instead let the caller pass in the read/write
1086 * flag.
1087 */
1088 opcode = READ_ONCE(sqe->opcode);
1089 if (opcode == IORING_OP_READ_FIXED ||
1090 opcode == IORING_OP_WRITE_FIXED) {
87e5e6da 1091 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
edafccee
JA
1092 *iovec = NULL;
1093 return ret;
1094 }
2b188cc1
JA
1095
1096 if (!s->has_user)
1097 return -EFAULT;
1098
1099#ifdef CONFIG_COMPAT
1100 if (ctx->compat)
1101 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1102 iovec, iter);
1103#endif
1104
1105 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1106}
1107
31b51510
JA
1108/*
1109 * Make a note of the last file/offset/direction we punted to async
1110 * context. We'll use this information to see if we can piggy back a
1111 * sequential request onto the previous one, if it's still hasn't been
1112 * completed by the async worker.
1113 */
1114static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1115{
1116 struct async_list *async_list = &req->ctx->pending_async[rw];
1117 struct kiocb *kiocb = &req->rw;
1118 struct file *filp = kiocb->ki_filp;
1119 off_t io_end = kiocb->ki_pos + len;
1120
1121 if (filp == async_list->file && kiocb->ki_pos == async_list->io_end) {
1122 unsigned long max_pages;
1123
1124 /* Use 8x RA size as a decent limiter for both reads/writes */
1125 max_pages = filp->f_ra.ra_pages;
1126 if (!max_pages)
b5420237 1127 max_pages = VM_READAHEAD_PAGES;
31b51510
JA
1128 max_pages *= 8;
1129
1130 /* If max pages are exceeded, reset the state */
1131 len >>= PAGE_SHIFT;
1132 if (async_list->io_pages + len <= max_pages) {
1133 req->flags |= REQ_F_SEQ_PREV;
1134 async_list->io_pages += len;
1135 } else {
1136 io_end = 0;
1137 async_list->io_pages = 0;
1138 }
1139 }
1140
1141 /* New file? Reset state. */
1142 if (async_list->file != filp) {
1143 async_list->io_pages = 0;
1144 async_list->file = filp;
1145 }
1146 async_list->io_end = io_end;
1147}
1148
e0c5c576 1149static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 1150 bool force_nonblock)
2b188cc1
JA
1151{
1152 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1153 struct kiocb *kiocb = &req->rw;
1154 struct iov_iter iter;
1155 struct file *file;
31b51510 1156 size_t iov_count;
9d93a3f5 1157 ssize_t read_size, ret;
2b188cc1 1158
8358e3a8 1159 ret = io_prep_rw(req, s, force_nonblock);
2b188cc1
JA
1160 if (ret)
1161 return ret;
1162 file = kiocb->ki_filp;
1163
2b188cc1 1164 if (unlikely(!(file->f_mode & FMODE_READ)))
09bb8394 1165 return -EBADF;
2b188cc1 1166 if (unlikely(!file->f_op->read_iter))
09bb8394 1167 return -EINVAL;
2b188cc1
JA
1168
1169 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
87e5e6da 1170 if (ret < 0)
09bb8394 1171 return ret;
2b188cc1 1172
9d93a3f5 1173 read_size = ret;
9e645e11
JA
1174 if (req->flags & REQ_F_LINK)
1175 req->result = read_size;
1176
31b51510
JA
1177 iov_count = iov_iter_count(&iter);
1178 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
1179 if (!ret) {
1180 ssize_t ret2;
1181
2b188cc1 1182 ret2 = call_read_iter(file, kiocb, &iter);
9d93a3f5
JA
1183 /*
1184 * In case of a short read, punt to async. This can happen
1185 * if we have data partially cached. Alternatively we can
1186 * return the short read, in which case the application will
1187 * need to issue another SQE and wait for it. That SQE will
1188 * need async punt anyway, so it's more efficient to do it
1189 * here.
1190 */
1191 if (force_nonblock && ret2 > 0 && ret2 < read_size)
1192 ret2 = -EAGAIN;
1193 /* Catch -EAGAIN return for forced non-blocking submission */
31b51510 1194 if (!force_nonblock || ret2 != -EAGAIN) {
2b188cc1 1195 io_rw_done(kiocb, ret2);
31b51510
JA
1196 } else {
1197 /*
1198 * If ->needs_lock is true, we're already in async
1199 * context.
1200 */
1201 if (!s->needs_lock)
1202 io_async_list_note(READ, req, iov_count);
2b188cc1 1203 ret = -EAGAIN;
31b51510 1204 }
2b188cc1
JA
1205 }
1206 kfree(iovec);
2b188cc1
JA
1207 return ret;
1208}
1209
e0c5c576 1210static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 1211 bool force_nonblock)
2b188cc1
JA
1212{
1213 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1214 struct kiocb *kiocb = &req->rw;
1215 struct iov_iter iter;
1216 struct file *file;
31b51510 1217 size_t iov_count;
87e5e6da 1218 ssize_t ret;
2b188cc1 1219
8358e3a8 1220 ret = io_prep_rw(req, s, force_nonblock);
2b188cc1
JA
1221 if (ret)
1222 return ret;
2b188cc1 1223
2b188cc1
JA
1224 file = kiocb->ki_filp;
1225 if (unlikely(!(file->f_mode & FMODE_WRITE)))
09bb8394 1226 return -EBADF;
2b188cc1 1227 if (unlikely(!file->f_op->write_iter))
09bb8394 1228 return -EINVAL;
2b188cc1
JA
1229
1230 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
87e5e6da 1231 if (ret < 0)
09bb8394 1232 return ret;
2b188cc1 1233
9e645e11
JA
1234 if (req->flags & REQ_F_LINK)
1235 req->result = ret;
1236
31b51510
JA
1237 iov_count = iov_iter_count(&iter);
1238
1239 ret = -EAGAIN;
1240 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1241 /* If ->needs_lock is true, we're already in async context. */
1242 if (!s->needs_lock)
1243 io_async_list_note(WRITE, req, iov_count);
1244 goto out_free;
1245 }
1246
1247 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
2b188cc1 1248 if (!ret) {
9bf7933f
RP
1249 ssize_t ret2;
1250
2b188cc1
JA
1251 /*
1252 * Open-code file_start_write here to grab freeze protection,
1253 * which will be released by another thread in
1254 * io_complete_rw(). Fool lockdep by telling it the lock got
1255 * released so that it doesn't complain about the held lock when
1256 * we return to userspace.
1257 */
1258 if (S_ISREG(file_inode(file)->i_mode)) {
1259 __sb_start_write(file_inode(file)->i_sb,
1260 SB_FREEZE_WRITE, true);
1261 __sb_writers_release(file_inode(file)->i_sb,
1262 SB_FREEZE_WRITE);
1263 }
1264 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f
RP
1265
1266 ret2 = call_write_iter(file, kiocb, &iter);
1267 if (!force_nonblock || ret2 != -EAGAIN) {
1268 io_rw_done(kiocb, ret2);
1269 } else {
1270 /*
1271 * If ->needs_lock is true, we're already in async
1272 * context.
1273 */
1274 if (!s->needs_lock)
1275 io_async_list_note(WRITE, req, iov_count);
1276 ret = -EAGAIN;
1277 }
2b188cc1 1278 }
31b51510 1279out_free:
2b188cc1 1280 kfree(iovec);
2b188cc1
JA
1281 return ret;
1282}
1283
1284/*
1285 * IORING_OP_NOP just posts a completion event, nothing else.
1286 */
1287static int io_nop(struct io_kiocb *req, u64 user_data)
1288{
1289 struct io_ring_ctx *ctx = req->ctx;
1290 long err = 0;
1291
def596e9
JA
1292 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1293 return -EINVAL;
1294
c71ffb67 1295 io_cqring_add_event(ctx, user_data, err);
e65ef56d 1296 io_put_req(req);
2b188cc1
JA
1297 return 0;
1298}
1299
c992fe29
CH
1300static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1301{
6b06314c 1302 struct io_ring_ctx *ctx = req->ctx;
c992fe29 1303
09bb8394
JA
1304 if (!req->file)
1305 return -EBADF;
c992fe29 1306
6b06314c 1307 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 1308 return -EINVAL;
edafccee 1309 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
1310 return -EINVAL;
1311
c992fe29
CH
1312 return 0;
1313}
1314
1315static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1316 bool force_nonblock)
1317{
1318 loff_t sqe_off = READ_ONCE(sqe->off);
1319 loff_t sqe_len = READ_ONCE(sqe->len);
1320 loff_t end = sqe_off + sqe_len;
1321 unsigned fsync_flags;
1322 int ret;
1323
1324 fsync_flags = READ_ONCE(sqe->fsync_flags);
1325 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1326 return -EINVAL;
1327
1328 ret = io_prep_fsync(req, sqe);
1329 if (ret)
1330 return ret;
1331
1332 /* fsync always requires a blocking context */
1333 if (force_nonblock)
1334 return -EAGAIN;
1335
1336 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1337 end > 0 ? end : LLONG_MAX,
1338 fsync_flags & IORING_FSYNC_DATASYNC);
1339
9e645e11
JA
1340 if (ret < 0 && (req->flags & REQ_F_LINK))
1341 req->flags |= REQ_F_FAIL_LINK;
c71ffb67 1342 io_cqring_add_event(req->ctx, sqe->user_data, ret);
e65ef56d 1343 io_put_req(req);
c992fe29
CH
1344 return 0;
1345}
1346
5d17b4a4
JA
1347static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1348{
1349 struct io_ring_ctx *ctx = req->ctx;
1350 int ret = 0;
1351
1352 if (!req->file)
1353 return -EBADF;
5d17b4a4
JA
1354
1355 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1356 return -EINVAL;
1357 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1358 return -EINVAL;
1359
5d17b4a4
JA
1360 return ret;
1361}
1362
1363static int io_sync_file_range(struct io_kiocb *req,
1364 const struct io_uring_sqe *sqe,
1365 bool force_nonblock)
1366{
1367 loff_t sqe_off;
1368 loff_t sqe_len;
1369 unsigned flags;
1370 int ret;
1371
1372 ret = io_prep_sfr(req, sqe);
1373 if (ret)
1374 return ret;
1375
1376 /* sync_file_range always requires a blocking context */
1377 if (force_nonblock)
1378 return -EAGAIN;
1379
1380 sqe_off = READ_ONCE(sqe->off);
1381 sqe_len = READ_ONCE(sqe->len);
1382 flags = READ_ONCE(sqe->sync_range_flags);
1383
1384 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1385
9e645e11
JA
1386 if (ret < 0 && (req->flags & REQ_F_LINK))
1387 req->flags |= REQ_F_FAIL_LINK;
c71ffb67 1388 io_cqring_add_event(req->ctx, sqe->user_data, ret);
5d17b4a4
JA
1389 io_put_req(req);
1390 return 0;
1391}
1392
0fa03c62 1393#if defined(CONFIG_NET)
aa1fa28f
JA
1394static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1395 bool force_nonblock,
1396 long (*fn)(struct socket *, struct user_msghdr __user *,
1397 unsigned int))
1398{
0fa03c62
JA
1399 struct socket *sock;
1400 int ret;
1401
1402 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1403 return -EINVAL;
1404
1405 sock = sock_from_file(req->file, &ret);
1406 if (sock) {
1407 struct user_msghdr __user *msg;
1408 unsigned flags;
1409
1410 flags = READ_ONCE(sqe->msg_flags);
1411 if (flags & MSG_DONTWAIT)
1412 req->flags |= REQ_F_NOWAIT;
1413 else if (force_nonblock)
1414 flags |= MSG_DONTWAIT;
1415
1416 msg = (struct user_msghdr __user *) (unsigned long)
1417 READ_ONCE(sqe->addr);
1418
aa1fa28f 1419 ret = fn(sock, msg, flags);
0fa03c62
JA
1420 if (force_nonblock && ret == -EAGAIN)
1421 return ret;
1422 }
1423
1424 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1425 io_put_req(req);
1426 return 0;
aa1fa28f
JA
1427}
1428#endif
1429
1430static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1431 bool force_nonblock)
1432{
1433#if defined(CONFIG_NET)
1434 return io_send_recvmsg(req, sqe, force_nonblock, __sys_sendmsg_sock);
1435#else
1436 return -EOPNOTSUPP;
1437#endif
1438}
1439
1440static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1441 bool force_nonblock)
1442{
1443#if defined(CONFIG_NET)
1444 return io_send_recvmsg(req, sqe, force_nonblock, __sys_recvmsg_sock);
0fa03c62
JA
1445#else
1446 return -EOPNOTSUPP;
1447#endif
1448}
1449
221c5eb2
JA
1450static void io_poll_remove_one(struct io_kiocb *req)
1451{
1452 struct io_poll_iocb *poll = &req->poll;
1453
1454 spin_lock(&poll->head->lock);
1455 WRITE_ONCE(poll->canceled, true);
1456 if (!list_empty(&poll->wait.entry)) {
1457 list_del_init(&poll->wait.entry);
1458 queue_work(req->ctx->sqo_wq, &req->work);
1459 }
1460 spin_unlock(&poll->head->lock);
1461
1462 list_del_init(&req->list);
1463}
1464
1465static void io_poll_remove_all(struct io_ring_ctx *ctx)
1466{
1467 struct io_kiocb *req;
1468
1469 spin_lock_irq(&ctx->completion_lock);
1470 while (!list_empty(&ctx->cancel_list)) {
1471 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1472 io_poll_remove_one(req);
1473 }
1474 spin_unlock_irq(&ctx->completion_lock);
1475}
1476
1477/*
1478 * Find a running poll command that matches one specified in sqe->addr,
1479 * and remove it if found.
1480 */
1481static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1482{
1483 struct io_ring_ctx *ctx = req->ctx;
1484 struct io_kiocb *poll_req, *next;
1485 int ret = -ENOENT;
1486
1487 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1488 return -EINVAL;
1489 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1490 sqe->poll_events)
1491 return -EINVAL;
1492
1493 spin_lock_irq(&ctx->completion_lock);
1494 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1495 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1496 io_poll_remove_one(poll_req);
1497 ret = 0;
1498 break;
1499 }
1500 }
1501 spin_unlock_irq(&ctx->completion_lock);
1502
c71ffb67 1503 io_cqring_add_event(req->ctx, sqe->user_data, ret);
e65ef56d 1504 io_put_req(req);
221c5eb2
JA
1505 return 0;
1506}
1507
8c838788
JA
1508static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1509 __poll_t mask)
221c5eb2 1510{
8c838788 1511 req->poll.done = true;
c71ffb67 1512 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
8c838788 1513 io_commit_cqring(ctx);
221c5eb2
JA
1514}
1515
1516static void io_poll_complete_work(struct work_struct *work)
1517{
1518 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1519 struct io_poll_iocb *poll = &req->poll;
1520 struct poll_table_struct pt = { ._key = poll->events };
1521 struct io_ring_ctx *ctx = req->ctx;
1522 __poll_t mask = 0;
1523
1524 if (!READ_ONCE(poll->canceled))
1525 mask = vfs_poll(poll->file, &pt) & poll->events;
1526
1527 /*
1528 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1529 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1530 * synchronize with them. In the cancellation case the list_del_init
1531 * itself is not actually needed, but harmless so we keep it in to
1532 * avoid further branches in the fast path.
1533 */
1534 spin_lock_irq(&ctx->completion_lock);
1535 if (!mask && !READ_ONCE(poll->canceled)) {
1536 add_wait_queue(poll->head, &poll->wait);
1537 spin_unlock_irq(&ctx->completion_lock);
1538 return;
1539 }
1540 list_del_init(&req->list);
8c838788 1541 io_poll_complete(ctx, req, mask);
221c5eb2
JA
1542 spin_unlock_irq(&ctx->completion_lock);
1543
8c838788
JA
1544 io_cqring_ev_posted(ctx);
1545 io_put_req(req);
221c5eb2
JA
1546}
1547
1548static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1549 void *key)
1550{
1551 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1552 wait);
1553 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1554 struct io_ring_ctx *ctx = req->ctx;
1555 __poll_t mask = key_to_poll(key);
8c838788 1556 unsigned long flags;
221c5eb2
JA
1557
1558 /* for instances that support it check for an event match first: */
8c838788
JA
1559 if (mask && !(mask & poll->events))
1560 return 0;
221c5eb2 1561
8c838788 1562 list_del_init(&poll->wait.entry);
221c5eb2 1563
8c838788
JA
1564 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1565 list_del(&req->list);
1566 io_poll_complete(ctx, req, mask);
1567 spin_unlock_irqrestore(&ctx->completion_lock, flags);
221c5eb2 1568
8c838788
JA
1569 io_cqring_ev_posted(ctx);
1570 io_put_req(req);
1571 } else {
1572 queue_work(ctx->sqo_wq, &req->work);
221c5eb2
JA
1573 }
1574
221c5eb2
JA
1575 return 1;
1576}
1577
1578struct io_poll_table {
1579 struct poll_table_struct pt;
1580 struct io_kiocb *req;
1581 int error;
1582};
1583
1584static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1585 struct poll_table_struct *p)
1586{
1587 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1588
1589 if (unlikely(pt->req->poll.head)) {
1590 pt->error = -EINVAL;
1591 return;
1592 }
1593
1594 pt->error = 0;
1595 pt->req->poll.head = head;
1596 add_wait_queue(head, &pt->req->poll.wait);
1597}
1598
1599static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1600{
1601 struct io_poll_iocb *poll = &req->poll;
1602 struct io_ring_ctx *ctx = req->ctx;
1603 struct io_poll_table ipt;
8c838788 1604 bool cancel = false;
221c5eb2
JA
1605 __poll_t mask;
1606 u16 events;
221c5eb2
JA
1607
1608 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1609 return -EINVAL;
1610 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1611 return -EINVAL;
09bb8394
JA
1612 if (!poll->file)
1613 return -EBADF;
221c5eb2
JA
1614
1615 INIT_WORK(&req->work, io_poll_complete_work);
1616 events = READ_ONCE(sqe->poll_events);
1617 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1618
221c5eb2 1619 poll->head = NULL;
8c838788 1620 poll->done = false;
221c5eb2
JA
1621 poll->canceled = false;
1622
1623 ipt.pt._qproc = io_poll_queue_proc;
1624 ipt.pt._key = poll->events;
1625 ipt.req = req;
1626 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1627
1628 /* initialized the list so that we can do list_empty checks */
1629 INIT_LIST_HEAD(&poll->wait.entry);
1630 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1631
221c5eb2 1632 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
1633
1634 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
1635 if (likely(poll->head)) {
1636 spin_lock(&poll->head->lock);
1637 if (unlikely(list_empty(&poll->wait.entry))) {
1638 if (ipt.error)
1639 cancel = true;
1640 ipt.error = 0;
1641 mask = 0;
1642 }
1643 if (mask || ipt.error)
1644 list_del_init(&poll->wait.entry);
1645 else if (cancel)
1646 WRITE_ONCE(poll->canceled, true);
1647 else if (!poll->done) /* actually waiting for an event */
1648 list_add_tail(&req->list, &ctx->cancel_list);
1649 spin_unlock(&poll->head->lock);
1650 }
1651 if (mask) { /* no async, we'd stolen it */
221c5eb2 1652 ipt.error = 0;
8c838788 1653 io_poll_complete(ctx, req, mask);
221c5eb2 1654 }
221c5eb2
JA
1655 spin_unlock_irq(&ctx->completion_lock);
1656
8c838788
JA
1657 if (mask) {
1658 io_cqring_ev_posted(ctx);
e65ef56d 1659 io_put_req(req);
221c5eb2 1660 }
8c838788 1661 return ipt.error;
221c5eb2
JA
1662}
1663
de0617e4
JA
1664static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1665 const struct io_uring_sqe *sqe)
1666{
1667 struct io_uring_sqe *sqe_copy;
1668
1669 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1670 return 0;
1671
1672 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1673 if (!sqe_copy)
1674 return -EAGAIN;
1675
1676 spin_lock_irq(&ctx->completion_lock);
1677 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1678 spin_unlock_irq(&ctx->completion_lock);
1679 kfree(sqe_copy);
1680 return 0;
1681 }
1682
1683 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1684 req->submit.sqe = sqe_copy;
1685
1686 INIT_WORK(&req->work, io_sq_wq_submit_work);
1687 list_add_tail(&req->list, &ctx->defer_list);
1688 spin_unlock_irq(&ctx->completion_lock);
1689 return -EIOCBQUEUED;
1690}
1691
2b188cc1 1692static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8358e3a8 1693 const struct sqe_submit *s, bool force_nonblock)
2b188cc1 1694{
e0c5c576 1695 int ret, opcode;
2b188cc1 1696
9e645e11
JA
1697 req->user_data = READ_ONCE(s->sqe->user_data);
1698
2b188cc1
JA
1699 if (unlikely(s->index >= ctx->sq_entries))
1700 return -EINVAL;
2b188cc1
JA
1701
1702 opcode = READ_ONCE(s->sqe->opcode);
1703 switch (opcode) {
1704 case IORING_OP_NOP:
1705 ret = io_nop(req, req->user_data);
1706 break;
1707 case IORING_OP_READV:
edafccee
JA
1708 if (unlikely(s->sqe->buf_index))
1709 return -EINVAL;
8358e3a8 1710 ret = io_read(req, s, force_nonblock);
2b188cc1
JA
1711 break;
1712 case IORING_OP_WRITEV:
edafccee
JA
1713 if (unlikely(s->sqe->buf_index))
1714 return -EINVAL;
8358e3a8 1715 ret = io_write(req, s, force_nonblock);
edafccee
JA
1716 break;
1717 case IORING_OP_READ_FIXED:
8358e3a8 1718 ret = io_read(req, s, force_nonblock);
edafccee
JA
1719 break;
1720 case IORING_OP_WRITE_FIXED:
8358e3a8 1721 ret = io_write(req, s, force_nonblock);
2b188cc1 1722 break;
c992fe29
CH
1723 case IORING_OP_FSYNC:
1724 ret = io_fsync(req, s->sqe, force_nonblock);
1725 break;
221c5eb2
JA
1726 case IORING_OP_POLL_ADD:
1727 ret = io_poll_add(req, s->sqe);
1728 break;
1729 case IORING_OP_POLL_REMOVE:
1730 ret = io_poll_remove(req, s->sqe);
1731 break;
5d17b4a4
JA
1732 case IORING_OP_SYNC_FILE_RANGE:
1733 ret = io_sync_file_range(req, s->sqe, force_nonblock);
1734 break;
0fa03c62
JA
1735 case IORING_OP_SENDMSG:
1736 ret = io_sendmsg(req, s->sqe, force_nonblock);
1737 break;
aa1fa28f
JA
1738 case IORING_OP_RECVMSG:
1739 ret = io_recvmsg(req, s->sqe, force_nonblock);
1740 break;
2b188cc1
JA
1741 default:
1742 ret = -EINVAL;
1743 break;
1744 }
1745
def596e9
JA
1746 if (ret)
1747 return ret;
1748
1749 if (ctx->flags & IORING_SETUP_IOPOLL) {
9e645e11 1750 if (req->result == -EAGAIN)
def596e9
JA
1751 return -EAGAIN;
1752
1753 /* workqueue context doesn't hold uring_lock, grab it now */
1754 if (s->needs_lock)
1755 mutex_lock(&ctx->uring_lock);
1756 io_iopoll_req_issued(req);
1757 if (s->needs_lock)
1758 mutex_unlock(&ctx->uring_lock);
1759 }
1760
1761 return 0;
2b188cc1
JA
1762}
1763
31b51510
JA
1764static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1765 const struct io_uring_sqe *sqe)
1766{
1767 switch (sqe->opcode) {
1768 case IORING_OP_READV:
1769 case IORING_OP_READ_FIXED:
1770 return &ctx->pending_async[READ];
1771 case IORING_OP_WRITEV:
1772 case IORING_OP_WRITE_FIXED:
1773 return &ctx->pending_async[WRITE];
1774 default:
1775 return NULL;
1776 }
1777}
1778
edafccee
JA
1779static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1780{
1781 u8 opcode = READ_ONCE(sqe->opcode);
1782
1783 return !(opcode == IORING_OP_READ_FIXED ||
1784 opcode == IORING_OP_WRITE_FIXED);
1785}
1786
2b188cc1
JA
1787static void io_sq_wq_submit_work(struct work_struct *work)
1788{
1789 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 1790 struct io_ring_ctx *ctx = req->ctx;
31b51510
JA
1791 struct mm_struct *cur_mm = NULL;
1792 struct async_list *async_list;
1793 LIST_HEAD(req_list);
edafccee 1794 mm_segment_t old_fs;
2b188cc1
JA
1795 int ret;
1796
31b51510
JA
1797 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1798restart:
1799 do {
1800 struct sqe_submit *s = &req->submit;
1801 const struct io_uring_sqe *sqe = s->sqe;
2b188cc1 1802
8449eeda 1803 /* Ensure we clear previously set non-block flag */
31b51510
JA
1804 req->rw.ki_flags &= ~IOCB_NOWAIT;
1805
1806 ret = 0;
1807 if (io_sqe_needs_user(sqe) && !cur_mm) {
1808 if (!mmget_not_zero(ctx->sqo_mm)) {
1809 ret = -EFAULT;
1810 } else {
1811 cur_mm = ctx->sqo_mm;
1812 use_mm(cur_mm);
1813 old_fs = get_fs();
1814 set_fs(USER_DS);
1815 }
1816 }
1817
1818 if (!ret) {
1819 s->has_user = cur_mm != NULL;
1820 s->needs_lock = true;
1821 do {
8358e3a8 1822 ret = __io_submit_sqe(ctx, req, s, false);
31b51510
JA
1823 /*
1824 * We can get EAGAIN for polled IO even though
1825 * we're forcing a sync submission from here,
1826 * since we can't wait for request slots on the
1827 * block side.
1828 */
1829 if (ret != -EAGAIN)
1830 break;
1831 cond_resched();
1832 } while (1);
1833 }
817869d2
JA
1834
1835 /* drop submission reference */
1836 io_put_req(req);
1837
31b51510 1838 if (ret) {
c71ffb67 1839 io_cqring_add_event(ctx, sqe->user_data, ret);
e65ef56d 1840 io_put_req(req);
31b51510
JA
1841 }
1842
1843 /* async context always use a copy of the sqe */
1844 kfree(sqe);
1845
1846 if (!async_list)
1847 break;
1848 if (!list_empty(&req_list)) {
1849 req = list_first_entry(&req_list, struct io_kiocb,
1850 list);
1851 list_del(&req->list);
1852 continue;
1853 }
1854 if (list_empty(&async_list->list))
1855 break;
1856
1857 req = NULL;
1858 spin_lock(&async_list->lock);
1859 if (list_empty(&async_list->list)) {
1860 spin_unlock(&async_list->lock);
1861 break;
1862 }
1863 list_splice_init(&async_list->list, &req_list);
1864 spin_unlock(&async_list->lock);
1865
1866 req = list_first_entry(&req_list, struct io_kiocb, list);
1867 list_del(&req->list);
1868 } while (req);
edafccee
JA
1869
1870 /*
31b51510
JA
1871 * Rare case of racing with a submitter. If we find the count has
1872 * dropped to zero AND we have pending work items, then restart
1873 * the processing. This is a tiny race window.
edafccee 1874 */
31b51510
JA
1875 if (async_list) {
1876 ret = atomic_dec_return(&async_list->cnt);
1877 while (!ret && !list_empty(&async_list->list)) {
1878 spin_lock(&async_list->lock);
1879 atomic_inc(&async_list->cnt);
1880 list_splice_init(&async_list->list, &req_list);
1881 spin_unlock(&async_list->lock);
1882
1883 if (!list_empty(&req_list)) {
1884 req = list_first_entry(&req_list,
1885 struct io_kiocb, list);
1886 list_del(&req->list);
1887 goto restart;
1888 }
1889 ret = atomic_dec_return(&async_list->cnt);
edafccee 1890 }
edafccee 1891 }
2b188cc1 1892
31b51510 1893 if (cur_mm) {
edafccee 1894 set_fs(old_fs);
31b51510
JA
1895 unuse_mm(cur_mm);
1896 mmput(cur_mm);
2b188cc1 1897 }
31b51510 1898}
2b188cc1 1899
31b51510
JA
1900/*
1901 * See if we can piggy back onto previously submitted work, that is still
1902 * running. We currently only allow this if the new request is sequential
1903 * to the previous one we punted.
1904 */
1905static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1906{
1907 bool ret = false;
1908
1909 if (!list)
1910 return false;
1911 if (!(req->flags & REQ_F_SEQ_PREV))
1912 return false;
1913 if (!atomic_read(&list->cnt))
1914 return false;
1915
1916 ret = true;
1917 spin_lock(&list->lock);
1918 list_add_tail(&req->list, &list->list);
1919 if (!atomic_read(&list->cnt)) {
1920 list_del_init(&req->list);
1921 ret = false;
1922 }
1923 spin_unlock(&list->lock);
1924 return ret;
2b188cc1
JA
1925}
1926
09bb8394
JA
1927static bool io_op_needs_file(const struct io_uring_sqe *sqe)
1928{
1929 int op = READ_ONCE(sqe->opcode);
1930
1931 switch (op) {
1932 case IORING_OP_NOP:
1933 case IORING_OP_POLL_REMOVE:
1934 return false;
1935 default:
1936 return true;
1937 }
1938}
1939
1940static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
1941 struct io_submit_state *state, struct io_kiocb *req)
1942{
1943 unsigned flags;
1944 int fd;
1945
1946 flags = READ_ONCE(s->sqe->flags);
1947 fd = READ_ONCE(s->sqe->fd);
1948
de0617e4
JA
1949 if (flags & IOSQE_IO_DRAIN) {
1950 req->flags |= REQ_F_IO_DRAIN;
1951 req->sequence = ctx->cached_sq_head - 1;
1952 }
1953
09bb8394
JA
1954 if (!io_op_needs_file(s->sqe)) {
1955 req->file = NULL;
1956 return 0;
1957 }
1958
1959 if (flags & IOSQE_FIXED_FILE) {
1960 if (unlikely(!ctx->user_files ||
1961 (unsigned) fd >= ctx->nr_user_files))
1962 return -EBADF;
1963 req->file = ctx->user_files[fd];
1964 req->flags |= REQ_F_FIXED_FILE;
1965 } else {
1966 if (s->needs_fixed_file)
1967 return -EBADF;
1968 req->file = io_file_get(state, fd);
1969 if (unlikely(!req->file))
1970 return -EBADF;
1971 }
1972
1973 return 0;
1974}
1975
9e645e11
JA
1976static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1977 struct sqe_submit *s)
2b188cc1 1978{
e0c5c576 1979 int ret;
2b188cc1 1980
8358e3a8 1981 ret = __io_submit_sqe(ctx, req, s, true);
8449eeda 1982 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
2b188cc1
JA
1983 struct io_uring_sqe *sqe_copy;
1984
1985 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1986 if (sqe_copy) {
31b51510
JA
1987 struct async_list *list;
1988
2b188cc1
JA
1989 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1990 s->sqe = sqe_copy;
1991
1992 memcpy(&req->submit, s, sizeof(*s));
31b51510
JA
1993 list = io_async_list_from_sqe(ctx, s->sqe);
1994 if (!io_add_to_prev_work(list, req)) {
1995 if (list)
1996 atomic_inc(&list->cnt);
1997 INIT_WORK(&req->work, io_sq_wq_submit_work);
1998 queue_work(ctx->sqo_wq, &req->work);
1999 }
e65ef56d
JA
2000
2001 /*
2002 * Queued up for async execution, worker will release
9e645e11 2003 * submit reference when the iocb is actually submitted.
e65ef56d
JA
2004 */
2005 return 0;
2b188cc1
JA
2006 }
2007 }
e65ef56d
JA
2008
2009 /* drop submission reference */
2010 io_put_req(req);
2011
2012 /* and drop final reference, if we failed */
9e645e11
JA
2013 if (ret) {
2014 io_cqring_add_event(ctx, req->user_data, ret);
2015 if (req->flags & REQ_F_LINK)
2016 req->flags |= REQ_F_FAIL_LINK;
e65ef56d 2017 io_put_req(req);
9e645e11 2018 }
2b188cc1
JA
2019
2020 return ret;
2021}
2022
9e645e11
JA
2023#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2024
2025static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
2026 struct io_submit_state *state, struct io_kiocb **link)
2027{
2028 struct io_uring_sqe *sqe_copy;
2029 struct io_kiocb *req;
2030 int ret;
2031
2032 /* enforce forwards compatibility on users */
2033 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2034 ret = -EINVAL;
2035 goto err;
2036 }
2037
2038 req = io_get_req(ctx, state);
2039 if (unlikely(!req)) {
2040 ret = -EAGAIN;
2041 goto err;
2042 }
2043
2044 ret = io_req_set_file(ctx, s, state, req);
2045 if (unlikely(ret)) {
2046err_req:
2047 io_free_req(req);
2048err:
2049 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2050 return;
2051 }
2052
2053 ret = io_req_defer(ctx, req, s->sqe);
2054 if (ret) {
2055 if (ret != -EIOCBQUEUED)
2056 goto err_req;
2057 return;
2058 }
2059
2060 /*
2061 * If we already have a head request, queue this one for async
2062 * submittal once the head completes. If we don't have a head but
2063 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2064 * submitted sync once the chain is complete. If none of those
2065 * conditions are true (normal request), then just queue it.
2066 */
2067 if (*link) {
2068 struct io_kiocb *prev = *link;
2069
2070 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2071 if (!sqe_copy) {
2072 ret = -EAGAIN;
2073 goto err_req;
2074 }
2075
2076 s->sqe = sqe_copy;
2077 memcpy(&req->submit, s, sizeof(*s));
2078 list_add_tail(&req->list, &prev->link_list);
2079 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2080 req->flags |= REQ_F_LINK;
2081
2082 memcpy(&req->submit, s, sizeof(*s));
2083 INIT_LIST_HEAD(&req->link_list);
2084 *link = req;
2085 } else {
2086 io_queue_sqe(ctx, req, s);
2087 }
2088}
2089
9a56a232
JA
2090/*
2091 * Batched submission is done, ensure local IO is flushed out.
2092 */
2093static void io_submit_state_end(struct io_submit_state *state)
2094{
2095 blk_finish_plug(&state->plug);
3d6770fb 2096 io_file_put(state);
2579f913
JA
2097 if (state->free_reqs)
2098 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2099 &state->reqs[state->cur_req]);
9a56a232
JA
2100}
2101
2102/*
2103 * Start submission side cache.
2104 */
2105static void io_submit_state_start(struct io_submit_state *state,
2106 struct io_ring_ctx *ctx, unsigned max_ios)
2107{
2108 blk_start_plug(&state->plug);
2579f913 2109 state->free_reqs = 0;
9a56a232
JA
2110 state->file = NULL;
2111 state->ios_left = max_ios;
2112}
2113
2b188cc1
JA
2114static void io_commit_sqring(struct io_ring_ctx *ctx)
2115{
2116 struct io_sq_ring *ring = ctx->sq_ring;
2117
2118 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
2119 /*
2120 * Ensure any loads from the SQEs are done at this point,
2121 * since once we write the new head, the application could
2122 * write new data to them.
2123 */
2124 smp_store_release(&ring->r.head, ctx->cached_sq_head);
2b188cc1
JA
2125 }
2126}
2127
2b188cc1
JA
2128/*
2129 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2130 * that is mapped by userspace. This means that care needs to be taken to
2131 * ensure that reads are stable, as we cannot rely on userspace always
2132 * being a good citizen. If members of the sqe are validated and then later
2133 * used, it's important that those reads are done through READ_ONCE() to
2134 * prevent a re-load down the line.
2135 */
2136static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2137{
2138 struct io_sq_ring *ring = ctx->sq_ring;
2139 unsigned head;
2140
2141 /*
2142 * The cached sq head (or cq tail) serves two purposes:
2143 *
2144 * 1) allows us to batch the cost of updating the user visible
2145 * head updates.
2146 * 2) allows the kernel side to track the head on its own, even
2147 * though the application is the one updating it.
2148 */
2149 head = ctx->cached_sq_head;
e523a29c
SB
2150 /* make sure SQ entry isn't read before tail */
2151 if (head == smp_load_acquire(&ring->r.tail))
2b188cc1
JA
2152 return false;
2153
2154 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
2155 if (head < ctx->sq_entries) {
2156 s->index = head;
2157 s->sqe = &ctx->sq_sqes[head];
2158 ctx->cached_sq_head++;
2159 return true;
2160 }
2161
2162 /* drop invalid entries */
2163 ctx->cached_sq_head++;
2164 ring->dropped++;
2b188cc1
JA
2165 return false;
2166}
2167
6c271ce2
JA
2168static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
2169 unsigned int nr, bool has_user, bool mm_fault)
2170{
2171 struct io_submit_state state, *statep = NULL;
9e645e11
JA
2172 struct io_kiocb *link = NULL;
2173 bool prev_was_link = false;
2174 int i, submitted = 0;
6c271ce2
JA
2175
2176 if (nr > IO_PLUG_THRESHOLD) {
2177 io_submit_state_start(&state, ctx, nr);
2178 statep = &state;
2179 }
2180
2181 for (i = 0; i < nr; i++) {
9e645e11
JA
2182 /*
2183 * If previous wasn't linked and we have a linked command,
2184 * that's the end of the chain. Submit the previous link.
2185 */
2186 if (!prev_was_link && link) {
2187 io_queue_sqe(ctx, link, &link->submit);
2188 link = NULL;
2189 }
2190 prev_was_link = (sqes[i].sqe->flags & IOSQE_IO_LINK) != 0;
2191
6c271ce2 2192 if (unlikely(mm_fault)) {
9e645e11
JA
2193 io_cqring_add_event(ctx, sqes[i].sqe->user_data,
2194 -EFAULT);
6c271ce2
JA
2195 } else {
2196 sqes[i].has_user = has_user;
2197 sqes[i].needs_lock = true;
2198 sqes[i].needs_fixed_file = true;
9e645e11 2199 io_submit_sqe(ctx, &sqes[i], statep, &link);
6c271ce2 2200 submitted++;
6c271ce2 2201 }
6c271ce2
JA
2202 }
2203
9e645e11
JA
2204 if (link)
2205 io_queue_sqe(ctx, link, &link->submit);
6c271ce2
JA
2206 if (statep)
2207 io_submit_state_end(&state);
2208
2209 return submitted;
2210}
2211
2212static int io_sq_thread(void *data)
2213{
2214 struct sqe_submit sqes[IO_IOPOLL_BATCH];
2215 struct io_ring_ctx *ctx = data;
2216 struct mm_struct *cur_mm = NULL;
2217 mm_segment_t old_fs;
2218 DEFINE_WAIT(wait);
2219 unsigned inflight;
2220 unsigned long timeout;
2221
2222 old_fs = get_fs();
2223 set_fs(USER_DS);
2224
2225 timeout = inflight = 0;
2bbcd6d3 2226 while (!kthread_should_park()) {
6c271ce2
JA
2227 bool all_fixed, mm_fault = false;
2228 int i;
2229
2230 if (inflight) {
2231 unsigned nr_events = 0;
2232
2233 if (ctx->flags & IORING_SETUP_IOPOLL) {
2234 /*
2235 * We disallow the app entering submit/complete
2236 * with polling, but we still need to lock the
2237 * ring to prevent racing with polled issue
2238 * that got punted to a workqueue.
2239 */
2240 mutex_lock(&ctx->uring_lock);
2241 io_iopoll_check(ctx, &nr_events, 0);
2242 mutex_unlock(&ctx->uring_lock);
2243 } else {
2244 /*
2245 * Normal IO, just pretend everything completed.
2246 * We don't have to poll completions for that.
2247 */
2248 nr_events = inflight;
2249 }
2250
2251 inflight -= nr_events;
2252 if (!inflight)
2253 timeout = jiffies + ctx->sq_thread_idle;
2254 }
2255
2256 if (!io_get_sqring(ctx, &sqes[0])) {
2257 /*
2258 * We're polling. If we're within the defined idle
2259 * period, then let us spin without work before going
2260 * to sleep.
2261 */
2262 if (inflight || !time_after(jiffies, timeout)) {
2263 cpu_relax();
2264 continue;
2265 }
2266
2267 /*
2268 * Drop cur_mm before scheduling, we can't hold it for
2269 * long periods (or over schedule()). Do this before
2270 * adding ourselves to the waitqueue, as the unuse/drop
2271 * may sleep.
2272 */
2273 if (cur_mm) {
2274 unuse_mm(cur_mm);
2275 mmput(cur_mm);
2276 cur_mm = NULL;
2277 }
2278
2279 prepare_to_wait(&ctx->sqo_wait, &wait,
2280 TASK_INTERRUPTIBLE);
2281
2282 /* Tell userspace we may need a wakeup call */
2283 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
2284 /* make sure to read SQ tail after writing flags */
2285 smp_mb();
6c271ce2
JA
2286
2287 if (!io_get_sqring(ctx, &sqes[0])) {
2bbcd6d3 2288 if (kthread_should_park()) {
6c271ce2
JA
2289 finish_wait(&ctx->sqo_wait, &wait);
2290 break;
2291 }
2292 if (signal_pending(current))
2293 flush_signals(current);
2294 schedule();
2295 finish_wait(&ctx->sqo_wait, &wait);
2296
2297 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2298 continue;
2299 }
2300 finish_wait(&ctx->sqo_wait, &wait);
2301
2302 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2303 }
2304
2305 i = 0;
2306 all_fixed = true;
2307 do {
2308 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2309 all_fixed = false;
2310
2311 i++;
2312 if (i == ARRAY_SIZE(sqes))
2313 break;
2314 } while (io_get_sqring(ctx, &sqes[i]));
2315
2316 /* Unless all new commands are FIXED regions, grab mm */
2317 if (!all_fixed && !cur_mm) {
2318 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2319 if (!mm_fault) {
2320 use_mm(ctx->sqo_mm);
2321 cur_mm = ctx->sqo_mm;
2322 }
2323 }
2324
2325 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2326 mm_fault);
2327
2328 /* Commit SQ ring head once we've consumed all SQEs */
2329 io_commit_sqring(ctx);
2330 }
2331
2332 set_fs(old_fs);
2333 if (cur_mm) {
2334 unuse_mm(cur_mm);
2335 mmput(cur_mm);
2336 }
06058632 2337
2bbcd6d3 2338 kthread_parkme();
06058632 2339
6c271ce2
JA
2340 return 0;
2341}
2342
2b188cc1
JA
2343static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2344{
9a56a232 2345 struct io_submit_state state, *statep = NULL;
9e645e11
JA
2346 struct io_kiocb *link = NULL;
2347 bool prev_was_link = false;
5c8b0b54 2348 int i, submit = 0;
2b188cc1 2349
9a56a232
JA
2350 if (to_submit > IO_PLUG_THRESHOLD) {
2351 io_submit_state_start(&state, ctx, to_submit);
2352 statep = &state;
2353 }
2b188cc1
JA
2354
2355 for (i = 0; i < to_submit; i++) {
2356 struct sqe_submit s;
2357
2358 if (!io_get_sqring(ctx, &s))
2359 break;
2360
9e645e11
JA
2361 /*
2362 * If previous wasn't linked and we have a linked command,
2363 * that's the end of the chain. Submit the previous link.
2364 */
2365 if (!prev_was_link && link) {
2366 io_queue_sqe(ctx, link, &link->submit);
2367 link = NULL;
2368 }
2369 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2370
2b188cc1 2371 s.has_user = true;
def596e9 2372 s.needs_lock = false;
6c271ce2 2373 s.needs_fixed_file = false;
5c8b0b54 2374 submit++;
9e645e11 2375 io_submit_sqe(ctx, &s, statep, &link);
2b188cc1
JA
2376 }
2377 io_commit_sqring(ctx);
2378
9e645e11
JA
2379 if (link)
2380 io_queue_sqe(ctx, link, &link->submit);
9a56a232
JA
2381 if (statep)
2382 io_submit_state_end(statep);
2b188cc1 2383
5c8b0b54 2384 return submit;
2b188cc1
JA
2385}
2386
2387static unsigned io_cqring_events(struct io_cq_ring *ring)
2388{
dc6ce4bc
JL
2389 /* See comment at the top of this file */
2390 smp_rmb();
2b188cc1
JA
2391 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
2392}
2393
2394/*
2395 * Wait until events become available, if we don't already have some. The
2396 * application must reap them itself, as they reside on the shared cq ring.
2397 */
2398static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2399 const sigset_t __user *sig, size_t sigsz)
2400{
2401 struct io_cq_ring *ring = ctx->cq_ring;
2402 sigset_t ksigmask, sigsaved;
2b188cc1
JA
2403 int ret;
2404
2b188cc1
JA
2405 if (io_cqring_events(ring) >= min_events)
2406 return 0;
2407
2408 if (sig) {
9e75ad5d
AB
2409#ifdef CONFIG_COMPAT
2410 if (in_compat_syscall())
2411 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2412 &ksigmask, &sigsaved, sigsz);
2413 else
2414#endif
2415 ret = set_user_sigmask(sig, &ksigmask,
2416 &sigsaved, sigsz);
2417
2b188cc1
JA
2418 if (ret)
2419 return ret;
2420 }
2421
fdb288a6
JL
2422 ret = wait_event_interruptible(ctx->wait, io_cqring_events(ring) >= min_events);
2423 if (ret == -ERESTARTSYS)
2b188cc1 2424 ret = -EINTR;
2b188cc1
JA
2425
2426 if (sig)
2427 restore_user_sigmask(sig, &sigsaved);
2428
2429 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2430}
2431
6b06314c
JA
2432static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2433{
2434#if defined(CONFIG_UNIX)
2435 if (ctx->ring_sock) {
2436 struct sock *sock = ctx->ring_sock->sk;
2437 struct sk_buff *skb;
2438
2439 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2440 kfree_skb(skb);
2441 }
2442#else
2443 int i;
2444
2445 for (i = 0; i < ctx->nr_user_files; i++)
2446 fput(ctx->user_files[i]);
2447#endif
2448}
2449
2450static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2451{
2452 if (!ctx->user_files)
2453 return -ENXIO;
2454
2455 __io_sqe_files_unregister(ctx);
2456 kfree(ctx->user_files);
2457 ctx->user_files = NULL;
2458 ctx->nr_user_files = 0;
2459 return 0;
2460}
2461
6c271ce2
JA
2462static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2463{
2464 if (ctx->sqo_thread) {
2bbcd6d3
RP
2465 /*
2466 * The park is a bit of a work-around, without it we get
2467 * warning spews on shutdown with SQPOLL set and affinity
2468 * set to a single CPU.
2469 */
06058632 2470 kthread_park(ctx->sqo_thread);
6c271ce2
JA
2471 kthread_stop(ctx->sqo_thread);
2472 ctx->sqo_thread = NULL;
2473 }
2474}
2475
6b06314c
JA
2476static void io_finish_async(struct io_ring_ctx *ctx)
2477{
6c271ce2
JA
2478 io_sq_thread_stop(ctx);
2479
6b06314c
JA
2480 if (ctx->sqo_wq) {
2481 destroy_workqueue(ctx->sqo_wq);
2482 ctx->sqo_wq = NULL;
2483 }
2484}
2485
2486#if defined(CONFIG_UNIX)
2487static void io_destruct_skb(struct sk_buff *skb)
2488{
2489 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2490
2491 io_finish_async(ctx);
2492 unix_destruct_scm(skb);
2493}
2494
2495/*
2496 * Ensure the UNIX gc is aware of our file set, so we are certain that
2497 * the io_uring can be safely unregistered on process exit, even if we have
2498 * loops in the file referencing.
2499 */
2500static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2501{
2502 struct sock *sk = ctx->ring_sock->sk;
2503 struct scm_fp_list *fpl;
2504 struct sk_buff *skb;
2505 int i;
2506
2507 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2508 unsigned long inflight = ctx->user->unix_inflight + nr;
2509
2510 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2511 return -EMFILE;
2512 }
2513
2514 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2515 if (!fpl)
2516 return -ENOMEM;
2517
2518 skb = alloc_skb(0, GFP_KERNEL);
2519 if (!skb) {
2520 kfree(fpl);
2521 return -ENOMEM;
2522 }
2523
2524 skb->sk = sk;
2525 skb->destructor = io_destruct_skb;
2526
2527 fpl->user = get_uid(ctx->user);
2528 for (i = 0; i < nr; i++) {
2529 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2530 unix_inflight(fpl->user, fpl->fp[i]);
2531 }
2532
2533 fpl->max = fpl->count = nr;
2534 UNIXCB(skb).fp = fpl;
2535 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2536 skb_queue_head(&sk->sk_receive_queue, skb);
2537
2538 for (i = 0; i < nr; i++)
2539 fput(fpl->fp[i]);
2540
2541 return 0;
2542}
2543
2544/*
2545 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2546 * causes regular reference counting to break down. We rely on the UNIX
2547 * garbage collection to take care of this problem for us.
2548 */
2549static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2550{
2551 unsigned left, total;
2552 int ret = 0;
2553
2554 total = 0;
2555 left = ctx->nr_user_files;
2556 while (left) {
2557 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
2558
2559 ret = __io_sqe_files_scm(ctx, this_files, total);
2560 if (ret)
2561 break;
2562 left -= this_files;
2563 total += this_files;
2564 }
2565
2566 if (!ret)
2567 return 0;
2568
2569 while (total < ctx->nr_user_files) {
2570 fput(ctx->user_files[total]);
2571 total++;
2572 }
2573
2574 return ret;
2575}
2576#else
2577static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2578{
2579 return 0;
2580}
2581#endif
2582
2583static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2584 unsigned nr_args)
2585{
2586 __s32 __user *fds = (__s32 __user *) arg;
2587 int fd, ret = 0;
2588 unsigned i;
2589
2590 if (ctx->user_files)
2591 return -EBUSY;
2592 if (!nr_args)
2593 return -EINVAL;
2594 if (nr_args > IORING_MAX_FIXED_FILES)
2595 return -EMFILE;
2596
2597 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2598 if (!ctx->user_files)
2599 return -ENOMEM;
2600
2601 for (i = 0; i < nr_args; i++) {
2602 ret = -EFAULT;
2603 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2604 break;
2605
2606 ctx->user_files[i] = fget(fd);
2607
2608 ret = -EBADF;
2609 if (!ctx->user_files[i])
2610 break;
2611 /*
2612 * Don't allow io_uring instances to be registered. If UNIX
2613 * isn't enabled, then this causes a reference cycle and this
2614 * instance can never get freed. If UNIX is enabled we'll
2615 * handle it just fine, but there's still no point in allowing
2616 * a ring fd as it doesn't support regular read/write anyway.
2617 */
2618 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2619 fput(ctx->user_files[i]);
2620 break;
2621 }
2622 ctx->nr_user_files++;
2623 ret = 0;
2624 }
2625
2626 if (ret) {
2627 for (i = 0; i < ctx->nr_user_files; i++)
2628 fput(ctx->user_files[i]);
2629
2630 kfree(ctx->user_files);
25adf50f 2631 ctx->user_files = NULL;
6b06314c
JA
2632 ctx->nr_user_files = 0;
2633 return ret;
2634 }
2635
2636 ret = io_sqe_files_scm(ctx);
2637 if (ret)
2638 io_sqe_files_unregister(ctx);
2639
2640 return ret;
2641}
2642
6c271ce2
JA
2643static int io_sq_offload_start(struct io_ring_ctx *ctx,
2644 struct io_uring_params *p)
2b188cc1
JA
2645{
2646 int ret;
2647
6c271ce2 2648 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
2649 mmgrab(current->mm);
2650 ctx->sqo_mm = current->mm;
2651
6c271ce2 2652 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
2653 ret = -EPERM;
2654 if (!capable(CAP_SYS_ADMIN))
2655 goto err;
2656
917257da
JA
2657 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2658 if (!ctx->sq_thread_idle)
2659 ctx->sq_thread_idle = HZ;
2660
6c271ce2 2661 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 2662 int cpu = p->sq_thread_cpu;
6c271ce2 2663
917257da 2664 ret = -EINVAL;
44a9bd18
JA
2665 if (cpu >= nr_cpu_ids)
2666 goto err;
7889f44d 2667 if (!cpu_online(cpu))
917257da
JA
2668 goto err;
2669
6c271ce2
JA
2670 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2671 ctx, cpu,
2672 "io_uring-sq");
2673 } else {
2674 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2675 "io_uring-sq");
2676 }
2677 if (IS_ERR(ctx->sqo_thread)) {
2678 ret = PTR_ERR(ctx->sqo_thread);
2679 ctx->sqo_thread = NULL;
2680 goto err;
2681 }
2682 wake_up_process(ctx->sqo_thread);
2683 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2684 /* Can't have SQ_AFF without SQPOLL */
2685 ret = -EINVAL;
2686 goto err;
2687 }
2688
2b188cc1
JA
2689 /* Do QD, or 2 * CPUS, whatever is smallest */
2690 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2691 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2692 if (!ctx->sqo_wq) {
2693 ret = -ENOMEM;
2694 goto err;
2695 }
2696
2697 return 0;
2698err:
6c271ce2 2699 io_sq_thread_stop(ctx);
2b188cc1
JA
2700 mmdrop(ctx->sqo_mm);
2701 ctx->sqo_mm = NULL;
2702 return ret;
2703}
2704
2705static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2706{
2707 atomic_long_sub(nr_pages, &user->locked_vm);
2708}
2709
2710static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2711{
2712 unsigned long page_limit, cur_pages, new_pages;
2713
2714 /* Don't allow more pages than we can safely lock */
2715 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2716
2717 do {
2718 cur_pages = atomic_long_read(&user->locked_vm);
2719 new_pages = cur_pages + nr_pages;
2720 if (new_pages > page_limit)
2721 return -ENOMEM;
2722 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2723 new_pages) != cur_pages);
2724
2725 return 0;
2726}
2727
2728static void io_mem_free(void *ptr)
2729{
52e04ef4
MR
2730 struct page *page;
2731
2732 if (!ptr)
2733 return;
2b188cc1 2734
52e04ef4 2735 page = virt_to_head_page(ptr);
2b188cc1
JA
2736 if (put_page_testzero(page))
2737 free_compound_page(page);
2738}
2739
2740static void *io_mem_alloc(size_t size)
2741{
2742 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2743 __GFP_NORETRY;
2744
2745 return (void *) __get_free_pages(gfp_flags, get_order(size));
2746}
2747
2748static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2749{
2750 struct io_sq_ring *sq_ring;
2751 struct io_cq_ring *cq_ring;
2752 size_t bytes;
2753
2754 bytes = struct_size(sq_ring, array, sq_entries);
2755 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2756 bytes += struct_size(cq_ring, cqes, cq_entries);
2757
2758 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2759}
2760
edafccee
JA
2761static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2762{
2763 int i, j;
2764
2765 if (!ctx->user_bufs)
2766 return -ENXIO;
2767
2768 for (i = 0; i < ctx->nr_user_bufs; i++) {
2769 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2770
2771 for (j = 0; j < imu->nr_bvecs; j++)
2772 put_page(imu->bvec[j].bv_page);
2773
2774 if (ctx->account_mem)
2775 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 2776 kvfree(imu->bvec);
edafccee
JA
2777 imu->nr_bvecs = 0;
2778 }
2779
2780 kfree(ctx->user_bufs);
2781 ctx->user_bufs = NULL;
2782 ctx->nr_user_bufs = 0;
2783 return 0;
2784}
2785
2786static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2787 void __user *arg, unsigned index)
2788{
2789 struct iovec __user *src;
2790
2791#ifdef CONFIG_COMPAT
2792 if (ctx->compat) {
2793 struct compat_iovec __user *ciovs;
2794 struct compat_iovec ciov;
2795
2796 ciovs = (struct compat_iovec __user *) arg;
2797 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2798 return -EFAULT;
2799
2800 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2801 dst->iov_len = ciov.iov_len;
2802 return 0;
2803 }
2804#endif
2805 src = (struct iovec __user *) arg;
2806 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2807 return -EFAULT;
2808 return 0;
2809}
2810
2811static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2812 unsigned nr_args)
2813{
2814 struct vm_area_struct **vmas = NULL;
2815 struct page **pages = NULL;
2816 int i, j, got_pages = 0;
2817 int ret = -EINVAL;
2818
2819 if (ctx->user_bufs)
2820 return -EBUSY;
2821 if (!nr_args || nr_args > UIO_MAXIOV)
2822 return -EINVAL;
2823
2824 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2825 GFP_KERNEL);
2826 if (!ctx->user_bufs)
2827 return -ENOMEM;
2828
2829 for (i = 0; i < nr_args; i++) {
2830 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2831 unsigned long off, start, end, ubuf;
2832 int pret, nr_pages;
2833 struct iovec iov;
2834 size_t size;
2835
2836 ret = io_copy_iov(ctx, &iov, arg, i);
2837 if (ret)
a278682d 2838 goto err;
edafccee
JA
2839
2840 /*
2841 * Don't impose further limits on the size and buffer
2842 * constraints here, we'll -EINVAL later when IO is
2843 * submitted if they are wrong.
2844 */
2845 ret = -EFAULT;
2846 if (!iov.iov_base || !iov.iov_len)
2847 goto err;
2848
2849 /* arbitrary limit, but we need something */
2850 if (iov.iov_len > SZ_1G)
2851 goto err;
2852
2853 ubuf = (unsigned long) iov.iov_base;
2854 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2855 start = ubuf >> PAGE_SHIFT;
2856 nr_pages = end - start;
2857
2858 if (ctx->account_mem) {
2859 ret = io_account_mem(ctx->user, nr_pages);
2860 if (ret)
2861 goto err;
2862 }
2863
2864 ret = 0;
2865 if (!pages || nr_pages > got_pages) {
2866 kfree(vmas);
2867 kfree(pages);
d4ef6475 2868 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 2869 GFP_KERNEL);
d4ef6475 2870 vmas = kvmalloc_array(nr_pages,
edafccee
JA
2871 sizeof(struct vm_area_struct *),
2872 GFP_KERNEL);
2873 if (!pages || !vmas) {
2874 ret = -ENOMEM;
2875 if (ctx->account_mem)
2876 io_unaccount_mem(ctx->user, nr_pages);
2877 goto err;
2878 }
2879 got_pages = nr_pages;
2880 }
2881
d4ef6475 2882 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
2883 GFP_KERNEL);
2884 ret = -ENOMEM;
2885 if (!imu->bvec) {
2886 if (ctx->account_mem)
2887 io_unaccount_mem(ctx->user, nr_pages);
2888 goto err;
2889 }
2890
2891 ret = 0;
2892 down_read(&current->mm->mmap_sem);
932f4a63
IW
2893 pret = get_user_pages(ubuf, nr_pages,
2894 FOLL_WRITE | FOLL_LONGTERM,
2895 pages, vmas);
edafccee
JA
2896 if (pret == nr_pages) {
2897 /* don't support file backed memory */
2898 for (j = 0; j < nr_pages; j++) {
2899 struct vm_area_struct *vma = vmas[j];
2900
2901 if (vma->vm_file &&
2902 !is_file_hugepages(vma->vm_file)) {
2903 ret = -EOPNOTSUPP;
2904 break;
2905 }
2906 }
2907 } else {
2908 ret = pret < 0 ? pret : -EFAULT;
2909 }
2910 up_read(&current->mm->mmap_sem);
2911 if (ret) {
2912 /*
2913 * if we did partial map, or found file backed vmas,
2914 * release any pages we did get
2915 */
2916 if (pret > 0) {
2917 for (j = 0; j < pret; j++)
2918 put_page(pages[j]);
2919 }
2920 if (ctx->account_mem)
2921 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 2922 kvfree(imu->bvec);
edafccee
JA
2923 goto err;
2924 }
2925
2926 off = ubuf & ~PAGE_MASK;
2927 size = iov.iov_len;
2928 for (j = 0; j < nr_pages; j++) {
2929 size_t vec_len;
2930
2931 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2932 imu->bvec[j].bv_page = pages[j];
2933 imu->bvec[j].bv_len = vec_len;
2934 imu->bvec[j].bv_offset = off;
2935 off = 0;
2936 size -= vec_len;
2937 }
2938 /* store original address for later verification */
2939 imu->ubuf = ubuf;
2940 imu->len = iov.iov_len;
2941 imu->nr_bvecs = nr_pages;
2942
2943 ctx->nr_user_bufs++;
2944 }
d4ef6475
MR
2945 kvfree(pages);
2946 kvfree(vmas);
edafccee
JA
2947 return 0;
2948err:
d4ef6475
MR
2949 kvfree(pages);
2950 kvfree(vmas);
edafccee
JA
2951 io_sqe_buffer_unregister(ctx);
2952 return ret;
2953}
2954
9b402849
JA
2955static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
2956{
2957 __s32 __user *fds = arg;
2958 int fd;
2959
2960 if (ctx->cq_ev_fd)
2961 return -EBUSY;
2962
2963 if (copy_from_user(&fd, fds, sizeof(*fds)))
2964 return -EFAULT;
2965
2966 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
2967 if (IS_ERR(ctx->cq_ev_fd)) {
2968 int ret = PTR_ERR(ctx->cq_ev_fd);
2969 ctx->cq_ev_fd = NULL;
2970 return ret;
2971 }
2972
2973 return 0;
2974}
2975
2976static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2977{
2978 if (ctx->cq_ev_fd) {
2979 eventfd_ctx_put(ctx->cq_ev_fd);
2980 ctx->cq_ev_fd = NULL;
2981 return 0;
2982 }
2983
2984 return -ENXIO;
2985}
2986
2b188cc1
JA
2987static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2988{
6b06314c 2989 io_finish_async(ctx);
2b188cc1
JA
2990 if (ctx->sqo_mm)
2991 mmdrop(ctx->sqo_mm);
def596e9
JA
2992
2993 io_iopoll_reap_events(ctx);
edafccee 2994 io_sqe_buffer_unregister(ctx);
6b06314c 2995 io_sqe_files_unregister(ctx);
9b402849 2996 io_eventfd_unregister(ctx);
def596e9 2997
2b188cc1
JA
2998#if defined(CONFIG_UNIX)
2999 if (ctx->ring_sock)
3000 sock_release(ctx->ring_sock);
3001#endif
3002
3003 io_mem_free(ctx->sq_ring);
3004 io_mem_free(ctx->sq_sqes);
3005 io_mem_free(ctx->cq_ring);
3006
3007 percpu_ref_exit(&ctx->refs);
3008 if (ctx->account_mem)
3009 io_unaccount_mem(ctx->user,
3010 ring_pages(ctx->sq_entries, ctx->cq_entries));
3011 free_uid(ctx->user);
3012 kfree(ctx);
3013}
3014
3015static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3016{
3017 struct io_ring_ctx *ctx = file->private_data;
3018 __poll_t mask = 0;
3019
3020 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
3021 /*
3022 * synchronizes with barrier from wq_has_sleeper call in
3023 * io_commit_cqring
3024 */
2b188cc1 3025 smp_rmb();
fb775faa
SB
3026 if (READ_ONCE(ctx->sq_ring->r.tail) - ctx->cached_sq_head !=
3027 ctx->sq_ring->ring_entries)
2b188cc1
JA
3028 mask |= EPOLLOUT | EPOLLWRNORM;
3029 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
3030 mask |= EPOLLIN | EPOLLRDNORM;
3031
3032 return mask;
3033}
3034
3035static int io_uring_fasync(int fd, struct file *file, int on)
3036{
3037 struct io_ring_ctx *ctx = file->private_data;
3038
3039 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3040}
3041
3042static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3043{
3044 mutex_lock(&ctx->uring_lock);
3045 percpu_ref_kill(&ctx->refs);
3046 mutex_unlock(&ctx->uring_lock);
3047
221c5eb2 3048 io_poll_remove_all(ctx);
def596e9 3049 io_iopoll_reap_events(ctx);
2b188cc1
JA
3050 wait_for_completion(&ctx->ctx_done);
3051 io_ring_ctx_free(ctx);
3052}
3053
3054static int io_uring_release(struct inode *inode, struct file *file)
3055{
3056 struct io_ring_ctx *ctx = file->private_data;
3057
3058 file->private_data = NULL;
3059 io_ring_ctx_wait_and_kill(ctx);
3060 return 0;
3061}
3062
3063static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3064{
3065 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3066 unsigned long sz = vma->vm_end - vma->vm_start;
3067 struct io_ring_ctx *ctx = file->private_data;
3068 unsigned long pfn;
3069 struct page *page;
3070 void *ptr;
3071
3072 switch (offset) {
3073 case IORING_OFF_SQ_RING:
3074 ptr = ctx->sq_ring;
3075 break;
3076 case IORING_OFF_SQES:
3077 ptr = ctx->sq_sqes;
3078 break;
3079 case IORING_OFF_CQ_RING:
3080 ptr = ctx->cq_ring;
3081 break;
3082 default:
3083 return -EINVAL;
3084 }
3085
3086 page = virt_to_head_page(ptr);
3087 if (sz > (PAGE_SIZE << compound_order(page)))
3088 return -EINVAL;
3089
3090 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3091 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3092}
3093
3094SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3095 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3096 size_t, sigsz)
3097{
3098 struct io_ring_ctx *ctx;
3099 long ret = -EBADF;
3100 int submitted = 0;
3101 struct fd f;
3102
6c271ce2 3103 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
3104 return -EINVAL;
3105
3106 f = fdget(fd);
3107 if (!f.file)
3108 return -EBADF;
3109
3110 ret = -EOPNOTSUPP;
3111 if (f.file->f_op != &io_uring_fops)
3112 goto out_fput;
3113
3114 ret = -ENXIO;
3115 ctx = f.file->private_data;
3116 if (!percpu_ref_tryget(&ctx->refs))
3117 goto out_fput;
3118
6c271ce2
JA
3119 /*
3120 * For SQ polling, the thread will do all submissions and completions.
3121 * Just return the requested submit count, and wake the thread if
3122 * we were asked to.
3123 */
3124 if (ctx->flags & IORING_SETUP_SQPOLL) {
3125 if (flags & IORING_ENTER_SQ_WAKEUP)
3126 wake_up(&ctx->sqo_wait);
3127 submitted = to_submit;
3128 goto out_ctx;
3129 }
3130
2b188cc1
JA
3131 ret = 0;
3132 if (to_submit) {
3133 to_submit = min(to_submit, ctx->sq_entries);
3134
3135 mutex_lock(&ctx->uring_lock);
3136 submitted = io_ring_submit(ctx, to_submit);
3137 mutex_unlock(&ctx->uring_lock);
2b188cc1
JA
3138 }
3139 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
3140 unsigned nr_events = 0;
3141
2b188cc1
JA
3142 min_complete = min(min_complete, ctx->cq_entries);
3143
def596e9
JA
3144 if (ctx->flags & IORING_SETUP_IOPOLL) {
3145 mutex_lock(&ctx->uring_lock);
3146 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3147 mutex_unlock(&ctx->uring_lock);
3148 } else {
3149 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3150 }
2b188cc1
JA
3151 }
3152
3153out_ctx:
3154 io_ring_drop_ctx_refs(ctx, 1);
3155out_fput:
3156 fdput(f);
3157 return submitted ? submitted : ret;
3158}
3159
3160static const struct file_operations io_uring_fops = {
3161 .release = io_uring_release,
3162 .mmap = io_uring_mmap,
3163 .poll = io_uring_poll,
3164 .fasync = io_uring_fasync,
3165};
3166
3167static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3168 struct io_uring_params *p)
3169{
3170 struct io_sq_ring *sq_ring;
3171 struct io_cq_ring *cq_ring;
3172 size_t size;
3173
3174 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
3175 if (!sq_ring)
3176 return -ENOMEM;
3177
3178 ctx->sq_ring = sq_ring;
3179 sq_ring->ring_mask = p->sq_entries - 1;
3180 sq_ring->ring_entries = p->sq_entries;
3181 ctx->sq_mask = sq_ring->ring_mask;
3182 ctx->sq_entries = sq_ring->ring_entries;
3183
3184 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3185 if (size == SIZE_MAX)
3186 return -EOVERFLOW;
3187
3188 ctx->sq_sqes = io_mem_alloc(size);
52e04ef4 3189 if (!ctx->sq_sqes)
2b188cc1 3190 return -ENOMEM;
2b188cc1
JA
3191
3192 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
52e04ef4 3193 if (!cq_ring)
2b188cc1 3194 return -ENOMEM;
2b188cc1
JA
3195
3196 ctx->cq_ring = cq_ring;
3197 cq_ring->ring_mask = p->cq_entries - 1;
3198 cq_ring->ring_entries = p->cq_entries;
3199 ctx->cq_mask = cq_ring->ring_mask;
3200 ctx->cq_entries = cq_ring->ring_entries;
3201 return 0;
3202}
3203
3204/*
3205 * Allocate an anonymous fd, this is what constitutes the application
3206 * visible backing of an io_uring instance. The application mmaps this
3207 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3208 * we have to tie this fd to a socket for file garbage collection purposes.
3209 */
3210static int io_uring_get_fd(struct io_ring_ctx *ctx)
3211{
3212 struct file *file;
3213 int ret;
3214
3215#if defined(CONFIG_UNIX)
3216 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3217 &ctx->ring_sock);
3218 if (ret)
3219 return ret;
3220#endif
3221
3222 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3223 if (ret < 0)
3224 goto err;
3225
3226 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3227 O_RDWR | O_CLOEXEC);
3228 if (IS_ERR(file)) {
3229 put_unused_fd(ret);
3230 ret = PTR_ERR(file);
3231 goto err;
3232 }
3233
3234#if defined(CONFIG_UNIX)
3235 ctx->ring_sock->file = file;
6b06314c 3236 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
3237#endif
3238 fd_install(ret, file);
3239 return ret;
3240err:
3241#if defined(CONFIG_UNIX)
3242 sock_release(ctx->ring_sock);
3243 ctx->ring_sock = NULL;
3244#endif
3245 return ret;
3246}
3247
3248static int io_uring_create(unsigned entries, struct io_uring_params *p)
3249{
3250 struct user_struct *user = NULL;
3251 struct io_ring_ctx *ctx;
3252 bool account_mem;
3253 int ret;
3254
3255 if (!entries || entries > IORING_MAX_ENTRIES)
3256 return -EINVAL;
3257
3258 /*
3259 * Use twice as many entries for the CQ ring. It's possible for the
3260 * application to drive a higher depth than the size of the SQ ring,
3261 * since the sqes are only used at submission time. This allows for
3262 * some flexibility in overcommitting a bit.
3263 */
3264 p->sq_entries = roundup_pow_of_two(entries);
3265 p->cq_entries = 2 * p->sq_entries;
3266
3267 user = get_uid(current_user());
3268 account_mem = !capable(CAP_IPC_LOCK);
3269
3270 if (account_mem) {
3271 ret = io_account_mem(user,
3272 ring_pages(p->sq_entries, p->cq_entries));
3273 if (ret) {
3274 free_uid(user);
3275 return ret;
3276 }
3277 }
3278
3279 ctx = io_ring_ctx_alloc(p);
3280 if (!ctx) {
3281 if (account_mem)
3282 io_unaccount_mem(user, ring_pages(p->sq_entries,
3283 p->cq_entries));
3284 free_uid(user);
3285 return -ENOMEM;
3286 }
3287 ctx->compat = in_compat_syscall();
3288 ctx->account_mem = account_mem;
3289 ctx->user = user;
3290
3291 ret = io_allocate_scq_urings(ctx, p);
3292 if (ret)
3293 goto err;
3294
6c271ce2 3295 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
3296 if (ret)
3297 goto err;
3298
3299 ret = io_uring_get_fd(ctx);
3300 if (ret < 0)
3301 goto err;
3302
3303 memset(&p->sq_off, 0, sizeof(p->sq_off));
3304 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
3305 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
3306 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
3307 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
3308 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
3309 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
3310 p->sq_off.array = offsetof(struct io_sq_ring, array);
3311
3312 memset(&p->cq_off, 0, sizeof(p->cq_off));
3313 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
3314 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
3315 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
3316 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
3317 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
3318 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
3319 return ret;
3320err:
3321 io_ring_ctx_wait_and_kill(ctx);
3322 return ret;
3323}
3324
3325/*
3326 * Sets up an aio uring context, and returns the fd. Applications asks for a
3327 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3328 * params structure passed in.
3329 */
3330static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3331{
3332 struct io_uring_params p;
3333 long ret;
3334 int i;
3335
3336 if (copy_from_user(&p, params, sizeof(p)))
3337 return -EFAULT;
3338 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3339 if (p.resv[i])
3340 return -EINVAL;
3341 }
3342
6c271ce2
JA
3343 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3344 IORING_SETUP_SQ_AFF))
2b188cc1
JA
3345 return -EINVAL;
3346
3347 ret = io_uring_create(entries, &p);
3348 if (ret < 0)
3349 return ret;
3350
3351 if (copy_to_user(params, &p, sizeof(p)))
3352 return -EFAULT;
3353
3354 return ret;
3355}
3356
3357SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3358 struct io_uring_params __user *, params)
3359{
3360 return io_uring_setup(entries, params);
3361}
3362
edafccee
JA
3363static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3364 void __user *arg, unsigned nr_args)
b19062a5
JA
3365 __releases(ctx->uring_lock)
3366 __acquires(ctx->uring_lock)
edafccee
JA
3367{
3368 int ret;
3369
35fa71a0
JA
3370 /*
3371 * We're inside the ring mutex, if the ref is already dying, then
3372 * someone else killed the ctx or is already going through
3373 * io_uring_register().
3374 */
3375 if (percpu_ref_is_dying(&ctx->refs))
3376 return -ENXIO;
3377
edafccee 3378 percpu_ref_kill(&ctx->refs);
b19062a5
JA
3379
3380 /*
3381 * Drop uring mutex before waiting for references to exit. If another
3382 * thread is currently inside io_uring_enter() it might need to grab
3383 * the uring_lock to make progress. If we hold it here across the drain
3384 * wait, then we can deadlock. It's safe to drop the mutex here, since
3385 * no new references will come in after we've killed the percpu ref.
3386 */
3387 mutex_unlock(&ctx->uring_lock);
edafccee 3388 wait_for_completion(&ctx->ctx_done);
b19062a5 3389 mutex_lock(&ctx->uring_lock);
edafccee
JA
3390
3391 switch (opcode) {
3392 case IORING_REGISTER_BUFFERS:
3393 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3394 break;
3395 case IORING_UNREGISTER_BUFFERS:
3396 ret = -EINVAL;
3397 if (arg || nr_args)
3398 break;
3399 ret = io_sqe_buffer_unregister(ctx);
3400 break;
6b06314c
JA
3401 case IORING_REGISTER_FILES:
3402 ret = io_sqe_files_register(ctx, arg, nr_args);
3403 break;
3404 case IORING_UNREGISTER_FILES:
3405 ret = -EINVAL;
3406 if (arg || nr_args)
3407 break;
3408 ret = io_sqe_files_unregister(ctx);
3409 break;
9b402849
JA
3410 case IORING_REGISTER_EVENTFD:
3411 ret = -EINVAL;
3412 if (nr_args != 1)
3413 break;
3414 ret = io_eventfd_register(ctx, arg);
3415 break;
3416 case IORING_UNREGISTER_EVENTFD:
3417 ret = -EINVAL;
3418 if (arg || nr_args)
3419 break;
3420 ret = io_eventfd_unregister(ctx);
3421 break;
edafccee
JA
3422 default:
3423 ret = -EINVAL;
3424 break;
3425 }
3426
3427 /* bring the ctx back to life */
3428 reinit_completion(&ctx->ctx_done);
3429 percpu_ref_reinit(&ctx->refs);
3430 return ret;
3431}
3432
3433SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3434 void __user *, arg, unsigned int, nr_args)
3435{
3436 struct io_ring_ctx *ctx;
3437 long ret = -EBADF;
3438 struct fd f;
3439
3440 f = fdget(fd);
3441 if (!f.file)
3442 return -EBADF;
3443
3444 ret = -EOPNOTSUPP;
3445 if (f.file->f_op != &io_uring_fops)
3446 goto out_fput;
3447
3448 ctx = f.file->private_data;
3449
3450 mutex_lock(&ctx->uring_lock);
3451 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3452 mutex_unlock(&ctx->uring_lock);
3453out_fput:
3454 fdput(f);
3455 return ret;
3456}
3457
2b188cc1
JA
3458static int __init io_uring_init(void)
3459{
3460 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3461 return 0;
3462};
3463__initcall(io_uring_init);