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