io_uring: support for generic async request cancel
[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>
6c271ce2 59#include <linux/kthread.h>
2b188cc1 60#include <linux/blkdev.h>
edafccee 61#include <linux/bvec.h>
2b188cc1
JA
62#include <linux/net.h>
63#include <net/sock.h>
64#include <net/af_unix.h>
6b06314c 65#include <net/scm.h>
2b188cc1
JA
66#include <linux/anon_inodes.h>
67#include <linux/sched/mm.h>
68#include <linux/uaccess.h>
69#include <linux/nospec.h>
edafccee
JA
70#include <linux/sizes.h>
71#include <linux/hugetlb.h>
2b188cc1 72
c826bd7a
DD
73#define CREATE_TRACE_POINTS
74#include <trace/events/io_uring.h>
75
2b188cc1
JA
76#include <uapi/linux/io_uring.h>
77
78#include "internal.h"
561fb04a 79#include "io-wq.h"
2b188cc1 80
5277deaa 81#define IORING_MAX_ENTRIES 32768
33a107f0 82#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
65e19f54
JA
83
84/*
85 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
86 */
87#define IORING_FILE_TABLE_SHIFT 9
88#define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
89#define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
90#define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
2b188cc1
JA
91
92struct io_uring {
93 u32 head ____cacheline_aligned_in_smp;
94 u32 tail ____cacheline_aligned_in_smp;
95};
96
1e84b97b 97/*
75b28aff
HV
98 * This data is shared with the application through the mmap at offsets
99 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
1e84b97b
SB
100 *
101 * The offsets to the member fields are published through struct
102 * io_sqring_offsets when calling io_uring_setup.
103 */
75b28aff 104struct io_rings {
1e84b97b
SB
105 /*
106 * Head and tail offsets into the ring; the offsets need to be
107 * masked to get valid indices.
108 *
75b28aff
HV
109 * The kernel controls head of the sq ring and the tail of the cq ring,
110 * and the application controls tail of the sq ring and the head of the
111 * cq ring.
1e84b97b 112 */
75b28aff 113 struct io_uring sq, cq;
1e84b97b 114 /*
75b28aff 115 * Bitmasks to apply to head and tail offsets (constant, equals
1e84b97b
SB
116 * ring_entries - 1)
117 */
75b28aff
HV
118 u32 sq_ring_mask, cq_ring_mask;
119 /* Ring sizes (constant, power of 2) */
120 u32 sq_ring_entries, cq_ring_entries;
1e84b97b
SB
121 /*
122 * Number of invalid entries dropped by the kernel due to
123 * invalid index stored in array
124 *
125 * Written by the kernel, shouldn't be modified by the
126 * application (i.e. get number of "new events" by comparing to
127 * cached value).
128 *
129 * After a new SQ head value was read by the application this
130 * counter includes all submissions that were dropped reaching
131 * the new SQ head (and possibly more).
132 */
75b28aff 133 u32 sq_dropped;
1e84b97b
SB
134 /*
135 * Runtime flags
136 *
137 * Written by the kernel, shouldn't be modified by the
138 * application.
139 *
140 * The application needs a full memory barrier before checking
141 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
142 */
75b28aff 143 u32 sq_flags;
1e84b97b
SB
144 /*
145 * Number of completion events lost because the queue was full;
146 * this should be avoided by the application by making sure
147 * there are not more requests pending thatn there is space in
148 * the completion queue.
149 *
150 * Written by the kernel, shouldn't be modified by the
151 * application (i.e. get number of "new events" by comparing to
152 * cached value).
153 *
154 * As completion events come in out of order this counter is not
155 * ordered with any other data.
156 */
75b28aff 157 u32 cq_overflow;
1e84b97b
SB
158 /*
159 * Ring buffer of completion events.
160 *
161 * The kernel writes completion events fresh every time they are
162 * produced, so the application is allowed to modify pending
163 * entries.
164 */
75b28aff 165 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
2b188cc1
JA
166};
167
edafccee
JA
168struct io_mapped_ubuf {
169 u64 ubuf;
170 size_t len;
171 struct bio_vec *bvec;
172 unsigned int nr_bvecs;
173};
174
65e19f54
JA
175struct fixed_file_table {
176 struct file **files;
177};
178
2b188cc1
JA
179struct io_ring_ctx {
180 struct {
181 struct percpu_ref refs;
182 } ____cacheline_aligned_in_smp;
183
184 struct {
185 unsigned int flags;
186 bool compat;
187 bool account_mem;
188
75b28aff
HV
189 /*
190 * Ring buffer of indices into array of io_uring_sqe, which is
191 * mmapped by the application using the IORING_OFF_SQES offset.
192 *
193 * This indirection could e.g. be used to assign fixed
194 * io_uring_sqe entries to operations and only submit them to
195 * the queue when needed.
196 *
197 * The kernel modifies neither the indices array nor the entries
198 * array.
199 */
200 u32 *sq_array;
2b188cc1
JA
201 unsigned cached_sq_head;
202 unsigned sq_entries;
203 unsigned sq_mask;
6c271ce2 204 unsigned sq_thread_idle;
498ccd9e 205 unsigned cached_sq_dropped;
2b188cc1 206 struct io_uring_sqe *sq_sqes;
de0617e4
JA
207
208 struct list_head defer_list;
5262f567 209 struct list_head timeout_list;
fcb323cc
JA
210
211 wait_queue_head_t inflight_wait;
2b188cc1
JA
212 } ____cacheline_aligned_in_smp;
213
214 /* IO offload */
561fb04a 215 struct io_wq *io_wq;
6c271ce2 216 struct task_struct *sqo_thread; /* if using sq thread polling */
2b188cc1 217 struct mm_struct *sqo_mm;
6c271ce2 218 wait_queue_head_t sqo_wait;
a4c0b3de 219 struct completion sqo_thread_started;
2b188cc1
JA
220
221 struct {
2b188cc1 222 unsigned cached_cq_tail;
498ccd9e 223 atomic_t cached_cq_overflow;
2b188cc1
JA
224 unsigned cq_entries;
225 unsigned cq_mask;
226 struct wait_queue_head cq_wait;
227 struct fasync_struct *cq_fasync;
9b402849 228 struct eventfd_ctx *cq_ev_fd;
5262f567 229 atomic_t cq_timeouts;
2b188cc1
JA
230 } ____cacheline_aligned_in_smp;
231
75b28aff
HV
232 struct io_rings *rings;
233
6b06314c
JA
234 /*
235 * If used, fixed file set. Writers must ensure that ->refs is dead,
236 * readers must ensure that ->refs is alive as long as the file* is
237 * used. Only updated through io_uring_register(2).
238 */
65e19f54 239 struct fixed_file_table *file_table;
6b06314c
JA
240 unsigned nr_user_files;
241
edafccee
JA
242 /* if used, fixed mapped user buffers */
243 unsigned nr_user_bufs;
244 struct io_mapped_ubuf *user_bufs;
245
2b188cc1
JA
246 struct user_struct *user;
247
248 struct completion ctx_done;
249
250 struct {
251 struct mutex uring_lock;
252 wait_queue_head_t wait;
253 } ____cacheline_aligned_in_smp;
254
255 struct {
256 spinlock_t completion_lock;
def596e9
JA
257 bool poll_multi_file;
258 /*
259 * ->poll_list is protected by the ctx->uring_lock for
260 * io_uring instances that don't use IORING_SETUP_SQPOLL.
261 * For SQPOLL, only the single threaded io_sq_thread() will
262 * manipulate the list, hence no extra locking is needed there.
263 */
264 struct list_head poll_list;
221c5eb2 265 struct list_head cancel_list;
fcb323cc
JA
266
267 spinlock_t inflight_lock;
268 struct list_head inflight_list;
2b188cc1
JA
269 } ____cacheline_aligned_in_smp;
270
271#if defined(CONFIG_UNIX)
272 struct socket *ring_sock;
273#endif
274};
275
276struct sqe_submit {
277 const struct io_uring_sqe *sqe;
fcb323cc
JA
278 struct file *ring_file;
279 int ring_fd;
8776f3fa 280 u32 sequence;
2b188cc1 281 bool has_user;
ba5290cc 282 bool in_async;
6c271ce2 283 bool needs_fixed_file;
2b188cc1
JA
284};
285
09bb8394
JA
286/*
287 * First field must be the file pointer in all the
288 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
289 */
221c5eb2
JA
290struct io_poll_iocb {
291 struct file *file;
292 struct wait_queue_head *head;
293 __poll_t events;
8c838788 294 bool done;
221c5eb2
JA
295 bool canceled;
296 struct wait_queue_entry wait;
297};
298
5262f567
JA
299struct io_timeout {
300 struct file *file;
301 struct hrtimer timer;
302};
303
09bb8394
JA
304/*
305 * NOTE! Each of the iocb union members has the file pointer
306 * as the first entry in their struct definition. So you can
307 * access the file pointer through any of the sub-structs,
308 * or directly as just 'ki_filp' in this struct.
309 */
2b188cc1 310struct io_kiocb {
221c5eb2 311 union {
09bb8394 312 struct file *file;
221c5eb2
JA
313 struct kiocb rw;
314 struct io_poll_iocb poll;
5262f567 315 struct io_timeout timeout;
221c5eb2 316 };
2b188cc1
JA
317
318 struct sqe_submit submit;
319
320 struct io_ring_ctx *ctx;
321 struct list_head list;
9e645e11 322 struct list_head link_list;
2b188cc1 323 unsigned int flags;
c16361c1 324 refcount_t refs;
8449eeda 325#define REQ_F_NOWAIT 1 /* must not punt to workers */
def596e9 326#define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
6b06314c 327#define REQ_F_FIXED_FILE 4 /* ctx owns file */
31b51510 328#define REQ_F_SEQ_PREV 8 /* sequential with previous */
e2033e33
SB
329#define REQ_F_IO_DRAIN 16 /* drain existing IO first */
330#define REQ_F_IO_DRAINED 32 /* drain done */
9e645e11 331#define REQ_F_LINK 64 /* linked sqes */
f7b76ac9
ZL
332#define REQ_F_LINK_DONE 128 /* linked sqes done */
333#define REQ_F_FAIL_LINK 256 /* fail rest of links */
4fe2c963 334#define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
5262f567 335#define REQ_F_TIMEOUT 1024 /* timeout request */
491381ce
JA
336#define REQ_F_ISREG 2048 /* regular file */
337#define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
fcb323cc 338#define REQ_F_INFLIGHT 8192 /* on inflight list */
2b188cc1 339 u64 user_data;
9e645e11 340 u32 result;
de0617e4 341 u32 sequence;
2b188cc1 342
fcb323cc
JA
343 struct list_head inflight_entry;
344
561fb04a 345 struct io_wq_work work;
2b188cc1
JA
346};
347
348#define IO_PLUG_THRESHOLD 2
def596e9 349#define IO_IOPOLL_BATCH 8
2b188cc1 350
9a56a232
JA
351struct io_submit_state {
352 struct blk_plug plug;
353
2579f913
JA
354 /*
355 * io_kiocb alloc cache
356 */
357 void *reqs[IO_IOPOLL_BATCH];
358 unsigned int free_reqs;
359 unsigned int cur_req;
360
9a56a232
JA
361 /*
362 * File reference cache
363 */
364 struct file *file;
365 unsigned int fd;
366 unsigned int has_refs;
367 unsigned int used_refs;
368 unsigned int ios_left;
369};
370
561fb04a 371static void io_wq_submit_work(struct io_wq_work **workptr);
5262f567
JA
372static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
373 long res);
4fe2c963 374static void __io_free_req(struct io_kiocb *req);
de0617e4 375
2b188cc1
JA
376static struct kmem_cache *req_cachep;
377
378static const struct file_operations io_uring_fops;
379
380struct sock *io_uring_get_socket(struct file *file)
381{
382#if defined(CONFIG_UNIX)
383 if (file->f_op == &io_uring_fops) {
384 struct io_ring_ctx *ctx = file->private_data;
385
386 return ctx->ring_sock->sk;
387 }
388#endif
389 return NULL;
390}
391EXPORT_SYMBOL(io_uring_get_socket);
392
393static void io_ring_ctx_ref_free(struct percpu_ref *ref)
394{
395 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
396
397 complete(&ctx->ctx_done);
398}
399
400static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
401{
402 struct io_ring_ctx *ctx;
403
404 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
405 if (!ctx)
406 return NULL;
407
21482896
RG
408 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
409 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
2b188cc1
JA
410 kfree(ctx);
411 return NULL;
412 }
413
414 ctx->flags = p->flags;
415 init_waitqueue_head(&ctx->cq_wait);
416 init_completion(&ctx->ctx_done);
a4c0b3de 417 init_completion(&ctx->sqo_thread_started);
2b188cc1
JA
418 mutex_init(&ctx->uring_lock);
419 init_waitqueue_head(&ctx->wait);
420 spin_lock_init(&ctx->completion_lock);
def596e9 421 INIT_LIST_HEAD(&ctx->poll_list);
221c5eb2 422 INIT_LIST_HEAD(&ctx->cancel_list);
de0617e4 423 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 424 INIT_LIST_HEAD(&ctx->timeout_list);
fcb323cc
JA
425 init_waitqueue_head(&ctx->inflight_wait);
426 spin_lock_init(&ctx->inflight_lock);
427 INIT_LIST_HEAD(&ctx->inflight_list);
2b188cc1
JA
428 return ctx;
429}
430
7adf4eaf
JA
431static inline bool __io_sequence_defer(struct io_ring_ctx *ctx,
432 struct io_kiocb *req)
433{
498ccd9e
JA
434 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
435 + atomic_read(&ctx->cached_cq_overflow);
7adf4eaf
JA
436}
437
de0617e4
JA
438static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
439 struct io_kiocb *req)
440{
7adf4eaf 441 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
de0617e4
JA
442 return false;
443
7adf4eaf 444 return __io_sequence_defer(ctx, req);
de0617e4
JA
445}
446
7adf4eaf 447static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
de0617e4
JA
448{
449 struct io_kiocb *req;
450
7adf4eaf
JA
451 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
452 if (req && !io_sequence_defer(ctx, req)) {
de0617e4
JA
453 list_del_init(&req->list);
454 return req;
455 }
456
457 return NULL;
458}
459
5262f567
JA
460static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
461{
7adf4eaf
JA
462 struct io_kiocb *req;
463
464 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
465 if (req && !__io_sequence_defer(ctx, req)) {
466 list_del_init(&req->list);
467 return req;
468 }
469
470 return NULL;
5262f567
JA
471}
472
de0617e4 473static void __io_commit_cqring(struct io_ring_ctx *ctx)
2b188cc1 474{
75b28aff 475 struct io_rings *rings = ctx->rings;
2b188cc1 476
75b28aff 477 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
2b188cc1 478 /* order cqe stores with ring update */
75b28aff 479 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
2b188cc1 480
2b188cc1
JA
481 if (wq_has_sleeper(&ctx->cq_wait)) {
482 wake_up_interruptible(&ctx->cq_wait);
483 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
484 }
485 }
486}
487
561fb04a 488static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
18d9be1a 489{
561fb04a
JA
490 u8 opcode = READ_ONCE(sqe->opcode);
491
492 return !(opcode == IORING_OP_READ_FIXED ||
493 opcode == IORING_OP_WRITE_FIXED);
494}
495
496static inline bool io_prep_async_work(struct io_kiocb *req)
497{
498 bool do_hashed = false;
54a91f3b 499
6cc47d1d
JA
500 if (req->submit.sqe) {
501 switch (req->submit.sqe->opcode) {
502 case IORING_OP_WRITEV:
503 case IORING_OP_WRITE_FIXED:
561fb04a 504 do_hashed = true;
6cc47d1d
JA
505 break;
506 }
561fb04a
JA
507 if (io_sqe_needs_user(req->submit.sqe))
508 req->work.flags |= IO_WQ_WORK_NEEDS_USER;
54a91f3b
JA
509 }
510
561fb04a
JA
511 return do_hashed;
512}
513
514static inline void io_queue_async_work(struct io_ring_ctx *ctx,
515 struct io_kiocb *req)
516{
517 bool do_hashed = io_prep_async_work(req);
518
519 trace_io_uring_queue_async_work(ctx, do_hashed, req, &req->work,
520 req->flags);
521 if (!do_hashed) {
522 io_wq_enqueue(ctx->io_wq, &req->work);
523 } else {
524 io_wq_enqueue_hashed(ctx->io_wq, &req->work,
525 file_inode(req->file));
526 }
18d9be1a
JA
527}
528
5262f567
JA
529static void io_kill_timeout(struct io_kiocb *req)
530{
531 int ret;
532
533 ret = hrtimer_try_to_cancel(&req->timeout.timer);
534 if (ret != -1) {
535 atomic_inc(&req->ctx->cq_timeouts);
842f9612 536 list_del_init(&req->list);
5262f567
JA
537 io_cqring_fill_event(req->ctx, req->user_data, 0);
538 __io_free_req(req);
539 }
540}
541
542static void io_kill_timeouts(struct io_ring_ctx *ctx)
543{
544 struct io_kiocb *req, *tmp;
545
546 spin_lock_irq(&ctx->completion_lock);
547 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
548 io_kill_timeout(req);
549 spin_unlock_irq(&ctx->completion_lock);
550}
551
de0617e4
JA
552static void io_commit_cqring(struct io_ring_ctx *ctx)
553{
554 struct io_kiocb *req;
555
5262f567
JA
556 while ((req = io_get_timeout_req(ctx)) != NULL)
557 io_kill_timeout(req);
558
de0617e4
JA
559 __io_commit_cqring(ctx);
560
561 while ((req = io_get_deferred_req(ctx)) != NULL) {
4fe2c963
JL
562 if (req->flags & REQ_F_SHADOW_DRAIN) {
563 /* Just for drain, free it. */
564 __io_free_req(req);
565 continue;
566 }
de0617e4 567 req->flags |= REQ_F_IO_DRAINED;
18d9be1a 568 io_queue_async_work(ctx, req);
de0617e4
JA
569 }
570}
571
2b188cc1
JA
572static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
573{
75b28aff 574 struct io_rings *rings = ctx->rings;
2b188cc1
JA
575 unsigned tail;
576
577 tail = ctx->cached_cq_tail;
115e12e5
SB
578 /*
579 * writes to the cq entry need to come after reading head; the
580 * control dependency is enough as we're using WRITE_ONCE to
581 * fill the cq entry
582 */
75b28aff 583 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
2b188cc1
JA
584 return NULL;
585
586 ctx->cached_cq_tail++;
75b28aff 587 return &rings->cqes[tail & ctx->cq_mask];
2b188cc1
JA
588}
589
590static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
c71ffb67 591 long res)
2b188cc1
JA
592{
593 struct io_uring_cqe *cqe;
594
595 /*
596 * If we can't get a cq entry, userspace overflowed the
597 * submission (by quite a lot). Increment the overflow count in
598 * the ring.
599 */
600 cqe = io_get_cqring(ctx);
601 if (cqe) {
602 WRITE_ONCE(cqe->user_data, ki_user_data);
603 WRITE_ONCE(cqe->res, res);
c71ffb67 604 WRITE_ONCE(cqe->flags, 0);
2b188cc1 605 } else {
498ccd9e
JA
606 WRITE_ONCE(ctx->rings->cq_overflow,
607 atomic_inc_return(&ctx->cached_cq_overflow));
2b188cc1
JA
608 }
609}
610
8c838788
JA
611static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
612{
613 if (waitqueue_active(&ctx->wait))
614 wake_up(&ctx->wait);
615 if (waitqueue_active(&ctx->sqo_wait))
616 wake_up(&ctx->sqo_wait);
9b402849
JA
617 if (ctx->cq_ev_fd)
618 eventfd_signal(ctx->cq_ev_fd, 1);
8c838788
JA
619}
620
621static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
c71ffb67 622 long res)
2b188cc1
JA
623{
624 unsigned long flags;
625
626 spin_lock_irqsave(&ctx->completion_lock, flags);
c71ffb67 627 io_cqring_fill_event(ctx, user_data, res);
2b188cc1
JA
628 io_commit_cqring(ctx);
629 spin_unlock_irqrestore(&ctx->completion_lock, flags);
630
8c838788 631 io_cqring_ev_posted(ctx);
2b188cc1
JA
632}
633
2579f913
JA
634static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
635 struct io_submit_state *state)
2b188cc1 636{
fd6fab2c 637 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2b188cc1
JA
638 struct io_kiocb *req;
639
640 if (!percpu_ref_tryget(&ctx->refs))
641 return NULL;
642
2579f913 643 if (!state) {
fd6fab2c 644 req = kmem_cache_alloc(req_cachep, gfp);
2579f913
JA
645 if (unlikely(!req))
646 goto out;
647 } else if (!state->free_reqs) {
648 size_t sz;
649 int ret;
650
651 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
fd6fab2c
JA
652 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
653
654 /*
655 * Bulk alloc is all-or-nothing. If we fail to get a batch,
656 * retry single alloc to be on the safe side.
657 */
658 if (unlikely(ret <= 0)) {
659 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
660 if (!state->reqs[0])
661 goto out;
662 ret = 1;
663 }
2579f913
JA
664 state->free_reqs = ret - 1;
665 state->cur_req = 1;
666 req = state->reqs[0];
667 } else {
668 req = state->reqs[state->cur_req];
669 state->free_reqs--;
670 state->cur_req++;
2b188cc1
JA
671 }
672
60c112b0 673 req->file = NULL;
2579f913
JA
674 req->ctx = ctx;
675 req->flags = 0;
e65ef56d
JA
676 /* one is dropped after submission, the other at completion */
677 refcount_set(&req->refs, 2);
9e645e11 678 req->result = 0;
561fb04a 679 INIT_IO_WORK(&req->work, io_wq_submit_work);
2579f913
JA
680 return req;
681out:
6805b32e 682 percpu_ref_put(&ctx->refs);
2b188cc1
JA
683 return NULL;
684}
685
def596e9
JA
686static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
687{
688 if (*nr) {
689 kmem_cache_free_bulk(req_cachep, *nr, reqs);
6805b32e 690 percpu_ref_put_many(&ctx->refs, *nr);
def596e9
JA
691 *nr = 0;
692 }
693}
694
9e645e11 695static void __io_free_req(struct io_kiocb *req)
2b188cc1 696{
fcb323cc
JA
697 struct io_ring_ctx *ctx = req->ctx;
698
09bb8394
JA
699 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
700 fput(req->file);
fcb323cc
JA
701 if (req->flags & REQ_F_INFLIGHT) {
702 unsigned long flags;
703
704 spin_lock_irqsave(&ctx->inflight_lock, flags);
705 list_del(&req->inflight_entry);
706 if (waitqueue_active(&ctx->inflight_wait))
707 wake_up(&ctx->inflight_wait);
708 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
709 }
710 percpu_ref_put(&ctx->refs);
e65ef56d
JA
711 kmem_cache_free(req_cachep, req);
712}
713
ba816ad6 714static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
9e645e11
JA
715{
716 struct io_kiocb *nxt;
717
718 /*
719 * The list should never be empty when we are called here. But could
720 * potentially happen if the chain is messed up, check to be on the
721 * safe side.
722 */
723 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
724 if (nxt) {
725 list_del(&nxt->list);
726 if (!list_empty(&req->link_list)) {
727 INIT_LIST_HEAD(&nxt->link_list);
728 list_splice(&req->link_list, &nxt->link_list);
729 nxt->flags |= REQ_F_LINK;
730 }
731
f7b76ac9 732 nxt->flags |= REQ_F_LINK_DONE;
ba816ad6
JA
733 /*
734 * If we're in async work, we can continue processing the chain
735 * in this context instead of having to queue up new async work.
736 */
561fb04a 737 if (nxtptr && current_work())
ba816ad6 738 *nxtptr = nxt;
561fb04a 739 else
ba816ad6 740 io_queue_async_work(req->ctx, nxt);
9e645e11
JA
741 }
742}
743
744/*
745 * Called if REQ_F_LINK is set, and we fail the head request
746 */
747static void io_fail_links(struct io_kiocb *req)
748{
749 struct io_kiocb *link;
750
751 while (!list_empty(&req->link_list)) {
752 link = list_first_entry(&req->link_list, struct io_kiocb, list);
753 list_del(&link->list);
754
c826bd7a 755 trace_io_uring_fail_link(req, link);
9e645e11
JA
756 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
757 __io_free_req(link);
758 }
759}
760
ba816ad6 761static void io_free_req(struct io_kiocb *req, struct io_kiocb **nxt)
9e645e11
JA
762{
763 /*
764 * If LINK is set, we have dependent requests in this chain. If we
765 * didn't fail this request, queue the first one up, moving any other
766 * dependencies to the next request. In case of failure, fail the rest
767 * of the chain.
768 */
769 if (req->flags & REQ_F_LINK) {
770 if (req->flags & REQ_F_FAIL_LINK)
771 io_fail_links(req);
772 else
ba816ad6 773 io_req_link_next(req, nxt);
9e645e11
JA
774 }
775
776 __io_free_req(req);
777}
778
ba816ad6
JA
779/*
780 * Drop reference to request, return next in chain (if there is one) if this
781 * was the last reference to this request.
782 */
783static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
e65ef56d 784{
ba816ad6
JA
785 struct io_kiocb *nxt = NULL;
786
e65ef56d 787 if (refcount_dec_and_test(&req->refs))
ba816ad6
JA
788 io_free_req(req, &nxt);
789
790 return nxt;
791}
792
793static void io_put_req(struct io_kiocb *req, struct io_kiocb **nxtptr)
794{
795 struct io_kiocb *nxt;
796
797 nxt = io_put_req_find_next(req);
798 if (nxt) {
561fb04a 799 if (nxtptr)
ba816ad6 800 *nxtptr = nxt;
561fb04a 801 else
ba816ad6 802 io_queue_async_work(nxt->ctx, nxt);
ba816ad6 803 }
2b188cc1
JA
804}
805
75b28aff 806static unsigned io_cqring_events(struct io_rings *rings)
a3a0e43f
JA
807{
808 /* See comment at the top of this file */
809 smp_rmb();
75b28aff 810 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
a3a0e43f
JA
811}
812
fb5ccc98
PB
813static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
814{
815 struct io_rings *rings = ctx->rings;
816
817 /* make sure SQ entry isn't read before tail */
818 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
819}
820
def596e9
JA
821/*
822 * Find and free completed poll iocbs
823 */
824static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
825 struct list_head *done)
826{
827 void *reqs[IO_IOPOLL_BATCH];
828 struct io_kiocb *req;
09bb8394 829 int to_free;
def596e9 830
09bb8394 831 to_free = 0;
def596e9
JA
832 while (!list_empty(done)) {
833 req = list_first_entry(done, struct io_kiocb, list);
834 list_del(&req->list);
835
9e645e11 836 io_cqring_fill_event(ctx, req->user_data, req->result);
def596e9
JA
837 (*nr_events)++;
838
09bb8394
JA
839 if (refcount_dec_and_test(&req->refs)) {
840 /* If we're not using fixed files, we have to pair the
841 * completion part with the file put. Use regular
842 * completions for those, only batch free for fixed
9e645e11 843 * file and non-linked commands.
09bb8394 844 */
9e645e11
JA
845 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
846 REQ_F_FIXED_FILE) {
09bb8394
JA
847 reqs[to_free++] = req;
848 if (to_free == ARRAY_SIZE(reqs))
849 io_free_req_many(ctx, reqs, &to_free);
6b06314c 850 } else {
ba816ad6 851 io_free_req(req, NULL);
6b06314c 852 }
9a56a232 853 }
def596e9 854 }
def596e9 855
09bb8394 856 io_commit_cqring(ctx);
def596e9
JA
857 io_free_req_many(ctx, reqs, &to_free);
858}
859
860static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
861 long min)
862{
863 struct io_kiocb *req, *tmp;
864 LIST_HEAD(done);
865 bool spin;
866 int ret;
867
868 /*
869 * Only spin for completions if we don't have multiple devices hanging
870 * off our complete list, and we're under the requested amount.
871 */
872 spin = !ctx->poll_multi_file && *nr_events < min;
873
874 ret = 0;
875 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
876 struct kiocb *kiocb = &req->rw;
877
878 /*
879 * Move completed entries to our local list. If we find a
880 * request that requires polling, break out and complete
881 * the done list first, if we have entries there.
882 */
883 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
884 list_move_tail(&req->list, &done);
885 continue;
886 }
887 if (!list_empty(&done))
888 break;
889
890 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
891 if (ret < 0)
892 break;
893
894 if (ret && spin)
895 spin = false;
896 ret = 0;
897 }
898
899 if (!list_empty(&done))
900 io_iopoll_complete(ctx, nr_events, &done);
901
902 return ret;
903}
904
905/*
906 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
907 * non-spinning poll check - we'll still enter the driver poll loop, but only
908 * as a non-spinning completion check.
909 */
910static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
911 long min)
912{
08f5439f 913 while (!list_empty(&ctx->poll_list) && !need_resched()) {
def596e9
JA
914 int ret;
915
916 ret = io_do_iopoll(ctx, nr_events, min);
917 if (ret < 0)
918 return ret;
919 if (!min || *nr_events >= min)
920 return 0;
921 }
922
923 return 1;
924}
925
926/*
927 * We can't just wait for polled events to come to us, we have to actively
928 * find and complete them.
929 */
930static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
931{
932 if (!(ctx->flags & IORING_SETUP_IOPOLL))
933 return;
934
935 mutex_lock(&ctx->uring_lock);
936 while (!list_empty(&ctx->poll_list)) {
937 unsigned int nr_events = 0;
938
939 io_iopoll_getevents(ctx, &nr_events, 1);
08f5439f
JA
940
941 /*
942 * Ensure we allow local-to-the-cpu processing to take place,
943 * in this case we need to ensure that we reap all events.
944 */
945 cond_resched();
def596e9
JA
946 }
947 mutex_unlock(&ctx->uring_lock);
948}
949
2b2ed975
JA
950static int __io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
951 long min)
def596e9 952{
2b2ed975 953 int iters = 0, ret = 0;
500f9fba 954
def596e9
JA
955 do {
956 int tmin = 0;
957
a3a0e43f
JA
958 /*
959 * Don't enter poll loop if we already have events pending.
960 * If we do, we can potentially be spinning for commands that
961 * already triggered a CQE (eg in error).
962 */
75b28aff 963 if (io_cqring_events(ctx->rings))
a3a0e43f
JA
964 break;
965
500f9fba
JA
966 /*
967 * If a submit got punted to a workqueue, we can have the
968 * application entering polling for a command before it gets
969 * issued. That app will hold the uring_lock for the duration
970 * of the poll right here, so we need to take a breather every
971 * now and then to ensure that the issue has a chance to add
972 * the poll to the issued list. Otherwise we can spin here
973 * forever, while the workqueue is stuck trying to acquire the
974 * very same mutex.
975 */
976 if (!(++iters & 7)) {
977 mutex_unlock(&ctx->uring_lock);
978 mutex_lock(&ctx->uring_lock);
979 }
980
def596e9
JA
981 if (*nr_events < min)
982 tmin = min - *nr_events;
983
984 ret = io_iopoll_getevents(ctx, nr_events, tmin);
985 if (ret <= 0)
986 break;
987 ret = 0;
988 } while (min && !*nr_events && !need_resched());
989
2b2ed975
JA
990 return ret;
991}
992
993static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
994 long min)
995{
996 int ret;
997
998 /*
999 * We disallow the app entering submit/complete with polling, but we
1000 * still need to lock the ring to prevent racing with polled issue
1001 * that got punted to a workqueue.
1002 */
1003 mutex_lock(&ctx->uring_lock);
1004 ret = __io_iopoll_check(ctx, nr_events, min);
500f9fba 1005 mutex_unlock(&ctx->uring_lock);
def596e9
JA
1006 return ret;
1007}
1008
491381ce 1009static void kiocb_end_write(struct io_kiocb *req)
2b188cc1 1010{
491381ce
JA
1011 /*
1012 * Tell lockdep we inherited freeze protection from submission
1013 * thread.
1014 */
1015 if (req->flags & REQ_F_ISREG) {
1016 struct inode *inode = file_inode(req->file);
2b188cc1 1017
491381ce 1018 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2b188cc1 1019 }
491381ce 1020 file_end_write(req->file);
2b188cc1
JA
1021}
1022
ba816ad6 1023static void io_complete_rw_common(struct kiocb *kiocb, long res)
2b188cc1
JA
1024{
1025 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1026
491381ce
JA
1027 if (kiocb->ki_flags & IOCB_WRITE)
1028 kiocb_end_write(req);
2b188cc1 1029
9e645e11
JA
1030 if ((req->flags & REQ_F_LINK) && res != req->result)
1031 req->flags |= REQ_F_FAIL_LINK;
c71ffb67 1032 io_cqring_add_event(req->ctx, req->user_data, res);
ba816ad6
JA
1033}
1034
1035static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
1036{
1037 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1038
1039 io_complete_rw_common(kiocb, res);
1040 io_put_req(req, NULL);
1041}
1042
1043static struct io_kiocb *__io_complete_rw(struct kiocb *kiocb, long res)
1044{
1045 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1046
1047 io_complete_rw_common(kiocb, res);
1048 return io_put_req_find_next(req);
2b188cc1
JA
1049}
1050
def596e9
JA
1051static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
1052{
1053 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
1054
491381ce
JA
1055 if (kiocb->ki_flags & IOCB_WRITE)
1056 kiocb_end_write(req);
def596e9 1057
9e645e11
JA
1058 if ((req->flags & REQ_F_LINK) && res != req->result)
1059 req->flags |= REQ_F_FAIL_LINK;
1060 req->result = res;
def596e9
JA
1061 if (res != -EAGAIN)
1062 req->flags |= REQ_F_IOPOLL_COMPLETED;
1063}
1064
1065/*
1066 * After the iocb has been issued, it's safe to be found on the poll list.
1067 * Adding the kiocb to the list AFTER submission ensures that we don't
1068 * find it from a io_iopoll_getevents() thread before the issuer is done
1069 * accessing the kiocb cookie.
1070 */
1071static void io_iopoll_req_issued(struct io_kiocb *req)
1072{
1073 struct io_ring_ctx *ctx = req->ctx;
1074
1075 /*
1076 * Track whether we have multiple files in our lists. This will impact
1077 * how we do polling eventually, not spinning if we're on potentially
1078 * different devices.
1079 */
1080 if (list_empty(&ctx->poll_list)) {
1081 ctx->poll_multi_file = false;
1082 } else if (!ctx->poll_multi_file) {
1083 struct io_kiocb *list_req;
1084
1085 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1086 list);
1087 if (list_req->rw.ki_filp != req->rw.ki_filp)
1088 ctx->poll_multi_file = true;
1089 }
1090
1091 /*
1092 * For fast devices, IO may have already completed. If it has, add
1093 * it to the front so we find it first.
1094 */
1095 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1096 list_add(&req->list, &ctx->poll_list);
1097 else
1098 list_add_tail(&req->list, &ctx->poll_list);
1099}
1100
3d6770fb 1101static void io_file_put(struct io_submit_state *state)
9a56a232 1102{
3d6770fb 1103 if (state->file) {
9a56a232
JA
1104 int diff = state->has_refs - state->used_refs;
1105
1106 if (diff)
1107 fput_many(state->file, diff);
1108 state->file = NULL;
1109 }
1110}
1111
1112/*
1113 * Get as many references to a file as we have IOs left in this submission,
1114 * assuming most submissions are for one file, or at least that each file
1115 * has more than one submission.
1116 */
1117static struct file *io_file_get(struct io_submit_state *state, int fd)
1118{
1119 if (!state)
1120 return fget(fd);
1121
1122 if (state->file) {
1123 if (state->fd == fd) {
1124 state->used_refs++;
1125 state->ios_left--;
1126 return state->file;
1127 }
3d6770fb 1128 io_file_put(state);
9a56a232
JA
1129 }
1130 state->file = fget_many(fd, state->ios_left);
1131 if (!state->file)
1132 return NULL;
1133
1134 state->fd = fd;
1135 state->has_refs = state->ios_left;
1136 state->used_refs = 1;
1137 state->ios_left--;
1138 return state->file;
1139}
1140
2b188cc1
JA
1141/*
1142 * If we tracked the file through the SCM inflight mechanism, we could support
1143 * any file. For now, just ensure that anything potentially problematic is done
1144 * inline.
1145 */
1146static bool io_file_supports_async(struct file *file)
1147{
1148 umode_t mode = file_inode(file)->i_mode;
1149
1150 if (S_ISBLK(mode) || S_ISCHR(mode))
1151 return true;
1152 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1153 return true;
1154
1155 return false;
1156}
1157
6c271ce2 1158static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
8358e3a8 1159 bool force_nonblock)
2b188cc1 1160{
6c271ce2 1161 const struct io_uring_sqe *sqe = s->sqe;
def596e9 1162 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 1163 struct kiocb *kiocb = &req->rw;
09bb8394
JA
1164 unsigned ioprio;
1165 int ret;
2b188cc1 1166
09bb8394
JA
1167 if (!req->file)
1168 return -EBADF;
2b188cc1 1169
491381ce
JA
1170 if (S_ISREG(file_inode(req->file)->i_mode))
1171 req->flags |= REQ_F_ISREG;
1172
1173 /*
1174 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1175 * we know to async punt it even if it was opened O_NONBLOCK
1176 */
1177 if (force_nonblock && !io_file_supports_async(req->file)) {
1178 req->flags |= REQ_F_MUST_PUNT;
1179 return -EAGAIN;
1180 }
6b06314c 1181
2b188cc1
JA
1182 kiocb->ki_pos = READ_ONCE(sqe->off);
1183 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1184 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1185
1186 ioprio = READ_ONCE(sqe->ioprio);
1187 if (ioprio) {
1188 ret = ioprio_check_cap(ioprio);
1189 if (ret)
09bb8394 1190 return ret;
2b188cc1
JA
1191
1192 kiocb->ki_ioprio = ioprio;
1193 } else
1194 kiocb->ki_ioprio = get_current_ioprio();
1195
1196 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1197 if (unlikely(ret))
09bb8394 1198 return ret;
8449eeda
SB
1199
1200 /* don't allow async punt if RWF_NOWAIT was requested */
491381ce
JA
1201 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1202 (req->file->f_flags & O_NONBLOCK))
8449eeda
SB
1203 req->flags |= REQ_F_NOWAIT;
1204
1205 if (force_nonblock)
2b188cc1 1206 kiocb->ki_flags |= IOCB_NOWAIT;
8449eeda 1207
def596e9 1208 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9
JA
1209 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1210 !kiocb->ki_filp->f_op->iopoll)
09bb8394 1211 return -EOPNOTSUPP;
2b188cc1 1212
def596e9
JA
1213 kiocb->ki_flags |= IOCB_HIPRI;
1214 kiocb->ki_complete = io_complete_rw_iopoll;
1215 } else {
09bb8394
JA
1216 if (kiocb->ki_flags & IOCB_HIPRI)
1217 return -EINVAL;
def596e9
JA
1218 kiocb->ki_complete = io_complete_rw;
1219 }
2b188cc1 1220 return 0;
2b188cc1
JA
1221}
1222
1223static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1224{
1225 switch (ret) {
1226 case -EIOCBQUEUED:
1227 break;
1228 case -ERESTARTSYS:
1229 case -ERESTARTNOINTR:
1230 case -ERESTARTNOHAND:
1231 case -ERESTART_RESTARTBLOCK:
1232 /*
1233 * We can't just restart the syscall, since previously
1234 * submitted sqes may already be in progress. Just fail this
1235 * IO with EINTR.
1236 */
1237 ret = -EINTR;
1238 /* fall through */
1239 default:
1240 kiocb->ki_complete(kiocb, ret, 0);
1241 }
1242}
1243
ba816ad6
JA
1244static void kiocb_done(struct kiocb *kiocb, ssize_t ret, struct io_kiocb **nxt,
1245 bool in_async)
1246{
1247 if (in_async && ret >= 0 && nxt && kiocb->ki_complete == io_complete_rw)
1248 *nxt = __io_complete_rw(kiocb, ret);
1249 else
1250 io_rw_done(kiocb, ret);
1251}
1252
edafccee
JA
1253static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1254 const struct io_uring_sqe *sqe,
1255 struct iov_iter *iter)
1256{
1257 size_t len = READ_ONCE(sqe->len);
1258 struct io_mapped_ubuf *imu;
1259 unsigned index, buf_index;
1260 size_t offset;
1261 u64 buf_addr;
1262
1263 /* attempt to use fixed buffers without having provided iovecs */
1264 if (unlikely(!ctx->user_bufs))
1265 return -EFAULT;
1266
1267 buf_index = READ_ONCE(sqe->buf_index);
1268 if (unlikely(buf_index >= ctx->nr_user_bufs))
1269 return -EFAULT;
1270
1271 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1272 imu = &ctx->user_bufs[index];
1273 buf_addr = READ_ONCE(sqe->addr);
1274
1275 /* overflow */
1276 if (buf_addr + len < buf_addr)
1277 return -EFAULT;
1278 /* not inside the mapped region */
1279 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1280 return -EFAULT;
1281
1282 /*
1283 * May not be a start of buffer, set size appropriately
1284 * and advance us to the beginning.
1285 */
1286 offset = buf_addr - imu->ubuf;
1287 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
1288
1289 if (offset) {
1290 /*
1291 * Don't use iov_iter_advance() here, as it's really slow for
1292 * using the latter parts of a big fixed buffer - it iterates
1293 * over each segment manually. We can cheat a bit here, because
1294 * we know that:
1295 *
1296 * 1) it's a BVEC iter, we set it up
1297 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1298 * first and last bvec
1299 *
1300 * So just find our index, and adjust the iterator afterwards.
1301 * If the offset is within the first bvec (or the whole first
1302 * bvec, just use iov_iter_advance(). This makes it easier
1303 * since we can just skip the first segment, which may not
1304 * be PAGE_SIZE aligned.
1305 */
1306 const struct bio_vec *bvec = imu->bvec;
1307
1308 if (offset <= bvec->bv_len) {
1309 iov_iter_advance(iter, offset);
1310 } else {
1311 unsigned long seg_skip;
1312
1313 /* skip first vec */
1314 offset -= bvec->bv_len;
1315 seg_skip = 1 + (offset >> PAGE_SHIFT);
1316
1317 iter->bvec = bvec + seg_skip;
1318 iter->nr_segs -= seg_skip;
99c79f66 1319 iter->count -= bvec->bv_len + offset;
bd11b3a3 1320 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
1321 }
1322 }
1323
edafccee
JA
1324 return 0;
1325}
1326
87e5e6da
JA
1327static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1328 const struct sqe_submit *s, struct iovec **iovec,
1329 struct iov_iter *iter)
2b188cc1
JA
1330{
1331 const struct io_uring_sqe *sqe = s->sqe;
1332 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1333 size_t sqe_len = READ_ONCE(sqe->len);
edafccee
JA
1334 u8 opcode;
1335
1336 /*
1337 * We're reading ->opcode for the second time, but the first read
1338 * doesn't care whether it's _FIXED or not, so it doesn't matter
1339 * whether ->opcode changes concurrently. The first read does care
1340 * about whether it is a READ or a WRITE, so we don't trust this read
1341 * for that purpose and instead let the caller pass in the read/write
1342 * flag.
1343 */
1344 opcode = READ_ONCE(sqe->opcode);
1345 if (opcode == IORING_OP_READ_FIXED ||
1346 opcode == IORING_OP_WRITE_FIXED) {
87e5e6da 1347 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
edafccee
JA
1348 *iovec = NULL;
1349 return ret;
1350 }
2b188cc1
JA
1351
1352 if (!s->has_user)
1353 return -EFAULT;
1354
1355#ifdef CONFIG_COMPAT
1356 if (ctx->compat)
1357 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1358 iovec, iter);
1359#endif
1360
1361 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1362}
1363
32960613
JA
1364/*
1365 * For files that don't have ->read_iter() and ->write_iter(), handle them
1366 * by looping over ->read() or ->write() manually.
1367 */
1368static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1369 struct iov_iter *iter)
1370{
1371 ssize_t ret = 0;
1372
1373 /*
1374 * Don't support polled IO through this interface, and we can't
1375 * support non-blocking either. For the latter, this just causes
1376 * the kiocb to be handled from an async context.
1377 */
1378 if (kiocb->ki_flags & IOCB_HIPRI)
1379 return -EOPNOTSUPP;
1380 if (kiocb->ki_flags & IOCB_NOWAIT)
1381 return -EAGAIN;
1382
1383 while (iov_iter_count(iter)) {
1384 struct iovec iovec = iov_iter_iovec(iter);
1385 ssize_t nr;
1386
1387 if (rw == READ) {
1388 nr = file->f_op->read(file, iovec.iov_base,
1389 iovec.iov_len, &kiocb->ki_pos);
1390 } else {
1391 nr = file->f_op->write(file, iovec.iov_base,
1392 iovec.iov_len, &kiocb->ki_pos);
1393 }
1394
1395 if (nr < 0) {
1396 if (!ret)
1397 ret = nr;
1398 break;
1399 }
1400 ret += nr;
1401 if (nr != iovec.iov_len)
1402 break;
1403 iov_iter_advance(iter, nr);
1404 }
1405
1406 return ret;
1407}
1408
e0c5c576 1409static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
ba816ad6 1410 struct io_kiocb **nxt, bool force_nonblock)
2b188cc1
JA
1411{
1412 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1413 struct kiocb *kiocb = &req->rw;
1414 struct iov_iter iter;
1415 struct file *file;
31b51510 1416 size_t iov_count;
9d93a3f5 1417 ssize_t read_size, ret;
2b188cc1 1418
8358e3a8 1419 ret = io_prep_rw(req, s, force_nonblock);
2b188cc1
JA
1420 if (ret)
1421 return ret;
1422 file = kiocb->ki_filp;
1423
2b188cc1 1424 if (unlikely(!(file->f_mode & FMODE_READ)))
09bb8394 1425 return -EBADF;
2b188cc1
JA
1426
1427 ret = io_import_iovec(req->ctx, READ, s, &iovec, &iter);
87e5e6da 1428 if (ret < 0)
09bb8394 1429 return ret;
2b188cc1 1430
9d93a3f5 1431 read_size = ret;
9e645e11
JA
1432 if (req->flags & REQ_F_LINK)
1433 req->result = read_size;
1434
31b51510
JA
1435 iov_count = iov_iter_count(&iter);
1436 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
2b188cc1
JA
1437 if (!ret) {
1438 ssize_t ret2;
1439
32960613
JA
1440 if (file->f_op->read_iter)
1441 ret2 = call_read_iter(file, kiocb, &iter);
1442 else
1443 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1444
9d93a3f5
JA
1445 /*
1446 * In case of a short read, punt to async. This can happen
1447 * if we have data partially cached. Alternatively we can
1448 * return the short read, in which case the application will
1449 * need to issue another SQE and wait for it. That SQE will
1450 * need async punt anyway, so it's more efficient to do it
1451 * here.
1452 */
491381ce
JA
1453 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1454 (req->flags & REQ_F_ISREG) &&
1455 ret2 > 0 && ret2 < read_size)
9d93a3f5
JA
1456 ret2 = -EAGAIN;
1457 /* Catch -EAGAIN return for forced non-blocking submission */
561fb04a 1458 if (!force_nonblock || ret2 != -EAGAIN)
ba5290cc 1459 kiocb_done(kiocb, ret2, nxt, s->in_async);
561fb04a 1460 else
2b188cc1
JA
1461 ret = -EAGAIN;
1462 }
1463 kfree(iovec);
2b188cc1
JA
1464 return ret;
1465}
1466
e0c5c576 1467static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
ba816ad6 1468 struct io_kiocb **nxt, bool force_nonblock)
2b188cc1
JA
1469{
1470 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1471 struct kiocb *kiocb = &req->rw;
1472 struct iov_iter iter;
1473 struct file *file;
31b51510 1474 size_t iov_count;
87e5e6da 1475 ssize_t ret;
2b188cc1 1476
8358e3a8 1477 ret = io_prep_rw(req, s, force_nonblock);
2b188cc1
JA
1478 if (ret)
1479 return ret;
2b188cc1 1480
2b188cc1
JA
1481 file = kiocb->ki_filp;
1482 if (unlikely(!(file->f_mode & FMODE_WRITE)))
09bb8394 1483 return -EBADF;
2b188cc1
JA
1484
1485 ret = io_import_iovec(req->ctx, WRITE, s, &iovec, &iter);
87e5e6da 1486 if (ret < 0)
09bb8394 1487 return ret;
2b188cc1 1488
9e645e11
JA
1489 if (req->flags & REQ_F_LINK)
1490 req->result = ret;
1491
31b51510
JA
1492 iov_count = iov_iter_count(&iter);
1493
1494 ret = -EAGAIN;
561fb04a 1495 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT))
31b51510 1496 goto out_free;
31b51510
JA
1497
1498 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
2b188cc1 1499 if (!ret) {
9bf7933f
RP
1500 ssize_t ret2;
1501
2b188cc1
JA
1502 /*
1503 * Open-code file_start_write here to grab freeze protection,
1504 * which will be released by another thread in
1505 * io_complete_rw(). Fool lockdep by telling it the lock got
1506 * released so that it doesn't complain about the held lock when
1507 * we return to userspace.
1508 */
491381ce 1509 if (req->flags & REQ_F_ISREG) {
2b188cc1
JA
1510 __sb_start_write(file_inode(file)->i_sb,
1511 SB_FREEZE_WRITE, true);
1512 __sb_writers_release(file_inode(file)->i_sb,
1513 SB_FREEZE_WRITE);
1514 }
1515 kiocb->ki_flags |= IOCB_WRITE;
9bf7933f 1516
32960613
JA
1517 if (file->f_op->write_iter)
1518 ret2 = call_write_iter(file, kiocb, &iter);
1519 else
1520 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
561fb04a 1521 if (!force_nonblock || ret2 != -EAGAIN)
ba5290cc 1522 kiocb_done(kiocb, ret2, nxt, s->in_async);
561fb04a 1523 else
9bf7933f 1524 ret = -EAGAIN;
2b188cc1 1525 }
31b51510 1526out_free:
2b188cc1 1527 kfree(iovec);
2b188cc1
JA
1528 return ret;
1529}
1530
1531/*
1532 * IORING_OP_NOP just posts a completion event, nothing else.
1533 */
1534static int io_nop(struct io_kiocb *req, u64 user_data)
1535{
1536 struct io_ring_ctx *ctx = req->ctx;
1537 long err = 0;
1538
def596e9
JA
1539 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1540 return -EINVAL;
1541
c71ffb67 1542 io_cqring_add_event(ctx, user_data, err);
ba816ad6 1543 io_put_req(req, NULL);
2b188cc1
JA
1544 return 0;
1545}
1546
c992fe29
CH
1547static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1548{
6b06314c 1549 struct io_ring_ctx *ctx = req->ctx;
c992fe29 1550
09bb8394
JA
1551 if (!req->file)
1552 return -EBADF;
c992fe29 1553
6b06314c 1554 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 1555 return -EINVAL;
edafccee 1556 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
c992fe29
CH
1557 return -EINVAL;
1558
c992fe29
CH
1559 return 0;
1560}
1561
1562static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1563 struct io_kiocb **nxt, bool force_nonblock)
c992fe29
CH
1564{
1565 loff_t sqe_off = READ_ONCE(sqe->off);
1566 loff_t sqe_len = READ_ONCE(sqe->len);
1567 loff_t end = sqe_off + sqe_len;
1568 unsigned fsync_flags;
1569 int ret;
1570
1571 fsync_flags = READ_ONCE(sqe->fsync_flags);
1572 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1573 return -EINVAL;
1574
1575 ret = io_prep_fsync(req, sqe);
1576 if (ret)
1577 return ret;
1578
1579 /* fsync always requires a blocking context */
1580 if (force_nonblock)
1581 return -EAGAIN;
1582
1583 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1584 end > 0 ? end : LLONG_MAX,
1585 fsync_flags & IORING_FSYNC_DATASYNC);
1586
9e645e11
JA
1587 if (ret < 0 && (req->flags & REQ_F_LINK))
1588 req->flags |= REQ_F_FAIL_LINK;
c71ffb67 1589 io_cqring_add_event(req->ctx, sqe->user_data, ret);
ba816ad6 1590 io_put_req(req, nxt);
c992fe29
CH
1591 return 0;
1592}
1593
5d17b4a4
JA
1594static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1595{
1596 struct io_ring_ctx *ctx = req->ctx;
1597 int ret = 0;
1598
1599 if (!req->file)
1600 return -EBADF;
5d17b4a4
JA
1601
1602 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1603 return -EINVAL;
1604 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1605 return -EINVAL;
1606
5d17b4a4
JA
1607 return ret;
1608}
1609
1610static int io_sync_file_range(struct io_kiocb *req,
1611 const struct io_uring_sqe *sqe,
ba816ad6 1612 struct io_kiocb **nxt,
5d17b4a4
JA
1613 bool force_nonblock)
1614{
1615 loff_t sqe_off;
1616 loff_t sqe_len;
1617 unsigned flags;
1618 int ret;
1619
1620 ret = io_prep_sfr(req, sqe);
1621 if (ret)
1622 return ret;
1623
1624 /* sync_file_range always requires a blocking context */
1625 if (force_nonblock)
1626 return -EAGAIN;
1627
1628 sqe_off = READ_ONCE(sqe->off);
1629 sqe_len = READ_ONCE(sqe->len);
1630 flags = READ_ONCE(sqe->sync_range_flags);
1631
1632 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1633
9e645e11
JA
1634 if (ret < 0 && (req->flags & REQ_F_LINK))
1635 req->flags |= REQ_F_FAIL_LINK;
c71ffb67 1636 io_cqring_add_event(req->ctx, sqe->user_data, ret);
ba816ad6 1637 io_put_req(req, nxt);
5d17b4a4
JA
1638 return 0;
1639}
1640
0fa03c62 1641#if defined(CONFIG_NET)
aa1fa28f 1642static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1643 struct io_kiocb **nxt, bool force_nonblock,
aa1fa28f
JA
1644 long (*fn)(struct socket *, struct user_msghdr __user *,
1645 unsigned int))
1646{
0fa03c62
JA
1647 struct socket *sock;
1648 int ret;
1649
1650 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1651 return -EINVAL;
1652
1653 sock = sock_from_file(req->file, &ret);
1654 if (sock) {
1655 struct user_msghdr __user *msg;
1656 unsigned flags;
1657
1658 flags = READ_ONCE(sqe->msg_flags);
1659 if (flags & MSG_DONTWAIT)
1660 req->flags |= REQ_F_NOWAIT;
1661 else if (force_nonblock)
1662 flags |= MSG_DONTWAIT;
1663
1664 msg = (struct user_msghdr __user *) (unsigned long)
1665 READ_ONCE(sqe->addr);
1666
aa1fa28f 1667 ret = fn(sock, msg, flags);
0fa03c62
JA
1668 if (force_nonblock && ret == -EAGAIN)
1669 return ret;
1670 }
1671
c71ffb67 1672 io_cqring_add_event(req->ctx, sqe->user_data, ret);
ba816ad6 1673 io_put_req(req, nxt);
5d17b4a4
JA
1674 return 0;
1675}
aa1fa28f
JA
1676#endif
1677
1678static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1679 struct io_kiocb **nxt, bool force_nonblock)
aa1fa28f
JA
1680{
1681#if defined(CONFIG_NET)
ba816ad6
JA
1682 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1683 __sys_sendmsg_sock);
aa1fa28f
JA
1684#else
1685 return -EOPNOTSUPP;
1686#endif
1687}
1688
1689static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
ba816ad6 1690 struct io_kiocb **nxt, bool force_nonblock)
aa1fa28f
JA
1691{
1692#if defined(CONFIG_NET)
ba816ad6
JA
1693 return io_send_recvmsg(req, sqe, nxt, force_nonblock,
1694 __sys_recvmsg_sock);
0fa03c62
JA
1695#else
1696 return -EOPNOTSUPP;
1697#endif
1698}
5d17b4a4 1699
17f2fe35
JA
1700static int io_accept(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1701 struct io_kiocb **nxt, bool force_nonblock)
1702{
1703#if defined(CONFIG_NET)
1704 struct sockaddr __user *addr;
1705 int __user *addr_len;
1706 unsigned file_flags;
1707 int flags, ret;
1708
1709 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
1710 return -EINVAL;
1711 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1712 return -EINVAL;
1713
1714 addr = (struct sockaddr __user *) (unsigned long) READ_ONCE(sqe->addr);
1715 addr_len = (int __user *) (unsigned long) READ_ONCE(sqe->addr2);
1716 flags = READ_ONCE(sqe->accept_flags);
1717 file_flags = force_nonblock ? O_NONBLOCK : 0;
1718
1719 ret = __sys_accept4_file(req->file, file_flags, addr, addr_len, flags);
1720 if (ret == -EAGAIN && force_nonblock) {
1721 req->work.flags |= IO_WQ_WORK_NEEDS_FILES;
1722 return -EAGAIN;
1723 }
1724 if (ret < 0 && (req->flags & REQ_F_LINK))
1725 req->flags |= REQ_F_FAIL_LINK;
1726 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1727 io_put_req(req, nxt);
1728 return 0;
1729#else
1730 return -EOPNOTSUPP;
1731#endif
1732}
1733
221c5eb2
JA
1734static void io_poll_remove_one(struct io_kiocb *req)
1735{
1736 struct io_poll_iocb *poll = &req->poll;
1737
1738 spin_lock(&poll->head->lock);
1739 WRITE_ONCE(poll->canceled, true);
1740 if (!list_empty(&poll->wait.entry)) {
1741 list_del_init(&poll->wait.entry);
18d9be1a 1742 io_queue_async_work(req->ctx, req);
221c5eb2
JA
1743 }
1744 spin_unlock(&poll->head->lock);
1745
1746 list_del_init(&req->list);
1747}
1748
1749static void io_poll_remove_all(struct io_ring_ctx *ctx)
1750{
1751 struct io_kiocb *req;
1752
1753 spin_lock_irq(&ctx->completion_lock);
1754 while (!list_empty(&ctx->cancel_list)) {
1755 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1756 io_poll_remove_one(req);
1757 }
1758 spin_unlock_irq(&ctx->completion_lock);
1759}
1760
1761/*
1762 * Find a running poll command that matches one specified in sqe->addr,
1763 * and remove it if found.
1764 */
1765static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1766{
1767 struct io_ring_ctx *ctx = req->ctx;
1768 struct io_kiocb *poll_req, *next;
1769 int ret = -ENOENT;
1770
1771 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1772 return -EINVAL;
1773 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1774 sqe->poll_events)
1775 return -EINVAL;
1776
1777 spin_lock_irq(&ctx->completion_lock);
1778 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1779 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1780 io_poll_remove_one(poll_req);
1781 ret = 0;
1782 break;
1783 }
1784 }
1785 spin_unlock_irq(&ctx->completion_lock);
1786
c71ffb67 1787 io_cqring_add_event(req->ctx, sqe->user_data, ret);
ba816ad6 1788 io_put_req(req, NULL);
221c5eb2
JA
1789 return 0;
1790}
1791
8c838788
JA
1792static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1793 __poll_t mask)
221c5eb2 1794{
8c838788 1795 req->poll.done = true;
c71ffb67 1796 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
8c838788 1797 io_commit_cqring(ctx);
221c5eb2
JA
1798}
1799
561fb04a 1800static void io_poll_complete_work(struct io_wq_work **workptr)
221c5eb2 1801{
561fb04a 1802 struct io_wq_work *work = *workptr;
221c5eb2
JA
1803 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1804 struct io_poll_iocb *poll = &req->poll;
1805 struct poll_table_struct pt = { ._key = poll->events };
1806 struct io_ring_ctx *ctx = req->ctx;
1807 __poll_t mask = 0;
1808
561fb04a
JA
1809 if (work->flags & IO_WQ_WORK_CANCEL)
1810 WRITE_ONCE(poll->canceled, true);
1811
221c5eb2
JA
1812 if (!READ_ONCE(poll->canceled))
1813 mask = vfs_poll(poll->file, &pt) & poll->events;
1814
1815 /*
1816 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1817 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1818 * synchronize with them. In the cancellation case the list_del_init
1819 * itself is not actually needed, but harmless so we keep it in to
1820 * avoid further branches in the fast path.
1821 */
1822 spin_lock_irq(&ctx->completion_lock);
1823 if (!mask && !READ_ONCE(poll->canceled)) {
1824 add_wait_queue(poll->head, &poll->wait);
1825 spin_unlock_irq(&ctx->completion_lock);
1826 return;
1827 }
1828 list_del_init(&req->list);
8c838788 1829 io_poll_complete(ctx, req, mask);
221c5eb2
JA
1830 spin_unlock_irq(&ctx->completion_lock);
1831
8c838788 1832 io_cqring_ev_posted(ctx);
ba816ad6 1833 io_put_req(req, NULL);
221c5eb2
JA
1834}
1835
1836static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1837 void *key)
1838{
1839 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1840 wait);
1841 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1842 struct io_ring_ctx *ctx = req->ctx;
1843 __poll_t mask = key_to_poll(key);
8c838788 1844 unsigned long flags;
221c5eb2
JA
1845
1846 /* for instances that support it check for an event match first: */
8c838788
JA
1847 if (mask && !(mask & poll->events))
1848 return 0;
221c5eb2 1849
8c838788 1850 list_del_init(&poll->wait.entry);
221c5eb2 1851
8c838788
JA
1852 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1853 list_del(&req->list);
1854 io_poll_complete(ctx, req, mask);
1855 spin_unlock_irqrestore(&ctx->completion_lock, flags);
221c5eb2 1856
8c838788 1857 io_cqring_ev_posted(ctx);
ba816ad6 1858 io_put_req(req, NULL);
8c838788 1859 } else {
18d9be1a 1860 io_queue_async_work(ctx, req);
221c5eb2
JA
1861 }
1862
221c5eb2
JA
1863 return 1;
1864}
1865
1866struct io_poll_table {
1867 struct poll_table_struct pt;
1868 struct io_kiocb *req;
1869 int error;
1870};
1871
1872static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1873 struct poll_table_struct *p)
1874{
1875 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1876
1877 if (unlikely(pt->req->poll.head)) {
1878 pt->error = -EINVAL;
1879 return;
1880 }
1881
1882 pt->error = 0;
1883 pt->req->poll.head = head;
1884 add_wait_queue(head, &pt->req->poll.wait);
1885}
1886
1887static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1888{
1889 struct io_poll_iocb *poll = &req->poll;
1890 struct io_ring_ctx *ctx = req->ctx;
1891 struct io_poll_table ipt;
8c838788 1892 bool cancel = false;
221c5eb2
JA
1893 __poll_t mask;
1894 u16 events;
221c5eb2
JA
1895
1896 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1897 return -EINVAL;
1898 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1899 return -EINVAL;
09bb8394
JA
1900 if (!poll->file)
1901 return -EBADF;
221c5eb2 1902
6cc47d1d 1903 req->submit.sqe = NULL;
561fb04a 1904 INIT_IO_WORK(&req->work, io_poll_complete_work);
221c5eb2
JA
1905 events = READ_ONCE(sqe->poll_events);
1906 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1907
221c5eb2 1908 poll->head = NULL;
8c838788 1909 poll->done = false;
221c5eb2
JA
1910 poll->canceled = false;
1911
1912 ipt.pt._qproc = io_poll_queue_proc;
1913 ipt.pt._key = poll->events;
1914 ipt.req = req;
1915 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1916
1917 /* initialized the list so that we can do list_empty checks */
1918 INIT_LIST_HEAD(&poll->wait.entry);
1919 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1920
36703247
JA
1921 INIT_LIST_HEAD(&req->list);
1922
221c5eb2 1923 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
1924
1925 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
1926 if (likely(poll->head)) {
1927 spin_lock(&poll->head->lock);
1928 if (unlikely(list_empty(&poll->wait.entry))) {
1929 if (ipt.error)
1930 cancel = true;
1931 ipt.error = 0;
1932 mask = 0;
1933 }
1934 if (mask || ipt.error)
1935 list_del_init(&poll->wait.entry);
1936 else if (cancel)
1937 WRITE_ONCE(poll->canceled, true);
1938 else if (!poll->done) /* actually waiting for an event */
1939 list_add_tail(&req->list, &ctx->cancel_list);
1940 spin_unlock(&poll->head->lock);
1941 }
1942 if (mask) { /* no async, we'd stolen it */
221c5eb2 1943 ipt.error = 0;
8c838788 1944 io_poll_complete(ctx, req, mask);
221c5eb2 1945 }
221c5eb2
JA
1946 spin_unlock_irq(&ctx->completion_lock);
1947
8c838788
JA
1948 if (mask) {
1949 io_cqring_ev_posted(ctx);
ba816ad6 1950 io_put_req(req, NULL);
221c5eb2 1951 }
8c838788 1952 return ipt.error;
221c5eb2
JA
1953}
1954
5262f567
JA
1955static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
1956{
1957 struct io_ring_ctx *ctx;
11365043 1958 struct io_kiocb *req;
5262f567
JA
1959 unsigned long flags;
1960
1961 req = container_of(timer, struct io_kiocb, timeout.timer);
1962 ctx = req->ctx;
1963 atomic_inc(&ctx->cq_timeouts);
1964
1965 spin_lock_irqsave(&ctx->completion_lock, flags);
ef03681a 1966 /*
11365043
JA
1967 * We could be racing with timeout deletion. If the list is empty,
1968 * then timeout lookup already found it and will be handling it.
ef03681a 1969 */
842f9612 1970 if (!list_empty(&req->list)) {
11365043 1971 struct io_kiocb *prev;
5262f567 1972
11365043
JA
1973 /*
1974 * Adjust the reqs sequence before the current one because it
1975 * will consume a slot in the cq_ring and the the cq_tail
1976 * pointer will be increased, otherwise other timeout reqs may
1977 * return in advance without waiting for enough wait_nr.
1978 */
1979 prev = req;
1980 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
1981 prev->sequence++;
11365043 1982 list_del_init(&req->list);
11365043 1983 }
842f9612
JA
1984
1985 io_cqring_fill_event(ctx, req->user_data, -ETIME);
1986 io_commit_cqring(ctx);
5262f567
JA
1987 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1988
842f9612
JA
1989 io_cqring_ev_posted(ctx);
1990 io_put_req(req, NULL);
11365043
JA
1991 return HRTIMER_NORESTART;
1992}
1993
1994/*
1995 * Remove or update an existing timeout command
1996 */
1997static int io_timeout_remove(struct io_kiocb *req,
1998 const struct io_uring_sqe *sqe)
1999{
2000 struct io_ring_ctx *ctx = req->ctx;
2001 struct io_kiocb *treq;
2002 int ret = -ENOENT;
2003 __u64 user_data;
2004 unsigned flags;
2005
2006 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2007 return -EINVAL;
2008 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
2009 return -EINVAL;
2010 flags = READ_ONCE(sqe->timeout_flags);
2011 if (flags)
2012 return -EINVAL;
2013
2014 user_data = READ_ONCE(sqe->addr);
2015 spin_lock_irq(&ctx->completion_lock);
2016 list_for_each_entry(treq, &ctx->timeout_list, list) {
2017 if (user_data == treq->user_data) {
2018 list_del_init(&treq->list);
2019 ret = 0;
2020 break;
2021 }
2022 }
2023
2024 /* didn't find timeout */
2025 if (ret) {
2026fill_ev:
2027 io_cqring_fill_event(ctx, req->user_data, ret);
2028 io_commit_cqring(ctx);
2029 spin_unlock_irq(&ctx->completion_lock);
2030 io_cqring_ev_posted(ctx);
2031 io_put_req(req, NULL);
2032 return 0;
2033 }
2034
2035 ret = hrtimer_try_to_cancel(&treq->timeout.timer);
2036 if (ret == -1) {
2037 ret = -EBUSY;
2038 goto fill_ev;
2039 }
2040
2041 io_cqring_fill_event(ctx, req->user_data, 0);
2042 io_cqring_fill_event(ctx, treq->user_data, -ECANCELED);
2043 io_commit_cqring(ctx);
2044 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
2045 io_cqring_ev_posted(ctx);
2046
11365043 2047 io_put_req(treq, NULL);
ba816ad6 2048 io_put_req(req, NULL);
11365043 2049 return 0;
5262f567
JA
2050}
2051
2052static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2053{
5da0fb1a 2054 unsigned count;
5262f567
JA
2055 struct io_ring_ctx *ctx = req->ctx;
2056 struct list_head *entry;
a41525ab 2057 enum hrtimer_mode mode;
bdf20073 2058 struct timespec64 ts;
a1f58ba4 2059 unsigned span = 0;
a41525ab 2060 unsigned flags;
5262f567
JA
2061
2062 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2063 return -EINVAL;
a41525ab
JA
2064 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len != 1)
2065 return -EINVAL;
2066 flags = READ_ONCE(sqe->timeout_flags);
2067 if (flags & ~IORING_TIMEOUT_ABS)
5262f567 2068 return -EINVAL;
bdf20073
AB
2069
2070 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
2071 return -EFAULT;
2072
11365043
JA
2073 if (flags & IORING_TIMEOUT_ABS)
2074 mode = HRTIMER_MODE_ABS;
2075 else
2076 mode = HRTIMER_MODE_REL;
2077
2078 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, mode);
2079
5262f567
JA
2080 /*
2081 * sqe->off holds how many events that need to occur for this
2082 * timeout event to be satisfied.
2083 */
2084 count = READ_ONCE(sqe->off);
2085 if (!count)
2086 count = 1;
2087
2088 req->sequence = ctx->cached_sq_head + count - 1;
5da0fb1a 2089 /* reuse it to store the count */
2090 req->submit.sequence = count;
5262f567
JA
2091 req->flags |= REQ_F_TIMEOUT;
2092
2093 /*
2094 * Insertion sort, ensuring the first entry in the list is always
2095 * the one we need first.
2096 */
5262f567
JA
2097 spin_lock_irq(&ctx->completion_lock);
2098 list_for_each_prev(entry, &ctx->timeout_list) {
2099 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5da0fb1a 2100 unsigned nxt_sq_head;
2101 long long tmp, tmp_nxt;
5262f567 2102
5da0fb1a 2103 /*
2104 * Since cached_sq_head + count - 1 can overflow, use type long
2105 * long to store it.
2106 */
2107 tmp = (long long)ctx->cached_sq_head + count - 1;
2108 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
2109 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
2110
2111 /*
2112 * cached_sq_head may overflow, and it will never overflow twice
2113 * once there is some timeout req still be valid.
2114 */
2115 if (ctx->cached_sq_head < nxt_sq_head)
8b07a65a 2116 tmp += UINT_MAX;
5da0fb1a 2117
a1f58ba4 2118 if (tmp > tmp_nxt)
5262f567 2119 break;
a1f58ba4 2120
2121 /*
2122 * Sequence of reqs after the insert one and itself should
2123 * be adjusted because each timeout req consumes a slot.
2124 */
2125 span++;
2126 nxt->sequence++;
5262f567 2127 }
a1f58ba4 2128 req->sequence -= span;
5262f567 2129 list_add(&req->list, entry);
5262f567 2130 req->timeout.timer.function = io_timeout_fn;
a41525ab 2131 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts), mode);
842f9612 2132 spin_unlock_irq(&ctx->completion_lock);
5262f567
JA
2133 return 0;
2134}
2135
62755e35
JA
2136static bool io_cancel_cb(struct io_wq_work *work, void *data)
2137{
2138 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2139
2140 return req->user_data == (unsigned long) data;
2141}
2142
2143static int io_async_cancel(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2144 struct io_kiocb **nxt)
2145{
2146 struct io_ring_ctx *ctx = req->ctx;
2147 enum io_wq_cancel cancel_ret;
2148 void *sqe_addr;
2149 int ret = 0;
2150
2151 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
2152 return -EINVAL;
2153 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
2154 sqe->cancel_flags)
2155 return -EINVAL;
2156
2157 sqe_addr = (void *) (unsigned long) READ_ONCE(sqe->addr);
2158 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr);
2159 switch (cancel_ret) {
2160 case IO_WQ_CANCEL_OK:
2161 ret = 0;
2162 break;
2163 case IO_WQ_CANCEL_RUNNING:
2164 ret = -EALREADY;
2165 break;
2166 case IO_WQ_CANCEL_NOTFOUND:
2167 ret = -ENOENT;
2168 break;
2169 }
2170
2171 if (ret < 0 && (req->flags & REQ_F_LINK))
2172 req->flags |= REQ_F_FAIL_LINK;
2173 io_cqring_add_event(req->ctx, sqe->user_data, ret);
2174 io_put_req(req, nxt);
2175 return 0;
2176}
2177
de0617e4
JA
2178static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
2179 const struct io_uring_sqe *sqe)
2180{
2181 struct io_uring_sqe *sqe_copy;
2182
2183 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
2184 return 0;
2185
2186 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2187 if (!sqe_copy)
2188 return -EAGAIN;
2189
2190 spin_lock_irq(&ctx->completion_lock);
2191 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
2192 spin_unlock_irq(&ctx->completion_lock);
2193 kfree(sqe_copy);
2194 return 0;
2195 }
2196
2197 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
2198 req->submit.sqe = sqe_copy;
2199
c826bd7a 2200 trace_io_uring_defer(ctx, req, false);
de0617e4
JA
2201 list_add_tail(&req->list, &ctx->defer_list);
2202 spin_unlock_irq(&ctx->completion_lock);
2203 return -EIOCBQUEUED;
2204}
2205
2b188cc1 2206static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
ba816ad6
JA
2207 const struct sqe_submit *s, struct io_kiocb **nxt,
2208 bool force_nonblock)
2b188cc1 2209{
e0c5c576 2210 int ret, opcode;
2b188cc1 2211
9e645e11
JA
2212 req->user_data = READ_ONCE(s->sqe->user_data);
2213
2b188cc1
JA
2214 opcode = READ_ONCE(s->sqe->opcode);
2215 switch (opcode) {
2216 case IORING_OP_NOP:
2217 ret = io_nop(req, req->user_data);
2218 break;
2219 case IORING_OP_READV:
edafccee
JA
2220 if (unlikely(s->sqe->buf_index))
2221 return -EINVAL;
ba816ad6 2222 ret = io_read(req, s, nxt, force_nonblock);
2b188cc1
JA
2223 break;
2224 case IORING_OP_WRITEV:
edafccee
JA
2225 if (unlikely(s->sqe->buf_index))
2226 return -EINVAL;
ba816ad6 2227 ret = io_write(req, s, nxt, force_nonblock);
edafccee
JA
2228 break;
2229 case IORING_OP_READ_FIXED:
ba816ad6 2230 ret = io_read(req, s, nxt, force_nonblock);
edafccee
JA
2231 break;
2232 case IORING_OP_WRITE_FIXED:
ba816ad6 2233 ret = io_write(req, s, nxt, force_nonblock);
2b188cc1 2234 break;
c992fe29 2235 case IORING_OP_FSYNC:
ba816ad6 2236 ret = io_fsync(req, s->sqe, nxt, force_nonblock);
c992fe29 2237 break;
221c5eb2
JA
2238 case IORING_OP_POLL_ADD:
2239 ret = io_poll_add(req, s->sqe);
2240 break;
2241 case IORING_OP_POLL_REMOVE:
2242 ret = io_poll_remove(req, s->sqe);
2243 break;
5d17b4a4 2244 case IORING_OP_SYNC_FILE_RANGE:
ba816ad6 2245 ret = io_sync_file_range(req, s->sqe, nxt, force_nonblock);
5d17b4a4 2246 break;
0fa03c62 2247 case IORING_OP_SENDMSG:
ba816ad6 2248 ret = io_sendmsg(req, s->sqe, nxt, force_nonblock);
0fa03c62 2249 break;
aa1fa28f 2250 case IORING_OP_RECVMSG:
ba816ad6 2251 ret = io_recvmsg(req, s->sqe, nxt, force_nonblock);
aa1fa28f 2252 break;
5262f567
JA
2253 case IORING_OP_TIMEOUT:
2254 ret = io_timeout(req, s->sqe);
2255 break;
11365043
JA
2256 case IORING_OP_TIMEOUT_REMOVE:
2257 ret = io_timeout_remove(req, s->sqe);
2258 break;
17f2fe35
JA
2259 case IORING_OP_ACCEPT:
2260 ret = io_accept(req, s->sqe, nxt, force_nonblock);
2261 break;
62755e35
JA
2262 case IORING_OP_ASYNC_CANCEL:
2263 ret = io_async_cancel(req, s->sqe, nxt);
2264 break;
2b188cc1
JA
2265 default:
2266 ret = -EINVAL;
2267 break;
2268 }
2269
def596e9
JA
2270 if (ret)
2271 return ret;
2272
2273 if (ctx->flags & IORING_SETUP_IOPOLL) {
9e645e11 2274 if (req->result == -EAGAIN)
def596e9
JA
2275 return -EAGAIN;
2276
2277 /* workqueue context doesn't hold uring_lock, grab it now */
ba5290cc 2278 if (s->in_async)
def596e9
JA
2279 mutex_lock(&ctx->uring_lock);
2280 io_iopoll_req_issued(req);
ba5290cc 2281 if (s->in_async)
def596e9
JA
2282 mutex_unlock(&ctx->uring_lock);
2283 }
2284
2285 return 0;
2b188cc1
JA
2286}
2287
561fb04a 2288static void io_wq_submit_work(struct io_wq_work **workptr)
2b188cc1 2289{
561fb04a 2290 struct io_wq_work *work = *workptr;
2b188cc1 2291 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 2292 struct io_ring_ctx *ctx = req->ctx;
561fb04a
JA
2293 struct sqe_submit *s = &req->submit;
2294 const struct io_uring_sqe *sqe = s->sqe;
2295 struct io_kiocb *nxt = NULL;
2296 int ret = 0;
2b188cc1 2297
561fb04a
JA
2298 /* Ensure we clear previously set non-block flag */
2299 req->rw.ki_flags &= ~IOCB_NOWAIT;
2b188cc1 2300
561fb04a
JA
2301 if (work->flags & IO_WQ_WORK_CANCEL)
2302 ret = -ECANCELED;
31b51510 2303
561fb04a
JA
2304 if (!ret) {
2305 s->has_user = (work->flags & IO_WQ_WORK_HAS_MM) != 0;
2306 s->in_async = true;
2307 do {
2308 ret = __io_submit_sqe(ctx, req, s, &nxt, false);
2309 /*
2310 * We can get EAGAIN for polled IO even though we're
2311 * forcing a sync submission from here, since we can't
2312 * wait for request slots on the block side.
2313 */
2314 if (ret != -EAGAIN)
2315 break;
2316 cond_resched();
2317 } while (1);
2318 }
31b51510 2319
561fb04a
JA
2320 /* drop submission reference */
2321 io_put_req(req, NULL);
817869d2 2322
561fb04a
JA
2323 if (ret) {
2324 io_cqring_add_event(ctx, sqe->user_data, ret);
ba816ad6 2325 io_put_req(req, NULL);
2b188cc1 2326 }
31b51510 2327
561fb04a
JA
2328 /* async context always use a copy of the sqe */
2329 kfree(sqe);
31b51510 2330
561fb04a
JA
2331 /* if a dependent link is ready, pass it back */
2332 if (!ret && nxt) {
2333 io_prep_async_work(nxt);
2334 *workptr = &nxt->work;
31b51510 2335 }
2b188cc1
JA
2336}
2337
09bb8394
JA
2338static bool io_op_needs_file(const struct io_uring_sqe *sqe)
2339{
2340 int op = READ_ONCE(sqe->opcode);
2341
2342 switch (op) {
2343 case IORING_OP_NOP:
2344 case IORING_OP_POLL_REMOVE:
2345 return false;
2346 default:
2347 return true;
2348 }
2349}
2350
65e19f54
JA
2351static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
2352 int index)
2353{
2354 struct fixed_file_table *table;
2355
2356 table = &ctx->file_table[index >> IORING_FILE_TABLE_SHIFT];
2357 return table->files[index & IORING_FILE_TABLE_MASK];
2358}
2359
09bb8394
JA
2360static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
2361 struct io_submit_state *state, struct io_kiocb *req)
2362{
2363 unsigned flags;
2364 int fd;
2365
2366 flags = READ_ONCE(s->sqe->flags);
2367 fd = READ_ONCE(s->sqe->fd);
2368
4fe2c963 2369 if (flags & IOSQE_IO_DRAIN)
de0617e4 2370 req->flags |= REQ_F_IO_DRAIN;
4fe2c963
JL
2371 /*
2372 * All io need record the previous position, if LINK vs DARIN,
2373 * it can be used to mark the position of the first IO in the
2374 * link list.
2375 */
2376 req->sequence = s->sequence;
de0617e4 2377
60c112b0 2378 if (!io_op_needs_file(s->sqe))
09bb8394 2379 return 0;
09bb8394
JA
2380
2381 if (flags & IOSQE_FIXED_FILE) {
65e19f54 2382 if (unlikely(!ctx->file_table ||
09bb8394
JA
2383 (unsigned) fd >= ctx->nr_user_files))
2384 return -EBADF;
b7620121 2385 fd = array_index_nospec(fd, ctx->nr_user_files);
65e19f54
JA
2386 req->file = io_file_from_index(ctx, fd);
2387 if (!req->file)
08a45173 2388 return -EBADF;
09bb8394
JA
2389 req->flags |= REQ_F_FIXED_FILE;
2390 } else {
2391 if (s->needs_fixed_file)
2392 return -EBADF;
c826bd7a 2393 trace_io_uring_file_get(ctx, fd);
09bb8394
JA
2394 req->file = io_file_get(state, fd);
2395 if (unlikely(!req->file))
2396 return -EBADF;
2397 }
2398
2399 return 0;
2400}
2401
fcb323cc
JA
2402static int io_grab_files(struct io_ring_ctx *ctx, struct io_kiocb *req)
2403{
2404 int ret = -EBADF;
2405
2406 rcu_read_lock();
2407 spin_lock_irq(&ctx->inflight_lock);
2408 /*
2409 * We use the f_ops->flush() handler to ensure that we can flush
2410 * out work accessing these files if the fd is closed. Check if
2411 * the fd has changed since we started down this path, and disallow
2412 * this operation if it has.
2413 */
2414 if (fcheck(req->submit.ring_fd) == req->submit.ring_file) {
2415 list_add(&req->inflight_entry, &ctx->inflight_list);
2416 req->flags |= REQ_F_INFLIGHT;
2417 req->work.files = current->files;
2418 ret = 0;
2419 }
2420 spin_unlock_irq(&ctx->inflight_lock);
2421 rcu_read_unlock();
2422
2423 return ret;
2424}
2425
4fe2c963 2426static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
bc808bce 2427 struct sqe_submit *s)
2b188cc1 2428{
e0c5c576 2429 int ret;
2b188cc1 2430
ba816ad6 2431 ret = __io_submit_sqe(ctx, req, s, NULL, true);
491381ce
JA
2432
2433 /*
2434 * We async punt it if the file wasn't marked NOWAIT, or if the file
2435 * doesn't support non-blocking read/write attempts
2436 */
2437 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2438 (req->flags & REQ_F_MUST_PUNT))) {
2b188cc1
JA
2439 struct io_uring_sqe *sqe_copy;
2440
954dab19 2441 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2b188cc1 2442 if (sqe_copy) {
2b188cc1 2443 s->sqe = sqe_copy;
2b188cc1 2444 memcpy(&req->submit, s, sizeof(*s));
fcb323cc
JA
2445 if (req->work.flags & IO_WQ_WORK_NEEDS_FILES) {
2446 ret = io_grab_files(ctx, req);
2447 if (ret) {
2448 kfree(sqe_copy);
2449 goto err;
2450 }
2451 }
e65ef56d
JA
2452
2453 /*
2454 * Queued up for async execution, worker will release
9e645e11 2455 * submit reference when the iocb is actually submitted.
e65ef56d 2456 */
fcb323cc 2457 io_queue_async_work(ctx, req);
e65ef56d 2458 return 0;
2b188cc1
JA
2459 }
2460 }
e65ef56d
JA
2461
2462 /* drop submission reference */
fcb323cc 2463err:
ba816ad6 2464 io_put_req(req, NULL);
e65ef56d
JA
2465
2466 /* and drop final reference, if we failed */
9e645e11
JA
2467 if (ret) {
2468 io_cqring_add_event(ctx, req->user_data, ret);
2469 if (req->flags & REQ_F_LINK)
2470 req->flags |= REQ_F_FAIL_LINK;
ba816ad6 2471 io_put_req(req, NULL);
9e645e11 2472 }
2b188cc1
JA
2473
2474 return ret;
2475}
2476
4fe2c963 2477static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
bc808bce 2478 struct sqe_submit *s)
4fe2c963
JL
2479{
2480 int ret;
2481
2482 ret = io_req_defer(ctx, req, s->sqe);
2483 if (ret) {
2484 if (ret != -EIOCBQUEUED) {
ba816ad6 2485 io_free_req(req, NULL);
4fe2c963
JL
2486 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2487 }
2488 return 0;
2489 }
2490
bc808bce 2491 return __io_queue_sqe(ctx, req, s);
4fe2c963
JL
2492}
2493
2494static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
bc808bce 2495 struct sqe_submit *s, struct io_kiocb *shadow)
4fe2c963
JL
2496{
2497 int ret;
2498 int need_submit = false;
2499
2500 if (!shadow)
bc808bce 2501 return io_queue_sqe(ctx, req, s);
4fe2c963
JL
2502
2503 /*
2504 * Mark the first IO in link list as DRAIN, let all the following
2505 * IOs enter the defer list. all IO needs to be completed before link
2506 * list.
2507 */
2508 req->flags |= REQ_F_IO_DRAIN;
2509 ret = io_req_defer(ctx, req, s->sqe);
2510 if (ret) {
2511 if (ret != -EIOCBQUEUED) {
ba816ad6 2512 io_free_req(req, NULL);
7b20238d 2513 __io_free_req(shadow);
4fe2c963
JL
2514 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2515 return 0;
2516 }
2517 } else {
2518 /*
2519 * If ret == 0 means that all IOs in front of link io are
2520 * running done. let's queue link head.
2521 */
2522 need_submit = true;
2523 }
2524
2525 /* Insert shadow req to defer_list, blocking next IOs */
2526 spin_lock_irq(&ctx->completion_lock);
c826bd7a 2527 trace_io_uring_defer(ctx, shadow, true);
4fe2c963
JL
2528 list_add_tail(&shadow->list, &ctx->defer_list);
2529 spin_unlock_irq(&ctx->completion_lock);
2530
2531 if (need_submit)
bc808bce 2532 return __io_queue_sqe(ctx, req, s);
4fe2c963
JL
2533
2534 return 0;
2535}
2536
9e645e11
JA
2537#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2538
2539static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
bc808bce 2540 struct io_submit_state *state, struct io_kiocb **link)
9e645e11
JA
2541{
2542 struct io_uring_sqe *sqe_copy;
2543 struct io_kiocb *req;
2544 int ret;
2545
2546 /* enforce forwards compatibility on users */
2547 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2548 ret = -EINVAL;
2549 goto err;
2550 }
2551
2552 req = io_get_req(ctx, state);
2553 if (unlikely(!req)) {
2554 ret = -EAGAIN;
2555 goto err;
2556 }
2557
2558 ret = io_req_set_file(ctx, s, state, req);
2559 if (unlikely(ret)) {
2560err_req:
ba816ad6 2561 io_free_req(req, NULL);
9e645e11
JA
2562err:
2563 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2564 return;
2565 }
2566
84d55dc5
PB
2567 req->user_data = s->sqe->user_data;
2568
9e645e11
JA
2569 /*
2570 * If we already have a head request, queue this one for async
2571 * submittal once the head completes. If we don't have a head but
2572 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2573 * submitted sync once the chain is complete. If none of those
2574 * conditions are true (normal request), then just queue it.
2575 */
2576 if (*link) {
2577 struct io_kiocb *prev = *link;
2578
2579 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2580 if (!sqe_copy) {
2581 ret = -EAGAIN;
2582 goto err_req;
2583 }
2584
2585 s->sqe = sqe_copy;
2586 memcpy(&req->submit, s, sizeof(*s));
c826bd7a 2587 trace_io_uring_link(ctx, req, prev);
9e645e11
JA
2588 list_add_tail(&req->list, &prev->link_list);
2589 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2590 req->flags |= REQ_F_LINK;
2591
2592 memcpy(&req->submit, s, sizeof(*s));
2593 INIT_LIST_HEAD(&req->link_list);
2594 *link = req;
2595 } else {
bc808bce 2596 io_queue_sqe(ctx, req, s);
9e645e11
JA
2597 }
2598}
2599
9a56a232
JA
2600/*
2601 * Batched submission is done, ensure local IO is flushed out.
2602 */
2603static void io_submit_state_end(struct io_submit_state *state)
2604{
2605 blk_finish_plug(&state->plug);
3d6770fb 2606 io_file_put(state);
2579f913
JA
2607 if (state->free_reqs)
2608 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2609 &state->reqs[state->cur_req]);
9a56a232
JA
2610}
2611
2612/*
2613 * Start submission side cache.
2614 */
2615static void io_submit_state_start(struct io_submit_state *state,
2616 struct io_ring_ctx *ctx, unsigned max_ios)
2617{
2618 blk_start_plug(&state->plug);
2579f913 2619 state->free_reqs = 0;
9a56a232
JA
2620 state->file = NULL;
2621 state->ios_left = max_ios;
2622}
2623
2b188cc1
JA
2624static void io_commit_sqring(struct io_ring_ctx *ctx)
2625{
75b28aff 2626 struct io_rings *rings = ctx->rings;
2b188cc1 2627
75b28aff 2628 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2b188cc1
JA
2629 /*
2630 * Ensure any loads from the SQEs are done at this point,
2631 * since once we write the new head, the application could
2632 * write new data to them.
2633 */
75b28aff 2634 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
2635 }
2636}
2637
2b188cc1
JA
2638/*
2639 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2640 * that is mapped by userspace. This means that care needs to be taken to
2641 * ensure that reads are stable, as we cannot rely on userspace always
2642 * being a good citizen. If members of the sqe are validated and then later
2643 * used, it's important that those reads are done through READ_ONCE() to
2644 * prevent a re-load down the line.
2645 */
2646static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2647{
75b28aff
HV
2648 struct io_rings *rings = ctx->rings;
2649 u32 *sq_array = ctx->sq_array;
2b188cc1
JA
2650 unsigned head;
2651
2652 /*
2653 * The cached sq head (or cq tail) serves two purposes:
2654 *
2655 * 1) allows us to batch the cost of updating the user visible
2656 * head updates.
2657 * 2) allows the kernel side to track the head on its own, even
2658 * though the application is the one updating it.
2659 */
2660 head = ctx->cached_sq_head;
e523a29c 2661 /* make sure SQ entry isn't read before tail */
75b28aff 2662 if (head == smp_load_acquire(&rings->sq.tail))
2b188cc1
JA
2663 return false;
2664
75b28aff 2665 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2b188cc1 2666 if (head < ctx->sq_entries) {
fcb323cc 2667 s->ring_file = NULL;
2b188cc1 2668 s->sqe = &ctx->sq_sqes[head];
8776f3fa 2669 s->sequence = ctx->cached_sq_head;
2b188cc1
JA
2670 ctx->cached_sq_head++;
2671 return true;
2672 }
2673
2674 /* drop invalid entries */
2675 ctx->cached_sq_head++;
498ccd9e
JA
2676 ctx->cached_sq_dropped++;
2677 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
2b188cc1
JA
2678 return false;
2679}
2680
fb5ccc98 2681static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
95a1b3ff 2682 struct mm_struct **mm)
6c271ce2
JA
2683{
2684 struct io_submit_state state, *statep = NULL;
9e645e11 2685 struct io_kiocb *link = NULL;
4fe2c963 2686 struct io_kiocb *shadow_req = NULL;
9e645e11
JA
2687 bool prev_was_link = false;
2688 int i, submitted = 0;
95a1b3ff 2689 bool mm_fault = false;
6c271ce2
JA
2690
2691 if (nr > IO_PLUG_THRESHOLD) {
2692 io_submit_state_start(&state, ctx, nr);
2693 statep = &state;
2694 }
2695
2696 for (i = 0; i < nr; i++) {
fb5ccc98
PB
2697 struct sqe_submit s;
2698
2699 if (!io_get_sqring(ctx, &s))
2700 break;
2701
95a1b3ff
PB
2702 if (io_sqe_needs_user(s.sqe) && !*mm) {
2703 mm_fault = mm_fault || !mmget_not_zero(ctx->sqo_mm);
2704 if (!mm_fault) {
2705 use_mm(ctx->sqo_mm);
2706 *mm = ctx->sqo_mm;
2707 }
2708 }
2709
9e645e11
JA
2710 /*
2711 * If previous wasn't linked and we have a linked command,
2712 * that's the end of the chain. Submit the previous link.
2713 */
2714 if (!prev_was_link && link) {
bc808bce 2715 io_queue_link_head(ctx, link, &link->submit, shadow_req);
9e645e11 2716 link = NULL;
5f5ad9ce 2717 shadow_req = NULL;
9e645e11 2718 }
fb5ccc98 2719 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
9e645e11 2720
fb5ccc98 2721 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
4fe2c963
JL
2722 if (!shadow_req) {
2723 shadow_req = io_get_req(ctx, NULL);
a1041c27
JL
2724 if (unlikely(!shadow_req))
2725 goto out;
4fe2c963
JL
2726 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2727 refcount_dec(&shadow_req->refs);
2728 }
fb5ccc98 2729 shadow_req->sequence = s.sequence;
4fe2c963
JL
2730 }
2731
a1041c27 2732out:
95a1b3ff
PB
2733 s.has_user = *mm != NULL;
2734 s.in_async = true;
2735 s.needs_fixed_file = true;
2736 trace_io_uring_submit_sqe(ctx, true, true);
2737 io_submit_sqe(ctx, &s, statep, &link);
2738 submitted++;
6c271ce2
JA
2739 }
2740
9e645e11 2741 if (link)
bc808bce 2742 io_queue_link_head(ctx, link, &link->submit, shadow_req);
6c271ce2
JA
2743 if (statep)
2744 io_submit_state_end(&state);
2745
2746 return submitted;
2747}
2748
2749static int io_sq_thread(void *data)
2750{
6c271ce2
JA
2751 struct io_ring_ctx *ctx = data;
2752 struct mm_struct *cur_mm = NULL;
2753 mm_segment_t old_fs;
2754 DEFINE_WAIT(wait);
2755 unsigned inflight;
2756 unsigned long timeout;
2757
a4c0b3de
JL
2758 complete(&ctx->sqo_thread_started);
2759
6c271ce2
JA
2760 old_fs = get_fs();
2761 set_fs(USER_DS);
2762
2763 timeout = inflight = 0;
2bbcd6d3 2764 while (!kthread_should_park()) {
fb5ccc98 2765 unsigned int to_submit;
6c271ce2
JA
2766
2767 if (inflight) {
2768 unsigned nr_events = 0;
2769
2770 if (ctx->flags & IORING_SETUP_IOPOLL) {
2b2ed975
JA
2771 /*
2772 * inflight is the count of the maximum possible
2773 * entries we submitted, but it can be smaller
2774 * if we dropped some of them. If we don't have
2775 * poll entries available, then we know that we
2776 * have nothing left to poll for. Reset the
2777 * inflight count to zero in that case.
2778 */
2779 mutex_lock(&ctx->uring_lock);
2780 if (!list_empty(&ctx->poll_list))
2781 __io_iopoll_check(ctx, &nr_events, 0);
2782 else
2783 inflight = 0;
2784 mutex_unlock(&ctx->uring_lock);
6c271ce2
JA
2785 } else {
2786 /*
2787 * Normal IO, just pretend everything completed.
2788 * We don't have to poll completions for that.
2789 */
2790 nr_events = inflight;
2791 }
2792
2793 inflight -= nr_events;
2794 if (!inflight)
2795 timeout = jiffies + ctx->sq_thread_idle;
2796 }
2797
fb5ccc98
PB
2798 to_submit = io_sqring_entries(ctx);
2799 if (!to_submit) {
6c271ce2
JA
2800 /*
2801 * We're polling. If we're within the defined idle
2802 * period, then let us spin without work before going
2803 * to sleep.
2804 */
2805 if (inflight || !time_after(jiffies, timeout)) {
9831a90c 2806 cond_resched();
6c271ce2
JA
2807 continue;
2808 }
2809
2810 /*
2811 * Drop cur_mm before scheduling, we can't hold it for
2812 * long periods (or over schedule()). Do this before
2813 * adding ourselves to the waitqueue, as the unuse/drop
2814 * may sleep.
2815 */
2816 if (cur_mm) {
2817 unuse_mm(cur_mm);
2818 mmput(cur_mm);
2819 cur_mm = NULL;
2820 }
2821
2822 prepare_to_wait(&ctx->sqo_wait, &wait,
2823 TASK_INTERRUPTIBLE);
2824
2825 /* Tell userspace we may need a wakeup call */
75b28aff 2826 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
2827 /* make sure to read SQ tail after writing flags */
2828 smp_mb();
6c271ce2 2829
fb5ccc98
PB
2830 to_submit = io_sqring_entries(ctx);
2831 if (!to_submit) {
2bbcd6d3 2832 if (kthread_should_park()) {
6c271ce2
JA
2833 finish_wait(&ctx->sqo_wait, &wait);
2834 break;
2835 }
2836 if (signal_pending(current))
2837 flush_signals(current);
2838 schedule();
2839 finish_wait(&ctx->sqo_wait, &wait);
2840
75b28aff 2841 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2842 continue;
2843 }
2844 finish_wait(&ctx->sqo_wait, &wait);
2845
75b28aff 2846 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2847 }
2848
fb5ccc98 2849 to_submit = min(to_submit, ctx->sq_entries);
95a1b3ff 2850 inflight += io_submit_sqes(ctx, to_submit, &cur_mm);
6c271ce2
JA
2851
2852 /* Commit SQ ring head once we've consumed all SQEs */
2853 io_commit_sqring(ctx);
2854 }
2855
2856 set_fs(old_fs);
2857 if (cur_mm) {
2858 unuse_mm(cur_mm);
2859 mmput(cur_mm);
2860 }
06058632 2861
2bbcd6d3 2862 kthread_parkme();
06058632 2863
6c271ce2
JA
2864 return 0;
2865}
2866
fcb323cc
JA
2867static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit,
2868 struct file *ring_file, int ring_fd)
2b188cc1 2869{
9a56a232 2870 struct io_submit_state state, *statep = NULL;
9e645e11 2871 struct io_kiocb *link = NULL;
4fe2c963 2872 struct io_kiocb *shadow_req = NULL;
9e645e11 2873 bool prev_was_link = false;
5c8b0b54 2874 int i, submit = 0;
2b188cc1 2875
9a56a232
JA
2876 if (to_submit > IO_PLUG_THRESHOLD) {
2877 io_submit_state_start(&state, ctx, to_submit);
2878 statep = &state;
2879 }
2b188cc1
JA
2880
2881 for (i = 0; i < to_submit; i++) {
2882 struct sqe_submit s;
2883
2884 if (!io_get_sqring(ctx, &s))
2885 break;
2886
9e645e11
JA
2887 /*
2888 * If previous wasn't linked and we have a linked command,
2889 * that's the end of the chain. Submit the previous link.
2890 */
2891 if (!prev_was_link && link) {
bc808bce 2892 io_queue_link_head(ctx, link, &link->submit, shadow_req);
9e645e11 2893 link = NULL;
5f5ad9ce 2894 shadow_req = NULL;
9e645e11
JA
2895 }
2896 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2897
4fe2c963
JL
2898 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2899 if (!shadow_req) {
2900 shadow_req = io_get_req(ctx, NULL);
a1041c27
JL
2901 if (unlikely(!shadow_req))
2902 goto out;
4fe2c963
JL
2903 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2904 refcount_dec(&shadow_req->refs);
2905 }
2906 shadow_req->sequence = s.sequence;
2907 }
2908
a1041c27 2909out:
fcb323cc 2910 s.ring_file = ring_file;
2b188cc1 2911 s.has_user = true;
ba5290cc 2912 s.in_async = false;
6c271ce2 2913 s.needs_fixed_file = false;
fcb323cc 2914 s.ring_fd = ring_fd;
5c8b0b54 2915 submit++;
c826bd7a 2916 trace_io_uring_submit_sqe(ctx, true, false);
bc808bce 2917 io_submit_sqe(ctx, &s, statep, &link);
2b188cc1 2918 }
2b188cc1 2919
9e645e11 2920 if (link)
bc808bce 2921 io_queue_link_head(ctx, link, &link->submit, shadow_req);
9a56a232
JA
2922 if (statep)
2923 io_submit_state_end(statep);
2b188cc1 2924
935d1e45
PB
2925 io_commit_sqring(ctx);
2926
5c8b0b54 2927 return submit;
2b188cc1
JA
2928}
2929
bda52162
JA
2930struct io_wait_queue {
2931 struct wait_queue_entry wq;
2932 struct io_ring_ctx *ctx;
2933 unsigned to_wait;
2934 unsigned nr_timeouts;
2935};
2936
2937static inline bool io_should_wake(struct io_wait_queue *iowq)
2938{
2939 struct io_ring_ctx *ctx = iowq->ctx;
2940
2941 /*
2942 * Wake up if we have enough events, or if a timeout occured since we
2943 * started waiting. For timeouts, we always want to return to userspace,
2944 * regardless of event count.
2945 */
2946 return io_cqring_events(ctx->rings) >= iowq->to_wait ||
2947 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2948}
2949
2950static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2951 int wake_flags, void *key)
2952{
2953 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
2954 wq);
2955
2956 if (!io_should_wake(iowq))
2957 return -1;
2958
2959 return autoremove_wake_function(curr, mode, wake_flags, key);
2960}
2961
2b188cc1
JA
2962/*
2963 * Wait until events become available, if we don't already have some. The
2964 * application must reap them itself, as they reside on the shared cq ring.
2965 */
2966static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2967 const sigset_t __user *sig, size_t sigsz)
2968{
bda52162
JA
2969 struct io_wait_queue iowq = {
2970 .wq = {
2971 .private = current,
2972 .func = io_wake_function,
2973 .entry = LIST_HEAD_INIT(iowq.wq.entry),
2974 },
2975 .ctx = ctx,
2976 .to_wait = min_events,
2977 };
75b28aff 2978 struct io_rings *rings = ctx->rings;
2b188cc1
JA
2979 int ret;
2980
75b28aff 2981 if (io_cqring_events(rings) >= min_events)
2b188cc1
JA
2982 return 0;
2983
2984 if (sig) {
9e75ad5d
AB
2985#ifdef CONFIG_COMPAT
2986 if (in_compat_syscall())
2987 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 2988 sigsz);
9e75ad5d
AB
2989 else
2990#endif
b772434b 2991 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 2992
2b188cc1
JA
2993 if (ret)
2994 return ret;
2995 }
2996
bda52162
JA
2997 ret = 0;
2998 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
c826bd7a 2999 trace_io_uring_cqring_wait(ctx, min_events);
bda52162
JA
3000 do {
3001 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3002 TASK_INTERRUPTIBLE);
3003 if (io_should_wake(&iowq))
3004 break;
3005 schedule();
3006 if (signal_pending(current)) {
3007 ret = -ERESTARTSYS;
3008 break;
3009 }
3010 } while (1);
3011 finish_wait(&ctx->wait, &iowq.wq);
3012
b772434b 3013 restore_saved_sigmask_unless(ret == -ERESTARTSYS);
97abc889
ON
3014 if (ret == -ERESTARTSYS)
3015 ret = -EINTR;
2b188cc1 3016
75b28aff 3017 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
3018}
3019
6b06314c
JA
3020static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3021{
3022#if defined(CONFIG_UNIX)
3023 if (ctx->ring_sock) {
3024 struct sock *sock = ctx->ring_sock->sk;
3025 struct sk_buff *skb;
3026
3027 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
3028 kfree_skb(skb);
3029 }
3030#else
3031 int i;
3032
65e19f54
JA
3033 for (i = 0; i < ctx->nr_user_files; i++) {
3034 struct file *file;
3035
3036 file = io_file_from_index(ctx, i);
3037 if (file)
3038 fput(file);
3039 }
6b06314c
JA
3040#endif
3041}
3042
3043static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3044{
65e19f54
JA
3045 unsigned nr_tables, i;
3046
3047 if (!ctx->file_table)
6b06314c
JA
3048 return -ENXIO;
3049
3050 __io_sqe_files_unregister(ctx);
65e19f54
JA
3051 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
3052 for (i = 0; i < nr_tables; i++)
3053 kfree(ctx->file_table[i].files);
3054 kfree(ctx->file_table);
3055 ctx->file_table = NULL;
6b06314c
JA
3056 ctx->nr_user_files = 0;
3057 return 0;
3058}
3059
6c271ce2
JA
3060static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3061{
3062 if (ctx->sqo_thread) {
a4c0b3de 3063 wait_for_completion(&ctx->sqo_thread_started);
2bbcd6d3
RP
3064 /*
3065 * The park is a bit of a work-around, without it we get
3066 * warning spews on shutdown with SQPOLL set and affinity
3067 * set to a single CPU.
3068 */
06058632 3069 kthread_park(ctx->sqo_thread);
6c271ce2
JA
3070 kthread_stop(ctx->sqo_thread);
3071 ctx->sqo_thread = NULL;
3072 }
3073}
3074
6b06314c
JA
3075static void io_finish_async(struct io_ring_ctx *ctx)
3076{
6c271ce2
JA
3077 io_sq_thread_stop(ctx);
3078
561fb04a
JA
3079 if (ctx->io_wq) {
3080 io_wq_destroy(ctx->io_wq);
3081 ctx->io_wq = NULL;
6b06314c
JA
3082 }
3083}
3084
3085#if defined(CONFIG_UNIX)
3086static void io_destruct_skb(struct sk_buff *skb)
3087{
3088 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
8a997340 3089
561fb04a
JA
3090 if (ctx->io_wq)
3091 io_wq_flush(ctx->io_wq);
6b06314c 3092
6b06314c
JA
3093 unix_destruct_scm(skb);
3094}
3095
3096/*
3097 * Ensure the UNIX gc is aware of our file set, so we are certain that
3098 * the io_uring can be safely unregistered on process exit, even if we have
3099 * loops in the file referencing.
3100 */
3101static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
3102{
3103 struct sock *sk = ctx->ring_sock->sk;
3104 struct scm_fp_list *fpl;
3105 struct sk_buff *skb;
08a45173 3106 int i, nr_files;
6b06314c
JA
3107
3108 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
3109 unsigned long inflight = ctx->user->unix_inflight + nr;
3110
3111 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
3112 return -EMFILE;
3113 }
3114
3115 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
3116 if (!fpl)
3117 return -ENOMEM;
3118
3119 skb = alloc_skb(0, GFP_KERNEL);
3120 if (!skb) {
3121 kfree(fpl);
3122 return -ENOMEM;
3123 }
3124
3125 skb->sk = sk;
6b06314c 3126
08a45173 3127 nr_files = 0;
6b06314c
JA
3128 fpl->user = get_uid(ctx->user);
3129 for (i = 0; i < nr; i++) {
65e19f54
JA
3130 struct file *file = io_file_from_index(ctx, i + offset);
3131
3132 if (!file)
08a45173 3133 continue;
65e19f54 3134 fpl->fp[nr_files] = get_file(file);
08a45173
JA
3135 unix_inflight(fpl->user, fpl->fp[nr_files]);
3136 nr_files++;
6b06314c
JA
3137 }
3138
08a45173
JA
3139 if (nr_files) {
3140 fpl->max = SCM_MAX_FD;
3141 fpl->count = nr_files;
3142 UNIXCB(skb).fp = fpl;
3143 skb->destructor = io_destruct_skb;
3144 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
3145 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 3146
08a45173
JA
3147 for (i = 0; i < nr_files; i++)
3148 fput(fpl->fp[i]);
3149 } else {
3150 kfree_skb(skb);
3151 kfree(fpl);
3152 }
6b06314c
JA
3153
3154 return 0;
3155}
3156
3157/*
3158 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
3159 * causes regular reference counting to break down. We rely on the UNIX
3160 * garbage collection to take care of this problem for us.
3161 */
3162static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3163{
3164 unsigned left, total;
3165 int ret = 0;
3166
3167 total = 0;
3168 left = ctx->nr_user_files;
3169 while (left) {
3170 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
3171
3172 ret = __io_sqe_files_scm(ctx, this_files, total);
3173 if (ret)
3174 break;
3175 left -= this_files;
3176 total += this_files;
3177 }
3178
3179 if (!ret)
3180 return 0;
3181
3182 while (total < ctx->nr_user_files) {
65e19f54
JA
3183 struct file *file = io_file_from_index(ctx, total);
3184
3185 if (file)
3186 fput(file);
6b06314c
JA
3187 total++;
3188 }
3189
3190 return ret;
3191}
3192#else
3193static int io_sqe_files_scm(struct io_ring_ctx *ctx)
3194{
3195 return 0;
3196}
3197#endif
3198
65e19f54
JA
3199static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
3200 unsigned nr_files)
3201{
3202 int i;
3203
3204 for (i = 0; i < nr_tables; i++) {
3205 struct fixed_file_table *table = &ctx->file_table[i];
3206 unsigned this_files;
3207
3208 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
3209 table->files = kcalloc(this_files, sizeof(struct file *),
3210 GFP_KERNEL);
3211 if (!table->files)
3212 break;
3213 nr_files -= this_files;
3214 }
3215
3216 if (i == nr_tables)
3217 return 0;
3218
3219 for (i = 0; i < nr_tables; i++) {
3220 struct fixed_file_table *table = &ctx->file_table[i];
3221 kfree(table->files);
3222 }
3223 return 1;
3224}
3225
6b06314c
JA
3226static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3227 unsigned nr_args)
3228{
3229 __s32 __user *fds = (__s32 __user *) arg;
65e19f54 3230 unsigned nr_tables;
6b06314c
JA
3231 int fd, ret = 0;
3232 unsigned i;
3233
65e19f54 3234 if (ctx->file_table)
6b06314c
JA
3235 return -EBUSY;
3236 if (!nr_args)
3237 return -EINVAL;
3238 if (nr_args > IORING_MAX_FIXED_FILES)
3239 return -EMFILE;
3240
65e19f54
JA
3241 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
3242 ctx->file_table = kcalloc(nr_tables, sizeof(struct fixed_file_table),
3243 GFP_KERNEL);
3244 if (!ctx->file_table)
6b06314c
JA
3245 return -ENOMEM;
3246
65e19f54
JA
3247 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
3248 kfree(ctx->file_table);
3249 return -ENOMEM;
3250 }
3251
08a45173 3252 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
65e19f54
JA
3253 struct fixed_file_table *table;
3254 unsigned index;
3255
6b06314c
JA
3256 ret = -EFAULT;
3257 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3258 break;
08a45173
JA
3259 /* allow sparse sets */
3260 if (fd == -1) {
3261 ret = 0;
3262 continue;
3263 }
6b06314c 3264
65e19f54
JA
3265 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3266 index = i & IORING_FILE_TABLE_MASK;
3267 table->files[index] = fget(fd);
6b06314c
JA
3268
3269 ret = -EBADF;
65e19f54 3270 if (!table->files[index])
6b06314c
JA
3271 break;
3272 /*
3273 * Don't allow io_uring instances to be registered. If UNIX
3274 * isn't enabled, then this causes a reference cycle and this
3275 * instance can never get freed. If UNIX is enabled we'll
3276 * handle it just fine, but there's still no point in allowing
3277 * a ring fd as it doesn't support regular read/write anyway.
3278 */
65e19f54
JA
3279 if (table->files[index]->f_op == &io_uring_fops) {
3280 fput(table->files[index]);
6b06314c
JA
3281 break;
3282 }
6b06314c
JA
3283 ret = 0;
3284 }
3285
3286 if (ret) {
65e19f54
JA
3287 for (i = 0; i < ctx->nr_user_files; i++) {
3288 struct file *file;
6b06314c 3289
65e19f54
JA
3290 file = io_file_from_index(ctx, i);
3291 if (file)
3292 fput(file);
3293 }
3294 for (i = 0; i < nr_tables; i++)
3295 kfree(ctx->file_table[i].files);
3296
3297 kfree(ctx->file_table);
3298 ctx->file_table = NULL;
6b06314c
JA
3299 ctx->nr_user_files = 0;
3300 return ret;
3301 }
3302
3303 ret = io_sqe_files_scm(ctx);
3304 if (ret)
3305 io_sqe_files_unregister(ctx);
3306
3307 return ret;
3308}
3309
c3a31e60
JA
3310static void io_sqe_file_unregister(struct io_ring_ctx *ctx, int index)
3311{
3312#if defined(CONFIG_UNIX)
65e19f54 3313 struct file *file = io_file_from_index(ctx, index);
c3a31e60
JA
3314 struct sock *sock = ctx->ring_sock->sk;
3315 struct sk_buff_head list, *head = &sock->sk_receive_queue;
3316 struct sk_buff *skb;
3317 int i;
3318
3319 __skb_queue_head_init(&list);
3320
3321 /*
3322 * Find the skb that holds this file in its SCM_RIGHTS. When found,
3323 * remove this entry and rearrange the file array.
3324 */
3325 skb = skb_dequeue(head);
3326 while (skb) {
3327 struct scm_fp_list *fp;
3328
3329 fp = UNIXCB(skb).fp;
3330 for (i = 0; i < fp->count; i++) {
3331 int left;
3332
3333 if (fp->fp[i] != file)
3334 continue;
3335
3336 unix_notinflight(fp->user, fp->fp[i]);
3337 left = fp->count - 1 - i;
3338 if (left) {
3339 memmove(&fp->fp[i], &fp->fp[i + 1],
3340 left * sizeof(struct file *));
3341 }
3342 fp->count--;
3343 if (!fp->count) {
3344 kfree_skb(skb);
3345 skb = NULL;
3346 } else {
3347 __skb_queue_tail(&list, skb);
3348 }
3349 fput(file);
3350 file = NULL;
3351 break;
3352 }
3353
3354 if (!file)
3355 break;
3356
3357 __skb_queue_tail(&list, skb);
3358
3359 skb = skb_dequeue(head);
3360 }
3361
3362 if (skb_peek(&list)) {
3363 spin_lock_irq(&head->lock);
3364 while ((skb = __skb_dequeue(&list)) != NULL)
3365 __skb_queue_tail(head, skb);
3366 spin_unlock_irq(&head->lock);
3367 }
3368#else
65e19f54 3369 fput(io_file_from_index(ctx, index));
c3a31e60
JA
3370#endif
3371}
3372
3373static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
3374 int index)
3375{
3376#if defined(CONFIG_UNIX)
3377 struct sock *sock = ctx->ring_sock->sk;
3378 struct sk_buff_head *head = &sock->sk_receive_queue;
3379 struct sk_buff *skb;
3380
3381 /*
3382 * See if we can merge this file into an existing skb SCM_RIGHTS
3383 * file set. If there's no room, fall back to allocating a new skb
3384 * and filling it in.
3385 */
3386 spin_lock_irq(&head->lock);
3387 skb = skb_peek(head);
3388 if (skb) {
3389 struct scm_fp_list *fpl = UNIXCB(skb).fp;
3390
3391 if (fpl->count < SCM_MAX_FD) {
3392 __skb_unlink(skb, head);
3393 spin_unlock_irq(&head->lock);
3394 fpl->fp[fpl->count] = get_file(file);
3395 unix_inflight(fpl->user, fpl->fp[fpl->count]);
3396 fpl->count++;
3397 spin_lock_irq(&head->lock);
3398 __skb_queue_head(head, skb);
3399 } else {
3400 skb = NULL;
3401 }
3402 }
3403 spin_unlock_irq(&head->lock);
3404
3405 if (skb) {
3406 fput(file);
3407 return 0;
3408 }
3409
3410 return __io_sqe_files_scm(ctx, 1, index);
3411#else
3412 return 0;
3413#endif
3414}
3415
3416static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
3417 unsigned nr_args)
3418{
3419 struct io_uring_files_update up;
3420 __s32 __user *fds;
3421 int fd, i, err;
3422 __u32 done;
3423
65e19f54 3424 if (!ctx->file_table)
c3a31e60
JA
3425 return -ENXIO;
3426 if (!nr_args)
3427 return -EINVAL;
3428 if (copy_from_user(&up, arg, sizeof(up)))
3429 return -EFAULT;
3430 if (check_add_overflow(up.offset, nr_args, &done))
3431 return -EOVERFLOW;
3432 if (done > ctx->nr_user_files)
3433 return -EINVAL;
3434
3435 done = 0;
3436 fds = (__s32 __user *) up.fds;
3437 while (nr_args) {
65e19f54
JA
3438 struct fixed_file_table *table;
3439 unsigned index;
3440
c3a31e60
JA
3441 err = 0;
3442 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3443 err = -EFAULT;
3444 break;
3445 }
3446 i = array_index_nospec(up.offset, ctx->nr_user_files);
65e19f54
JA
3447 table = &ctx->file_table[i >> IORING_FILE_TABLE_SHIFT];
3448 index = i & IORING_FILE_TABLE_MASK;
3449 if (table->files[index]) {
c3a31e60 3450 io_sqe_file_unregister(ctx, i);
65e19f54 3451 table->files[index] = NULL;
c3a31e60
JA
3452 }
3453 if (fd != -1) {
3454 struct file *file;
3455
3456 file = fget(fd);
3457 if (!file) {
3458 err = -EBADF;
3459 break;
3460 }
3461 /*
3462 * Don't allow io_uring instances to be registered. If
3463 * UNIX isn't enabled, then this causes a reference
3464 * cycle and this instance can never get freed. If UNIX
3465 * is enabled we'll handle it just fine, but there's
3466 * still no point in allowing a ring fd as it doesn't
3467 * support regular read/write anyway.
3468 */
3469 if (file->f_op == &io_uring_fops) {
3470 fput(file);
3471 err = -EBADF;
3472 break;
3473 }
65e19f54 3474 table->files[index] = file;
c3a31e60
JA
3475 err = io_sqe_file_register(ctx, file, i);
3476 if (err)
3477 break;
3478 }
3479 nr_args--;
3480 done++;
3481 up.offset++;
3482 }
3483
3484 return done ? done : err;
3485}
3486
6c271ce2
JA
3487static int io_sq_offload_start(struct io_ring_ctx *ctx,
3488 struct io_uring_params *p)
2b188cc1 3489{
561fb04a 3490 unsigned concurrency;
2b188cc1
JA
3491 int ret;
3492
6c271ce2 3493 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
3494 mmgrab(current->mm);
3495 ctx->sqo_mm = current->mm;
3496
6c271ce2 3497 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
3498 ret = -EPERM;
3499 if (!capable(CAP_SYS_ADMIN))
3500 goto err;
3501
917257da
JA
3502 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3503 if (!ctx->sq_thread_idle)
3504 ctx->sq_thread_idle = HZ;
3505
6c271ce2 3506 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 3507 int cpu = p->sq_thread_cpu;
6c271ce2 3508
917257da 3509 ret = -EINVAL;
44a9bd18
JA
3510 if (cpu >= nr_cpu_ids)
3511 goto err;
7889f44d 3512 if (!cpu_online(cpu))
917257da
JA
3513 goto err;
3514
6c271ce2
JA
3515 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3516 ctx, cpu,
3517 "io_uring-sq");
3518 } else {
3519 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3520 "io_uring-sq");
3521 }
3522 if (IS_ERR(ctx->sqo_thread)) {
3523 ret = PTR_ERR(ctx->sqo_thread);
3524 ctx->sqo_thread = NULL;
3525 goto err;
3526 }
3527 wake_up_process(ctx->sqo_thread);
3528 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3529 /* Can't have SQ_AFF without SQPOLL */
3530 ret = -EINVAL;
3531 goto err;
3532 }
3533
561fb04a
JA
3534 /* Do QD, or 4 * CPUS, whatever is smallest */
3535 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
3536 ctx->io_wq = io_wq_create(concurrency, ctx->sqo_mm);
975c99a5
JA
3537 if (IS_ERR(ctx->io_wq)) {
3538 ret = PTR_ERR(ctx->io_wq);
3539 ctx->io_wq = NULL;
2b188cc1
JA
3540 goto err;
3541 }
3542
3543 return 0;
3544err:
54a91f3b 3545 io_finish_async(ctx);
2b188cc1
JA
3546 mmdrop(ctx->sqo_mm);
3547 ctx->sqo_mm = NULL;
3548 return ret;
3549}
3550
3551static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3552{
3553 atomic_long_sub(nr_pages, &user->locked_vm);
3554}
3555
3556static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3557{
3558 unsigned long page_limit, cur_pages, new_pages;
3559
3560 /* Don't allow more pages than we can safely lock */
3561 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3562
3563 do {
3564 cur_pages = atomic_long_read(&user->locked_vm);
3565 new_pages = cur_pages + nr_pages;
3566 if (new_pages > page_limit)
3567 return -ENOMEM;
3568 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3569 new_pages) != cur_pages);
3570
3571 return 0;
3572}
3573
3574static void io_mem_free(void *ptr)
3575{
52e04ef4
MR
3576 struct page *page;
3577
3578 if (!ptr)
3579 return;
2b188cc1 3580
52e04ef4 3581 page = virt_to_head_page(ptr);
2b188cc1
JA
3582 if (put_page_testzero(page))
3583 free_compound_page(page);
3584}
3585
3586static void *io_mem_alloc(size_t size)
3587{
3588 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3589 __GFP_NORETRY;
3590
3591 return (void *) __get_free_pages(gfp_flags, get_order(size));
3592}
3593
75b28aff
HV
3594static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3595 size_t *sq_offset)
3596{
3597 struct io_rings *rings;
3598 size_t off, sq_array_size;
3599
3600 off = struct_size(rings, cqes, cq_entries);
3601 if (off == SIZE_MAX)
3602 return SIZE_MAX;
3603
3604#ifdef CONFIG_SMP
3605 off = ALIGN(off, SMP_CACHE_BYTES);
3606 if (off == 0)
3607 return SIZE_MAX;
3608#endif
3609
3610 sq_array_size = array_size(sizeof(u32), sq_entries);
3611 if (sq_array_size == SIZE_MAX)
3612 return SIZE_MAX;
3613
3614 if (check_add_overflow(off, sq_array_size, &off))
3615 return SIZE_MAX;
3616
3617 if (sq_offset)
3618 *sq_offset = off;
3619
3620 return off;
3621}
3622
2b188cc1
JA
3623static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3624{
75b28aff 3625 size_t pages;
2b188cc1 3626
75b28aff
HV
3627 pages = (size_t)1 << get_order(
3628 rings_size(sq_entries, cq_entries, NULL));
3629 pages += (size_t)1 << get_order(
3630 array_size(sizeof(struct io_uring_sqe), sq_entries));
2b188cc1 3631
75b28aff 3632 return pages;
2b188cc1
JA
3633}
3634
edafccee
JA
3635static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3636{
3637 int i, j;
3638
3639 if (!ctx->user_bufs)
3640 return -ENXIO;
3641
3642 for (i = 0; i < ctx->nr_user_bufs; i++) {
3643 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3644
3645 for (j = 0; j < imu->nr_bvecs; j++)
27c4d3a3 3646 put_user_page(imu->bvec[j].bv_page);
edafccee
JA
3647
3648 if (ctx->account_mem)
3649 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 3650 kvfree(imu->bvec);
edafccee
JA
3651 imu->nr_bvecs = 0;
3652 }
3653
3654 kfree(ctx->user_bufs);
3655 ctx->user_bufs = NULL;
3656 ctx->nr_user_bufs = 0;
3657 return 0;
3658}
3659
3660static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3661 void __user *arg, unsigned index)
3662{
3663 struct iovec __user *src;
3664
3665#ifdef CONFIG_COMPAT
3666 if (ctx->compat) {
3667 struct compat_iovec __user *ciovs;
3668 struct compat_iovec ciov;
3669
3670 ciovs = (struct compat_iovec __user *) arg;
3671 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3672 return -EFAULT;
3673
3674 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3675 dst->iov_len = ciov.iov_len;
3676 return 0;
3677 }
3678#endif
3679 src = (struct iovec __user *) arg;
3680 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3681 return -EFAULT;
3682 return 0;
3683}
3684
3685static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3686 unsigned nr_args)
3687{
3688 struct vm_area_struct **vmas = NULL;
3689 struct page **pages = NULL;
3690 int i, j, got_pages = 0;
3691 int ret = -EINVAL;
3692
3693 if (ctx->user_bufs)
3694 return -EBUSY;
3695 if (!nr_args || nr_args > UIO_MAXIOV)
3696 return -EINVAL;
3697
3698 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3699 GFP_KERNEL);
3700 if (!ctx->user_bufs)
3701 return -ENOMEM;
3702
3703 for (i = 0; i < nr_args; i++) {
3704 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3705 unsigned long off, start, end, ubuf;
3706 int pret, nr_pages;
3707 struct iovec iov;
3708 size_t size;
3709
3710 ret = io_copy_iov(ctx, &iov, arg, i);
3711 if (ret)
a278682d 3712 goto err;
edafccee
JA
3713
3714 /*
3715 * Don't impose further limits on the size and buffer
3716 * constraints here, we'll -EINVAL later when IO is
3717 * submitted if they are wrong.
3718 */
3719 ret = -EFAULT;
3720 if (!iov.iov_base || !iov.iov_len)
3721 goto err;
3722
3723 /* arbitrary limit, but we need something */
3724 if (iov.iov_len > SZ_1G)
3725 goto err;
3726
3727 ubuf = (unsigned long) iov.iov_base;
3728 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3729 start = ubuf >> PAGE_SHIFT;
3730 nr_pages = end - start;
3731
3732 if (ctx->account_mem) {
3733 ret = io_account_mem(ctx->user, nr_pages);
3734 if (ret)
3735 goto err;
3736 }
3737
3738 ret = 0;
3739 if (!pages || nr_pages > got_pages) {
3740 kfree(vmas);
3741 kfree(pages);
d4ef6475 3742 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 3743 GFP_KERNEL);
d4ef6475 3744 vmas = kvmalloc_array(nr_pages,
edafccee
JA
3745 sizeof(struct vm_area_struct *),
3746 GFP_KERNEL);
3747 if (!pages || !vmas) {
3748 ret = -ENOMEM;
3749 if (ctx->account_mem)
3750 io_unaccount_mem(ctx->user, nr_pages);
3751 goto err;
3752 }
3753 got_pages = nr_pages;
3754 }
3755
d4ef6475 3756 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
3757 GFP_KERNEL);
3758 ret = -ENOMEM;
3759 if (!imu->bvec) {
3760 if (ctx->account_mem)
3761 io_unaccount_mem(ctx->user, nr_pages);
3762 goto err;
3763 }
3764
3765 ret = 0;
3766 down_read(&current->mm->mmap_sem);
932f4a63
IW
3767 pret = get_user_pages(ubuf, nr_pages,
3768 FOLL_WRITE | FOLL_LONGTERM,
3769 pages, vmas);
edafccee
JA
3770 if (pret == nr_pages) {
3771 /* don't support file backed memory */
3772 for (j = 0; j < nr_pages; j++) {
3773 struct vm_area_struct *vma = vmas[j];
3774
3775 if (vma->vm_file &&
3776 !is_file_hugepages(vma->vm_file)) {
3777 ret = -EOPNOTSUPP;
3778 break;
3779 }
3780 }
3781 } else {
3782 ret = pret < 0 ? pret : -EFAULT;
3783 }
3784 up_read(&current->mm->mmap_sem);
3785 if (ret) {
3786 /*
3787 * if we did partial map, or found file backed vmas,
3788 * release any pages we did get
3789 */
27c4d3a3
JH
3790 if (pret > 0)
3791 put_user_pages(pages, pret);
edafccee
JA
3792 if (ctx->account_mem)
3793 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 3794 kvfree(imu->bvec);
edafccee
JA
3795 goto err;
3796 }
3797
3798 off = ubuf & ~PAGE_MASK;
3799 size = iov.iov_len;
3800 for (j = 0; j < nr_pages; j++) {
3801 size_t vec_len;
3802
3803 vec_len = min_t(size_t, size, PAGE_SIZE - off);
3804 imu->bvec[j].bv_page = pages[j];
3805 imu->bvec[j].bv_len = vec_len;
3806 imu->bvec[j].bv_offset = off;
3807 off = 0;
3808 size -= vec_len;
3809 }
3810 /* store original address for later verification */
3811 imu->ubuf = ubuf;
3812 imu->len = iov.iov_len;
3813 imu->nr_bvecs = nr_pages;
3814
3815 ctx->nr_user_bufs++;
3816 }
d4ef6475
MR
3817 kvfree(pages);
3818 kvfree(vmas);
edafccee
JA
3819 return 0;
3820err:
d4ef6475
MR
3821 kvfree(pages);
3822 kvfree(vmas);
edafccee
JA
3823 io_sqe_buffer_unregister(ctx);
3824 return ret;
3825}
3826
9b402849
JA
3827static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
3828{
3829 __s32 __user *fds = arg;
3830 int fd;
3831
3832 if (ctx->cq_ev_fd)
3833 return -EBUSY;
3834
3835 if (copy_from_user(&fd, fds, sizeof(*fds)))
3836 return -EFAULT;
3837
3838 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
3839 if (IS_ERR(ctx->cq_ev_fd)) {
3840 int ret = PTR_ERR(ctx->cq_ev_fd);
3841 ctx->cq_ev_fd = NULL;
3842 return ret;
3843 }
3844
3845 return 0;
3846}
3847
3848static int io_eventfd_unregister(struct io_ring_ctx *ctx)
3849{
3850 if (ctx->cq_ev_fd) {
3851 eventfd_ctx_put(ctx->cq_ev_fd);
3852 ctx->cq_ev_fd = NULL;
3853 return 0;
3854 }
3855
3856 return -ENXIO;
3857}
3858
2b188cc1
JA
3859static void io_ring_ctx_free(struct io_ring_ctx *ctx)
3860{
6b06314c 3861 io_finish_async(ctx);
2b188cc1
JA
3862 if (ctx->sqo_mm)
3863 mmdrop(ctx->sqo_mm);
def596e9
JA
3864
3865 io_iopoll_reap_events(ctx);
edafccee 3866 io_sqe_buffer_unregister(ctx);
6b06314c 3867 io_sqe_files_unregister(ctx);
9b402849 3868 io_eventfd_unregister(ctx);
def596e9 3869
2b188cc1 3870#if defined(CONFIG_UNIX)
355e8d26
EB
3871 if (ctx->ring_sock) {
3872 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 3873 sock_release(ctx->ring_sock);
355e8d26 3874 }
2b188cc1
JA
3875#endif
3876
75b28aff 3877 io_mem_free(ctx->rings);
2b188cc1 3878 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
3879
3880 percpu_ref_exit(&ctx->refs);
3881 if (ctx->account_mem)
3882 io_unaccount_mem(ctx->user,
3883 ring_pages(ctx->sq_entries, ctx->cq_entries));
3884 free_uid(ctx->user);
3885 kfree(ctx);
3886}
3887
3888static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3889{
3890 struct io_ring_ctx *ctx = file->private_data;
3891 __poll_t mask = 0;
3892
3893 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
3894 /*
3895 * synchronizes with barrier from wq_has_sleeper call in
3896 * io_commit_cqring
3897 */
2b188cc1 3898 smp_rmb();
75b28aff
HV
3899 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
3900 ctx->rings->sq_ring_entries)
2b188cc1 3901 mask |= EPOLLOUT | EPOLLWRNORM;
daa5de54 3902 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
2b188cc1
JA
3903 mask |= EPOLLIN | EPOLLRDNORM;
3904
3905 return mask;
3906}
3907
3908static int io_uring_fasync(int fd, struct file *file, int on)
3909{
3910 struct io_ring_ctx *ctx = file->private_data;
3911
3912 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3913}
3914
3915static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3916{
3917 mutex_lock(&ctx->uring_lock);
3918 percpu_ref_kill(&ctx->refs);
3919 mutex_unlock(&ctx->uring_lock);
3920
5262f567 3921 io_kill_timeouts(ctx);
221c5eb2 3922 io_poll_remove_all(ctx);
561fb04a
JA
3923
3924 if (ctx->io_wq)
3925 io_wq_cancel_all(ctx->io_wq);
3926
def596e9 3927 io_iopoll_reap_events(ctx);
2b188cc1
JA
3928 wait_for_completion(&ctx->ctx_done);
3929 io_ring_ctx_free(ctx);
3930}
3931
3932static int io_uring_release(struct inode *inode, struct file *file)
3933{
3934 struct io_ring_ctx *ctx = file->private_data;
3935
3936 file->private_data = NULL;
3937 io_ring_ctx_wait_and_kill(ctx);
3938 return 0;
3939}
3940
fcb323cc
JA
3941static void io_uring_cancel_files(struct io_ring_ctx *ctx,
3942 struct files_struct *files)
3943{
3944 struct io_kiocb *req;
3945 DEFINE_WAIT(wait);
3946
3947 while (!list_empty_careful(&ctx->inflight_list)) {
3948 enum io_wq_cancel ret = IO_WQ_CANCEL_NOTFOUND;
3949
3950 spin_lock_irq(&ctx->inflight_lock);
3951 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
3952 if (req->work.files == files) {
3953 ret = io_wq_cancel_work(ctx->io_wq, &req->work);
3954 break;
3955 }
3956 }
3957 if (ret == IO_WQ_CANCEL_RUNNING)
3958 prepare_to_wait(&ctx->inflight_wait, &wait,
3959 TASK_UNINTERRUPTIBLE);
3960
3961 spin_unlock_irq(&ctx->inflight_lock);
3962
3963 /*
3964 * We need to keep going until we get NOTFOUND. We only cancel
3965 * one work at the time.
3966 *
3967 * If we get CANCEL_RUNNING, then wait for a work to complete
3968 * before continuing.
3969 */
3970 if (ret == IO_WQ_CANCEL_OK)
3971 continue;
3972 else if (ret != IO_WQ_CANCEL_RUNNING)
3973 break;
3974 schedule();
3975 }
3976}
3977
3978static int io_uring_flush(struct file *file, void *data)
3979{
3980 struct io_ring_ctx *ctx = file->private_data;
3981
3982 io_uring_cancel_files(ctx, data);
3983 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
3984 io_wq_cancel_all(ctx->io_wq);
3985 return 0;
3986}
3987
2b188cc1
JA
3988static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3989{
3990 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3991 unsigned long sz = vma->vm_end - vma->vm_start;
3992 struct io_ring_ctx *ctx = file->private_data;
3993 unsigned long pfn;
3994 struct page *page;
3995 void *ptr;
3996
3997 switch (offset) {
3998 case IORING_OFF_SQ_RING:
75b28aff
HV
3999 case IORING_OFF_CQ_RING:
4000 ptr = ctx->rings;
2b188cc1
JA
4001 break;
4002 case IORING_OFF_SQES:
4003 ptr = ctx->sq_sqes;
4004 break;
2b188cc1
JA
4005 default:
4006 return -EINVAL;
4007 }
4008
4009 page = virt_to_head_page(ptr);
a50b854e 4010 if (sz > page_size(page))
2b188cc1
JA
4011 return -EINVAL;
4012
4013 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
4014 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
4015}
4016
4017SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
4018 u32, min_complete, u32, flags, const sigset_t __user *, sig,
4019 size_t, sigsz)
4020{
4021 struct io_ring_ctx *ctx;
4022 long ret = -EBADF;
4023 int submitted = 0;
4024 struct fd f;
4025
6c271ce2 4026 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
4027 return -EINVAL;
4028
4029 f = fdget(fd);
4030 if (!f.file)
4031 return -EBADF;
4032
4033 ret = -EOPNOTSUPP;
4034 if (f.file->f_op != &io_uring_fops)
4035 goto out_fput;
4036
4037 ret = -ENXIO;
4038 ctx = f.file->private_data;
4039 if (!percpu_ref_tryget(&ctx->refs))
4040 goto out_fput;
4041
6c271ce2
JA
4042 /*
4043 * For SQ polling, the thread will do all submissions and completions.
4044 * Just return the requested submit count, and wake the thread if
4045 * we were asked to.
4046 */
b2a9eada 4047 ret = 0;
6c271ce2
JA
4048 if (ctx->flags & IORING_SETUP_SQPOLL) {
4049 if (flags & IORING_ENTER_SQ_WAKEUP)
4050 wake_up(&ctx->sqo_wait);
4051 submitted = to_submit;
b2a9eada 4052 } else if (to_submit) {
2b188cc1
JA
4053 to_submit = min(to_submit, ctx->sq_entries);
4054
4055 mutex_lock(&ctx->uring_lock);
fcb323cc 4056 submitted = io_ring_submit(ctx, to_submit, f.file, fd);
2b188cc1 4057 mutex_unlock(&ctx->uring_lock);
2b188cc1
JA
4058 }
4059 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
4060 unsigned nr_events = 0;
4061
2b188cc1
JA
4062 min_complete = min(min_complete, ctx->cq_entries);
4063
def596e9 4064 if (ctx->flags & IORING_SETUP_IOPOLL) {
def596e9 4065 ret = io_iopoll_check(ctx, &nr_events, min_complete);
def596e9
JA
4066 } else {
4067 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
4068 }
2b188cc1
JA
4069 }
4070
6805b32e 4071 percpu_ref_put(&ctx->refs);
2b188cc1
JA
4072out_fput:
4073 fdput(f);
4074 return submitted ? submitted : ret;
4075}
4076
4077static const struct file_operations io_uring_fops = {
4078 .release = io_uring_release,
fcb323cc 4079 .flush = io_uring_flush,
2b188cc1
JA
4080 .mmap = io_uring_mmap,
4081 .poll = io_uring_poll,
4082 .fasync = io_uring_fasync,
4083};
4084
4085static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
4086 struct io_uring_params *p)
4087{
75b28aff
HV
4088 struct io_rings *rings;
4089 size_t size, sq_array_offset;
2b188cc1 4090
75b28aff
HV
4091 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
4092 if (size == SIZE_MAX)
4093 return -EOVERFLOW;
4094
4095 rings = io_mem_alloc(size);
4096 if (!rings)
2b188cc1
JA
4097 return -ENOMEM;
4098
75b28aff
HV
4099 ctx->rings = rings;
4100 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
4101 rings->sq_ring_mask = p->sq_entries - 1;
4102 rings->cq_ring_mask = p->cq_entries - 1;
4103 rings->sq_ring_entries = p->sq_entries;
4104 rings->cq_ring_entries = p->cq_entries;
4105 ctx->sq_mask = rings->sq_ring_mask;
4106 ctx->cq_mask = rings->cq_ring_mask;
4107 ctx->sq_entries = rings->sq_ring_entries;
4108 ctx->cq_entries = rings->cq_ring_entries;
2b188cc1
JA
4109
4110 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
4111 if (size == SIZE_MAX)
4112 return -EOVERFLOW;
4113
4114 ctx->sq_sqes = io_mem_alloc(size);
52e04ef4 4115 if (!ctx->sq_sqes)
2b188cc1 4116 return -ENOMEM;
2b188cc1 4117
2b188cc1
JA
4118 return 0;
4119}
4120
4121/*
4122 * Allocate an anonymous fd, this is what constitutes the application
4123 * visible backing of an io_uring instance. The application mmaps this
4124 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
4125 * we have to tie this fd to a socket for file garbage collection purposes.
4126 */
4127static int io_uring_get_fd(struct io_ring_ctx *ctx)
4128{
4129 struct file *file;
4130 int ret;
4131
4132#if defined(CONFIG_UNIX)
4133 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
4134 &ctx->ring_sock);
4135 if (ret)
4136 return ret;
4137#endif
4138
4139 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
4140 if (ret < 0)
4141 goto err;
4142
4143 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
4144 O_RDWR | O_CLOEXEC);
4145 if (IS_ERR(file)) {
4146 put_unused_fd(ret);
4147 ret = PTR_ERR(file);
4148 goto err;
4149 }
4150
4151#if defined(CONFIG_UNIX)
4152 ctx->ring_sock->file = file;
6b06314c 4153 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
4154#endif
4155 fd_install(ret, file);
4156 return ret;
4157err:
4158#if defined(CONFIG_UNIX)
4159 sock_release(ctx->ring_sock);
4160 ctx->ring_sock = NULL;
4161#endif
4162 return ret;
4163}
4164
4165static int io_uring_create(unsigned entries, struct io_uring_params *p)
4166{
4167 struct user_struct *user = NULL;
4168 struct io_ring_ctx *ctx;
4169 bool account_mem;
4170 int ret;
4171
4172 if (!entries || entries > IORING_MAX_ENTRIES)
4173 return -EINVAL;
4174
4175 /*
4176 * Use twice as many entries for the CQ ring. It's possible for the
4177 * application to drive a higher depth than the size of the SQ ring,
4178 * since the sqes are only used at submission time. This allows for
33a107f0
JA
4179 * some flexibility in overcommitting a bit. If the application has
4180 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
4181 * of CQ ring entries manually.
2b188cc1
JA
4182 */
4183 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
4184 if (p->flags & IORING_SETUP_CQSIZE) {
4185 /*
4186 * If IORING_SETUP_CQSIZE is set, we do the same roundup
4187 * to a power-of-two, if it isn't already. We do NOT impose
4188 * any cq vs sq ring sizing.
4189 */
4190 if (p->cq_entries < p->sq_entries || p->cq_entries > IORING_MAX_CQ_ENTRIES)
4191 return -EINVAL;
4192 p->cq_entries = roundup_pow_of_two(p->cq_entries);
4193 } else {
4194 p->cq_entries = 2 * p->sq_entries;
4195 }
2b188cc1
JA
4196
4197 user = get_uid(current_user());
4198 account_mem = !capable(CAP_IPC_LOCK);
4199
4200 if (account_mem) {
4201 ret = io_account_mem(user,
4202 ring_pages(p->sq_entries, p->cq_entries));
4203 if (ret) {
4204 free_uid(user);
4205 return ret;
4206 }
4207 }
4208
4209 ctx = io_ring_ctx_alloc(p);
4210 if (!ctx) {
4211 if (account_mem)
4212 io_unaccount_mem(user, ring_pages(p->sq_entries,
4213 p->cq_entries));
4214 free_uid(user);
4215 return -ENOMEM;
4216 }
4217 ctx->compat = in_compat_syscall();
4218 ctx->account_mem = account_mem;
4219 ctx->user = user;
4220
4221 ret = io_allocate_scq_urings(ctx, p);
4222 if (ret)
4223 goto err;
4224
6c271ce2 4225 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
4226 if (ret)
4227 goto err;
4228
2b188cc1 4229 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
4230 p->sq_off.head = offsetof(struct io_rings, sq.head);
4231 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4232 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4233 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4234 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4235 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4236 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
4237
4238 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
4239 p->cq_off.head = offsetof(struct io_rings, cq.head);
4240 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4241 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4242 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4243 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4244 p->cq_off.cqes = offsetof(struct io_rings, cqes);
ac90f249 4245
044c1ab3
JA
4246 /*
4247 * Install ring fd as the very last thing, so we don't risk someone
4248 * having closed it before we finish setup
4249 */
4250 ret = io_uring_get_fd(ctx);
4251 if (ret < 0)
4252 goto err;
4253
ac90f249 4254 p->features = IORING_FEAT_SINGLE_MMAP;
c826bd7a 4255 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
4256 return ret;
4257err:
4258 io_ring_ctx_wait_and_kill(ctx);
4259 return ret;
4260}
4261
4262/*
4263 * Sets up an aio uring context, and returns the fd. Applications asks for a
4264 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4265 * params structure passed in.
4266 */
4267static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4268{
4269 struct io_uring_params p;
4270 long ret;
4271 int i;
4272
4273 if (copy_from_user(&p, params, sizeof(p)))
4274 return -EFAULT;
4275 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4276 if (p.resv[i])
4277 return -EINVAL;
4278 }
4279
6c271ce2 4280 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
33a107f0 4281 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE))
2b188cc1
JA
4282 return -EINVAL;
4283
4284 ret = io_uring_create(entries, &p);
4285 if (ret < 0)
4286 return ret;
4287
4288 if (copy_to_user(params, &p, sizeof(p)))
4289 return -EFAULT;
4290
4291 return ret;
4292}
4293
4294SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4295 struct io_uring_params __user *, params)
4296{
4297 return io_uring_setup(entries, params);
4298}
4299
edafccee
JA
4300static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4301 void __user *arg, unsigned nr_args)
b19062a5
JA
4302 __releases(ctx->uring_lock)
4303 __acquires(ctx->uring_lock)
edafccee
JA
4304{
4305 int ret;
4306
35fa71a0
JA
4307 /*
4308 * We're inside the ring mutex, if the ref is already dying, then
4309 * someone else killed the ctx or is already going through
4310 * io_uring_register().
4311 */
4312 if (percpu_ref_is_dying(&ctx->refs))
4313 return -ENXIO;
4314
edafccee 4315 percpu_ref_kill(&ctx->refs);
b19062a5
JA
4316
4317 /*
4318 * Drop uring mutex before waiting for references to exit. If another
4319 * thread is currently inside io_uring_enter() it might need to grab
4320 * the uring_lock to make progress. If we hold it here across the drain
4321 * wait, then we can deadlock. It's safe to drop the mutex here, since
4322 * no new references will come in after we've killed the percpu ref.
4323 */
4324 mutex_unlock(&ctx->uring_lock);
edafccee 4325 wait_for_completion(&ctx->ctx_done);
b19062a5 4326 mutex_lock(&ctx->uring_lock);
edafccee
JA
4327
4328 switch (opcode) {
4329 case IORING_REGISTER_BUFFERS:
4330 ret = io_sqe_buffer_register(ctx, arg, nr_args);
4331 break;
4332 case IORING_UNREGISTER_BUFFERS:
4333 ret = -EINVAL;
4334 if (arg || nr_args)
4335 break;
4336 ret = io_sqe_buffer_unregister(ctx);
4337 break;
6b06314c
JA
4338 case IORING_REGISTER_FILES:
4339 ret = io_sqe_files_register(ctx, arg, nr_args);
4340 break;
4341 case IORING_UNREGISTER_FILES:
4342 ret = -EINVAL;
4343 if (arg || nr_args)
4344 break;
4345 ret = io_sqe_files_unregister(ctx);
4346 break;
c3a31e60
JA
4347 case IORING_REGISTER_FILES_UPDATE:
4348 ret = io_sqe_files_update(ctx, arg, nr_args);
4349 break;
9b402849
JA
4350 case IORING_REGISTER_EVENTFD:
4351 ret = -EINVAL;
4352 if (nr_args != 1)
4353 break;
4354 ret = io_eventfd_register(ctx, arg);
4355 break;
4356 case IORING_UNREGISTER_EVENTFD:
4357 ret = -EINVAL;
4358 if (arg || nr_args)
4359 break;
4360 ret = io_eventfd_unregister(ctx);
4361 break;
edafccee
JA
4362 default:
4363 ret = -EINVAL;
4364 break;
4365 }
4366
4367 /* bring the ctx back to life */
4368 reinit_completion(&ctx->ctx_done);
4369 percpu_ref_reinit(&ctx->refs);
4370 return ret;
4371}
4372
4373SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4374 void __user *, arg, unsigned int, nr_args)
4375{
4376 struct io_ring_ctx *ctx;
4377 long ret = -EBADF;
4378 struct fd f;
4379
4380 f = fdget(fd);
4381 if (!f.file)
4382 return -EBADF;
4383
4384 ret = -EOPNOTSUPP;
4385 if (f.file->f_op != &io_uring_fops)
4386 goto out_fput;
4387
4388 ctx = f.file->private_data;
4389
4390 mutex_lock(&ctx->uring_lock);
4391 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4392 mutex_unlock(&ctx->uring_lock);
c826bd7a
DD
4393 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
4394 ctx->cq_ev_fd != NULL, ret);
edafccee
JA
4395out_fput:
4396 fdput(f);
4397 return ret;
4398}
4399
2b188cc1
JA
4400static int __init io_uring_init(void)
4401{
4402 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4403 return 0;
4404};
4405__initcall(io_uring_init);