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