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