]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/io_uring.c
io_uring: add support for sqe links
[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
221c5eb2
JA
1393static void io_poll_remove_one(struct io_kiocb *req)
1394{
1395 struct io_poll_iocb *poll = &req->poll;
1396
1397 spin_lock(&poll->head->lock);
1398 WRITE_ONCE(poll->canceled, true);
1399 if (!list_empty(&poll->wait.entry)) {
1400 list_del_init(&poll->wait.entry);
1401 queue_work(req->ctx->sqo_wq, &req->work);
1402 }
1403 spin_unlock(&poll->head->lock);
1404
1405 list_del_init(&req->list);
1406}
1407
1408static void io_poll_remove_all(struct io_ring_ctx *ctx)
1409{
1410 struct io_kiocb *req;
1411
1412 spin_lock_irq(&ctx->completion_lock);
1413 while (!list_empty(&ctx->cancel_list)) {
1414 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1415 io_poll_remove_one(req);
1416 }
1417 spin_unlock_irq(&ctx->completion_lock);
1418}
1419
1420/*
1421 * Find a running poll command that matches one specified in sqe->addr,
1422 * and remove it if found.
1423 */
1424static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1425{
1426 struct io_ring_ctx *ctx = req->ctx;
1427 struct io_kiocb *poll_req, *next;
1428 int ret = -ENOENT;
1429
1430 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1431 return -EINVAL;
1432 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1433 sqe->poll_events)
1434 return -EINVAL;
1435
1436 spin_lock_irq(&ctx->completion_lock);
1437 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1438 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1439 io_poll_remove_one(poll_req);
1440 ret = 0;
1441 break;
1442 }
1443 }
1444 spin_unlock_irq(&ctx->completion_lock);
1445
c71ffb67 1446 io_cqring_add_event(req->ctx, sqe->user_data, ret);
e65ef56d 1447 io_put_req(req);
221c5eb2
JA
1448 return 0;
1449}
1450
8c838788
JA
1451static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1452 __poll_t mask)
221c5eb2 1453{
8c838788 1454 req->poll.done = true;
c71ffb67 1455 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
8c838788 1456 io_commit_cqring(ctx);
221c5eb2
JA
1457}
1458
1459static void io_poll_complete_work(struct work_struct *work)
1460{
1461 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1462 struct io_poll_iocb *poll = &req->poll;
1463 struct poll_table_struct pt = { ._key = poll->events };
1464 struct io_ring_ctx *ctx = req->ctx;
1465 __poll_t mask = 0;
1466
1467 if (!READ_ONCE(poll->canceled))
1468 mask = vfs_poll(poll->file, &pt) & poll->events;
1469
1470 /*
1471 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1472 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1473 * synchronize with them. In the cancellation case the list_del_init
1474 * itself is not actually needed, but harmless so we keep it in to
1475 * avoid further branches in the fast path.
1476 */
1477 spin_lock_irq(&ctx->completion_lock);
1478 if (!mask && !READ_ONCE(poll->canceled)) {
1479 add_wait_queue(poll->head, &poll->wait);
1480 spin_unlock_irq(&ctx->completion_lock);
1481 return;
1482 }
1483 list_del_init(&req->list);
8c838788 1484 io_poll_complete(ctx, req, mask);
221c5eb2
JA
1485 spin_unlock_irq(&ctx->completion_lock);
1486
8c838788
JA
1487 io_cqring_ev_posted(ctx);
1488 io_put_req(req);
221c5eb2
JA
1489}
1490
1491static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1492 void *key)
1493{
1494 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1495 wait);
1496 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1497 struct io_ring_ctx *ctx = req->ctx;
1498 __poll_t mask = key_to_poll(key);
8c838788 1499 unsigned long flags;
221c5eb2
JA
1500
1501 /* for instances that support it check for an event match first: */
8c838788
JA
1502 if (mask && !(mask & poll->events))
1503 return 0;
221c5eb2 1504
8c838788 1505 list_del_init(&poll->wait.entry);
221c5eb2 1506
8c838788
JA
1507 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1508 list_del(&req->list);
1509 io_poll_complete(ctx, req, mask);
1510 spin_unlock_irqrestore(&ctx->completion_lock, flags);
221c5eb2 1511
8c838788
JA
1512 io_cqring_ev_posted(ctx);
1513 io_put_req(req);
1514 } else {
1515 queue_work(ctx->sqo_wq, &req->work);
221c5eb2
JA
1516 }
1517
221c5eb2
JA
1518 return 1;
1519}
1520
1521struct io_poll_table {
1522 struct poll_table_struct pt;
1523 struct io_kiocb *req;
1524 int error;
1525};
1526
1527static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1528 struct poll_table_struct *p)
1529{
1530 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1531
1532 if (unlikely(pt->req->poll.head)) {
1533 pt->error = -EINVAL;
1534 return;
1535 }
1536
1537 pt->error = 0;
1538 pt->req->poll.head = head;
1539 add_wait_queue(head, &pt->req->poll.wait);
1540}
1541
1542static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1543{
1544 struct io_poll_iocb *poll = &req->poll;
1545 struct io_ring_ctx *ctx = req->ctx;
1546 struct io_poll_table ipt;
8c838788 1547 bool cancel = false;
221c5eb2
JA
1548 __poll_t mask;
1549 u16 events;
221c5eb2
JA
1550
1551 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1552 return -EINVAL;
1553 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1554 return -EINVAL;
09bb8394
JA
1555 if (!poll->file)
1556 return -EBADF;
221c5eb2
JA
1557
1558 INIT_WORK(&req->work, io_poll_complete_work);
1559 events = READ_ONCE(sqe->poll_events);
1560 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1561
221c5eb2 1562 poll->head = NULL;
8c838788 1563 poll->done = false;
221c5eb2
JA
1564 poll->canceled = false;
1565
1566 ipt.pt._qproc = io_poll_queue_proc;
1567 ipt.pt._key = poll->events;
1568 ipt.req = req;
1569 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1570
1571 /* initialized the list so that we can do list_empty checks */
1572 INIT_LIST_HEAD(&poll->wait.entry);
1573 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1574
221c5eb2 1575 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
1576
1577 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
1578 if (likely(poll->head)) {
1579 spin_lock(&poll->head->lock);
1580 if (unlikely(list_empty(&poll->wait.entry))) {
1581 if (ipt.error)
1582 cancel = true;
1583 ipt.error = 0;
1584 mask = 0;
1585 }
1586 if (mask || ipt.error)
1587 list_del_init(&poll->wait.entry);
1588 else if (cancel)
1589 WRITE_ONCE(poll->canceled, true);
1590 else if (!poll->done) /* actually waiting for an event */
1591 list_add_tail(&req->list, &ctx->cancel_list);
1592 spin_unlock(&poll->head->lock);
1593 }
1594 if (mask) { /* no async, we'd stolen it */
221c5eb2 1595 ipt.error = 0;
8c838788 1596 io_poll_complete(ctx, req, mask);
221c5eb2 1597 }
221c5eb2
JA
1598 spin_unlock_irq(&ctx->completion_lock);
1599
8c838788
JA
1600 if (mask) {
1601 io_cqring_ev_posted(ctx);
e65ef56d 1602 io_put_req(req);
221c5eb2 1603 }
8c838788 1604 return ipt.error;
221c5eb2
JA
1605}
1606
de0617e4
JA
1607static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1608 const struct io_uring_sqe *sqe)
1609{
1610 struct io_uring_sqe *sqe_copy;
1611
1612 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1613 return 0;
1614
1615 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1616 if (!sqe_copy)
1617 return -EAGAIN;
1618
1619 spin_lock_irq(&ctx->completion_lock);
1620 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1621 spin_unlock_irq(&ctx->completion_lock);
1622 kfree(sqe_copy);
1623 return 0;
1624 }
1625
1626 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1627 req->submit.sqe = sqe_copy;
1628
1629 INIT_WORK(&req->work, io_sq_wq_submit_work);
1630 list_add_tail(&req->list, &ctx->defer_list);
1631 spin_unlock_irq(&ctx->completion_lock);
1632 return -EIOCBQUEUED;
1633}
1634
2b188cc1 1635static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8358e3a8 1636 const struct sqe_submit *s, bool force_nonblock)
2b188cc1 1637{
e0c5c576 1638 int ret, opcode;
2b188cc1 1639
9e645e11
JA
1640 req->user_data = READ_ONCE(s->sqe->user_data);
1641
2b188cc1
JA
1642 if (unlikely(s->index >= ctx->sq_entries))
1643 return -EINVAL;
2b188cc1
JA
1644
1645 opcode = READ_ONCE(s->sqe->opcode);
1646 switch (opcode) {
1647 case IORING_OP_NOP:
1648 ret = io_nop(req, req->user_data);
1649 break;
1650 case IORING_OP_READV:
edafccee
JA
1651 if (unlikely(s->sqe->buf_index))
1652 return -EINVAL;
8358e3a8 1653 ret = io_read(req, s, force_nonblock);
2b188cc1
JA
1654 break;
1655 case IORING_OP_WRITEV:
edafccee
JA
1656 if (unlikely(s->sqe->buf_index))
1657 return -EINVAL;
8358e3a8 1658 ret = io_write(req, s, force_nonblock);
edafccee
JA
1659 break;
1660 case IORING_OP_READ_FIXED:
8358e3a8 1661 ret = io_read(req, s, force_nonblock);
edafccee
JA
1662 break;
1663 case IORING_OP_WRITE_FIXED:
8358e3a8 1664 ret = io_write(req, s, force_nonblock);
2b188cc1 1665 break;
c992fe29
CH
1666 case IORING_OP_FSYNC:
1667 ret = io_fsync(req, s->sqe, force_nonblock);
1668 break;
221c5eb2
JA
1669 case IORING_OP_POLL_ADD:
1670 ret = io_poll_add(req, s->sqe);
1671 break;
1672 case IORING_OP_POLL_REMOVE:
1673 ret = io_poll_remove(req, s->sqe);
1674 break;
5d17b4a4
JA
1675 case IORING_OP_SYNC_FILE_RANGE:
1676 ret = io_sync_file_range(req, s->sqe, force_nonblock);
1677 break;
2b188cc1
JA
1678 default:
1679 ret = -EINVAL;
1680 break;
1681 }
1682
def596e9
JA
1683 if (ret)
1684 return ret;
1685
1686 if (ctx->flags & IORING_SETUP_IOPOLL) {
9e645e11 1687 if (req->result == -EAGAIN)
def596e9
JA
1688 return -EAGAIN;
1689
1690 /* workqueue context doesn't hold uring_lock, grab it now */
1691 if (s->needs_lock)
1692 mutex_lock(&ctx->uring_lock);
1693 io_iopoll_req_issued(req);
1694 if (s->needs_lock)
1695 mutex_unlock(&ctx->uring_lock);
1696 }
1697
1698 return 0;
2b188cc1
JA
1699}
1700
31b51510
JA
1701static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1702 const struct io_uring_sqe *sqe)
1703{
1704 switch (sqe->opcode) {
1705 case IORING_OP_READV:
1706 case IORING_OP_READ_FIXED:
1707 return &ctx->pending_async[READ];
1708 case IORING_OP_WRITEV:
1709 case IORING_OP_WRITE_FIXED:
1710 return &ctx->pending_async[WRITE];
1711 default:
1712 return NULL;
1713 }
1714}
1715
edafccee
JA
1716static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1717{
1718 u8 opcode = READ_ONCE(sqe->opcode);
1719
1720 return !(opcode == IORING_OP_READ_FIXED ||
1721 opcode == IORING_OP_WRITE_FIXED);
1722}
1723
2b188cc1
JA
1724static void io_sq_wq_submit_work(struct work_struct *work)
1725{
1726 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 1727 struct io_ring_ctx *ctx = req->ctx;
31b51510
JA
1728 struct mm_struct *cur_mm = NULL;
1729 struct async_list *async_list;
1730 LIST_HEAD(req_list);
edafccee 1731 mm_segment_t old_fs;
2b188cc1
JA
1732 int ret;
1733
31b51510
JA
1734 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1735restart:
1736 do {
1737 struct sqe_submit *s = &req->submit;
1738 const struct io_uring_sqe *sqe = s->sqe;
2b188cc1 1739
8449eeda 1740 /* Ensure we clear previously set non-block flag */
31b51510
JA
1741 req->rw.ki_flags &= ~IOCB_NOWAIT;
1742
1743 ret = 0;
1744 if (io_sqe_needs_user(sqe) && !cur_mm) {
1745 if (!mmget_not_zero(ctx->sqo_mm)) {
1746 ret = -EFAULT;
1747 } else {
1748 cur_mm = ctx->sqo_mm;
1749 use_mm(cur_mm);
1750 old_fs = get_fs();
1751 set_fs(USER_DS);
1752 }
1753 }
1754
1755 if (!ret) {
1756 s->has_user = cur_mm != NULL;
1757 s->needs_lock = true;
1758 do {
8358e3a8 1759 ret = __io_submit_sqe(ctx, req, s, false);
31b51510
JA
1760 /*
1761 * We can get EAGAIN for polled IO even though
1762 * we're forcing a sync submission from here,
1763 * since we can't wait for request slots on the
1764 * block side.
1765 */
1766 if (ret != -EAGAIN)
1767 break;
1768 cond_resched();
1769 } while (1);
1770 }
817869d2
JA
1771
1772 /* drop submission reference */
1773 io_put_req(req);
1774
31b51510 1775 if (ret) {
c71ffb67 1776 io_cqring_add_event(ctx, sqe->user_data, ret);
e65ef56d 1777 io_put_req(req);
31b51510
JA
1778 }
1779
1780 /* async context always use a copy of the sqe */
1781 kfree(sqe);
1782
1783 if (!async_list)
1784 break;
1785 if (!list_empty(&req_list)) {
1786 req = list_first_entry(&req_list, struct io_kiocb,
1787 list);
1788 list_del(&req->list);
1789 continue;
1790 }
1791 if (list_empty(&async_list->list))
1792 break;
1793
1794 req = NULL;
1795 spin_lock(&async_list->lock);
1796 if (list_empty(&async_list->list)) {
1797 spin_unlock(&async_list->lock);
1798 break;
1799 }
1800 list_splice_init(&async_list->list, &req_list);
1801 spin_unlock(&async_list->lock);
1802
1803 req = list_first_entry(&req_list, struct io_kiocb, list);
1804 list_del(&req->list);
1805 } while (req);
edafccee
JA
1806
1807 /*
31b51510
JA
1808 * Rare case of racing with a submitter. If we find the count has
1809 * dropped to zero AND we have pending work items, then restart
1810 * the processing. This is a tiny race window.
edafccee 1811 */
31b51510
JA
1812 if (async_list) {
1813 ret = atomic_dec_return(&async_list->cnt);
1814 while (!ret && !list_empty(&async_list->list)) {
1815 spin_lock(&async_list->lock);
1816 atomic_inc(&async_list->cnt);
1817 list_splice_init(&async_list->list, &req_list);
1818 spin_unlock(&async_list->lock);
1819
1820 if (!list_empty(&req_list)) {
1821 req = list_first_entry(&req_list,
1822 struct io_kiocb, list);
1823 list_del(&req->list);
1824 goto restart;
1825 }
1826 ret = atomic_dec_return(&async_list->cnt);
edafccee 1827 }
edafccee 1828 }
2b188cc1 1829
31b51510 1830 if (cur_mm) {
edafccee 1831 set_fs(old_fs);
31b51510
JA
1832 unuse_mm(cur_mm);
1833 mmput(cur_mm);
2b188cc1 1834 }
31b51510 1835}
2b188cc1 1836
31b51510
JA
1837/*
1838 * See if we can piggy back onto previously submitted work, that is still
1839 * running. We currently only allow this if the new request is sequential
1840 * to the previous one we punted.
1841 */
1842static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1843{
1844 bool ret = false;
1845
1846 if (!list)
1847 return false;
1848 if (!(req->flags & REQ_F_SEQ_PREV))
1849 return false;
1850 if (!atomic_read(&list->cnt))
1851 return false;
1852
1853 ret = true;
1854 spin_lock(&list->lock);
1855 list_add_tail(&req->list, &list->list);
1856 if (!atomic_read(&list->cnt)) {
1857 list_del_init(&req->list);
1858 ret = false;
1859 }
1860 spin_unlock(&list->lock);
1861 return ret;
2b188cc1
JA
1862}
1863
09bb8394
JA
1864static bool io_op_needs_file(const struct io_uring_sqe *sqe)
1865{
1866 int op = READ_ONCE(sqe->opcode);
1867
1868 switch (op) {
1869 case IORING_OP_NOP:
1870 case IORING_OP_POLL_REMOVE:
1871 return false;
1872 default:
1873 return true;
1874 }
1875}
1876
1877static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
1878 struct io_submit_state *state, struct io_kiocb *req)
1879{
1880 unsigned flags;
1881 int fd;
1882
1883 flags = READ_ONCE(s->sqe->flags);
1884 fd = READ_ONCE(s->sqe->fd);
1885
de0617e4
JA
1886 if (flags & IOSQE_IO_DRAIN) {
1887 req->flags |= REQ_F_IO_DRAIN;
1888 req->sequence = ctx->cached_sq_head - 1;
1889 }
1890
09bb8394
JA
1891 if (!io_op_needs_file(s->sqe)) {
1892 req->file = NULL;
1893 return 0;
1894 }
1895
1896 if (flags & IOSQE_FIXED_FILE) {
1897 if (unlikely(!ctx->user_files ||
1898 (unsigned) fd >= ctx->nr_user_files))
1899 return -EBADF;
1900 req->file = ctx->user_files[fd];
1901 req->flags |= REQ_F_FIXED_FILE;
1902 } else {
1903 if (s->needs_fixed_file)
1904 return -EBADF;
1905 req->file = io_file_get(state, fd);
1906 if (unlikely(!req->file))
1907 return -EBADF;
1908 }
1909
1910 return 0;
1911}
1912
9e645e11
JA
1913static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1914 struct sqe_submit *s)
2b188cc1 1915{
e0c5c576 1916 int ret;
2b188cc1 1917
8358e3a8 1918 ret = __io_submit_sqe(ctx, req, s, true);
8449eeda 1919 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
2b188cc1
JA
1920 struct io_uring_sqe *sqe_copy;
1921
1922 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1923 if (sqe_copy) {
31b51510
JA
1924 struct async_list *list;
1925
2b188cc1
JA
1926 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1927 s->sqe = sqe_copy;
1928
1929 memcpy(&req->submit, s, sizeof(*s));
31b51510
JA
1930 list = io_async_list_from_sqe(ctx, s->sqe);
1931 if (!io_add_to_prev_work(list, req)) {
1932 if (list)
1933 atomic_inc(&list->cnt);
1934 INIT_WORK(&req->work, io_sq_wq_submit_work);
1935 queue_work(ctx->sqo_wq, &req->work);
1936 }
e65ef56d
JA
1937
1938 /*
1939 * Queued up for async execution, worker will release
9e645e11 1940 * submit reference when the iocb is actually submitted.
e65ef56d
JA
1941 */
1942 return 0;
2b188cc1
JA
1943 }
1944 }
e65ef56d
JA
1945
1946 /* drop submission reference */
1947 io_put_req(req);
1948
1949 /* and drop final reference, if we failed */
9e645e11
JA
1950 if (ret) {
1951 io_cqring_add_event(ctx, req->user_data, ret);
1952 if (req->flags & REQ_F_LINK)
1953 req->flags |= REQ_F_FAIL_LINK;
e65ef56d 1954 io_put_req(req);
9e645e11 1955 }
2b188cc1
JA
1956
1957 return ret;
1958}
1959
9e645e11
JA
1960#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
1961
1962static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1963 struct io_submit_state *state, struct io_kiocb **link)
1964{
1965 struct io_uring_sqe *sqe_copy;
1966 struct io_kiocb *req;
1967 int ret;
1968
1969 /* enforce forwards compatibility on users */
1970 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
1971 ret = -EINVAL;
1972 goto err;
1973 }
1974
1975 req = io_get_req(ctx, state);
1976 if (unlikely(!req)) {
1977 ret = -EAGAIN;
1978 goto err;
1979 }
1980
1981 ret = io_req_set_file(ctx, s, state, req);
1982 if (unlikely(ret)) {
1983err_req:
1984 io_free_req(req);
1985err:
1986 io_cqring_add_event(ctx, s->sqe->user_data, ret);
1987 return;
1988 }
1989
1990 ret = io_req_defer(ctx, req, s->sqe);
1991 if (ret) {
1992 if (ret != -EIOCBQUEUED)
1993 goto err_req;
1994 return;
1995 }
1996
1997 /*
1998 * If we already have a head request, queue this one for async
1999 * submittal once the head completes. If we don't have a head but
2000 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2001 * submitted sync once the chain is complete. If none of those
2002 * conditions are true (normal request), then just queue it.
2003 */
2004 if (*link) {
2005 struct io_kiocb *prev = *link;
2006
2007 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2008 if (!sqe_copy) {
2009 ret = -EAGAIN;
2010 goto err_req;
2011 }
2012
2013 s->sqe = sqe_copy;
2014 memcpy(&req->submit, s, sizeof(*s));
2015 list_add_tail(&req->list, &prev->link_list);
2016 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2017 req->flags |= REQ_F_LINK;
2018
2019 memcpy(&req->submit, s, sizeof(*s));
2020 INIT_LIST_HEAD(&req->link_list);
2021 *link = req;
2022 } else {
2023 io_queue_sqe(ctx, req, s);
2024 }
2025}
2026
9a56a232
JA
2027/*
2028 * Batched submission is done, ensure local IO is flushed out.
2029 */
2030static void io_submit_state_end(struct io_submit_state *state)
2031{
2032 blk_finish_plug(&state->plug);
3d6770fb 2033 io_file_put(state);
2579f913
JA
2034 if (state->free_reqs)
2035 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2036 &state->reqs[state->cur_req]);
9a56a232
JA
2037}
2038
2039/*
2040 * Start submission side cache.
2041 */
2042static void io_submit_state_start(struct io_submit_state *state,
2043 struct io_ring_ctx *ctx, unsigned max_ios)
2044{
2045 blk_start_plug(&state->plug);
2579f913 2046 state->free_reqs = 0;
9a56a232
JA
2047 state->file = NULL;
2048 state->ios_left = max_ios;
2049}
2050
2b188cc1
JA
2051static void io_commit_sqring(struct io_ring_ctx *ctx)
2052{
2053 struct io_sq_ring *ring = ctx->sq_ring;
2054
2055 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
2056 /*
2057 * Ensure any loads from the SQEs are done at this point,
2058 * since once we write the new head, the application could
2059 * write new data to them.
2060 */
2061 smp_store_release(&ring->r.head, ctx->cached_sq_head);
2b188cc1
JA
2062 }
2063}
2064
2b188cc1
JA
2065/*
2066 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2067 * that is mapped by userspace. This means that care needs to be taken to
2068 * ensure that reads are stable, as we cannot rely on userspace always
2069 * being a good citizen. If members of the sqe are validated and then later
2070 * used, it's important that those reads are done through READ_ONCE() to
2071 * prevent a re-load down the line.
2072 */
2073static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2074{
2075 struct io_sq_ring *ring = ctx->sq_ring;
2076 unsigned head;
2077
2078 /*
2079 * The cached sq head (or cq tail) serves two purposes:
2080 *
2081 * 1) allows us to batch the cost of updating the user visible
2082 * head updates.
2083 * 2) allows the kernel side to track the head on its own, even
2084 * though the application is the one updating it.
2085 */
2086 head = ctx->cached_sq_head;
e523a29c
SB
2087 /* make sure SQ entry isn't read before tail */
2088 if (head == smp_load_acquire(&ring->r.tail))
2b188cc1
JA
2089 return false;
2090
2091 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
2092 if (head < ctx->sq_entries) {
2093 s->index = head;
2094 s->sqe = &ctx->sq_sqes[head];
2095 ctx->cached_sq_head++;
2096 return true;
2097 }
2098
2099 /* drop invalid entries */
2100 ctx->cached_sq_head++;
2101 ring->dropped++;
2b188cc1
JA
2102 return false;
2103}
2104
6c271ce2
JA
2105static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
2106 unsigned int nr, bool has_user, bool mm_fault)
2107{
2108 struct io_submit_state state, *statep = NULL;
9e645e11
JA
2109 struct io_kiocb *link = NULL;
2110 bool prev_was_link = false;
2111 int i, submitted = 0;
6c271ce2
JA
2112
2113 if (nr > IO_PLUG_THRESHOLD) {
2114 io_submit_state_start(&state, ctx, nr);
2115 statep = &state;
2116 }
2117
2118 for (i = 0; i < nr; i++) {
9e645e11
JA
2119 /*
2120 * If previous wasn't linked and we have a linked command,
2121 * that's the end of the chain. Submit the previous link.
2122 */
2123 if (!prev_was_link && link) {
2124 io_queue_sqe(ctx, link, &link->submit);
2125 link = NULL;
2126 }
2127 prev_was_link = (sqes[i].sqe->flags & IOSQE_IO_LINK) != 0;
2128
6c271ce2 2129 if (unlikely(mm_fault)) {
9e645e11
JA
2130 io_cqring_add_event(ctx, sqes[i].sqe->user_data,
2131 -EFAULT);
6c271ce2
JA
2132 } else {
2133 sqes[i].has_user = has_user;
2134 sqes[i].needs_lock = true;
2135 sqes[i].needs_fixed_file = true;
9e645e11 2136 io_submit_sqe(ctx, &sqes[i], statep, &link);
6c271ce2 2137 submitted++;
6c271ce2 2138 }
6c271ce2
JA
2139 }
2140
9e645e11
JA
2141 if (link)
2142 io_queue_sqe(ctx, link, &link->submit);
6c271ce2
JA
2143 if (statep)
2144 io_submit_state_end(&state);
2145
2146 return submitted;
2147}
2148
2149static int io_sq_thread(void *data)
2150{
2151 struct sqe_submit sqes[IO_IOPOLL_BATCH];
2152 struct io_ring_ctx *ctx = data;
2153 struct mm_struct *cur_mm = NULL;
2154 mm_segment_t old_fs;
2155 DEFINE_WAIT(wait);
2156 unsigned inflight;
2157 unsigned long timeout;
2158
2159 old_fs = get_fs();
2160 set_fs(USER_DS);
2161
2162 timeout = inflight = 0;
2bbcd6d3 2163 while (!kthread_should_park()) {
6c271ce2
JA
2164 bool all_fixed, mm_fault = false;
2165 int i;
2166
2167 if (inflight) {
2168 unsigned nr_events = 0;
2169
2170 if (ctx->flags & IORING_SETUP_IOPOLL) {
2171 /*
2172 * We disallow the app entering submit/complete
2173 * with polling, but we still need to lock the
2174 * ring to prevent racing with polled issue
2175 * that got punted to a workqueue.
2176 */
2177 mutex_lock(&ctx->uring_lock);
2178 io_iopoll_check(ctx, &nr_events, 0);
2179 mutex_unlock(&ctx->uring_lock);
2180 } else {
2181 /*
2182 * Normal IO, just pretend everything completed.
2183 * We don't have to poll completions for that.
2184 */
2185 nr_events = inflight;
2186 }
2187
2188 inflight -= nr_events;
2189 if (!inflight)
2190 timeout = jiffies + ctx->sq_thread_idle;
2191 }
2192
2193 if (!io_get_sqring(ctx, &sqes[0])) {
2194 /*
2195 * We're polling. If we're within the defined idle
2196 * period, then let us spin without work before going
2197 * to sleep.
2198 */
2199 if (inflight || !time_after(jiffies, timeout)) {
2200 cpu_relax();
2201 continue;
2202 }
2203
2204 /*
2205 * Drop cur_mm before scheduling, we can't hold it for
2206 * long periods (or over schedule()). Do this before
2207 * adding ourselves to the waitqueue, as the unuse/drop
2208 * may sleep.
2209 */
2210 if (cur_mm) {
2211 unuse_mm(cur_mm);
2212 mmput(cur_mm);
2213 cur_mm = NULL;
2214 }
2215
2216 prepare_to_wait(&ctx->sqo_wait, &wait,
2217 TASK_INTERRUPTIBLE);
2218
2219 /* Tell userspace we may need a wakeup call */
2220 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
2221 /* make sure to read SQ tail after writing flags */
2222 smp_mb();
6c271ce2
JA
2223
2224 if (!io_get_sqring(ctx, &sqes[0])) {
2bbcd6d3 2225 if (kthread_should_park()) {
6c271ce2
JA
2226 finish_wait(&ctx->sqo_wait, &wait);
2227 break;
2228 }
2229 if (signal_pending(current))
2230 flush_signals(current);
2231 schedule();
2232 finish_wait(&ctx->sqo_wait, &wait);
2233
2234 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2235 continue;
2236 }
2237 finish_wait(&ctx->sqo_wait, &wait);
2238
2239 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2240 }
2241
2242 i = 0;
2243 all_fixed = true;
2244 do {
2245 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2246 all_fixed = false;
2247
2248 i++;
2249 if (i == ARRAY_SIZE(sqes))
2250 break;
2251 } while (io_get_sqring(ctx, &sqes[i]));
2252
2253 /* Unless all new commands are FIXED regions, grab mm */
2254 if (!all_fixed && !cur_mm) {
2255 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2256 if (!mm_fault) {
2257 use_mm(ctx->sqo_mm);
2258 cur_mm = ctx->sqo_mm;
2259 }
2260 }
2261
2262 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2263 mm_fault);
2264
2265 /* Commit SQ ring head once we've consumed all SQEs */
2266 io_commit_sqring(ctx);
2267 }
2268
2269 set_fs(old_fs);
2270 if (cur_mm) {
2271 unuse_mm(cur_mm);
2272 mmput(cur_mm);
2273 }
06058632 2274
2bbcd6d3 2275 kthread_parkme();
06058632 2276
6c271ce2
JA
2277 return 0;
2278}
2279
2b188cc1
JA
2280static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2281{
9a56a232 2282 struct io_submit_state state, *statep = NULL;
9e645e11
JA
2283 struct io_kiocb *link = NULL;
2284 bool prev_was_link = false;
5c8b0b54 2285 int i, submit = 0;
2b188cc1 2286
9a56a232
JA
2287 if (to_submit > IO_PLUG_THRESHOLD) {
2288 io_submit_state_start(&state, ctx, to_submit);
2289 statep = &state;
2290 }
2b188cc1
JA
2291
2292 for (i = 0; i < to_submit; i++) {
2293 struct sqe_submit s;
2294
2295 if (!io_get_sqring(ctx, &s))
2296 break;
2297
9e645e11
JA
2298 /*
2299 * If previous wasn't linked and we have a linked command,
2300 * that's the end of the chain. Submit the previous link.
2301 */
2302 if (!prev_was_link && link) {
2303 io_queue_sqe(ctx, link, &link->submit);
2304 link = NULL;
2305 }
2306 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2307
2b188cc1 2308 s.has_user = true;
def596e9 2309 s.needs_lock = false;
6c271ce2 2310 s.needs_fixed_file = false;
5c8b0b54 2311 submit++;
9e645e11 2312 io_submit_sqe(ctx, &s, statep, &link);
2b188cc1
JA
2313 }
2314 io_commit_sqring(ctx);
2315
9e645e11
JA
2316 if (link)
2317 io_queue_sqe(ctx, link, &link->submit);
9a56a232
JA
2318 if (statep)
2319 io_submit_state_end(statep);
2b188cc1 2320
5c8b0b54 2321 return submit;
2b188cc1
JA
2322}
2323
2324static unsigned io_cqring_events(struct io_cq_ring *ring)
2325{
dc6ce4bc
JL
2326 /* See comment at the top of this file */
2327 smp_rmb();
2b188cc1
JA
2328 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
2329}
2330
2331/*
2332 * Wait until events become available, if we don't already have some. The
2333 * application must reap them itself, as they reside on the shared cq ring.
2334 */
2335static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2336 const sigset_t __user *sig, size_t sigsz)
2337{
2338 struct io_cq_ring *ring = ctx->cq_ring;
2339 sigset_t ksigmask, sigsaved;
2b188cc1
JA
2340 int ret;
2341
2b188cc1
JA
2342 if (io_cqring_events(ring) >= min_events)
2343 return 0;
2344
2345 if (sig) {
9e75ad5d
AB
2346#ifdef CONFIG_COMPAT
2347 if (in_compat_syscall())
2348 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2349 &ksigmask, &sigsaved, sigsz);
2350 else
2351#endif
2352 ret = set_user_sigmask(sig, &ksigmask,
2353 &sigsaved, sigsz);
2354
2b188cc1
JA
2355 if (ret)
2356 return ret;
2357 }
2358
fdb288a6
JL
2359 ret = wait_event_interruptible(ctx->wait, io_cqring_events(ring) >= min_events);
2360 if (ret == -ERESTARTSYS)
2b188cc1 2361 ret = -EINTR;
2b188cc1
JA
2362
2363 if (sig)
2364 restore_user_sigmask(sig, &sigsaved);
2365
2366 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2367}
2368
6b06314c
JA
2369static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2370{
2371#if defined(CONFIG_UNIX)
2372 if (ctx->ring_sock) {
2373 struct sock *sock = ctx->ring_sock->sk;
2374 struct sk_buff *skb;
2375
2376 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2377 kfree_skb(skb);
2378 }
2379#else
2380 int i;
2381
2382 for (i = 0; i < ctx->nr_user_files; i++)
2383 fput(ctx->user_files[i]);
2384#endif
2385}
2386
2387static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2388{
2389 if (!ctx->user_files)
2390 return -ENXIO;
2391
2392 __io_sqe_files_unregister(ctx);
2393 kfree(ctx->user_files);
2394 ctx->user_files = NULL;
2395 ctx->nr_user_files = 0;
2396 return 0;
2397}
2398
6c271ce2
JA
2399static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2400{
2401 if (ctx->sqo_thread) {
2bbcd6d3
RP
2402 /*
2403 * The park is a bit of a work-around, without it we get
2404 * warning spews on shutdown with SQPOLL set and affinity
2405 * set to a single CPU.
2406 */
06058632 2407 kthread_park(ctx->sqo_thread);
6c271ce2
JA
2408 kthread_stop(ctx->sqo_thread);
2409 ctx->sqo_thread = NULL;
2410 }
2411}
2412
6b06314c
JA
2413static void io_finish_async(struct io_ring_ctx *ctx)
2414{
6c271ce2
JA
2415 io_sq_thread_stop(ctx);
2416
6b06314c
JA
2417 if (ctx->sqo_wq) {
2418 destroy_workqueue(ctx->sqo_wq);
2419 ctx->sqo_wq = NULL;
2420 }
2421}
2422
2423#if defined(CONFIG_UNIX)
2424static void io_destruct_skb(struct sk_buff *skb)
2425{
2426 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2427
2428 io_finish_async(ctx);
2429 unix_destruct_scm(skb);
2430}
2431
2432/*
2433 * Ensure the UNIX gc is aware of our file set, so we are certain that
2434 * the io_uring can be safely unregistered on process exit, even if we have
2435 * loops in the file referencing.
2436 */
2437static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2438{
2439 struct sock *sk = ctx->ring_sock->sk;
2440 struct scm_fp_list *fpl;
2441 struct sk_buff *skb;
2442 int i;
2443
2444 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2445 unsigned long inflight = ctx->user->unix_inflight + nr;
2446
2447 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2448 return -EMFILE;
2449 }
2450
2451 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2452 if (!fpl)
2453 return -ENOMEM;
2454
2455 skb = alloc_skb(0, GFP_KERNEL);
2456 if (!skb) {
2457 kfree(fpl);
2458 return -ENOMEM;
2459 }
2460
2461 skb->sk = sk;
2462 skb->destructor = io_destruct_skb;
2463
2464 fpl->user = get_uid(ctx->user);
2465 for (i = 0; i < nr; i++) {
2466 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2467 unix_inflight(fpl->user, fpl->fp[i]);
2468 }
2469
2470 fpl->max = fpl->count = nr;
2471 UNIXCB(skb).fp = fpl;
2472 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2473 skb_queue_head(&sk->sk_receive_queue, skb);
2474
2475 for (i = 0; i < nr; i++)
2476 fput(fpl->fp[i]);
2477
2478 return 0;
2479}
2480
2481/*
2482 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2483 * causes regular reference counting to break down. We rely on the UNIX
2484 * garbage collection to take care of this problem for us.
2485 */
2486static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2487{
2488 unsigned left, total;
2489 int ret = 0;
2490
2491 total = 0;
2492 left = ctx->nr_user_files;
2493 while (left) {
2494 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
2495
2496 ret = __io_sqe_files_scm(ctx, this_files, total);
2497 if (ret)
2498 break;
2499 left -= this_files;
2500 total += this_files;
2501 }
2502
2503 if (!ret)
2504 return 0;
2505
2506 while (total < ctx->nr_user_files) {
2507 fput(ctx->user_files[total]);
2508 total++;
2509 }
2510
2511 return ret;
2512}
2513#else
2514static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2515{
2516 return 0;
2517}
2518#endif
2519
2520static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2521 unsigned nr_args)
2522{
2523 __s32 __user *fds = (__s32 __user *) arg;
2524 int fd, ret = 0;
2525 unsigned i;
2526
2527 if (ctx->user_files)
2528 return -EBUSY;
2529 if (!nr_args)
2530 return -EINVAL;
2531 if (nr_args > IORING_MAX_FIXED_FILES)
2532 return -EMFILE;
2533
2534 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2535 if (!ctx->user_files)
2536 return -ENOMEM;
2537
2538 for (i = 0; i < nr_args; i++) {
2539 ret = -EFAULT;
2540 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2541 break;
2542
2543 ctx->user_files[i] = fget(fd);
2544
2545 ret = -EBADF;
2546 if (!ctx->user_files[i])
2547 break;
2548 /*
2549 * Don't allow io_uring instances to be registered. If UNIX
2550 * isn't enabled, then this causes a reference cycle and this
2551 * instance can never get freed. If UNIX is enabled we'll
2552 * handle it just fine, but there's still no point in allowing
2553 * a ring fd as it doesn't support regular read/write anyway.
2554 */
2555 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2556 fput(ctx->user_files[i]);
2557 break;
2558 }
2559 ctx->nr_user_files++;
2560 ret = 0;
2561 }
2562
2563 if (ret) {
2564 for (i = 0; i < ctx->nr_user_files; i++)
2565 fput(ctx->user_files[i]);
2566
2567 kfree(ctx->user_files);
25adf50f 2568 ctx->user_files = NULL;
6b06314c
JA
2569 ctx->nr_user_files = 0;
2570 return ret;
2571 }
2572
2573 ret = io_sqe_files_scm(ctx);
2574 if (ret)
2575 io_sqe_files_unregister(ctx);
2576
2577 return ret;
2578}
2579
6c271ce2
JA
2580static int io_sq_offload_start(struct io_ring_ctx *ctx,
2581 struct io_uring_params *p)
2b188cc1
JA
2582{
2583 int ret;
2584
6c271ce2 2585 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
2586 mmgrab(current->mm);
2587 ctx->sqo_mm = current->mm;
2588
6c271ce2 2589 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
2590 ret = -EPERM;
2591 if (!capable(CAP_SYS_ADMIN))
2592 goto err;
2593
917257da
JA
2594 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2595 if (!ctx->sq_thread_idle)
2596 ctx->sq_thread_idle = HZ;
2597
6c271ce2 2598 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 2599 int cpu = p->sq_thread_cpu;
6c271ce2 2600
917257da 2601 ret = -EINVAL;
44a9bd18
JA
2602 if (cpu >= nr_cpu_ids)
2603 goto err;
7889f44d 2604 if (!cpu_online(cpu))
917257da
JA
2605 goto err;
2606
6c271ce2
JA
2607 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2608 ctx, cpu,
2609 "io_uring-sq");
2610 } else {
2611 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2612 "io_uring-sq");
2613 }
2614 if (IS_ERR(ctx->sqo_thread)) {
2615 ret = PTR_ERR(ctx->sqo_thread);
2616 ctx->sqo_thread = NULL;
2617 goto err;
2618 }
2619 wake_up_process(ctx->sqo_thread);
2620 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2621 /* Can't have SQ_AFF without SQPOLL */
2622 ret = -EINVAL;
2623 goto err;
2624 }
2625
2b188cc1
JA
2626 /* Do QD, or 2 * CPUS, whatever is smallest */
2627 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2628 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2629 if (!ctx->sqo_wq) {
2630 ret = -ENOMEM;
2631 goto err;
2632 }
2633
2634 return 0;
2635err:
6c271ce2 2636 io_sq_thread_stop(ctx);
2b188cc1
JA
2637 mmdrop(ctx->sqo_mm);
2638 ctx->sqo_mm = NULL;
2639 return ret;
2640}
2641
2642static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2643{
2644 atomic_long_sub(nr_pages, &user->locked_vm);
2645}
2646
2647static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2648{
2649 unsigned long page_limit, cur_pages, new_pages;
2650
2651 /* Don't allow more pages than we can safely lock */
2652 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2653
2654 do {
2655 cur_pages = atomic_long_read(&user->locked_vm);
2656 new_pages = cur_pages + nr_pages;
2657 if (new_pages > page_limit)
2658 return -ENOMEM;
2659 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2660 new_pages) != cur_pages);
2661
2662 return 0;
2663}
2664
2665static void io_mem_free(void *ptr)
2666{
52e04ef4
MR
2667 struct page *page;
2668
2669 if (!ptr)
2670 return;
2b188cc1 2671
52e04ef4 2672 page = virt_to_head_page(ptr);
2b188cc1
JA
2673 if (put_page_testzero(page))
2674 free_compound_page(page);
2675}
2676
2677static void *io_mem_alloc(size_t size)
2678{
2679 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2680 __GFP_NORETRY;
2681
2682 return (void *) __get_free_pages(gfp_flags, get_order(size));
2683}
2684
2685static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2686{
2687 struct io_sq_ring *sq_ring;
2688 struct io_cq_ring *cq_ring;
2689 size_t bytes;
2690
2691 bytes = struct_size(sq_ring, array, sq_entries);
2692 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2693 bytes += struct_size(cq_ring, cqes, cq_entries);
2694
2695 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2696}
2697
edafccee
JA
2698static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2699{
2700 int i, j;
2701
2702 if (!ctx->user_bufs)
2703 return -ENXIO;
2704
2705 for (i = 0; i < ctx->nr_user_bufs; i++) {
2706 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2707
2708 for (j = 0; j < imu->nr_bvecs; j++)
2709 put_page(imu->bvec[j].bv_page);
2710
2711 if (ctx->account_mem)
2712 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 2713 kvfree(imu->bvec);
edafccee
JA
2714 imu->nr_bvecs = 0;
2715 }
2716
2717 kfree(ctx->user_bufs);
2718 ctx->user_bufs = NULL;
2719 ctx->nr_user_bufs = 0;
2720 return 0;
2721}
2722
2723static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2724 void __user *arg, unsigned index)
2725{
2726 struct iovec __user *src;
2727
2728#ifdef CONFIG_COMPAT
2729 if (ctx->compat) {
2730 struct compat_iovec __user *ciovs;
2731 struct compat_iovec ciov;
2732
2733 ciovs = (struct compat_iovec __user *) arg;
2734 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2735 return -EFAULT;
2736
2737 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2738 dst->iov_len = ciov.iov_len;
2739 return 0;
2740 }
2741#endif
2742 src = (struct iovec __user *) arg;
2743 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2744 return -EFAULT;
2745 return 0;
2746}
2747
2748static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2749 unsigned nr_args)
2750{
2751 struct vm_area_struct **vmas = NULL;
2752 struct page **pages = NULL;
2753 int i, j, got_pages = 0;
2754 int ret = -EINVAL;
2755
2756 if (ctx->user_bufs)
2757 return -EBUSY;
2758 if (!nr_args || nr_args > UIO_MAXIOV)
2759 return -EINVAL;
2760
2761 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2762 GFP_KERNEL);
2763 if (!ctx->user_bufs)
2764 return -ENOMEM;
2765
2766 for (i = 0; i < nr_args; i++) {
2767 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2768 unsigned long off, start, end, ubuf;
2769 int pret, nr_pages;
2770 struct iovec iov;
2771 size_t size;
2772
2773 ret = io_copy_iov(ctx, &iov, arg, i);
2774 if (ret)
a278682d 2775 goto err;
edafccee
JA
2776
2777 /*
2778 * Don't impose further limits on the size and buffer
2779 * constraints here, we'll -EINVAL later when IO is
2780 * submitted if they are wrong.
2781 */
2782 ret = -EFAULT;
2783 if (!iov.iov_base || !iov.iov_len)
2784 goto err;
2785
2786 /* arbitrary limit, but we need something */
2787 if (iov.iov_len > SZ_1G)
2788 goto err;
2789
2790 ubuf = (unsigned long) iov.iov_base;
2791 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2792 start = ubuf >> PAGE_SHIFT;
2793 nr_pages = end - start;
2794
2795 if (ctx->account_mem) {
2796 ret = io_account_mem(ctx->user, nr_pages);
2797 if (ret)
2798 goto err;
2799 }
2800
2801 ret = 0;
2802 if (!pages || nr_pages > got_pages) {
2803 kfree(vmas);
2804 kfree(pages);
d4ef6475 2805 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 2806 GFP_KERNEL);
d4ef6475 2807 vmas = kvmalloc_array(nr_pages,
edafccee
JA
2808 sizeof(struct vm_area_struct *),
2809 GFP_KERNEL);
2810 if (!pages || !vmas) {
2811 ret = -ENOMEM;
2812 if (ctx->account_mem)
2813 io_unaccount_mem(ctx->user, nr_pages);
2814 goto err;
2815 }
2816 got_pages = nr_pages;
2817 }
2818
d4ef6475 2819 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
2820 GFP_KERNEL);
2821 ret = -ENOMEM;
2822 if (!imu->bvec) {
2823 if (ctx->account_mem)
2824 io_unaccount_mem(ctx->user, nr_pages);
2825 goto err;
2826 }
2827
2828 ret = 0;
2829 down_read(&current->mm->mmap_sem);
932f4a63
IW
2830 pret = get_user_pages(ubuf, nr_pages,
2831 FOLL_WRITE | FOLL_LONGTERM,
2832 pages, vmas);
edafccee
JA
2833 if (pret == nr_pages) {
2834 /* don't support file backed memory */
2835 for (j = 0; j < nr_pages; j++) {
2836 struct vm_area_struct *vma = vmas[j];
2837
2838 if (vma->vm_file &&
2839 !is_file_hugepages(vma->vm_file)) {
2840 ret = -EOPNOTSUPP;
2841 break;
2842 }
2843 }
2844 } else {
2845 ret = pret < 0 ? pret : -EFAULT;
2846 }
2847 up_read(&current->mm->mmap_sem);
2848 if (ret) {
2849 /*
2850 * if we did partial map, or found file backed vmas,
2851 * release any pages we did get
2852 */
2853 if (pret > 0) {
2854 for (j = 0; j < pret; j++)
2855 put_page(pages[j]);
2856 }
2857 if (ctx->account_mem)
2858 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 2859 kvfree(imu->bvec);
edafccee
JA
2860 goto err;
2861 }
2862
2863 off = ubuf & ~PAGE_MASK;
2864 size = iov.iov_len;
2865 for (j = 0; j < nr_pages; j++) {
2866 size_t vec_len;
2867
2868 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2869 imu->bvec[j].bv_page = pages[j];
2870 imu->bvec[j].bv_len = vec_len;
2871 imu->bvec[j].bv_offset = off;
2872 off = 0;
2873 size -= vec_len;
2874 }
2875 /* store original address for later verification */
2876 imu->ubuf = ubuf;
2877 imu->len = iov.iov_len;
2878 imu->nr_bvecs = nr_pages;
2879
2880 ctx->nr_user_bufs++;
2881 }
d4ef6475
MR
2882 kvfree(pages);
2883 kvfree(vmas);
edafccee
JA
2884 return 0;
2885err:
d4ef6475
MR
2886 kvfree(pages);
2887 kvfree(vmas);
edafccee
JA
2888 io_sqe_buffer_unregister(ctx);
2889 return ret;
2890}
2891
9b402849
JA
2892static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
2893{
2894 __s32 __user *fds = arg;
2895 int fd;
2896
2897 if (ctx->cq_ev_fd)
2898 return -EBUSY;
2899
2900 if (copy_from_user(&fd, fds, sizeof(*fds)))
2901 return -EFAULT;
2902
2903 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
2904 if (IS_ERR(ctx->cq_ev_fd)) {
2905 int ret = PTR_ERR(ctx->cq_ev_fd);
2906 ctx->cq_ev_fd = NULL;
2907 return ret;
2908 }
2909
2910 return 0;
2911}
2912
2913static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2914{
2915 if (ctx->cq_ev_fd) {
2916 eventfd_ctx_put(ctx->cq_ev_fd);
2917 ctx->cq_ev_fd = NULL;
2918 return 0;
2919 }
2920
2921 return -ENXIO;
2922}
2923
2b188cc1
JA
2924static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2925{
6b06314c 2926 io_finish_async(ctx);
2b188cc1
JA
2927 if (ctx->sqo_mm)
2928 mmdrop(ctx->sqo_mm);
def596e9
JA
2929
2930 io_iopoll_reap_events(ctx);
edafccee 2931 io_sqe_buffer_unregister(ctx);
6b06314c 2932 io_sqe_files_unregister(ctx);
9b402849 2933 io_eventfd_unregister(ctx);
def596e9 2934
2b188cc1
JA
2935#if defined(CONFIG_UNIX)
2936 if (ctx->ring_sock)
2937 sock_release(ctx->ring_sock);
2938#endif
2939
2940 io_mem_free(ctx->sq_ring);
2941 io_mem_free(ctx->sq_sqes);
2942 io_mem_free(ctx->cq_ring);
2943
2944 percpu_ref_exit(&ctx->refs);
2945 if (ctx->account_mem)
2946 io_unaccount_mem(ctx->user,
2947 ring_pages(ctx->sq_entries, ctx->cq_entries));
2948 free_uid(ctx->user);
2949 kfree(ctx);
2950}
2951
2952static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2953{
2954 struct io_ring_ctx *ctx = file->private_data;
2955 __poll_t mask = 0;
2956
2957 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
2958 /*
2959 * synchronizes with barrier from wq_has_sleeper call in
2960 * io_commit_cqring
2961 */
2b188cc1 2962 smp_rmb();
fb775faa
SB
2963 if (READ_ONCE(ctx->sq_ring->r.tail) - ctx->cached_sq_head !=
2964 ctx->sq_ring->ring_entries)
2b188cc1
JA
2965 mask |= EPOLLOUT | EPOLLWRNORM;
2966 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2967 mask |= EPOLLIN | EPOLLRDNORM;
2968
2969 return mask;
2970}
2971
2972static int io_uring_fasync(int fd, struct file *file, int on)
2973{
2974 struct io_ring_ctx *ctx = file->private_data;
2975
2976 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2977}
2978
2979static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2980{
2981 mutex_lock(&ctx->uring_lock);
2982 percpu_ref_kill(&ctx->refs);
2983 mutex_unlock(&ctx->uring_lock);
2984
221c5eb2 2985 io_poll_remove_all(ctx);
def596e9 2986 io_iopoll_reap_events(ctx);
2b188cc1
JA
2987 wait_for_completion(&ctx->ctx_done);
2988 io_ring_ctx_free(ctx);
2989}
2990
2991static int io_uring_release(struct inode *inode, struct file *file)
2992{
2993 struct io_ring_ctx *ctx = file->private_data;
2994
2995 file->private_data = NULL;
2996 io_ring_ctx_wait_and_kill(ctx);
2997 return 0;
2998}
2999
3000static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3001{
3002 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3003 unsigned long sz = vma->vm_end - vma->vm_start;
3004 struct io_ring_ctx *ctx = file->private_data;
3005 unsigned long pfn;
3006 struct page *page;
3007 void *ptr;
3008
3009 switch (offset) {
3010 case IORING_OFF_SQ_RING:
3011 ptr = ctx->sq_ring;
3012 break;
3013 case IORING_OFF_SQES:
3014 ptr = ctx->sq_sqes;
3015 break;
3016 case IORING_OFF_CQ_RING:
3017 ptr = ctx->cq_ring;
3018 break;
3019 default:
3020 return -EINVAL;
3021 }
3022
3023 page = virt_to_head_page(ptr);
3024 if (sz > (PAGE_SIZE << compound_order(page)))
3025 return -EINVAL;
3026
3027 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3028 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3029}
3030
3031SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3032 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3033 size_t, sigsz)
3034{
3035 struct io_ring_ctx *ctx;
3036 long ret = -EBADF;
3037 int submitted = 0;
3038 struct fd f;
3039
6c271ce2 3040 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
3041 return -EINVAL;
3042
3043 f = fdget(fd);
3044 if (!f.file)
3045 return -EBADF;
3046
3047 ret = -EOPNOTSUPP;
3048 if (f.file->f_op != &io_uring_fops)
3049 goto out_fput;
3050
3051 ret = -ENXIO;
3052 ctx = f.file->private_data;
3053 if (!percpu_ref_tryget(&ctx->refs))
3054 goto out_fput;
3055
6c271ce2
JA
3056 /*
3057 * For SQ polling, the thread will do all submissions and completions.
3058 * Just return the requested submit count, and wake the thread if
3059 * we were asked to.
3060 */
3061 if (ctx->flags & IORING_SETUP_SQPOLL) {
3062 if (flags & IORING_ENTER_SQ_WAKEUP)
3063 wake_up(&ctx->sqo_wait);
3064 submitted = to_submit;
3065 goto out_ctx;
3066 }
3067
2b188cc1
JA
3068 ret = 0;
3069 if (to_submit) {
3070 to_submit = min(to_submit, ctx->sq_entries);
3071
3072 mutex_lock(&ctx->uring_lock);
3073 submitted = io_ring_submit(ctx, to_submit);
3074 mutex_unlock(&ctx->uring_lock);
2b188cc1
JA
3075 }
3076 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
3077 unsigned nr_events = 0;
3078
2b188cc1
JA
3079 min_complete = min(min_complete, ctx->cq_entries);
3080
def596e9
JA
3081 if (ctx->flags & IORING_SETUP_IOPOLL) {
3082 mutex_lock(&ctx->uring_lock);
3083 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3084 mutex_unlock(&ctx->uring_lock);
3085 } else {
3086 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3087 }
2b188cc1
JA
3088 }
3089
3090out_ctx:
3091 io_ring_drop_ctx_refs(ctx, 1);
3092out_fput:
3093 fdput(f);
3094 return submitted ? submitted : ret;
3095}
3096
3097static const struct file_operations io_uring_fops = {
3098 .release = io_uring_release,
3099 .mmap = io_uring_mmap,
3100 .poll = io_uring_poll,
3101 .fasync = io_uring_fasync,
3102};
3103
3104static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3105 struct io_uring_params *p)
3106{
3107 struct io_sq_ring *sq_ring;
3108 struct io_cq_ring *cq_ring;
3109 size_t size;
3110
3111 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
3112 if (!sq_ring)
3113 return -ENOMEM;
3114
3115 ctx->sq_ring = sq_ring;
3116 sq_ring->ring_mask = p->sq_entries - 1;
3117 sq_ring->ring_entries = p->sq_entries;
3118 ctx->sq_mask = sq_ring->ring_mask;
3119 ctx->sq_entries = sq_ring->ring_entries;
3120
3121 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3122 if (size == SIZE_MAX)
3123 return -EOVERFLOW;
3124
3125 ctx->sq_sqes = io_mem_alloc(size);
52e04ef4 3126 if (!ctx->sq_sqes)
2b188cc1 3127 return -ENOMEM;
2b188cc1
JA
3128
3129 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
52e04ef4 3130 if (!cq_ring)
2b188cc1 3131 return -ENOMEM;
2b188cc1
JA
3132
3133 ctx->cq_ring = cq_ring;
3134 cq_ring->ring_mask = p->cq_entries - 1;
3135 cq_ring->ring_entries = p->cq_entries;
3136 ctx->cq_mask = cq_ring->ring_mask;
3137 ctx->cq_entries = cq_ring->ring_entries;
3138 return 0;
3139}
3140
3141/*
3142 * Allocate an anonymous fd, this is what constitutes the application
3143 * visible backing of an io_uring instance. The application mmaps this
3144 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
3145 * we have to tie this fd to a socket for file garbage collection purposes.
3146 */
3147static int io_uring_get_fd(struct io_ring_ctx *ctx)
3148{
3149 struct file *file;
3150 int ret;
3151
3152#if defined(CONFIG_UNIX)
3153 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
3154 &ctx->ring_sock);
3155 if (ret)
3156 return ret;
3157#endif
3158
3159 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3160 if (ret < 0)
3161 goto err;
3162
3163 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3164 O_RDWR | O_CLOEXEC);
3165 if (IS_ERR(file)) {
3166 put_unused_fd(ret);
3167 ret = PTR_ERR(file);
3168 goto err;
3169 }
3170
3171#if defined(CONFIG_UNIX)
3172 ctx->ring_sock->file = file;
6b06314c 3173 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
3174#endif
3175 fd_install(ret, file);
3176 return ret;
3177err:
3178#if defined(CONFIG_UNIX)
3179 sock_release(ctx->ring_sock);
3180 ctx->ring_sock = NULL;
3181#endif
3182 return ret;
3183}
3184
3185static int io_uring_create(unsigned entries, struct io_uring_params *p)
3186{
3187 struct user_struct *user = NULL;
3188 struct io_ring_ctx *ctx;
3189 bool account_mem;
3190 int ret;
3191
3192 if (!entries || entries > IORING_MAX_ENTRIES)
3193 return -EINVAL;
3194
3195 /*
3196 * Use twice as many entries for the CQ ring. It's possible for the
3197 * application to drive a higher depth than the size of the SQ ring,
3198 * since the sqes are only used at submission time. This allows for
3199 * some flexibility in overcommitting a bit.
3200 */
3201 p->sq_entries = roundup_pow_of_two(entries);
3202 p->cq_entries = 2 * p->sq_entries;
3203
3204 user = get_uid(current_user());
3205 account_mem = !capable(CAP_IPC_LOCK);
3206
3207 if (account_mem) {
3208 ret = io_account_mem(user,
3209 ring_pages(p->sq_entries, p->cq_entries));
3210 if (ret) {
3211 free_uid(user);
3212 return ret;
3213 }
3214 }
3215
3216 ctx = io_ring_ctx_alloc(p);
3217 if (!ctx) {
3218 if (account_mem)
3219 io_unaccount_mem(user, ring_pages(p->sq_entries,
3220 p->cq_entries));
3221 free_uid(user);
3222 return -ENOMEM;
3223 }
3224 ctx->compat = in_compat_syscall();
3225 ctx->account_mem = account_mem;
3226 ctx->user = user;
3227
3228 ret = io_allocate_scq_urings(ctx, p);
3229 if (ret)
3230 goto err;
3231
6c271ce2 3232 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
3233 if (ret)
3234 goto err;
3235
3236 ret = io_uring_get_fd(ctx);
3237 if (ret < 0)
3238 goto err;
3239
3240 memset(&p->sq_off, 0, sizeof(p->sq_off));
3241 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
3242 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
3243 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
3244 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
3245 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
3246 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
3247 p->sq_off.array = offsetof(struct io_sq_ring, array);
3248
3249 memset(&p->cq_off, 0, sizeof(p->cq_off));
3250 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
3251 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
3252 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
3253 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
3254 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
3255 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
3256 return ret;
3257err:
3258 io_ring_ctx_wait_and_kill(ctx);
3259 return ret;
3260}
3261
3262/*
3263 * Sets up an aio uring context, and returns the fd. Applications asks for a
3264 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3265 * params structure passed in.
3266 */
3267static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3268{
3269 struct io_uring_params p;
3270 long ret;
3271 int i;
3272
3273 if (copy_from_user(&p, params, sizeof(p)))
3274 return -EFAULT;
3275 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3276 if (p.resv[i])
3277 return -EINVAL;
3278 }
3279
6c271ce2
JA
3280 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3281 IORING_SETUP_SQ_AFF))
2b188cc1
JA
3282 return -EINVAL;
3283
3284 ret = io_uring_create(entries, &p);
3285 if (ret < 0)
3286 return ret;
3287
3288 if (copy_to_user(params, &p, sizeof(p)))
3289 return -EFAULT;
3290
3291 return ret;
3292}
3293
3294SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3295 struct io_uring_params __user *, params)
3296{
3297 return io_uring_setup(entries, params);
3298}
3299
edafccee
JA
3300static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3301 void __user *arg, unsigned nr_args)
b19062a5
JA
3302 __releases(ctx->uring_lock)
3303 __acquires(ctx->uring_lock)
edafccee
JA
3304{
3305 int ret;
3306
35fa71a0
JA
3307 /*
3308 * We're inside the ring mutex, if the ref is already dying, then
3309 * someone else killed the ctx or is already going through
3310 * io_uring_register().
3311 */
3312 if (percpu_ref_is_dying(&ctx->refs))
3313 return -ENXIO;
3314
edafccee 3315 percpu_ref_kill(&ctx->refs);
b19062a5
JA
3316
3317 /*
3318 * Drop uring mutex before waiting for references to exit. If another
3319 * thread is currently inside io_uring_enter() it might need to grab
3320 * the uring_lock to make progress. If we hold it here across the drain
3321 * wait, then we can deadlock. It's safe to drop the mutex here, since
3322 * no new references will come in after we've killed the percpu ref.
3323 */
3324 mutex_unlock(&ctx->uring_lock);
edafccee 3325 wait_for_completion(&ctx->ctx_done);
b19062a5 3326 mutex_lock(&ctx->uring_lock);
edafccee
JA
3327
3328 switch (opcode) {
3329 case IORING_REGISTER_BUFFERS:
3330 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3331 break;
3332 case IORING_UNREGISTER_BUFFERS:
3333 ret = -EINVAL;
3334 if (arg || nr_args)
3335 break;
3336 ret = io_sqe_buffer_unregister(ctx);
3337 break;
6b06314c
JA
3338 case IORING_REGISTER_FILES:
3339 ret = io_sqe_files_register(ctx, arg, nr_args);
3340 break;
3341 case IORING_UNREGISTER_FILES:
3342 ret = -EINVAL;
3343 if (arg || nr_args)
3344 break;
3345 ret = io_sqe_files_unregister(ctx);
3346 break;
9b402849
JA
3347 case IORING_REGISTER_EVENTFD:
3348 ret = -EINVAL;
3349 if (nr_args != 1)
3350 break;
3351 ret = io_eventfd_register(ctx, arg);
3352 break;
3353 case IORING_UNREGISTER_EVENTFD:
3354 ret = -EINVAL;
3355 if (arg || nr_args)
3356 break;
3357 ret = io_eventfd_unregister(ctx);
3358 break;
edafccee
JA
3359 default:
3360 ret = -EINVAL;
3361 break;
3362 }
3363
3364 /* bring the ctx back to life */
3365 reinit_completion(&ctx->ctx_done);
3366 percpu_ref_reinit(&ctx->refs);
3367 return ret;
3368}
3369
3370SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3371 void __user *, arg, unsigned int, nr_args)
3372{
3373 struct io_ring_ctx *ctx;
3374 long ret = -EBADF;
3375 struct fd f;
3376
3377 f = fdget(fd);
3378 if (!f.file)
3379 return -EBADF;
3380
3381 ret = -EOPNOTSUPP;
3382 if (f.file->f_op != &io_uring_fops)
3383 goto out_fput;
3384
3385 ctx = f.file->private_data;
3386
3387 mutex_lock(&ctx->uring_lock);
3388 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3389 mutex_unlock(&ctx->uring_lock);
3390out_fput:
3391 fdput(f);
3392 return ret;
3393}
3394
2b188cc1
JA
3395static int __init io_uring_init(void)
3396{
3397 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3398 return 0;
3399};
3400__initcall(io_uring_init);