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