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