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