]> git.ipfire.org Git - thirdparty/linux.git/blame - fs/io_uring.c
fs: add sync_file_range() helper
[thirdparty/linux.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
221c5eb2
JA
1270static void io_poll_remove_one(struct io_kiocb *req)
1271{
1272 struct io_poll_iocb *poll = &req->poll;
1273
1274 spin_lock(&poll->head->lock);
1275 WRITE_ONCE(poll->canceled, true);
1276 if (!list_empty(&poll->wait.entry)) {
1277 list_del_init(&poll->wait.entry);
1278 queue_work(req->ctx->sqo_wq, &req->work);
1279 }
1280 spin_unlock(&poll->head->lock);
1281
1282 list_del_init(&req->list);
1283}
1284
1285static void io_poll_remove_all(struct io_ring_ctx *ctx)
1286{
1287 struct io_kiocb *req;
1288
1289 spin_lock_irq(&ctx->completion_lock);
1290 while (!list_empty(&ctx->cancel_list)) {
1291 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1292 io_poll_remove_one(req);
1293 }
1294 spin_unlock_irq(&ctx->completion_lock);
1295}
1296
1297/*
1298 * Find a running poll command that matches one specified in sqe->addr,
1299 * and remove it if found.
1300 */
1301static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1302{
1303 struct io_ring_ctx *ctx = req->ctx;
1304 struct io_kiocb *poll_req, *next;
1305 int ret = -ENOENT;
1306
1307 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1308 return -EINVAL;
1309 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1310 sqe->poll_events)
1311 return -EINVAL;
1312
1313 spin_lock_irq(&ctx->completion_lock);
1314 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1315 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1316 io_poll_remove_one(poll_req);
1317 ret = 0;
1318 break;
1319 }
1320 }
1321 spin_unlock_irq(&ctx->completion_lock);
1322
1323 io_cqring_add_event(req->ctx, sqe->user_data, ret, 0);
e65ef56d 1324 io_put_req(req);
221c5eb2
JA
1325 return 0;
1326}
1327
8c838788
JA
1328static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1329 __poll_t mask)
221c5eb2 1330{
8c838788
JA
1331 req->poll.done = true;
1332 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask), 0);
1333 io_commit_cqring(ctx);
221c5eb2
JA
1334}
1335
1336static void io_poll_complete_work(struct work_struct *work)
1337{
1338 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1339 struct io_poll_iocb *poll = &req->poll;
1340 struct poll_table_struct pt = { ._key = poll->events };
1341 struct io_ring_ctx *ctx = req->ctx;
1342 __poll_t mask = 0;
1343
1344 if (!READ_ONCE(poll->canceled))
1345 mask = vfs_poll(poll->file, &pt) & poll->events;
1346
1347 /*
1348 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1349 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1350 * synchronize with them. In the cancellation case the list_del_init
1351 * itself is not actually needed, but harmless so we keep it in to
1352 * avoid further branches in the fast path.
1353 */
1354 spin_lock_irq(&ctx->completion_lock);
1355 if (!mask && !READ_ONCE(poll->canceled)) {
1356 add_wait_queue(poll->head, &poll->wait);
1357 spin_unlock_irq(&ctx->completion_lock);
1358 return;
1359 }
1360 list_del_init(&req->list);
8c838788 1361 io_poll_complete(ctx, req, mask);
221c5eb2
JA
1362 spin_unlock_irq(&ctx->completion_lock);
1363
8c838788
JA
1364 io_cqring_ev_posted(ctx);
1365 io_put_req(req);
221c5eb2
JA
1366}
1367
1368static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1369 void *key)
1370{
1371 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1372 wait);
1373 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1374 struct io_ring_ctx *ctx = req->ctx;
1375 __poll_t mask = key_to_poll(key);
8c838788 1376 unsigned long flags;
221c5eb2
JA
1377
1378 /* for instances that support it check for an event match first: */
8c838788
JA
1379 if (mask && !(mask & poll->events))
1380 return 0;
221c5eb2 1381
8c838788 1382 list_del_init(&poll->wait.entry);
221c5eb2 1383
8c838788
JA
1384 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1385 list_del(&req->list);
1386 io_poll_complete(ctx, req, mask);
1387 spin_unlock_irqrestore(&ctx->completion_lock, flags);
221c5eb2 1388
8c838788
JA
1389 io_cqring_ev_posted(ctx);
1390 io_put_req(req);
1391 } else {
1392 queue_work(ctx->sqo_wq, &req->work);
221c5eb2
JA
1393 }
1394
221c5eb2
JA
1395 return 1;
1396}
1397
1398struct io_poll_table {
1399 struct poll_table_struct pt;
1400 struct io_kiocb *req;
1401 int error;
1402};
1403
1404static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1405 struct poll_table_struct *p)
1406{
1407 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1408
1409 if (unlikely(pt->req->poll.head)) {
1410 pt->error = -EINVAL;
1411 return;
1412 }
1413
1414 pt->error = 0;
1415 pt->req->poll.head = head;
1416 add_wait_queue(head, &pt->req->poll.wait);
1417}
1418
1419static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1420{
1421 struct io_poll_iocb *poll = &req->poll;
1422 struct io_ring_ctx *ctx = req->ctx;
1423 struct io_poll_table ipt;
8c838788 1424 bool cancel = false;
221c5eb2
JA
1425 __poll_t mask;
1426 u16 events;
221c5eb2
JA
1427
1428 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1429 return -EINVAL;
1430 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1431 return -EINVAL;
09bb8394
JA
1432 if (!poll->file)
1433 return -EBADF;
221c5eb2
JA
1434
1435 INIT_WORK(&req->work, io_poll_complete_work);
1436 events = READ_ONCE(sqe->poll_events);
1437 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1438
221c5eb2 1439 poll->head = NULL;
8c838788 1440 poll->done = false;
221c5eb2
JA
1441 poll->canceled = false;
1442
1443 ipt.pt._qproc = io_poll_queue_proc;
1444 ipt.pt._key = poll->events;
1445 ipt.req = req;
1446 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1447
1448 /* initialized the list so that we can do list_empty checks */
1449 INIT_LIST_HEAD(&poll->wait.entry);
1450 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1451
221c5eb2 1452 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
221c5eb2
JA
1453
1454 spin_lock_irq(&ctx->completion_lock);
8c838788
JA
1455 if (likely(poll->head)) {
1456 spin_lock(&poll->head->lock);
1457 if (unlikely(list_empty(&poll->wait.entry))) {
1458 if (ipt.error)
1459 cancel = true;
1460 ipt.error = 0;
1461 mask = 0;
1462 }
1463 if (mask || ipt.error)
1464 list_del_init(&poll->wait.entry);
1465 else if (cancel)
1466 WRITE_ONCE(poll->canceled, true);
1467 else if (!poll->done) /* actually waiting for an event */
1468 list_add_tail(&req->list, &ctx->cancel_list);
1469 spin_unlock(&poll->head->lock);
1470 }
1471 if (mask) { /* no async, we'd stolen it */
1472 req->error = mangle_poll(mask);
221c5eb2 1473 ipt.error = 0;
8c838788 1474 io_poll_complete(ctx, req, mask);
221c5eb2 1475 }
221c5eb2
JA
1476 spin_unlock_irq(&ctx->completion_lock);
1477
8c838788
JA
1478 if (mask) {
1479 io_cqring_ev_posted(ctx);
e65ef56d 1480 io_put_req(req);
221c5eb2 1481 }
8c838788 1482 return ipt.error;
221c5eb2
JA
1483}
1484
de0617e4
JA
1485static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
1486 const struct io_uring_sqe *sqe)
1487{
1488 struct io_uring_sqe *sqe_copy;
1489
1490 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
1491 return 0;
1492
1493 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1494 if (!sqe_copy)
1495 return -EAGAIN;
1496
1497 spin_lock_irq(&ctx->completion_lock);
1498 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
1499 spin_unlock_irq(&ctx->completion_lock);
1500 kfree(sqe_copy);
1501 return 0;
1502 }
1503
1504 memcpy(sqe_copy, sqe, sizeof(*sqe_copy));
1505 req->submit.sqe = sqe_copy;
1506
1507 INIT_WORK(&req->work, io_sq_wq_submit_work);
1508 list_add_tail(&req->list, &ctx->defer_list);
1509 spin_unlock_irq(&ctx->completion_lock);
1510 return -EIOCBQUEUED;
1511}
1512
2b188cc1 1513static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8358e3a8 1514 const struct sqe_submit *s, bool force_nonblock)
2b188cc1 1515{
e0c5c576 1516 int ret, opcode;
2b188cc1
JA
1517
1518 if (unlikely(s->index >= ctx->sq_entries))
1519 return -EINVAL;
1520 req->user_data = READ_ONCE(s->sqe->user_data);
1521
1522 opcode = READ_ONCE(s->sqe->opcode);
1523 switch (opcode) {
1524 case IORING_OP_NOP:
1525 ret = io_nop(req, req->user_data);
1526 break;
1527 case IORING_OP_READV:
edafccee
JA
1528 if (unlikely(s->sqe->buf_index))
1529 return -EINVAL;
8358e3a8 1530 ret = io_read(req, s, force_nonblock);
2b188cc1
JA
1531 break;
1532 case IORING_OP_WRITEV:
edafccee
JA
1533 if (unlikely(s->sqe->buf_index))
1534 return -EINVAL;
8358e3a8 1535 ret = io_write(req, s, force_nonblock);
edafccee
JA
1536 break;
1537 case IORING_OP_READ_FIXED:
8358e3a8 1538 ret = io_read(req, s, force_nonblock);
edafccee
JA
1539 break;
1540 case IORING_OP_WRITE_FIXED:
8358e3a8 1541 ret = io_write(req, s, force_nonblock);
2b188cc1 1542 break;
c992fe29
CH
1543 case IORING_OP_FSYNC:
1544 ret = io_fsync(req, s->sqe, force_nonblock);
1545 break;
221c5eb2
JA
1546 case IORING_OP_POLL_ADD:
1547 ret = io_poll_add(req, s->sqe);
1548 break;
1549 case IORING_OP_POLL_REMOVE:
1550 ret = io_poll_remove(req, s->sqe);
1551 break;
2b188cc1
JA
1552 default:
1553 ret = -EINVAL;
1554 break;
1555 }
1556
def596e9
JA
1557 if (ret)
1558 return ret;
1559
1560 if (ctx->flags & IORING_SETUP_IOPOLL) {
1561 if (req->error == -EAGAIN)
1562 return -EAGAIN;
1563
1564 /* workqueue context doesn't hold uring_lock, grab it now */
1565 if (s->needs_lock)
1566 mutex_lock(&ctx->uring_lock);
1567 io_iopoll_req_issued(req);
1568 if (s->needs_lock)
1569 mutex_unlock(&ctx->uring_lock);
1570 }
1571
1572 return 0;
2b188cc1
JA
1573}
1574
31b51510
JA
1575static struct async_list *io_async_list_from_sqe(struct io_ring_ctx *ctx,
1576 const struct io_uring_sqe *sqe)
1577{
1578 switch (sqe->opcode) {
1579 case IORING_OP_READV:
1580 case IORING_OP_READ_FIXED:
1581 return &ctx->pending_async[READ];
1582 case IORING_OP_WRITEV:
1583 case IORING_OP_WRITE_FIXED:
1584 return &ctx->pending_async[WRITE];
1585 default:
1586 return NULL;
1587 }
1588}
1589
edafccee
JA
1590static inline bool io_sqe_needs_user(const struct io_uring_sqe *sqe)
1591{
1592 u8 opcode = READ_ONCE(sqe->opcode);
1593
1594 return !(opcode == IORING_OP_READ_FIXED ||
1595 opcode == IORING_OP_WRITE_FIXED);
1596}
1597
2b188cc1
JA
1598static void io_sq_wq_submit_work(struct work_struct *work)
1599{
1600 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2b188cc1 1601 struct io_ring_ctx *ctx = req->ctx;
31b51510
JA
1602 struct mm_struct *cur_mm = NULL;
1603 struct async_list *async_list;
1604 LIST_HEAD(req_list);
edafccee 1605 mm_segment_t old_fs;
2b188cc1
JA
1606 int ret;
1607
31b51510
JA
1608 async_list = io_async_list_from_sqe(ctx, req->submit.sqe);
1609restart:
1610 do {
1611 struct sqe_submit *s = &req->submit;
1612 const struct io_uring_sqe *sqe = s->sqe;
2b188cc1 1613
8449eeda 1614 /* Ensure we clear previously set non-block flag */
31b51510
JA
1615 req->rw.ki_flags &= ~IOCB_NOWAIT;
1616
1617 ret = 0;
1618 if (io_sqe_needs_user(sqe) && !cur_mm) {
1619 if (!mmget_not_zero(ctx->sqo_mm)) {
1620 ret = -EFAULT;
1621 } else {
1622 cur_mm = ctx->sqo_mm;
1623 use_mm(cur_mm);
1624 old_fs = get_fs();
1625 set_fs(USER_DS);
1626 }
1627 }
1628
1629 if (!ret) {
1630 s->has_user = cur_mm != NULL;
1631 s->needs_lock = true;
1632 do {
8358e3a8 1633 ret = __io_submit_sqe(ctx, req, s, false);
31b51510
JA
1634 /*
1635 * We can get EAGAIN for polled IO even though
1636 * we're forcing a sync submission from here,
1637 * since we can't wait for request slots on the
1638 * block side.
1639 */
1640 if (ret != -EAGAIN)
1641 break;
1642 cond_resched();
1643 } while (1);
1644 }
817869d2
JA
1645
1646 /* drop submission reference */
1647 io_put_req(req);
1648
31b51510
JA
1649 if (ret) {
1650 io_cqring_add_event(ctx, sqe->user_data, ret, 0);
e65ef56d 1651 io_put_req(req);
31b51510
JA
1652 }
1653
1654 /* async context always use a copy of the sqe */
1655 kfree(sqe);
1656
1657 if (!async_list)
1658 break;
1659 if (!list_empty(&req_list)) {
1660 req = list_first_entry(&req_list, struct io_kiocb,
1661 list);
1662 list_del(&req->list);
1663 continue;
1664 }
1665 if (list_empty(&async_list->list))
1666 break;
1667
1668 req = NULL;
1669 spin_lock(&async_list->lock);
1670 if (list_empty(&async_list->list)) {
1671 spin_unlock(&async_list->lock);
1672 break;
1673 }
1674 list_splice_init(&async_list->list, &req_list);
1675 spin_unlock(&async_list->lock);
1676
1677 req = list_first_entry(&req_list, struct io_kiocb, list);
1678 list_del(&req->list);
1679 } while (req);
edafccee
JA
1680
1681 /*
31b51510
JA
1682 * Rare case of racing with a submitter. If we find the count has
1683 * dropped to zero AND we have pending work items, then restart
1684 * the processing. This is a tiny race window.
edafccee 1685 */
31b51510
JA
1686 if (async_list) {
1687 ret = atomic_dec_return(&async_list->cnt);
1688 while (!ret && !list_empty(&async_list->list)) {
1689 spin_lock(&async_list->lock);
1690 atomic_inc(&async_list->cnt);
1691 list_splice_init(&async_list->list, &req_list);
1692 spin_unlock(&async_list->lock);
1693
1694 if (!list_empty(&req_list)) {
1695 req = list_first_entry(&req_list,
1696 struct io_kiocb, list);
1697 list_del(&req->list);
1698 goto restart;
1699 }
1700 ret = atomic_dec_return(&async_list->cnt);
edafccee 1701 }
edafccee 1702 }
2b188cc1 1703
31b51510 1704 if (cur_mm) {
edafccee 1705 set_fs(old_fs);
31b51510
JA
1706 unuse_mm(cur_mm);
1707 mmput(cur_mm);
2b188cc1 1708 }
31b51510 1709}
2b188cc1 1710
31b51510
JA
1711/*
1712 * See if we can piggy back onto previously submitted work, that is still
1713 * running. We currently only allow this if the new request is sequential
1714 * to the previous one we punted.
1715 */
1716static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
1717{
1718 bool ret = false;
1719
1720 if (!list)
1721 return false;
1722 if (!(req->flags & REQ_F_SEQ_PREV))
1723 return false;
1724 if (!atomic_read(&list->cnt))
1725 return false;
1726
1727 ret = true;
1728 spin_lock(&list->lock);
1729 list_add_tail(&req->list, &list->list);
1730 if (!atomic_read(&list->cnt)) {
1731 list_del_init(&req->list);
1732 ret = false;
1733 }
1734 spin_unlock(&list->lock);
1735 return ret;
2b188cc1
JA
1736}
1737
09bb8394
JA
1738static bool io_op_needs_file(const struct io_uring_sqe *sqe)
1739{
1740 int op = READ_ONCE(sqe->opcode);
1741
1742 switch (op) {
1743 case IORING_OP_NOP:
1744 case IORING_OP_POLL_REMOVE:
1745 return false;
1746 default:
1747 return true;
1748 }
1749}
1750
1751static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
1752 struct io_submit_state *state, struct io_kiocb *req)
1753{
1754 unsigned flags;
1755 int fd;
1756
1757 flags = READ_ONCE(s->sqe->flags);
1758 fd = READ_ONCE(s->sqe->fd);
1759
de0617e4
JA
1760 if (flags & IOSQE_IO_DRAIN) {
1761 req->flags |= REQ_F_IO_DRAIN;
1762 req->sequence = ctx->cached_sq_head - 1;
1763 }
1764
09bb8394
JA
1765 if (!io_op_needs_file(s->sqe)) {
1766 req->file = NULL;
1767 return 0;
1768 }
1769
1770 if (flags & IOSQE_FIXED_FILE) {
1771 if (unlikely(!ctx->user_files ||
1772 (unsigned) fd >= ctx->nr_user_files))
1773 return -EBADF;
1774 req->file = ctx->user_files[fd];
1775 req->flags |= REQ_F_FIXED_FILE;
1776 } else {
1777 if (s->needs_fixed_file)
1778 return -EBADF;
1779 req->file = io_file_get(state, fd);
1780 if (unlikely(!req->file))
1781 return -EBADF;
1782 }
1783
1784 return 0;
1785}
1786
9a56a232
JA
1787static int io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
1788 struct io_submit_state *state)
2b188cc1
JA
1789{
1790 struct io_kiocb *req;
e0c5c576 1791 int ret;
2b188cc1
JA
1792
1793 /* enforce forwards compatibility on users */
de0617e4 1794 if (unlikely(s->sqe->flags & ~(IOSQE_FIXED_FILE | IOSQE_IO_DRAIN)))
2b188cc1
JA
1795 return -EINVAL;
1796
2579f913 1797 req = io_get_req(ctx, state);
2b188cc1
JA
1798 if (unlikely(!req))
1799 return -EAGAIN;
1800
09bb8394
JA
1801 ret = io_req_set_file(ctx, s, state, req);
1802 if (unlikely(ret))
1803 goto out;
2b188cc1 1804
de0617e4
JA
1805 ret = io_req_defer(ctx, req, s->sqe);
1806 if (ret) {
1807 if (ret == -EIOCBQUEUED)
1808 ret = 0;
1809 return ret;
1810 }
1811
8358e3a8 1812 ret = __io_submit_sqe(ctx, req, s, true);
8449eeda 1813 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
2b188cc1
JA
1814 struct io_uring_sqe *sqe_copy;
1815
1816 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
1817 if (sqe_copy) {
31b51510
JA
1818 struct async_list *list;
1819
2b188cc1
JA
1820 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
1821 s->sqe = sqe_copy;
1822
1823 memcpy(&req->submit, s, sizeof(*s));
31b51510
JA
1824 list = io_async_list_from_sqe(ctx, s->sqe);
1825 if (!io_add_to_prev_work(list, req)) {
1826 if (list)
1827 atomic_inc(&list->cnt);
1828 INIT_WORK(&req->work, io_sq_wq_submit_work);
1829 queue_work(ctx->sqo_wq, &req->work);
1830 }
e65ef56d
JA
1831
1832 /*
1833 * Queued up for async execution, worker will release
1834 * submit reference when the iocb is actually
1835 * submitted.
1836 */
1837 return 0;
2b188cc1
JA
1838 }
1839 }
e65ef56d 1840
09bb8394 1841out:
e65ef56d
JA
1842 /* drop submission reference */
1843 io_put_req(req);
1844
1845 /* and drop final reference, if we failed */
2b188cc1 1846 if (ret)
e65ef56d 1847 io_put_req(req);
2b188cc1
JA
1848
1849 return ret;
1850}
1851
9a56a232
JA
1852/*
1853 * Batched submission is done, ensure local IO is flushed out.
1854 */
1855static void io_submit_state_end(struct io_submit_state *state)
1856{
1857 blk_finish_plug(&state->plug);
3d6770fb 1858 io_file_put(state);
2579f913
JA
1859 if (state->free_reqs)
1860 kmem_cache_free_bulk(req_cachep, state->free_reqs,
1861 &state->reqs[state->cur_req]);
9a56a232
JA
1862}
1863
1864/*
1865 * Start submission side cache.
1866 */
1867static void io_submit_state_start(struct io_submit_state *state,
1868 struct io_ring_ctx *ctx, unsigned max_ios)
1869{
1870 blk_start_plug(&state->plug);
2579f913 1871 state->free_reqs = 0;
9a56a232
JA
1872 state->file = NULL;
1873 state->ios_left = max_ios;
1874}
1875
2b188cc1
JA
1876static void io_commit_sqring(struct io_ring_ctx *ctx)
1877{
1878 struct io_sq_ring *ring = ctx->sq_ring;
1879
1880 if (ctx->cached_sq_head != READ_ONCE(ring->r.head)) {
1881 /*
1882 * Ensure any loads from the SQEs are done at this point,
1883 * since once we write the new head, the application could
1884 * write new data to them.
1885 */
1886 smp_store_release(&ring->r.head, ctx->cached_sq_head);
2b188cc1
JA
1887 }
1888}
1889
2b188cc1
JA
1890/*
1891 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
1892 * that is mapped by userspace. This means that care needs to be taken to
1893 * ensure that reads are stable, as we cannot rely on userspace always
1894 * being a good citizen. If members of the sqe are validated and then later
1895 * used, it's important that those reads are done through READ_ONCE() to
1896 * prevent a re-load down the line.
1897 */
1898static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
1899{
1900 struct io_sq_ring *ring = ctx->sq_ring;
1901 unsigned head;
1902
1903 /*
1904 * The cached sq head (or cq tail) serves two purposes:
1905 *
1906 * 1) allows us to batch the cost of updating the user visible
1907 * head updates.
1908 * 2) allows the kernel side to track the head on its own, even
1909 * though the application is the one updating it.
1910 */
1911 head = ctx->cached_sq_head;
e523a29c
SB
1912 /* make sure SQ entry isn't read before tail */
1913 if (head == smp_load_acquire(&ring->r.tail))
2b188cc1
JA
1914 return false;
1915
1916 head = READ_ONCE(ring->array[head & ctx->sq_mask]);
1917 if (head < ctx->sq_entries) {
1918 s->index = head;
1919 s->sqe = &ctx->sq_sqes[head];
1920 ctx->cached_sq_head++;
1921 return true;
1922 }
1923
1924 /* drop invalid entries */
1925 ctx->cached_sq_head++;
1926 ring->dropped++;
2b188cc1
JA
1927 return false;
1928}
1929
6c271ce2
JA
1930static int io_submit_sqes(struct io_ring_ctx *ctx, struct sqe_submit *sqes,
1931 unsigned int nr, bool has_user, bool mm_fault)
1932{
1933 struct io_submit_state state, *statep = NULL;
1934 int ret, i, submitted = 0;
1935
1936 if (nr > IO_PLUG_THRESHOLD) {
1937 io_submit_state_start(&state, ctx, nr);
1938 statep = &state;
1939 }
1940
1941 for (i = 0; i < nr; i++) {
1942 if (unlikely(mm_fault)) {
1943 ret = -EFAULT;
1944 } else {
1945 sqes[i].has_user = has_user;
1946 sqes[i].needs_lock = true;
1947 sqes[i].needs_fixed_file = true;
1948 ret = io_submit_sqe(ctx, &sqes[i], statep);
1949 }
1950 if (!ret) {
1951 submitted++;
1952 continue;
1953 }
1954
1955 io_cqring_add_event(ctx, sqes[i].sqe->user_data, ret, 0);
1956 }
1957
1958 if (statep)
1959 io_submit_state_end(&state);
1960
1961 return submitted;
1962}
1963
1964static int io_sq_thread(void *data)
1965{
1966 struct sqe_submit sqes[IO_IOPOLL_BATCH];
1967 struct io_ring_ctx *ctx = data;
1968 struct mm_struct *cur_mm = NULL;
1969 mm_segment_t old_fs;
1970 DEFINE_WAIT(wait);
1971 unsigned inflight;
1972 unsigned long timeout;
1973
1974 old_fs = get_fs();
1975 set_fs(USER_DS);
1976
1977 timeout = inflight = 0;
1978 while (!kthread_should_stop() && !ctx->sqo_stop) {
1979 bool all_fixed, mm_fault = false;
1980 int i;
1981
1982 if (inflight) {
1983 unsigned nr_events = 0;
1984
1985 if (ctx->flags & IORING_SETUP_IOPOLL) {
1986 /*
1987 * We disallow the app entering submit/complete
1988 * with polling, but we still need to lock the
1989 * ring to prevent racing with polled issue
1990 * that got punted to a workqueue.
1991 */
1992 mutex_lock(&ctx->uring_lock);
1993 io_iopoll_check(ctx, &nr_events, 0);
1994 mutex_unlock(&ctx->uring_lock);
1995 } else {
1996 /*
1997 * Normal IO, just pretend everything completed.
1998 * We don't have to poll completions for that.
1999 */
2000 nr_events = inflight;
2001 }
2002
2003 inflight -= nr_events;
2004 if (!inflight)
2005 timeout = jiffies + ctx->sq_thread_idle;
2006 }
2007
2008 if (!io_get_sqring(ctx, &sqes[0])) {
2009 /*
2010 * We're polling. If we're within the defined idle
2011 * period, then let us spin without work before going
2012 * to sleep.
2013 */
2014 if (inflight || !time_after(jiffies, timeout)) {
2015 cpu_relax();
2016 continue;
2017 }
2018
2019 /*
2020 * Drop cur_mm before scheduling, we can't hold it for
2021 * long periods (or over schedule()). Do this before
2022 * adding ourselves to the waitqueue, as the unuse/drop
2023 * may sleep.
2024 */
2025 if (cur_mm) {
2026 unuse_mm(cur_mm);
2027 mmput(cur_mm);
2028 cur_mm = NULL;
2029 }
2030
2031 prepare_to_wait(&ctx->sqo_wait, &wait,
2032 TASK_INTERRUPTIBLE);
2033
2034 /* Tell userspace we may need a wakeup call */
2035 ctx->sq_ring->flags |= IORING_SQ_NEED_WAKEUP;
0d7bae69
SB
2036 /* make sure to read SQ tail after writing flags */
2037 smp_mb();
6c271ce2
JA
2038
2039 if (!io_get_sqring(ctx, &sqes[0])) {
2040 if (kthread_should_stop()) {
2041 finish_wait(&ctx->sqo_wait, &wait);
2042 break;
2043 }
2044 if (signal_pending(current))
2045 flush_signals(current);
2046 schedule();
2047 finish_wait(&ctx->sqo_wait, &wait);
2048
2049 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2050 continue;
2051 }
2052 finish_wait(&ctx->sqo_wait, &wait);
2053
2054 ctx->sq_ring->flags &= ~IORING_SQ_NEED_WAKEUP;
6c271ce2
JA
2055 }
2056
2057 i = 0;
2058 all_fixed = true;
2059 do {
2060 if (all_fixed && io_sqe_needs_user(sqes[i].sqe))
2061 all_fixed = false;
2062
2063 i++;
2064 if (i == ARRAY_SIZE(sqes))
2065 break;
2066 } while (io_get_sqring(ctx, &sqes[i]));
2067
2068 /* Unless all new commands are FIXED regions, grab mm */
2069 if (!all_fixed && !cur_mm) {
2070 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2071 if (!mm_fault) {
2072 use_mm(ctx->sqo_mm);
2073 cur_mm = ctx->sqo_mm;
2074 }
2075 }
2076
2077 inflight += io_submit_sqes(ctx, sqes, i, cur_mm != NULL,
2078 mm_fault);
2079
2080 /* Commit SQ ring head once we've consumed all SQEs */
2081 io_commit_sqring(ctx);
2082 }
2083
2084 set_fs(old_fs);
2085 if (cur_mm) {
2086 unuse_mm(cur_mm);
2087 mmput(cur_mm);
2088 }
06058632
JA
2089
2090 if (kthread_should_park())
2091 kthread_parkme();
2092
6c271ce2
JA
2093 return 0;
2094}
2095
2b188cc1
JA
2096static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2097{
9a56a232 2098 struct io_submit_state state, *statep = NULL;
5c8b0b54 2099 int i, submit = 0;
2b188cc1 2100
9a56a232
JA
2101 if (to_submit > IO_PLUG_THRESHOLD) {
2102 io_submit_state_start(&state, ctx, to_submit);
2103 statep = &state;
2104 }
2b188cc1
JA
2105
2106 for (i = 0; i < to_submit; i++) {
2107 struct sqe_submit s;
5c8b0b54 2108 int ret;
2b188cc1
JA
2109
2110 if (!io_get_sqring(ctx, &s))
2111 break;
2112
2113 s.has_user = true;
def596e9 2114 s.needs_lock = false;
6c271ce2 2115 s.needs_fixed_file = false;
5c8b0b54 2116 submit++;
def596e9 2117
9a56a232 2118 ret = io_submit_sqe(ctx, &s, statep);
5c8b0b54
JA
2119 if (ret)
2120 io_cqring_add_event(ctx, s.sqe->user_data, ret, 0);
2b188cc1
JA
2121 }
2122 io_commit_sqring(ctx);
2123
9a56a232
JA
2124 if (statep)
2125 io_submit_state_end(statep);
2b188cc1 2126
5c8b0b54 2127 return submit;
2b188cc1
JA
2128}
2129
2130static unsigned io_cqring_events(struct io_cq_ring *ring)
2131{
2132 return READ_ONCE(ring->r.tail) - READ_ONCE(ring->r.head);
2133}
2134
2135/*
2136 * Wait until events become available, if we don't already have some. The
2137 * application must reap them itself, as they reside on the shared cq ring.
2138 */
2139static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2140 const sigset_t __user *sig, size_t sigsz)
2141{
2142 struct io_cq_ring *ring = ctx->cq_ring;
2143 sigset_t ksigmask, sigsaved;
2144 DEFINE_WAIT(wait);
2145 int ret;
2146
2147 /* See comment at the top of this file */
2148 smp_rmb();
2149 if (io_cqring_events(ring) >= min_events)
2150 return 0;
2151
2152 if (sig) {
9e75ad5d
AB
2153#ifdef CONFIG_COMPAT
2154 if (in_compat_syscall())
2155 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2156 &ksigmask, &sigsaved, sigsz);
2157 else
2158#endif
2159 ret = set_user_sigmask(sig, &ksigmask,
2160 &sigsaved, sigsz);
2161
2b188cc1
JA
2162 if (ret)
2163 return ret;
2164 }
2165
2166 do {
2167 prepare_to_wait(&ctx->wait, &wait, TASK_INTERRUPTIBLE);
2168
2169 ret = 0;
2170 /* See comment at the top of this file */
2171 smp_rmb();
2172 if (io_cqring_events(ring) >= min_events)
2173 break;
2174
2175 schedule();
2176
2177 ret = -EINTR;
2178 if (signal_pending(current))
2179 break;
2180 } while (1);
2181
2182 finish_wait(&ctx->wait, &wait);
2183
2184 if (sig)
2185 restore_user_sigmask(sig, &sigsaved);
2186
2187 return READ_ONCE(ring->r.head) == READ_ONCE(ring->r.tail) ? ret : 0;
2188}
2189
6b06314c
JA
2190static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
2191{
2192#if defined(CONFIG_UNIX)
2193 if (ctx->ring_sock) {
2194 struct sock *sock = ctx->ring_sock->sk;
2195 struct sk_buff *skb;
2196
2197 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
2198 kfree_skb(skb);
2199 }
2200#else
2201 int i;
2202
2203 for (i = 0; i < ctx->nr_user_files; i++)
2204 fput(ctx->user_files[i]);
2205#endif
2206}
2207
2208static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
2209{
2210 if (!ctx->user_files)
2211 return -ENXIO;
2212
2213 __io_sqe_files_unregister(ctx);
2214 kfree(ctx->user_files);
2215 ctx->user_files = NULL;
2216 ctx->nr_user_files = 0;
2217 return 0;
2218}
2219
6c271ce2
JA
2220static void io_sq_thread_stop(struct io_ring_ctx *ctx)
2221{
2222 if (ctx->sqo_thread) {
2223 ctx->sqo_stop = 1;
2224 mb();
06058632 2225 kthread_park(ctx->sqo_thread);
6c271ce2
JA
2226 kthread_stop(ctx->sqo_thread);
2227 ctx->sqo_thread = NULL;
2228 }
2229}
2230
6b06314c
JA
2231static void io_finish_async(struct io_ring_ctx *ctx)
2232{
6c271ce2
JA
2233 io_sq_thread_stop(ctx);
2234
6b06314c
JA
2235 if (ctx->sqo_wq) {
2236 destroy_workqueue(ctx->sqo_wq);
2237 ctx->sqo_wq = NULL;
2238 }
2239}
2240
2241#if defined(CONFIG_UNIX)
2242static void io_destruct_skb(struct sk_buff *skb)
2243{
2244 struct io_ring_ctx *ctx = skb->sk->sk_user_data;
2245
2246 io_finish_async(ctx);
2247 unix_destruct_scm(skb);
2248}
2249
2250/*
2251 * Ensure the UNIX gc is aware of our file set, so we are certain that
2252 * the io_uring can be safely unregistered on process exit, even if we have
2253 * loops in the file referencing.
2254 */
2255static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
2256{
2257 struct sock *sk = ctx->ring_sock->sk;
2258 struct scm_fp_list *fpl;
2259 struct sk_buff *skb;
2260 int i;
2261
2262 if (!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
2263 unsigned long inflight = ctx->user->unix_inflight + nr;
2264
2265 if (inflight > task_rlimit(current, RLIMIT_NOFILE))
2266 return -EMFILE;
2267 }
2268
2269 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
2270 if (!fpl)
2271 return -ENOMEM;
2272
2273 skb = alloc_skb(0, GFP_KERNEL);
2274 if (!skb) {
2275 kfree(fpl);
2276 return -ENOMEM;
2277 }
2278
2279 skb->sk = sk;
2280 skb->destructor = io_destruct_skb;
2281
2282 fpl->user = get_uid(ctx->user);
2283 for (i = 0; i < nr; i++) {
2284 fpl->fp[i] = get_file(ctx->user_files[i + offset]);
2285 unix_inflight(fpl->user, fpl->fp[i]);
2286 }
2287
2288 fpl->max = fpl->count = nr;
2289 UNIXCB(skb).fp = fpl;
2290 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2291 skb_queue_head(&sk->sk_receive_queue, skb);
2292
2293 for (i = 0; i < nr; i++)
2294 fput(fpl->fp[i]);
2295
2296 return 0;
2297}
2298
2299/*
2300 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
2301 * causes regular reference counting to break down. We rely on the UNIX
2302 * garbage collection to take care of this problem for us.
2303 */
2304static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2305{
2306 unsigned left, total;
2307 int ret = 0;
2308
2309 total = 0;
2310 left = ctx->nr_user_files;
2311 while (left) {
2312 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
2313 int ret;
2314
2315 ret = __io_sqe_files_scm(ctx, this_files, total);
2316 if (ret)
2317 break;
2318 left -= this_files;
2319 total += this_files;
2320 }
2321
2322 if (!ret)
2323 return 0;
2324
2325 while (total < ctx->nr_user_files) {
2326 fput(ctx->user_files[total]);
2327 total++;
2328 }
2329
2330 return ret;
2331}
2332#else
2333static int io_sqe_files_scm(struct io_ring_ctx *ctx)
2334{
2335 return 0;
2336}
2337#endif
2338
2339static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
2340 unsigned nr_args)
2341{
2342 __s32 __user *fds = (__s32 __user *) arg;
2343 int fd, ret = 0;
2344 unsigned i;
2345
2346 if (ctx->user_files)
2347 return -EBUSY;
2348 if (!nr_args)
2349 return -EINVAL;
2350 if (nr_args > IORING_MAX_FIXED_FILES)
2351 return -EMFILE;
2352
2353 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
2354 if (!ctx->user_files)
2355 return -ENOMEM;
2356
2357 for (i = 0; i < nr_args; i++) {
2358 ret = -EFAULT;
2359 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
2360 break;
2361
2362 ctx->user_files[i] = fget(fd);
2363
2364 ret = -EBADF;
2365 if (!ctx->user_files[i])
2366 break;
2367 /*
2368 * Don't allow io_uring instances to be registered. If UNIX
2369 * isn't enabled, then this causes a reference cycle and this
2370 * instance can never get freed. If UNIX is enabled we'll
2371 * handle it just fine, but there's still no point in allowing
2372 * a ring fd as it doesn't support regular read/write anyway.
2373 */
2374 if (ctx->user_files[i]->f_op == &io_uring_fops) {
2375 fput(ctx->user_files[i]);
2376 break;
2377 }
2378 ctx->nr_user_files++;
2379 ret = 0;
2380 }
2381
2382 if (ret) {
2383 for (i = 0; i < ctx->nr_user_files; i++)
2384 fput(ctx->user_files[i]);
2385
2386 kfree(ctx->user_files);
25adf50f 2387 ctx->user_files = NULL;
6b06314c
JA
2388 ctx->nr_user_files = 0;
2389 return ret;
2390 }
2391
2392 ret = io_sqe_files_scm(ctx);
2393 if (ret)
2394 io_sqe_files_unregister(ctx);
2395
2396 return ret;
2397}
2398
6c271ce2
JA
2399static int io_sq_offload_start(struct io_ring_ctx *ctx,
2400 struct io_uring_params *p)
2b188cc1
JA
2401{
2402 int ret;
2403
6c271ce2 2404 init_waitqueue_head(&ctx->sqo_wait);
2b188cc1
JA
2405 mmgrab(current->mm);
2406 ctx->sqo_mm = current->mm;
2407
6c271ce2 2408 if (ctx->flags & IORING_SETUP_SQPOLL) {
3ec482d1
JA
2409 ret = -EPERM;
2410 if (!capable(CAP_SYS_ADMIN))
2411 goto err;
2412
917257da
JA
2413 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
2414 if (!ctx->sq_thread_idle)
2415 ctx->sq_thread_idle = HZ;
2416
6c271ce2 2417 if (p->flags & IORING_SETUP_SQ_AFF) {
975554b0
MR
2418 int cpu = array_index_nospec(p->sq_thread_cpu,
2419 nr_cpu_ids);
6c271ce2 2420
917257da 2421 ret = -EINVAL;
975554b0 2422 if (!cpu_possible(cpu))
917257da
JA
2423 goto err;
2424
6c271ce2
JA
2425 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
2426 ctx, cpu,
2427 "io_uring-sq");
2428 } else {
2429 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
2430 "io_uring-sq");
2431 }
2432 if (IS_ERR(ctx->sqo_thread)) {
2433 ret = PTR_ERR(ctx->sqo_thread);
2434 ctx->sqo_thread = NULL;
2435 goto err;
2436 }
2437 wake_up_process(ctx->sqo_thread);
2438 } else if (p->flags & IORING_SETUP_SQ_AFF) {
2439 /* Can't have SQ_AFF without SQPOLL */
2440 ret = -EINVAL;
2441 goto err;
2442 }
2443
2b188cc1
JA
2444 /* Do QD, or 2 * CPUS, whatever is smallest */
2445 ctx->sqo_wq = alloc_workqueue("io_ring-wq", WQ_UNBOUND | WQ_FREEZABLE,
2446 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
2447 if (!ctx->sqo_wq) {
2448 ret = -ENOMEM;
2449 goto err;
2450 }
2451
2452 return 0;
2453err:
6c271ce2 2454 io_sq_thread_stop(ctx);
2b188cc1
JA
2455 mmdrop(ctx->sqo_mm);
2456 ctx->sqo_mm = NULL;
2457 return ret;
2458}
2459
2460static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
2461{
2462 atomic_long_sub(nr_pages, &user->locked_vm);
2463}
2464
2465static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
2466{
2467 unsigned long page_limit, cur_pages, new_pages;
2468
2469 /* Don't allow more pages than we can safely lock */
2470 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
2471
2472 do {
2473 cur_pages = atomic_long_read(&user->locked_vm);
2474 new_pages = cur_pages + nr_pages;
2475 if (new_pages > page_limit)
2476 return -ENOMEM;
2477 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
2478 new_pages) != cur_pages);
2479
2480 return 0;
2481}
2482
2483static void io_mem_free(void *ptr)
2484{
52e04ef4
MR
2485 struct page *page;
2486
2487 if (!ptr)
2488 return;
2b188cc1 2489
52e04ef4 2490 page = virt_to_head_page(ptr);
2b188cc1
JA
2491 if (put_page_testzero(page))
2492 free_compound_page(page);
2493}
2494
2495static void *io_mem_alloc(size_t size)
2496{
2497 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
2498 __GFP_NORETRY;
2499
2500 return (void *) __get_free_pages(gfp_flags, get_order(size));
2501}
2502
2503static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
2504{
2505 struct io_sq_ring *sq_ring;
2506 struct io_cq_ring *cq_ring;
2507 size_t bytes;
2508
2509 bytes = struct_size(sq_ring, array, sq_entries);
2510 bytes += array_size(sizeof(struct io_uring_sqe), sq_entries);
2511 bytes += struct_size(cq_ring, cqes, cq_entries);
2512
2513 return (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
2514}
2515
edafccee
JA
2516static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
2517{
2518 int i, j;
2519
2520 if (!ctx->user_bufs)
2521 return -ENXIO;
2522
2523 for (i = 0; i < ctx->nr_user_bufs; i++) {
2524 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2525
2526 for (j = 0; j < imu->nr_bvecs; j++)
2527 put_page(imu->bvec[j].bv_page);
2528
2529 if (ctx->account_mem)
2530 io_unaccount_mem(ctx->user, imu->nr_bvecs);
d4ef6475 2531 kvfree(imu->bvec);
edafccee
JA
2532 imu->nr_bvecs = 0;
2533 }
2534
2535 kfree(ctx->user_bufs);
2536 ctx->user_bufs = NULL;
2537 ctx->nr_user_bufs = 0;
2538 return 0;
2539}
2540
2541static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
2542 void __user *arg, unsigned index)
2543{
2544 struct iovec __user *src;
2545
2546#ifdef CONFIG_COMPAT
2547 if (ctx->compat) {
2548 struct compat_iovec __user *ciovs;
2549 struct compat_iovec ciov;
2550
2551 ciovs = (struct compat_iovec __user *) arg;
2552 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
2553 return -EFAULT;
2554
2555 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
2556 dst->iov_len = ciov.iov_len;
2557 return 0;
2558 }
2559#endif
2560 src = (struct iovec __user *) arg;
2561 if (copy_from_user(dst, &src[index], sizeof(*dst)))
2562 return -EFAULT;
2563 return 0;
2564}
2565
2566static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
2567 unsigned nr_args)
2568{
2569 struct vm_area_struct **vmas = NULL;
2570 struct page **pages = NULL;
2571 int i, j, got_pages = 0;
2572 int ret = -EINVAL;
2573
2574 if (ctx->user_bufs)
2575 return -EBUSY;
2576 if (!nr_args || nr_args > UIO_MAXIOV)
2577 return -EINVAL;
2578
2579 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
2580 GFP_KERNEL);
2581 if (!ctx->user_bufs)
2582 return -ENOMEM;
2583
2584 for (i = 0; i < nr_args; i++) {
2585 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
2586 unsigned long off, start, end, ubuf;
2587 int pret, nr_pages;
2588 struct iovec iov;
2589 size_t size;
2590
2591 ret = io_copy_iov(ctx, &iov, arg, i);
2592 if (ret)
2593 break;
2594
2595 /*
2596 * Don't impose further limits on the size and buffer
2597 * constraints here, we'll -EINVAL later when IO is
2598 * submitted if they are wrong.
2599 */
2600 ret = -EFAULT;
2601 if (!iov.iov_base || !iov.iov_len)
2602 goto err;
2603
2604 /* arbitrary limit, but we need something */
2605 if (iov.iov_len > SZ_1G)
2606 goto err;
2607
2608 ubuf = (unsigned long) iov.iov_base;
2609 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2610 start = ubuf >> PAGE_SHIFT;
2611 nr_pages = end - start;
2612
2613 if (ctx->account_mem) {
2614 ret = io_account_mem(ctx->user, nr_pages);
2615 if (ret)
2616 goto err;
2617 }
2618
2619 ret = 0;
2620 if (!pages || nr_pages > got_pages) {
2621 kfree(vmas);
2622 kfree(pages);
d4ef6475 2623 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
edafccee 2624 GFP_KERNEL);
d4ef6475 2625 vmas = kvmalloc_array(nr_pages,
edafccee
JA
2626 sizeof(struct vm_area_struct *),
2627 GFP_KERNEL);
2628 if (!pages || !vmas) {
2629 ret = -ENOMEM;
2630 if (ctx->account_mem)
2631 io_unaccount_mem(ctx->user, nr_pages);
2632 goto err;
2633 }
2634 got_pages = nr_pages;
2635 }
2636
d4ef6475 2637 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
edafccee
JA
2638 GFP_KERNEL);
2639 ret = -ENOMEM;
2640 if (!imu->bvec) {
2641 if (ctx->account_mem)
2642 io_unaccount_mem(ctx->user, nr_pages);
2643 goto err;
2644 }
2645
2646 ret = 0;
2647 down_read(&current->mm->mmap_sem);
2648 pret = get_user_pages_longterm(ubuf, nr_pages, FOLL_WRITE,
2649 pages, vmas);
2650 if (pret == nr_pages) {
2651 /* don't support file backed memory */
2652 for (j = 0; j < nr_pages; j++) {
2653 struct vm_area_struct *vma = vmas[j];
2654
2655 if (vma->vm_file &&
2656 !is_file_hugepages(vma->vm_file)) {
2657 ret = -EOPNOTSUPP;
2658 break;
2659 }
2660 }
2661 } else {
2662 ret = pret < 0 ? pret : -EFAULT;
2663 }
2664 up_read(&current->mm->mmap_sem);
2665 if (ret) {
2666 /*
2667 * if we did partial map, or found file backed vmas,
2668 * release any pages we did get
2669 */
2670 if (pret > 0) {
2671 for (j = 0; j < pret; j++)
2672 put_page(pages[j]);
2673 }
2674 if (ctx->account_mem)
2675 io_unaccount_mem(ctx->user, nr_pages);
d4ef6475 2676 kvfree(imu->bvec);
edafccee
JA
2677 goto err;
2678 }
2679
2680 off = ubuf & ~PAGE_MASK;
2681 size = iov.iov_len;
2682 for (j = 0; j < nr_pages; j++) {
2683 size_t vec_len;
2684
2685 vec_len = min_t(size_t, size, PAGE_SIZE - off);
2686 imu->bvec[j].bv_page = pages[j];
2687 imu->bvec[j].bv_len = vec_len;
2688 imu->bvec[j].bv_offset = off;
2689 off = 0;
2690 size -= vec_len;
2691 }
2692 /* store original address for later verification */
2693 imu->ubuf = ubuf;
2694 imu->len = iov.iov_len;
2695 imu->nr_bvecs = nr_pages;
2696
2697 ctx->nr_user_bufs++;
2698 }
d4ef6475
MR
2699 kvfree(pages);
2700 kvfree(vmas);
edafccee
JA
2701 return 0;
2702err:
d4ef6475
MR
2703 kvfree(pages);
2704 kvfree(vmas);
edafccee
JA
2705 io_sqe_buffer_unregister(ctx);
2706 return ret;
2707}
2708
2b188cc1
JA
2709static void io_ring_ctx_free(struct io_ring_ctx *ctx)
2710{
6b06314c 2711 io_finish_async(ctx);
2b188cc1
JA
2712 if (ctx->sqo_mm)
2713 mmdrop(ctx->sqo_mm);
def596e9
JA
2714
2715 io_iopoll_reap_events(ctx);
edafccee 2716 io_sqe_buffer_unregister(ctx);
6b06314c 2717 io_sqe_files_unregister(ctx);
def596e9 2718
2b188cc1
JA
2719#if defined(CONFIG_UNIX)
2720 if (ctx->ring_sock)
2721 sock_release(ctx->ring_sock);
2722#endif
2723
2724 io_mem_free(ctx->sq_ring);
2725 io_mem_free(ctx->sq_sqes);
2726 io_mem_free(ctx->cq_ring);
2727
2728 percpu_ref_exit(&ctx->refs);
2729 if (ctx->account_mem)
2730 io_unaccount_mem(ctx->user,
2731 ring_pages(ctx->sq_entries, ctx->cq_entries));
2732 free_uid(ctx->user);
2733 kfree(ctx);
2734}
2735
2736static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2737{
2738 struct io_ring_ctx *ctx = file->private_data;
2739 __poll_t mask = 0;
2740
2741 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
2742 /*
2743 * synchronizes with barrier from wq_has_sleeper call in
2744 * io_commit_cqring
2745 */
2b188cc1 2746 smp_rmb();
fb775faa
SB
2747 if (READ_ONCE(ctx->sq_ring->r.tail) - ctx->cached_sq_head !=
2748 ctx->sq_ring->ring_entries)
2b188cc1
JA
2749 mask |= EPOLLOUT | EPOLLWRNORM;
2750 if (READ_ONCE(ctx->cq_ring->r.head) != ctx->cached_cq_tail)
2751 mask |= EPOLLIN | EPOLLRDNORM;
2752
2753 return mask;
2754}
2755
2756static int io_uring_fasync(int fd, struct file *file, int on)
2757{
2758 struct io_ring_ctx *ctx = file->private_data;
2759
2760 return fasync_helper(fd, file, on, &ctx->cq_fasync);
2761}
2762
2763static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2764{
2765 mutex_lock(&ctx->uring_lock);
2766 percpu_ref_kill(&ctx->refs);
2767 mutex_unlock(&ctx->uring_lock);
2768
221c5eb2 2769 io_poll_remove_all(ctx);
def596e9 2770 io_iopoll_reap_events(ctx);
2b188cc1
JA
2771 wait_for_completion(&ctx->ctx_done);
2772 io_ring_ctx_free(ctx);
2773}
2774
2775static int io_uring_release(struct inode *inode, struct file *file)
2776{
2777 struct io_ring_ctx *ctx = file->private_data;
2778
2779 file->private_data = NULL;
2780 io_ring_ctx_wait_and_kill(ctx);
2781 return 0;
2782}
2783
2784static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
2785{
2786 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
2787 unsigned long sz = vma->vm_end - vma->vm_start;
2788 struct io_ring_ctx *ctx = file->private_data;
2789 unsigned long pfn;
2790 struct page *page;
2791 void *ptr;
2792
2793 switch (offset) {
2794 case IORING_OFF_SQ_RING:
2795 ptr = ctx->sq_ring;
2796 break;
2797 case IORING_OFF_SQES:
2798 ptr = ctx->sq_sqes;
2799 break;
2800 case IORING_OFF_CQ_RING:
2801 ptr = ctx->cq_ring;
2802 break;
2803 default:
2804 return -EINVAL;
2805 }
2806
2807 page = virt_to_head_page(ptr);
2808 if (sz > (PAGE_SIZE << compound_order(page)))
2809 return -EINVAL;
2810
2811 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
2812 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2813}
2814
2815SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2816 u32, min_complete, u32, flags, const sigset_t __user *, sig,
2817 size_t, sigsz)
2818{
2819 struct io_ring_ctx *ctx;
2820 long ret = -EBADF;
2821 int submitted = 0;
2822 struct fd f;
2823
6c271ce2 2824 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
2b188cc1
JA
2825 return -EINVAL;
2826
2827 f = fdget(fd);
2828 if (!f.file)
2829 return -EBADF;
2830
2831 ret = -EOPNOTSUPP;
2832 if (f.file->f_op != &io_uring_fops)
2833 goto out_fput;
2834
2835 ret = -ENXIO;
2836 ctx = f.file->private_data;
2837 if (!percpu_ref_tryget(&ctx->refs))
2838 goto out_fput;
2839
6c271ce2
JA
2840 /*
2841 * For SQ polling, the thread will do all submissions and completions.
2842 * Just return the requested submit count, and wake the thread if
2843 * we were asked to.
2844 */
2845 if (ctx->flags & IORING_SETUP_SQPOLL) {
2846 if (flags & IORING_ENTER_SQ_WAKEUP)
2847 wake_up(&ctx->sqo_wait);
2848 submitted = to_submit;
2849 goto out_ctx;
2850 }
2851
2b188cc1
JA
2852 ret = 0;
2853 if (to_submit) {
2854 to_submit = min(to_submit, ctx->sq_entries);
2855
2856 mutex_lock(&ctx->uring_lock);
2857 submitted = io_ring_submit(ctx, to_submit);
2858 mutex_unlock(&ctx->uring_lock);
2b188cc1
JA
2859 }
2860 if (flags & IORING_ENTER_GETEVENTS) {
def596e9
JA
2861 unsigned nr_events = 0;
2862
2b188cc1
JA
2863 min_complete = min(min_complete, ctx->cq_entries);
2864
def596e9
JA
2865 if (ctx->flags & IORING_SETUP_IOPOLL) {
2866 mutex_lock(&ctx->uring_lock);
2867 ret = io_iopoll_check(ctx, &nr_events, min_complete);
2868 mutex_unlock(&ctx->uring_lock);
2869 } else {
2870 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
2871 }
2b188cc1
JA
2872 }
2873
2874out_ctx:
2875 io_ring_drop_ctx_refs(ctx, 1);
2876out_fput:
2877 fdput(f);
2878 return submitted ? submitted : ret;
2879}
2880
2881static const struct file_operations io_uring_fops = {
2882 .release = io_uring_release,
2883 .mmap = io_uring_mmap,
2884 .poll = io_uring_poll,
2885 .fasync = io_uring_fasync,
2886};
2887
2888static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2889 struct io_uring_params *p)
2890{
2891 struct io_sq_ring *sq_ring;
2892 struct io_cq_ring *cq_ring;
2893 size_t size;
2894
2895 sq_ring = io_mem_alloc(struct_size(sq_ring, array, p->sq_entries));
2896 if (!sq_ring)
2897 return -ENOMEM;
2898
2899 ctx->sq_ring = sq_ring;
2900 sq_ring->ring_mask = p->sq_entries - 1;
2901 sq_ring->ring_entries = p->sq_entries;
2902 ctx->sq_mask = sq_ring->ring_mask;
2903 ctx->sq_entries = sq_ring->ring_entries;
2904
2905 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
2906 if (size == SIZE_MAX)
2907 return -EOVERFLOW;
2908
2909 ctx->sq_sqes = io_mem_alloc(size);
52e04ef4 2910 if (!ctx->sq_sqes)
2b188cc1 2911 return -ENOMEM;
2b188cc1
JA
2912
2913 cq_ring = io_mem_alloc(struct_size(cq_ring, cqes, p->cq_entries));
52e04ef4 2914 if (!cq_ring)
2b188cc1 2915 return -ENOMEM;
2b188cc1
JA
2916
2917 ctx->cq_ring = cq_ring;
2918 cq_ring->ring_mask = p->cq_entries - 1;
2919 cq_ring->ring_entries = p->cq_entries;
2920 ctx->cq_mask = cq_ring->ring_mask;
2921 ctx->cq_entries = cq_ring->ring_entries;
2922 return 0;
2923}
2924
2925/*
2926 * Allocate an anonymous fd, this is what constitutes the application
2927 * visible backing of an io_uring instance. The application mmaps this
2928 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
2929 * we have to tie this fd to a socket for file garbage collection purposes.
2930 */
2931static int io_uring_get_fd(struct io_ring_ctx *ctx)
2932{
2933 struct file *file;
2934 int ret;
2935
2936#if defined(CONFIG_UNIX)
2937 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
2938 &ctx->ring_sock);
2939 if (ret)
2940 return ret;
2941#endif
2942
2943 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2944 if (ret < 0)
2945 goto err;
2946
2947 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
2948 O_RDWR | O_CLOEXEC);
2949 if (IS_ERR(file)) {
2950 put_unused_fd(ret);
2951 ret = PTR_ERR(file);
2952 goto err;
2953 }
2954
2955#if defined(CONFIG_UNIX)
2956 ctx->ring_sock->file = file;
6b06314c 2957 ctx->ring_sock->sk->sk_user_data = ctx;
2b188cc1
JA
2958#endif
2959 fd_install(ret, file);
2960 return ret;
2961err:
2962#if defined(CONFIG_UNIX)
2963 sock_release(ctx->ring_sock);
2964 ctx->ring_sock = NULL;
2965#endif
2966 return ret;
2967}
2968
2969static int io_uring_create(unsigned entries, struct io_uring_params *p)
2970{
2971 struct user_struct *user = NULL;
2972 struct io_ring_ctx *ctx;
2973 bool account_mem;
2974 int ret;
2975
2976 if (!entries || entries > IORING_MAX_ENTRIES)
2977 return -EINVAL;
2978
2979 /*
2980 * Use twice as many entries for the CQ ring. It's possible for the
2981 * application to drive a higher depth than the size of the SQ ring,
2982 * since the sqes are only used at submission time. This allows for
2983 * some flexibility in overcommitting a bit.
2984 */
2985 p->sq_entries = roundup_pow_of_two(entries);
2986 p->cq_entries = 2 * p->sq_entries;
2987
2988 user = get_uid(current_user());
2989 account_mem = !capable(CAP_IPC_LOCK);
2990
2991 if (account_mem) {
2992 ret = io_account_mem(user,
2993 ring_pages(p->sq_entries, p->cq_entries));
2994 if (ret) {
2995 free_uid(user);
2996 return ret;
2997 }
2998 }
2999
3000 ctx = io_ring_ctx_alloc(p);
3001 if (!ctx) {
3002 if (account_mem)
3003 io_unaccount_mem(user, ring_pages(p->sq_entries,
3004 p->cq_entries));
3005 free_uid(user);
3006 return -ENOMEM;
3007 }
3008 ctx->compat = in_compat_syscall();
3009 ctx->account_mem = account_mem;
3010 ctx->user = user;
3011
3012 ret = io_allocate_scq_urings(ctx, p);
3013 if (ret)
3014 goto err;
3015
6c271ce2 3016 ret = io_sq_offload_start(ctx, p);
2b188cc1
JA
3017 if (ret)
3018 goto err;
3019
3020 ret = io_uring_get_fd(ctx);
3021 if (ret < 0)
3022 goto err;
3023
3024 memset(&p->sq_off, 0, sizeof(p->sq_off));
3025 p->sq_off.head = offsetof(struct io_sq_ring, r.head);
3026 p->sq_off.tail = offsetof(struct io_sq_ring, r.tail);
3027 p->sq_off.ring_mask = offsetof(struct io_sq_ring, ring_mask);
3028 p->sq_off.ring_entries = offsetof(struct io_sq_ring, ring_entries);
3029 p->sq_off.flags = offsetof(struct io_sq_ring, flags);
3030 p->sq_off.dropped = offsetof(struct io_sq_ring, dropped);
3031 p->sq_off.array = offsetof(struct io_sq_ring, array);
3032
3033 memset(&p->cq_off, 0, sizeof(p->cq_off));
3034 p->cq_off.head = offsetof(struct io_cq_ring, r.head);
3035 p->cq_off.tail = offsetof(struct io_cq_ring, r.tail);
3036 p->cq_off.ring_mask = offsetof(struct io_cq_ring, ring_mask);
3037 p->cq_off.ring_entries = offsetof(struct io_cq_ring, ring_entries);
3038 p->cq_off.overflow = offsetof(struct io_cq_ring, overflow);
3039 p->cq_off.cqes = offsetof(struct io_cq_ring, cqes);
3040 return ret;
3041err:
3042 io_ring_ctx_wait_and_kill(ctx);
3043 return ret;
3044}
3045
3046/*
3047 * Sets up an aio uring context, and returns the fd. Applications asks for a
3048 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3049 * params structure passed in.
3050 */
3051static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3052{
3053 struct io_uring_params p;
3054 long ret;
3055 int i;
3056
3057 if (copy_from_user(&p, params, sizeof(p)))
3058 return -EFAULT;
3059 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3060 if (p.resv[i])
3061 return -EINVAL;
3062 }
3063
6c271ce2
JA
3064 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3065 IORING_SETUP_SQ_AFF))
2b188cc1
JA
3066 return -EINVAL;
3067
3068 ret = io_uring_create(entries, &p);
3069 if (ret < 0)
3070 return ret;
3071
3072 if (copy_to_user(params, &p, sizeof(p)))
3073 return -EFAULT;
3074
3075 return ret;
3076}
3077
3078SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3079 struct io_uring_params __user *, params)
3080{
3081 return io_uring_setup(entries, params);
3082}
3083
edafccee
JA
3084static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3085 void __user *arg, unsigned nr_args)
b19062a5
JA
3086 __releases(ctx->uring_lock)
3087 __acquires(ctx->uring_lock)
edafccee
JA
3088{
3089 int ret;
3090
35fa71a0
JA
3091 /*
3092 * We're inside the ring mutex, if the ref is already dying, then
3093 * someone else killed the ctx or is already going through
3094 * io_uring_register().
3095 */
3096 if (percpu_ref_is_dying(&ctx->refs))
3097 return -ENXIO;
3098
edafccee 3099 percpu_ref_kill(&ctx->refs);
b19062a5
JA
3100
3101 /*
3102 * Drop uring mutex before waiting for references to exit. If another
3103 * thread is currently inside io_uring_enter() it might need to grab
3104 * the uring_lock to make progress. If we hold it here across the drain
3105 * wait, then we can deadlock. It's safe to drop the mutex here, since
3106 * no new references will come in after we've killed the percpu ref.
3107 */
3108 mutex_unlock(&ctx->uring_lock);
edafccee 3109 wait_for_completion(&ctx->ctx_done);
b19062a5 3110 mutex_lock(&ctx->uring_lock);
edafccee
JA
3111
3112 switch (opcode) {
3113 case IORING_REGISTER_BUFFERS:
3114 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3115 break;
3116 case IORING_UNREGISTER_BUFFERS:
3117 ret = -EINVAL;
3118 if (arg || nr_args)
3119 break;
3120 ret = io_sqe_buffer_unregister(ctx);
3121 break;
6b06314c
JA
3122 case IORING_REGISTER_FILES:
3123 ret = io_sqe_files_register(ctx, arg, nr_args);
3124 break;
3125 case IORING_UNREGISTER_FILES:
3126 ret = -EINVAL;
3127 if (arg || nr_args)
3128 break;
3129 ret = io_sqe_files_unregister(ctx);
3130 break;
edafccee
JA
3131 default:
3132 ret = -EINVAL;
3133 break;
3134 }
3135
3136 /* bring the ctx back to life */
3137 reinit_completion(&ctx->ctx_done);
3138 percpu_ref_reinit(&ctx->refs);
3139 return ret;
3140}
3141
3142SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
3143 void __user *, arg, unsigned int, nr_args)
3144{
3145 struct io_ring_ctx *ctx;
3146 long ret = -EBADF;
3147 struct fd f;
3148
3149 f = fdget(fd);
3150 if (!f.file)
3151 return -EBADF;
3152
3153 ret = -EOPNOTSUPP;
3154 if (f.file->f_op != &io_uring_fops)
3155 goto out_fput;
3156
3157 ctx = f.file->private_data;
3158
3159 mutex_lock(&ctx->uring_lock);
3160 ret = __io_uring_register(ctx, opcode, arg, nr_args);
3161 mutex_unlock(&ctx->uring_lock);
3162out_fput:
3163 fdput(f);
3164 return ret;
3165}
3166
2b188cc1
JA
3167static int __init io_uring_init(void)
3168{
3169 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
3170 return 0;
3171};
3172__initcall(io_uring_init);