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