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