io_uring: clean up io_lockdep_assert_cq_locked
[linux-2.6-block.git] / io_uring / 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
d068b506 14 * through a control-dependency in io_get_cqe (smp_store_release to
1e84b97b
SB
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>
52de1fe1 46#include <net/compat.h>
2b188cc1
JA
47#include <linux/refcount.h>
48#include <linux/uio.h>
6b47ee6e 49#include <linux/bits.h>
2b188cc1
JA
50
51#include <linux/sched/signal.h>
52#include <linux/fs.h>
53#include <linux/file.h>
54#include <linux/fdtable.h>
55#include <linux/mm.h>
56#include <linux/mman.h>
2b188cc1
JA
57#include <linux/percpu.h>
58#include <linux/slab.h>
edafccee 59#include <linux/bvec.h>
2b188cc1
JA
60#include <linux/net.h>
61#include <net/sock.h>
2b188cc1
JA
62#include <linux/anon_inodes.h>
63#include <linux/sched/mm.h>
64#include <linux/uaccess.h>
65#include <linux/nospec.h>
aa4c3967 66#include <linux/highmem.h>
15b71abe 67#include <linux/fsnotify.h>
4840e418 68#include <linux/fadvise.h>
b41e9852 69#include <linux/task_work.h>
0f212204 70#include <linux/io_uring.h>
b66509b8 71#include <linux/io_uring/cmd.h>
5bd2182d 72#include <linux/audit.h>
cdc1404a 73#include <linux/security.h>
d808459b 74#include <asm/shmparam.h>
2b188cc1 75
c826bd7a
DD
76#define CREATE_TRACE_POINTS
77#include <trace/events/io_uring.h>
78
2b188cc1
JA
79#include <uapi/linux/io_uring.h>
80
561fb04a 81#include "io-wq.h"
2b188cc1 82
de23077e 83#include "io_uring.h"
329061d3 84#include "opdef.h"
e418bbc9 85#include "refs.h"
c9f06aa7 86#include "tctx.h"
c4320315 87#include "register.h"
17437f31 88#include "sqpoll.h"
a4ad4f74 89#include "fdinfo.h"
3b77495a 90#include "kbuf.h"
73572984 91#include "rsrc.h"
38513c46 92#include "cancel.h"
43e0bbbd 93#include "net.h"
eb42cebb 94#include "notif.h"
f31ecf67 95#include "waitid.h"
194bb58c 96#include "futex.h"
8d0c12a8 97#include "napi.h"
da12d9ab 98#include "uring_cmd.h"
e27f928e 99
59915143 100#include "timeout.h"
329061d3 101#include "poll.h"
c92fcfc2 102#include "rw.h"
9b797a37 103#include "alloc_cache.h"
5e2a18d9 104
5277deaa 105#define IORING_MAX_ENTRIES 32768
33a107f0 106#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
65e19f54 107
68fe256a
PB
108#define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110
5562a8d7
PB
111#define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
68fe256a 113
c854357b 114#define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
9cae36a0
JA
115 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
116 REQ_F_ASYNC_DATA)
b16fed66 117
a538be5b
PB
118#define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
119 IO_REQ_CLEAN_FLAGS)
120
09899b19
PB
121#define IO_TCTX_REFS_CACHE_NR (1U << 10)
122
6dd0be1e 123#define IO_COMPL_BATCH 32
bf019da7 124#define IO_REQ_ALLOC_BATCH 8
258b29a9 125
27dc8338
PB
126struct io_defer_entry {
127 struct list_head list;
128 struct io_kiocb *req;
9cf7c104 129 u32 seq;
2b188cc1
JA
130};
131
0756a869
PB
132/* requests with any of those set should undergo io_disarm_next() */
133#define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
da1a08c5 134#define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
0756a869 135
b4bc35cf
PB
136/*
137 * No waiters. It's larger than any valid value of the tw counter
138 * so that tests against ->cq_wait_nr would fail and skip wake_up().
139 */
140#define IO_CQ_WAKE_INIT (-1U)
141/* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
142#define IO_CQ_WAKE_FORCE (IO_CQ_WAKE_INIT >> 1)
143
affa87db 144static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9936c7c2 145 struct task_struct *task,
3dd0c97a 146 bool cancel_all);
1ffc5422 147
cbc2e203 148static void io_queue_sqe(struct io_kiocb *req);
de0617e4 149
c1755c25 150struct kmem_cache *req_cachep;
73eaa2b5 151static struct workqueue_struct *iou_wq __ro_after_init;
2b188cc1 152
76d3ccec
MR
153static int __read_mostly sysctl_io_uring_disabled;
154static int __read_mostly sysctl_io_uring_group = -1;
155
156#ifdef CONFIG_SYSCTL
157static struct ctl_table kernel_io_uring_disabled_table[] = {
158 {
159 .procname = "io_uring_disabled",
160 .data = &sysctl_io_uring_disabled,
161 .maxlen = sizeof(sysctl_io_uring_disabled),
162 .mode = 0644,
163 .proc_handler = proc_dointvec_minmax,
164 .extra1 = SYSCTL_ZERO,
165 .extra2 = SYSCTL_TWO,
166 },
167 {
168 .procname = "io_uring_group",
169 .data = &sysctl_io_uring_group,
170 .maxlen = sizeof(gid_t),
171 .mode = 0644,
172 .proc_handler = proc_dointvec,
173 },
174 {},
175};
176#endif
177
faf88dde
PB
178static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
179{
180 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
181}
182
0fc8c2ac
DY
183static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
184{
185 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
186}
187
9cae36a0
JA
188static bool io_match_linked(struct io_kiocb *head)
189{
190 struct io_kiocb *req;
191
192 io_for_each_link(req, head) {
193 if (req->flags & REQ_F_INFLIGHT)
194 return true;
195 }
196 return false;
6af3f48b
PB
197}
198
199/*
200 * As io_match_task() but protected against racing with linked timeouts.
201 * User must not hold timeout_lock.
202 */
329061d3
JA
203bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
204 bool cancel_all)
6af3f48b 205{
9cae36a0
JA
206 bool matched;
207
6af3f48b
PB
208 if (task && head->task != task)
209 return false;
9cae36a0
JA
210 if (cancel_all)
211 return true;
212
213 if (head->flags & REQ_F_LINK_TIMEOUT) {
214 struct io_ring_ctx *ctx = head->ctx;
215
216 /* protect against races with linked timeouts */
217 spin_lock_irq(&ctx->timeout_lock);
218 matched = io_match_linked(head);
219 spin_unlock_irq(&ctx->timeout_lock);
220 } else {
221 matched = io_match_linked(head);
222 }
223 return matched;
6af3f48b
PB
224}
225
a8295b98
HX
226static inline void req_fail_link_node(struct io_kiocb *req, int res)
227{
228 req_set_fail(req);
97b388d7 229 io_req_set_res(req, res, 0);
a8295b98
HX
230}
231
fa05457a
PB
232static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
233{
234 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
a8295b98
HX
235}
236
c072481d 237static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
2b188cc1
JA
238{
239 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
240
0f158b4c 241 complete(&ctx->ref_comp);
2b188cc1
JA
242}
243
c072481d 244static __cold void io_fallback_req_func(struct work_struct *work)
f56165e6
PB
245{
246 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
247 fallback_work.work);
248 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
249 struct io_kiocb *req, *tmp;
8e5b3b89 250 struct io_tw_state ts = {};
f56165e6 251
f7b32e78 252 percpu_ref_get(&ctx->refs);
31f084b7 253 mutex_lock(&ctx->uring_lock);
3218e5d3 254 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
a282967c 255 req->io_task_work.func(req, &ts);
31f084b7
PB
256 io_submit_flush_completions(ctx);
257 mutex_unlock(&ctx->uring_lock);
f7b32e78 258 percpu_ref_put(&ctx->refs);
f56165e6
PB
259}
260
e6f89be6
PB
261static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
262{
263 unsigned hash_buckets = 1U << bits;
264 size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
265
266 table->hbs = kmalloc(hash_size, GFP_KERNEL);
267 if (!table->hbs)
268 return -ENOMEM;
269
270 table->hash_bits = bits;
271 init_hash_table(table, hash_buckets);
272 return 0;
273}
274
c072481d 275static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
2b188cc1
JA
276{
277 struct io_ring_ctx *ctx;
9cfc7e94 278 int hash_bits;
2b188cc1
JA
279
280 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
281 if (!ctx)
282 return NULL;
283
9cfc7e94
JA
284 xa_init(&ctx->io_bl_xa);
285
78076bb6
JA
286 /*
287 * Use 5 bits less than the max cq entries, that should give us around
4a07723f
PB
288 * 32 entries per hash list if totally full and uniformly spread, but
289 * don't keep too many buckets to not overconsume memory.
78076bb6 290 */
4a07723f
PB
291 hash_bits = ilog2(p->cq_entries) - 5;
292 hash_bits = clamp(hash_bits, 1, 8);
e6f89be6 293 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
78076bb6 294 goto err;
9ca9fb24
PB
295 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
296 goto err;
21482896 297 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
48904229 298 0, GFP_KERNEL))
206aefde 299 goto err;
2b188cc1
JA
300
301 ctx->flags = p->flags;
b4bc35cf 302 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
90554200 303 init_waitqueue_head(&ctx->sqo_sq_wait);
69fb2131 304 INIT_LIST_HEAD(&ctx->sqd_list);
1d7bb1d5 305 INIT_LIST_HEAD(&ctx->cq_overflow_list);
cc3cec83 306 INIT_LIST_HEAD(&ctx->io_buffers_cache);
c392cbec 307 INIT_HLIST_HEAD(&ctx->io_buf_list);
69bbc6ad
PB
308 io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
309 sizeof(struct io_rsrc_node));
310 io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX,
311 sizeof(struct async_poll));
312 io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
313 sizeof(struct io_async_msghdr));
194bb58c 314 io_futex_cache_init(ctx);
0f158b4c 315 init_completion(&ctx->ref_comp);
61cf9370 316 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
2b188cc1 317 mutex_init(&ctx->uring_lock);
311997b3 318 init_waitqueue_head(&ctx->cq_wait);
7b235dd8 319 init_waitqueue_head(&ctx->poll_wq);
4ea15b56 320 init_waitqueue_head(&ctx->rsrc_quiesce_wq);
2b188cc1 321 spin_lock_init(&ctx->completion_lock);
89850fce 322 spin_lock_init(&ctx->timeout_lock);
5eef4e87 323 INIT_WQ_LIST(&ctx->iopoll_list);
cc3cec83 324 INIT_LIST_HEAD(&ctx->io_buffers_comp);
de0617e4 325 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 326 INIT_LIST_HEAD(&ctx->timeout_list);
ef9dd637 327 INIT_LIST_HEAD(&ctx->ltimeout_list);
d67d2263 328 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
c0e0d6ba 329 init_llist_head(&ctx->work_llist);
13bf43f5 330 INIT_LIST_HEAD(&ctx->tctx_list);
c2b6c6bc
PB
331 ctx->submit_state.free_list.next = NULL;
332 INIT_WQ_LIST(&ctx->locked_free_list);
f31ecf67 333 INIT_HLIST_HEAD(&ctx->waitid_list);
194bb58c
JA
334#ifdef CONFIG_FUTEX
335 INIT_HLIST_HEAD(&ctx->futex_list);
336#endif
9011bf9a 337 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
6f33b0bc 338 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
93b8cc60 339 INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
8d0c12a8
SR
340 io_napi_init(ctx);
341
2b188cc1 342 return ctx;
206aefde 343err:
e6f89be6 344 kfree(ctx->cancel_table.hbs);
9ca9fb24 345 kfree(ctx->cancel_table_locked.hbs);
9cfc7e94 346 xa_destroy(&ctx->io_bl_xa);
206aefde
JA
347 kfree(ctx);
348 return NULL;
2b188cc1
JA
349}
350
8f6ed49a
PB
351static void io_account_cq_overflow(struct io_ring_ctx *ctx)
352{
353 struct io_rings *r = ctx->rings;
354
355 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
356 ctx->cq_extra--;
357}
358
9cf7c104 359static bool req_need_defer(struct io_kiocb *req, u32 seq)
7adf4eaf 360{
2bc9930e
JA
361 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
362 struct io_ring_ctx *ctx = req->ctx;
a197f664 363
8f6ed49a 364 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
2bc9930e 365 }
de0617e4 366
9d858b21 367 return false;
de0617e4
JA
368}
369
5a754dea
PB
370static void io_clean_op(struct io_kiocb *req)
371{
372 if (req->flags & REQ_F_BUFFER_SELECTED) {
373 spin_lock(&req->ctx->completion_lock);
374 io_put_kbuf_comp(req);
375 spin_unlock(&req->ctx->completion_lock);
376 }
377
378 if (req->flags & REQ_F_NEED_CLEANUP) {
379 const struct io_cold_def *def = &io_cold_defs[req->opcode];
380
381 if (def->cleanup)
382 def->cleanup(req);
383 }
384 if ((req->flags & REQ_F_POLLED) && req->apoll) {
385 kfree(req->apoll->double_poll);
386 kfree(req->apoll);
387 req->apoll = NULL;
388 }
389 if (req->flags & REQ_F_INFLIGHT) {
390 struct io_uring_task *tctx = req->task->io_uring;
391
392 atomic_dec(&tctx->inflight_tracked);
393 }
394 if (req->flags & REQ_F_CREDS)
395 put_cred(req->creds);
396 if (req->flags & REQ_F_ASYNC_DATA) {
397 kfree(req->async_data);
398 req->async_data = NULL;
399 }
400 req->flags &= ~IO_REQ_CLEAN_FLAGS;
401}
402
9cae36a0
JA
403static inline void io_req_track_inflight(struct io_kiocb *req)
404{
405 if (!(req->flags & REQ_F_INFLIGHT)) {
406 req->flags |= REQ_F_INFLIGHT;
386e4fb6 407 atomic_inc(&req->task->io_uring->inflight_tracked);
9cae36a0
JA
408 }
409}
410
fd08e530
PB
411static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
412{
906c6caa
PB
413 if (WARN_ON_ONCE(!req->link))
414 return NULL;
415
4d13d1a4
PB
416 req->flags &= ~REQ_F_ARM_LTIMEOUT;
417 req->flags |= REQ_F_LINK_TIMEOUT;
fd08e530
PB
418
419 /* linked timeouts should have two refs once prep'ed */
48dcd38d 420 io_req_set_refcount(req);
4d13d1a4
PB
421 __io_req_set_refcount(req->link, 2);
422 return req->link;
fd08e530
PB
423}
424
425static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
426{
4d13d1a4 427 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
fd08e530
PB
428 return NULL;
429 return __io_prep_linked_timeout(req);
430}
431
cb2d344c
PB
432static noinline void __io_arm_ltimeout(struct io_kiocb *req)
433{
434 io_queue_linked_timeout(__io_prep_linked_timeout(req));
435}
436
437static inline void io_arm_ltimeout(struct io_kiocb *req)
438{
439 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
440 __io_arm_ltimeout(req);
441}
442
1e6fa521
JA
443static void io_prep_async_work(struct io_kiocb *req)
444{
a7dd2782 445 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1e6fa521
JA
446 struct io_ring_ctx *ctx = req->ctx;
447
b8e64b53
PB
448 if (!(req->flags & REQ_F_CREDS)) {
449 req->flags |= REQ_F_CREDS;
c10d1f98 450 req->creds = get_current_cred();
b8e64b53 451 }
003e8dcc 452
e1d675df
PB
453 req->work.list.next = NULL;
454 req->work.flags = 0;
feaadc4f
PB
455 if (req->flags & REQ_F_FORCE_ASYNC)
456 req->work.flags |= IO_WQ_WORK_CONCURRENT;
457
3beed235 458 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
8487f083 459 req->flags |= io_file_get_flags(req->file);
f6b543fd 460
8b1df11f 461 if (req->file && (req->flags & REQ_F_ISREG)) {
d4755e15
JA
462 bool should_hash = def->hash_reg_file;
463
464 /* don't serialize this request if the fs doesn't need it */
465 if (should_hash && (req->file->f_flags & O_DIRECT) &&
466 (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE))
467 should_hash = false;
468 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
1e6fa521 469 io_wq_hash_work(&req->work, file_inode(req->file));
4b982bd0 470 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1e6fa521
JA
471 if (def->unbound_nonreg_file)
472 req->work.flags |= IO_WQ_WORK_UNBOUND;
473 }
561fb04a 474}
cccf0ee8 475
cbdcb435 476static void io_prep_async_link(struct io_kiocb *req)
561fb04a 477{
cbdcb435 478 struct io_kiocb *cur;
54a91f3b 479
44eff40a
PB
480 if (req->flags & REQ_F_LINK_TIMEOUT) {
481 struct io_ring_ctx *ctx = req->ctx;
482
674ee8e1 483 spin_lock_irq(&ctx->timeout_lock);
44eff40a
PB
484 io_for_each_link(cur, req)
485 io_prep_async_work(cur);
674ee8e1 486 spin_unlock_irq(&ctx->timeout_lock);
44eff40a
PB
487 } else {
488 io_for_each_link(cur, req)
489 io_prep_async_work(cur);
490 }
561fb04a
JA
491}
492
6e6b8c62 493static void io_queue_iowq(struct io_kiocb *req)
561fb04a 494{
cbdcb435 495 struct io_kiocb *link = io_prep_linked_timeout(req);
5aa75ed5 496 struct io_uring_task *tctx = req->task->io_uring;
561fb04a 497
3bfe6106
JA
498 BUG_ON(!tctx);
499 BUG_ON(!tctx->io_wq);
561fb04a 500
cbdcb435
PB
501 /* init ->work of the whole link before punting */
502 io_prep_async_link(req);
991468dc
JA
503
504 /*
505 * Not expected to happen, but if we do have a bug where this _can_
506 * happen, catch it here and ensure the request is marked as
507 * canceled. That will make io-wq go through the usual work cancel
508 * procedure rather than attempt to run this request (or create a new
509 * worker for it).
510 */
511 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
512 req->work.flags |= IO_WQ_WORK_CANCEL;
513
48863ffd 514 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
ebf93667 515 io_wq_enqueue(tctx->io_wq, &req->work);
7271ef3a
JA
516 if (link)
517 io_queue_linked_timeout(link);
cbdcb435
PB
518}
519
c072481d 520static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
de0617e4 521{
441b8a78 522 while (!list_empty(&ctx->defer_list)) {
27dc8338
PB
523 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
524 struct io_defer_entry, list);
de0617e4 525
9cf7c104 526 if (req_need_defer(de->req, de->seq))
04518945 527 break;
27dc8338 528 list_del_init(&de->list);
907d1df3 529 io_req_task_queue(de->req);
27dc8338 530 kfree(de);
441b8a78 531 }
04518945
PB
532}
533
c4320315 534void io_eventfd_ops(struct rcu_head *rcu)
f2842ab5 535{
d8e9214f 536 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
21a091b9 537 int ops = atomic_xchg(&ev_fd->ops, 0);
305bef98 538
21a091b9 539 if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT))
120ae585 540 eventfd_signal_mask(ev_fd->cq_ev_fd, EPOLL_URING_WAKE);
d8e9214f 541
21a091b9
DY
542 /* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback
543 * ordering in a race but if references are 0 we know we have to free
544 * it regardless.
305bef98 545 */
21a091b9
DY
546 if (atomic_dec_and_test(&ev_fd->refs)) {
547 eventfd_ctx_put(ev_fd->cq_ev_fd);
548 kfree(ev_fd);
549 }
d8e9214f
DY
550}
551
77bc59b4 552static void io_eventfd_signal(struct io_ring_ctx *ctx)
f2842ab5 553{
21a091b9 554 struct io_ev_fd *ev_fd = NULL;
77bc59b4 555
77bc59b4
UA
556 rcu_read_lock();
557 /*
558 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
559 * and eventfd_signal
560 */
561 ev_fd = rcu_dereference(ctx->io_ev_fd);
562
563 /*
564 * Check again if ev_fd exists incase an io_eventfd_unregister call
565 * completed between the NULL check of ctx->io_ev_fd at the start of
566 * the function and rcu_read_lock.
567 */
568 if (unlikely(!ev_fd))
569 goto out;
7e55a19c 570 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
77bc59b4 571 goto out;
21a091b9
DY
572 if (ev_fd->eventfd_async && !io_wq_current_is_worker())
573 goto out;
77bc59b4 574
21a091b9 575 if (likely(eventfd_signal_allowed())) {
120ae585 576 eventfd_signal_mask(ev_fd->cq_ev_fd, EPOLL_URING_WAKE);
21a091b9
DY
577 } else {
578 atomic_inc(&ev_fd->refs);
579 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops))
44a84da4 580 call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops);
21a091b9
DY
581 else
582 atomic_dec(&ev_fd->refs);
583 }
584
77bc59b4
UA
585out:
586 rcu_read_unlock();
f2842ab5
JA
587}
588
21a091b9
DY
589static void io_eventfd_flush_signal(struct io_ring_ctx *ctx)
590{
591 bool skip;
592
593 spin_lock(&ctx->completion_lock);
594
595 /*
596 * Eventfd should only get triggered when at least one event has been
597 * posted. Some applications rely on the eventfd notification count
598 * only changing IFF a new CQE has been added to the CQ ring. There's
599 * no depedency on 1:1 relationship between how many times this
600 * function is called (and hence the eventfd count) and number of CQEs
601 * posted to the CQ ring.
602 */
603 skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail;
604 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
605 spin_unlock(&ctx->completion_lock);
606 if (skip)
607 return;
608
609 io_eventfd_signal(ctx);
610}
611
a830ffd2
PB
612void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
613{
bca39f39
PB
614 if (ctx->poll_activated)
615 io_poll_wq_wake(ctx);
e5f30f6f
PB
616 if (ctx->off_timeout_used)
617 io_flush_timeouts(ctx);
618 if (ctx->drain_active) {
a830ffd2 619 spin_lock(&ctx->completion_lock);
e5f30f6f 620 io_queue_deferred(ctx);
a830ffd2
PB
621 spin_unlock(&ctx->completion_lock);
622 }
623 if (ctx->has_evfd)
21a091b9 624 io_eventfd_flush_signal(ctx);
a830ffd2
PB
625}
626
f66f7342 627static inline void __io_cq_lock(struct io_ring_ctx *ctx)
f66f7342 628{
ec26c225 629 if (!ctx->lockless_cq)
f66f7342
PB
630 spin_lock(&ctx->completion_lock);
631}
632
902ce82c
PB
633static inline void __io_cq_unlock(struct io_ring_ctx *ctx)
634{
635 if (!ctx->lockless_cq)
636 spin_unlock(&ctx->completion_lock);
637}
638
6971253f
PB
639static inline void io_cq_lock(struct io_ring_ctx *ctx)
640 __acquires(ctx->completion_lock)
641{
642 spin_lock(&ctx->completion_lock);
643}
644
f66f7342 645static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
3181e22f
PB
646{
647 io_commit_cqring(ctx);
54927baf 648 if (!ctx->task_complete) {
ec26c225
PB
649 if (!ctx->lockless_cq)
650 spin_unlock(&ctx->completion_lock);
651 /* IOPOLL rings only need to wake up if it's also SQPOLL */
652 if (!ctx->syscall_iopoll)
653 io_cqring_wake(ctx);
3181e22f 654 }
54927baf 655 io_commit_cqring_flush(ctx);
3181e22f
PB
656}
657
0fdb9a19 658static void io_cq_unlock_post(struct io_ring_ctx *ctx)
5d772916 659 __releases(ctx->completion_lock)
25399321 660{
f66f7342
PB
661 io_commit_cqring(ctx);
662 spin_unlock(&ctx->completion_lock);
f66f7342 663 io_cqring_wake(ctx);
54927baf 664 io_commit_cqring_flush(ctx);
25399321
PB
665}
666
a85381d8
PB
667static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
668{
669 struct io_overflow_cqe *ocqe;
670 LIST_HEAD(list);
671
f432b76b 672 spin_lock(&ctx->completion_lock);
a85381d8
PB
673 list_splice_init(&ctx->cq_overflow_list, &list);
674 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
f432b76b 675 spin_unlock(&ctx->completion_lock);
a85381d8
PB
676
677 while (!list_empty(&list)) {
678 ocqe = list_first_entry(&list, struct io_overflow_cqe, list);
679 list_del(&ocqe->list);
680 kfree(ocqe);
681 }
682}
683
1b346e4a 684static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1d7bb1d5 685{
e45a3e05 686 size_t cqe_size = sizeof(struct io_uring_cqe);
1d7bb1d5 687
a85381d8 688 if (__io_cqring_events(ctx) == ctx->cq_entries)
1b346e4a 689 return;
1d7bb1d5 690
e45a3e05
SR
691 if (ctx->flags & IORING_SETUP_CQE32)
692 cqe_size <<= 1;
693
25399321 694 io_cq_lock(ctx);
6c2450ae 695 while (!list_empty(&ctx->cq_overflow_list)) {
59fbc409 696 struct io_uring_cqe *cqe;
6c2450ae 697 struct io_overflow_cqe *ocqe;
e6c8aa9a 698
59fbc409 699 if (!io_get_cqe_overflow(ctx, &cqe, true))
1d7bb1d5 700 break;
6c2450ae
PB
701 ocqe = list_first_entry(&ctx->cq_overflow_list,
702 struct io_overflow_cqe, list);
a85381d8 703 memcpy(cqe, &ocqe->cqe, cqe_size);
6c2450ae
PB
704 list_del(&ocqe->list);
705 kfree(ocqe);
1d7bb1d5
JA
706 }
707
1b346e4a 708 if (list_empty(&ctx->cq_overflow_list)) {
10988a0a 709 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
3a4b89a2 710 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
09e88404 711 }
25399321 712 io_cq_unlock_post(ctx);
1d7bb1d5
JA
713}
714
52ea806a
JA
715static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
716{
717 /* iopoll syncs against uring_lock, not completion_lock */
718 if (ctx->flags & IORING_SETUP_IOPOLL)
719 mutex_lock(&ctx->uring_lock);
720 __io_cqring_overflow_flush(ctx);
721 if (ctx->flags & IORING_SETUP_IOPOLL)
722 mutex_unlock(&ctx->uring_lock);
723}
724
1b346e4a 725static void io_cqring_overflow_flush(struct io_ring_ctx *ctx)
6c503150 726{
52ea806a
JA
727 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
728 io_cqring_do_overflow_flush(ctx);
6c503150
PB
729}
730
5afa4650 731/* can be called by any task */
2fdd6fb5 732static void io_put_task_remote(struct task_struct *task)
6a290a14
PB
733{
734 struct io_uring_task *tctx = task->io_uring;
735
2fdd6fb5 736 percpu_counter_sub(&tctx->inflight, 1);
8d664282 737 if (unlikely(atomic_read(&tctx->in_cancel)))
9d170164 738 wake_up(&tctx->wait);
2fdd6fb5 739 put_task_struct(task);
9d170164
PB
740}
741
5afa4650 742/* used by a task to put its own references */
2fdd6fb5 743static void io_put_task_local(struct task_struct *task)
5afa4650 744{
2fdd6fb5 745 task->io_uring->cached_refs++;
5afa4650
PB
746}
747
89800a2d 748/* must to be called somewhat shortly after putting a request */
2fdd6fb5 749static inline void io_put_task(struct task_struct *task)
89800a2d
PB
750{
751 if (likely(task == current))
2fdd6fb5 752 io_put_task_local(task);
89800a2d 753 else
2fdd6fb5 754 io_put_task_remote(task);
89800a2d
PB
755}
756
63809137 757void io_task_refs_refill(struct io_uring_task *tctx)
9a10867a
PB
758{
759 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
760
761 percpu_counter_add(&tctx->inflight, refill);
762 refcount_add(refill, &current->usage);
763 tctx->cached_refs += refill;
764}
765
3cc7fdb9
PB
766static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
767{
768 struct io_uring_task *tctx = task->io_uring;
769 unsigned int refs = tctx->cached_refs;
770
771 if (refs) {
772 tctx->cached_refs = 0;
773 percpu_counter_sub(&tctx->inflight, refs);
774 put_task_struct_many(task, refs);
775 }
776}
777
68494a65
PB
778static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
779 s32 res, u32 cflags, u64 extra1, u64 extra2)
2b188cc1 780{
cce4b8b0 781 struct io_overflow_cqe *ocqe;
e45a3e05
SR
782 size_t ocq_size = sizeof(struct io_overflow_cqe);
783 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2b188cc1 784
f26cc959
PB
785 lockdep_assert_held(&ctx->completion_lock);
786
e45a3e05
SR
787 if (is_cqe32)
788 ocq_size += sizeof(struct io_uring_cqe);
2b188cc1 789
e45a3e05 790 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
08dcd028 791 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
cce4b8b0
PB
792 if (!ocqe) {
793 /*
794 * If we're in ring overflow flush mode, or in task cancel mode,
795 * or cannot allocate an overflow entry, then we need to drop it
796 * on the floor.
797 */
8f6ed49a 798 io_account_cq_overflow(ctx);
155bc950 799 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
cce4b8b0 800 return false;
2b188cc1 801 }
cce4b8b0 802 if (list_empty(&ctx->cq_overflow_list)) {
10988a0a 803 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
3a4b89a2 804 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
20c0b380 805
cce4b8b0 806 }
d4d19c19 807 ocqe->cqe.user_data = user_data;
cce4b8b0
PB
808 ocqe->cqe.res = res;
809 ocqe->cqe.flags = cflags;
e45a3e05
SR
810 if (is_cqe32) {
811 ocqe->cqe.big_cqe[0] = extra1;
812 ocqe->cqe.big_cqe[1] = extra2;
813 }
cce4b8b0
PB
814 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
815 return true;
2b188cc1
JA
816}
817
056695bf 818void io_req_cqe_overflow(struct io_kiocb *req)
68494a65 819{
056695bf
PB
820 io_cqring_event_overflow(req->ctx, req->cqe.user_data,
821 req->cqe.res, req->cqe.flags,
b24c5d75
PB
822 req->big_cqe.extra1, req->big_cqe.extra2);
823 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
68494a65
PB
824}
825
faf88dde
PB
826/*
827 * writes to the cq entry need to come after reading head; the
828 * control dependency is enough as we're using WRITE_ONCE to
829 * fill the cq entry
830 */
20d6b633 831bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
faf88dde
PB
832{
833 struct io_rings *rings = ctx->rings;
834 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
faf88dde
PB
835 unsigned int free, queued, len;
836
aa1df3a3
PB
837 /*
838 * Posting into the CQ when there are pending overflowed CQEs may break
839 * ordering guarantees, which will affect links, F_MORE users and more.
840 * Force overflow the completion.
841 */
842 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
20d6b633 843 return false;
faf88dde
PB
844
845 /* userspace may cheat modifying the tail, be safe and do min */
846 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
847 free = ctx->cq_entries - queued;
848 /* we need a contiguous range, limit based on the current array offset */
849 len = min(free, ctx->cq_entries - off);
850 if (!len)
20d6b633 851 return false;
faf88dde 852
b3659a65
PB
853 if (ctx->flags & IORING_SETUP_CQE32) {
854 off <<= 1;
855 len <<= 1;
856 }
857
faf88dde
PB
858 ctx->cqe_cached = &rings->cqes[off];
859 ctx->cqe_sentinel = ctx->cqe_cached + len;
20d6b633 860 return true;
faf88dde
PB
861}
862
f66f7342
PB
863static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
864 u32 cflags)
bcda7baa 865{
cd94903d
PB
866 struct io_uring_cqe *cqe;
867
913a571a 868 ctx->cq_extra++;
cd94903d
PB
869
870 /*
871 * If we can't get a cq entry, userspace overflowed the
872 * submission (by quite a lot). Increment the overflow count in
873 * the ring.
874 */
59fbc409 875 if (likely(io_get_cqe(ctx, &cqe))) {
e0486f3f
DY
876 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
877
cd94903d
PB
878 WRITE_ONCE(cqe->user_data, user_data);
879 WRITE_ONCE(cqe->res, res);
880 WRITE_ONCE(cqe->flags, cflags);
c5595975
PB
881
882 if (ctx->flags & IORING_SETUP_CQE32) {
883 WRITE_ONCE(cqe->big_cqe[0], 0);
884 WRITE_ONCE(cqe->big_cqe[1], 0);
885 }
cd94903d
PB
886 return true;
887 }
52120f0f 888 return false;
bcda7baa
JA
889}
890
e5c12945 891bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
d245bca6
PB
892{
893 bool filled;
894
25399321 895 io_cq_lock(ctx);
f66f7342 896 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
e5c12945 897 if (!filled)
f66f7342
PB
898 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
899
25399321 900 io_cq_unlock_post(ctx);
d245bca6
PB
901 return filled;
902}
903
b6b2bb58
PB
904/*
905 * A helper for multishot requests posting additional CQEs.
906 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
907 */
e5c12945 908bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
2b188cc1 909{
d86eaed1 910 struct io_ring_ctx *ctx = req->ctx;
902ce82c 911 bool posted;
9b8c5475 912
e0e4ab52 913 lockdep_assert(!io_wq_current_is_worker());
9b8c5475
DY
914 lockdep_assert_held(&ctx->uring_lock);
915
902ce82c
PB
916 __io_cq_lock(ctx);
917 posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
918 ctx->submit_state.cq_flush = true;
919 __io_cq_unlock_post(ctx);
920 return posted;
9b8c5475
DY
921}
922
0667db14 923static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
2b188cc1 924{
fa18fa22 925 struct io_ring_ctx *ctx = req->ctx;
2ad4c6d0 926 struct io_rsrc_node *rsrc_node = NULL;
fa18fa22 927
0667db14
PB
928 /*
929 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
930 * the submitter task context, IOPOLL protects with uring_lock.
931 */
932 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL)) {
933 req->io_task_work.func = io_req_task_complete;
934 io_req_task_work_add(req);
935 return;
936 }
937
fa18fa22 938 io_cq_lock(ctx);
00b0db56
PB
939 if (!(req->flags & REQ_F_CQE_SKIP)) {
940 if (!io_fill_cqe_req(ctx, req))
941 io_req_cqe_overflow(req);
942 }
fa18fa22 943
c7dae4ba
JA
944 /*
945 * If we're the last reference to this request, add to our locked
946 * free_list cache.
947 */
de9b4cca 948 if (req_ref_put_and_test(req)) {
da1a08c5 949 if (req->flags & IO_REQ_LINK_FLAGS) {
0756a869 950 if (req->flags & IO_DISARM_MASK)
7a612350
PB
951 io_disarm_next(req);
952 if (req->link) {
953 io_req_task_queue(req->link);
954 req->link = NULL;
955 }
956 }
68a2cc1b 957 io_put_kbuf_comp(req);
3b7a612f
PB
958 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
959 io_clean_op(req);
17bc2837 960 io_put_file(req);
3b7a612f 961
2ad4c6d0 962 rsrc_node = req->rsrc_node;
8197b053
PB
963 /*
964 * Selected buffer deallocation in io_clean_op() assumes that
965 * we don't hold ->completion_lock. Clean them here to avoid
966 * deadlocks.
967 */
2fdd6fb5 968 io_put_task_remote(req->task);
c2b6c6bc 969 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
d0acdee2 970 ctx->locked_free_nr++;
180f829f 971 }
25399321 972 io_cq_unlock_post(ctx);
2ad4c6d0 973
ef8ae64f
PB
974 if (rsrc_node) {
975 io_ring_submit_lock(ctx, issue_flags);
1f2c8f61 976 io_put_rsrc_node(ctx, rsrc_node);
ef8ae64f
PB
977 io_ring_submit_unlock(ctx, issue_flags);
978 }
4e3d9ff9
JA
979}
980
973fc83f 981void io_req_defer_failed(struct io_kiocb *req, s32 res)
e276ae34 982 __must_hold(&ctx->uring_lock)
f41db273 983{
f30bd4d0 984 const struct io_cold_def *def = &io_cold_defs[req->opcode];
a47b255e 985
e276ae34
PB
986 lockdep_assert_held(&req->ctx->uring_lock);
987
93d2bcd2 988 req_set_fail(req);
97b388d7 989 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
a47b255e
PB
990 if (def->fail)
991 def->fail(req);
973fc83f 992 io_req_complete_defer(req);
f41db273
PB
993}
994
864ea921
PB
995/*
996 * Don't initialise the fields below on every allocation, but do that in
997 * advance and keep them valid across allocations.
998 */
999static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1000{
1001 req->ctx = ctx;
1002 req->link = NULL;
1003 req->async_data = NULL;
1004 /* not necessary, but safer to zero */
31d3ba92 1005 memset(&req->cqe, 0, sizeof(req->cqe));
b24c5d75 1006 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
864ea921
PB
1007}
1008
dac7a098 1009static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
cd0ca2e0 1010 struct io_submit_state *state)
dac7a098 1011{
79ebeaee 1012 spin_lock(&ctx->completion_lock);
c2b6c6bc 1013 wq_list_splice(&ctx->locked_free_list, &state->free_list);
d0acdee2 1014 ctx->locked_free_nr = 0;
79ebeaee 1015 spin_unlock(&ctx->completion_lock);
dac7a098
PB
1016}
1017
5d5901a3
PB
1018/*
1019 * A request might get retired back into the request caches even before opcode
1020 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1021 * Because of that, io_alloc_req() should be called only under ->uring_lock
1022 * and with extra caution to not get a request that is still worked on.
1023 */
bd1a3783 1024__cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
5d5901a3 1025 __must_hold(&ctx->uring_lock)
2b188cc1 1026{
864ea921 1027 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
3ab665b7 1028 void *reqs[IO_REQ_ALLOC_BATCH];
864ea921 1029 int ret, i;
e5d1bc0a 1030
23a5c43b
PB
1031 /*
1032 * If we have more than a batch's worth of requests in our IRQ side
1033 * locked cache, grab the lock and move them over to our submission
1034 * side cache.
1035 */
a6d97a8a 1036 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
23a5c43b 1037 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
88ab95be 1038 if (!io_req_cache_empty(ctx))
23a5c43b
PB
1039 return true;
1040 }
e5d1bc0a 1041
3ab665b7 1042 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
fd6fab2c 1043
864ea921
PB
1044 /*
1045 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1046 * retry single alloc to be on the safe side.
1047 */
1048 if (unlikely(ret <= 0)) {
3ab665b7
PB
1049 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1050 if (!reqs[0])
a33ae9ce 1051 return false;
864ea921 1052 ret = 1;
2b188cc1 1053 }
864ea921 1054
37f0e767 1055 percpu_ref_get_many(&ctx->refs, ret);
3ab665b7 1056 for (i = 0; i < ret; i++) {
23a5c43b 1057 struct io_kiocb *req = reqs[i];
3ab665b7
PB
1058
1059 io_preinit_req(req, ctx);
fa05457a 1060 io_req_add_to_cache(req, ctx);
3ab665b7 1061 }
a33ae9ce
PB
1062 return true;
1063}
1064
03adabe8
PB
1065__cold void io_free_req(struct io_kiocb *req)
1066{
6ec9afc7
PB
1067 /* refs were already put, restore them for io_req_task_complete() */
1068 req->flags &= ~REQ_F_REFCOUNT;
1069 /* we only want to free it, don't post CQEs */
1070 req->flags |= REQ_F_CQE_SKIP;
1071 req->io_task_work.func = io_req_task_complete;
03adabe8
PB
1072 io_req_task_work_add(req);
1073}
1074
d81499bf
PB
1075static void __io_req_find_next_prep(struct io_kiocb *req)
1076{
1077 struct io_ring_ctx *ctx = req->ctx;
d81499bf 1078
6971253f 1079 spin_lock(&ctx->completion_lock);
305bef98 1080 io_disarm_next(req);
6971253f 1081 spin_unlock(&ctx->completion_lock);
d81499bf
PB
1082}
1083
1084static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
c69f8dbe 1085{
33cc89a9 1086 struct io_kiocb *nxt;
944e58bf 1087
9e645e11
JA
1088 /*
1089 * If LINK is set, we have dependent requests in this chain. If we
1090 * didn't fail this request, queue the first one up, moving any other
1091 * dependencies to the next request. In case of failure, fail the rest
1092 * of the chain.
1093 */
d81499bf
PB
1094 if (unlikely(req->flags & IO_DISARM_MASK))
1095 __io_req_find_next_prep(req);
33cc89a9
PB
1096 nxt = req->link;
1097 req->link = NULL;
1098 return nxt;
4d7dd462 1099}
9e645e11 1100
a282967c 1101static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
2c32395d
PB
1102{
1103 if (!ctx)
1104 return;
ef060ea9
JA
1105 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1106 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
8e5b3b89
PB
1107
1108 io_submit_flush_completions(ctx);
1109 mutex_unlock(&ctx->uring_lock);
2c32395d
PB
1110 percpu_ref_put(&ctx->refs);
1111}
1112
af5d68f8
JA
1113/*
1114 * Run queued task_work, returning the number of entries processed in *count.
1115 * If more entries than max_entries are available, stop processing once this
1116 * is reached and return the rest of the list.
1117 */
1118struct llist_node *io_handle_tw_list(struct llist_node *node,
1119 unsigned int *count,
1120 unsigned int max_entries)
9f8d032a 1121{
42c0905f
JA
1122 struct io_ring_ctx *ctx = NULL;
1123 struct io_tw_state ts = { };
c6dd763c 1124
592b4805 1125 do {
f88262e6 1126 struct llist_node *next = node->next;
9f8d032a
HX
1127 struct io_kiocb *req = container_of(node, struct io_kiocb,
1128 io_task_work.node);
1129
42c0905f
JA
1130 if (req->ctx != ctx) {
1131 ctx_flush_and_put(ctx, &ts);
1132 ctx = req->ctx;
92219afb 1133 mutex_lock(&ctx->uring_lock);
42c0905f 1134 percpu_ref_get(&ctx->refs);
13bfa6f1 1135 }
c92fcfc2
JA
1136 INDIRECT_CALL_2(req->io_task_work.func,
1137 io_poll_task_func, io_req_rw_complete,
42c0905f 1138 req, &ts);
9f8d032a 1139 node = next;
2708af1a 1140 (*count)++;
f5868008 1141 if (unlikely(need_resched())) {
42c0905f
JA
1142 ctx_flush_and_put(ctx, &ts);
1143 ctx = NULL;
f5868008
JA
1144 cond_resched();
1145 }
af5d68f8 1146 } while (node && *count < max_entries);
c6dd763c 1147
42c0905f 1148 ctx_flush_and_put(ctx, &ts);
af5d68f8 1149 return node;
9f8d032a
HX
1150}
1151
923d1592
DY
1152/**
1153 * io_llist_xchg - swap all entries in a lock-less list
1154 * @head: the head of lock-less list to delete all entries
1155 * @new: new entry as the head of the list
1156 *
1157 * If list is empty, return NULL, otherwise, return the pointer to the first entry.
1158 * The order of entries returned is from the newest to the oldest added one.
1159 */
1160static inline struct llist_node *io_llist_xchg(struct llist_head *head,
1161 struct llist_node *new)
1162{
1163 return xchg(&head->first, new);
1164}
1165
dfbe5561 1166static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
10e1c0d5
JA
1167{
1168 struct llist_node *node = llist_del_all(&tctx->task_list);
dfbe5561 1169 struct io_ring_ctx *last_ctx = NULL;
10e1c0d5
JA
1170 struct io_kiocb *req;
1171
1172 while (node) {
1173 req = container_of(node, struct io_kiocb, io_task_work.node);
1174 node = node->next;
dfbe5561
JA
1175 if (sync && last_ctx != req->ctx) {
1176 if (last_ctx) {
1177 flush_delayed_work(&last_ctx->fallback_work);
1178 percpu_ref_put(&last_ctx->refs);
1179 }
1180 last_ctx = req->ctx;
1181 percpu_ref_get(&last_ctx->refs);
1182 }
10e1c0d5
JA
1183 if (llist_add(&req->io_task_work.node,
1184 &req->ctx->fallback_llist))
1185 schedule_delayed_work(&req->ctx->fallback_work, 1);
1186 }
dfbe5561
JA
1187
1188 if (last_ctx) {
1189 flush_delayed_work(&last_ctx->fallback_work);
1190 percpu_ref_put(&last_ctx->refs);
1191 }
10e1c0d5
JA
1192}
1193
af5d68f8
JA
1194struct llist_node *tctx_task_work_run(struct io_uring_task *tctx,
1195 unsigned int max_entries,
1196 unsigned int *count)
c40f6379 1197{
77e443ab 1198 struct llist_node *node;
3a0c037b 1199
77e443ab 1200 if (unlikely(current->flags & PF_EXITING)) {
dfbe5561 1201 io_fallback_tw(tctx, true);
af5d68f8 1202 return NULL;
77e443ab 1203 }
3a0c037b 1204
592b4805 1205 node = llist_del_all(&tctx->task_list);
af5d68f8
JA
1206 if (node) {
1207 node = llist_reverse_order(node);
1208 node = io_handle_tw_list(node, count, max_entries);
1209 }
3cc7fdb9 1210
8d664282
JA
1211 /* relaxed read is enough as only the task itself sets ->in_cancel */
1212 if (unlikely(atomic_read(&tctx->in_cancel)))
3cc7fdb9 1213 io_uring_drop_tctx_refs(current);
c6dd763c 1214
af5d68f8
JA
1215 trace_io_uring_task_work_run(tctx, *count);
1216 return node;
1217}
1218
1219void tctx_task_work(struct callback_head *cb)
1220{
1221 struct io_uring_task *tctx;
1222 struct llist_node *ret;
1223 unsigned int count = 0;
1224
1225 tctx = container_of(cb, struct io_uring_task, task_work);
1226 ret = tctx_task_work_run(tctx, UINT_MAX, &count);
1227 /* can't happen */
1228 WARN_ON_ONCE(ret);
7cbf1722
JA
1229}
1230
91c7884a 1231static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
c0e0d6ba
DY
1232{
1233 struct io_ring_ctx *ctx = req->ctx;
8751d154 1234 unsigned nr_wait, nr_tw, nr_tw_prev;
e8c40771 1235 struct llist_node *head;
c0e0d6ba 1236
b4bc35cf
PB
1237 /* See comment above IO_CQ_WAKE_INIT */
1238 BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
c0e0d6ba 1239
b4bc35cf
PB
1240 /*
1241 * We don't know how many reuqests is there in the link and whether
1242 * they can even be queued lazily, fall back to non-lazy.
1243 */
8751d154
PB
1244 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1245 flags &= ~IOU_F_TWQ_LAZY_WAKE;
ce8e04f6 1246
e8c40771 1247 head = READ_ONCE(ctx->work_llist.first);
51509400 1248 do {
8751d154 1249 nr_tw_prev = 0;
e8c40771
PB
1250 if (head) {
1251 struct io_kiocb *first_req = container_of(head,
8751d154
PB
1252 struct io_kiocb,
1253 io_task_work.node);
1254 /*
1255 * Might be executed at any moment, rely on
1256 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1257 */
1258 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1259 }
b4bc35cf
PB
1260
1261 /*
1262 * Theoretically, it can overflow, but that's fine as one of
1263 * previous adds should've tried to wake the task.
1264 */
8751d154 1265 nr_tw = nr_tw_prev + 1;
8751d154 1266 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
b4bc35cf 1267 nr_tw = IO_CQ_WAKE_FORCE;
8751d154
PB
1268
1269 req->nr_tw = nr_tw;
e8c40771
PB
1270 req->io_task_work.node.next = head;
1271 } while (!try_cmpxchg(&ctx->work_llist.first, &head,
51509400
PB
1272 &req->io_task_work.node));
1273
d381099f
PB
1274 /*
1275 * cmpxchg implies a full barrier, which pairs with the barrier
1276 * in set_current_state() on the io_cqring_wait() side. It's used
1277 * to ensure that either we see updated ->cq_wait_nr, or waiters
1278 * going to sleep will observe the work added to the list, which
1279 * is similar to the wait/wawke task state sync.
1280 */
1281
e8c40771 1282 if (!head) {
8751d154
PB
1283 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1284 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1285 if (ctx->has_evfd)
1286 io_eventfd_signal(ctx);
c0e0d6ba
DY
1287 }
1288
8751d154 1289 nr_wait = atomic_read(&ctx->cq_wait_nr);
b4bc35cf
PB
1290 /* not enough or no one is waiting */
1291 if (nr_tw < nr_wait)
8751d154 1292 return;
b4bc35cf
PB
1293 /* the previous add has already woken it up */
1294 if (nr_tw_prev >= nr_wait)
8751d154 1295 return;
8751d154 1296 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
c0e0d6ba
DY
1297}
1298
91c7884a 1299static void io_req_normal_work_add(struct io_kiocb *req)
7cbf1722 1300{
c34398a8 1301 struct io_uring_task *tctx = req->task->io_uring;
9f010507 1302 struct io_ring_ctx *ctx = req->ctx;
7cbf1722 1303
7cbf1722 1304 /* task_work already pending, we're done */
32d91f05 1305 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
e09ee510 1306 return;
7cbf1722 1307
ef060ea9
JA
1308 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1309 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1310
af5d68f8 1311 /* SQPOLL doesn't need the task_work added, it'll run it itself */
78f9b61b
JA
1312 if (ctx->flags & IORING_SETUP_SQPOLL) {
1313 struct io_sq_data *sqd = ctx->sq_data;
1314
1315 if (wq_has_sleeper(&sqd->wait))
1316 wake_up(&sqd->wait);
af5d68f8 1317 return;
78f9b61b 1318 }
af5d68f8 1319
3fe07bcd 1320 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
e09ee510 1321 return;
2215bed9 1322
dfbe5561 1323 io_fallback_tw(tctx, false);
c0e0d6ba
DY
1324}
1325
91c7884a
PB
1326void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1327{
1328 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
1329 rcu_read_lock();
1330 io_req_local_work_add(req, flags);
1331 rcu_read_unlock();
1332 } else {
1333 io_req_normal_work_add(req);
1334 }
1335}
1336
c0e0d6ba
DY
1337static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1338{
1339 struct llist_node *node;
1340
1341 node = llist_del_all(&ctx->work_llist);
1342 while (node) {
1343 struct io_kiocb *req = container_of(node, struct io_kiocb,
1344 io_task_work.node);
1345
1346 node = node->next;
91c7884a 1347 io_req_normal_work_add(req);
c0e0d6ba
DY
1348 }
1349}
1350
9fe3eaea
JA
1351static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1352 int min_events)
1353{
1354 if (llist_empty(&ctx->work_llist))
1355 return false;
1356 if (events < min_events)
1357 return true;
1358 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1359 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1360 return false;
1361}
1362
1363static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1364 int min_events)
c0e0d6ba 1365{
c0e0d6ba 1366 struct llist_node *node;
c3f4d39e 1367 unsigned int loops = 0;
140102ae 1368 int ret = 0;
c0e0d6ba 1369
140102ae 1370 if (WARN_ON_ONCE(ctx->submitter_task != current))
c0e0d6ba 1371 return -EEXIST;
c3f4d39e
PB
1372 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1373 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
c0e0d6ba 1374again:
3af0356c
JA
1375 /*
1376 * llists are in reverse order, flip it back the right way before
1377 * running the pending items.
1378 */
1379 node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
c3f4d39e 1380 while (node) {
c0e0d6ba
DY
1381 struct llist_node *next = node->next;
1382 struct io_kiocb *req = container_of(node, struct io_kiocb,
1383 io_task_work.node);
c92fcfc2
JA
1384 INDIRECT_CALL_2(req->io_task_work.func,
1385 io_poll_task_func, io_req_rw_complete,
1386 req, ts);
c0e0d6ba
DY
1387 ret++;
1388 node = next;
1389 }
c3f4d39e 1390 loops++;
c0e0d6ba 1391
9fe3eaea 1392 if (io_run_local_work_continue(ctx, ret, min_events))
c0e0d6ba 1393 goto again;
92219afb
PB
1394 io_submit_flush_completions(ctx);
1395 if (io_run_local_work_continue(ctx, ret, min_events))
1396 goto again;
9fe3eaea 1397
f75d5036 1398 trace_io_uring_local_work_run(ctx, ret, loops);
c0e0d6ba 1399 return ret;
8ac5d85a
JA
1400}
1401
9fe3eaea
JA
1402static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1403 int min_events)
360173ab 1404{
8e5b3b89 1405 struct io_tw_state ts = {};
360173ab
PB
1406
1407 if (llist_empty(&ctx->work_llist))
1408 return 0;
8e5b3b89 1409 return __io_run_local_work(ctx, &ts, min_events);
360173ab
PB
1410}
1411
9fe3eaea 1412static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
8ac5d85a 1413{
8e5b3b89 1414 struct io_tw_state ts = {};
8ac5d85a
JA
1415 int ret;
1416
92219afb 1417 mutex_lock(&ctx->uring_lock);
9fe3eaea 1418 ret = __io_run_local_work(ctx, &ts, min_events);
92219afb 1419 mutex_unlock(&ctx->uring_lock);
8ac5d85a 1420 return ret;
c0e0d6ba
DY
1421}
1422
a282967c 1423static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
c40f6379 1424{
a282967c 1425 io_tw_lock(req->ctx, ts);
973fc83f 1426 io_req_defer_failed(req, req->cqe.res);
c40f6379
JA
1427}
1428
a282967c 1429void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
c40f6379 1430{
a282967c 1431 io_tw_lock(req->ctx, ts);
316319e8 1432 /* req->task == current here, checking PF_EXITING is safe */
6bb30855 1433 if (unlikely(req->task->flags & PF_EXITING))
973fc83f 1434 io_req_defer_failed(req, -EFAULT);
6bb30855 1435 else if (req->flags & REQ_F_FORCE_ASYNC)
6e6b8c62 1436 io_queue_iowq(req);
6bb30855
DY
1437 else
1438 io_queue_sqe(req);
c40f6379
JA
1439}
1440
59915143 1441void io_req_task_queue_fail(struct io_kiocb *req, int ret)
c40f6379 1442{
97b388d7 1443 io_req_set_res(req, ret, 0);
5b0a6acc 1444 req->io_task_work.func = io_req_task_cancel;
3fe07bcd 1445 io_req_task_work_add(req);
c40f6379
JA
1446}
1447
f3b44f92 1448void io_req_task_queue(struct io_kiocb *req)
a3df7698 1449{
5b0a6acc 1450 req->io_task_work.func = io_req_task_submit;
3fe07bcd 1451 io_req_task_work_add(req);
a3df7698
PB
1452}
1453
59915143 1454void io_queue_next(struct io_kiocb *req)
c69f8dbe 1455{
9b5f7bd9 1456 struct io_kiocb *nxt = io_req_find_next(req);
944e58bf
PB
1457
1458 if (nxt)
906a8c3f 1459 io_req_task_queue(nxt);
c69f8dbe
JL
1460}
1461
ec26c225
PB
1462static void io_free_batch_list(struct io_ring_ctx *ctx,
1463 struct io_wq_work_node *node)
3aa83bfb 1464 __must_hold(&ctx->uring_lock)
5af1d13e 1465{
3aa83bfb
PB
1466 do {
1467 struct io_kiocb *req = container_of(node, struct io_kiocb,
1468 comp_list);
2d6500d4 1469
a538be5b
PB
1470 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1471 if (req->flags & REQ_F_REFCOUNT) {
1472 node = req->comp_list.next;
1473 if (!req_ref_put_and_test(req))
1474 continue;
1475 }
b605a7fa
PB
1476 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1477 struct async_poll *apoll = req->apoll;
1478
1479 if (apoll->double_poll)
1480 kfree(apoll->double_poll);
9731bc98
JA
1481 if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache))
1482 kfree(apoll);
b605a7fa
PB
1483 req->flags &= ~REQ_F_POLLED;
1484 }
da1a08c5 1485 if (req->flags & IO_REQ_LINK_FLAGS)
57859f4d 1486 io_queue_next(req);
a538be5b
PB
1487 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1488 io_clean_op(req);
c1e53a69 1489 }
17bc2837 1490 io_put_file(req);
2d6500d4 1491
ab409402 1492 io_req_put_rsrc_locked(req, ctx);
5af1d13e 1493
2fdd6fb5 1494 io_put_task(req->task);
c1e53a69 1495 node = req->comp_list.next;
fa05457a 1496 io_req_add_to_cache(req, ctx);
3aa83bfb 1497 } while (node);
7a743e22
PB
1498}
1499
ec26c225 1500void __io_submit_flush_completions(struct io_ring_ctx *ctx)
a141dd89 1501 __must_hold(&ctx->uring_lock)
905c172f 1502{
cd0ca2e0 1503 struct io_submit_state *state = &ctx->submit_state;
fa780334 1504 struct io_wq_work_node *node;
905c172f 1505
f66f7342 1506 __io_cq_lock(ctx);
fa780334 1507 __wq_list_for_each(node, &state->compl_reqs) {
d9dee430
PB
1508 struct io_kiocb *req = container_of(node, struct io_kiocb,
1509 comp_list);
3d4aeb9f 1510
f66f7342 1511 if (!(req->flags & REQ_F_CQE_SKIP) &&
00b0db56 1512 unlikely(!io_fill_cqe_req(ctx, req))) {
27122c07 1513 if (ctx->lockless_cq) {
f66f7342
PB
1514 spin_lock(&ctx->completion_lock);
1515 io_req_cqe_overflow(req);
1516 spin_unlock(&ctx->completion_lock);
1517 } else {
1518 io_req_cqe_overflow(req);
1519 }
1520 }
905c172f 1521 }
c98c81a4 1522 __io_cq_unlock_post(ctx);
d9dee430 1523
931147dd
DY
1524 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) {
1525 io_free_batch_list(ctx, state->compl_reqs.first);
1526 INIT_WQ_LIST(&state->compl_reqs);
1527 }
902ce82c 1528 ctx->submit_state.cq_flush = false;
7a743e22
PB
1529}
1530
6c503150 1531static unsigned io_cqring_events(struct io_ring_ctx *ctx)
a3a0e43f
JA
1532{
1533 /* See comment at the top of this file */
1534 smp_rmb();
e23de15f 1535 return __io_cqring_events(ctx);
a3a0e43f
JA
1536}
1537
def596e9
JA
1538/*
1539 * We can't just wait for polled events to come to us, we have to actively
1540 * find and complete them.
1541 */
c072481d 1542static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
def596e9
JA
1543{
1544 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1545 return;
1546
1547 mutex_lock(&ctx->uring_lock);
5eef4e87 1548 while (!wq_list_empty(&ctx->iopoll_list)) {
b2edc0a7 1549 /* let it sleep and repeat later if can't complete a request */
5ba3c874 1550 if (io_do_iopoll(ctx, true) == 0)
b2edc0a7 1551 break;
08f5439f
JA
1552 /*
1553 * Ensure we allow local-to-the-cpu processing to take place,
1554 * in this case we need to ensure that we reap all events.
3fcee5a6 1555 * Also let task_work, etc. to progress by releasing the mutex
08f5439f 1556 */
3fcee5a6
PB
1557 if (need_resched()) {
1558 mutex_unlock(&ctx->uring_lock);
1559 cond_resched();
1560 mutex_lock(&ctx->uring_lock);
1561 }
def596e9
JA
1562 }
1563 mutex_unlock(&ctx->uring_lock);
1564}
1565
7668b92a 1566static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
def596e9 1567{
7668b92a 1568 unsigned int nr_events = 0;
155bc950 1569 unsigned long check_cq;
500f9fba 1570
76de6749
PB
1571 if (!io_allowed_run_tw(ctx))
1572 return -EEXIST;
1573
3a08576b
PB
1574 check_cq = READ_ONCE(ctx->check_cq);
1575 if (unlikely(check_cq)) {
1576 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
a85381d8 1577 __io_cqring_overflow_flush(ctx);
3a08576b
PB
1578 /*
1579 * Similarly do not spin if we have not informed the user of any
1580 * dropped CQE.
1581 */
1582 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1583 return -EBADR;
1584 }
f39c8a5b
PB
1585 /*
1586 * Don't enter poll loop if we already have events pending.
1587 * If we do, we can potentially be spinning for commands that
1588 * already triggered a CQE (eg in error).
1589 */
f39c8a5b 1590 if (io_cqring_events(ctx))
d487b43c 1591 return 0;
155bc950 1592
def596e9 1593 do {
9e4bef2b
JA
1594 int ret = 0;
1595
500f9fba
JA
1596 /*
1597 * If a submit got punted to a workqueue, we can have the
1598 * application entering polling for a command before it gets
1599 * issued. That app will hold the uring_lock for the duration
1600 * of the poll right here, so we need to take a breather every
1601 * now and then to ensure that the issue has a chance to add
1602 * the poll to the issued list. Otherwise we can spin here
1603 * forever, while the workqueue is stuck trying to acquire the
1604 * very same mutex.
1605 */
dac6a0ea
JA
1606 if (wq_list_empty(&ctx->iopoll_list) ||
1607 io_task_work_pending(ctx)) {
8f487ef2
PB
1608 u32 tail = ctx->cached_cq_tail;
1609
9fe3eaea 1610 (void) io_run_local_work_locked(ctx, min);
def596e9 1611
dac6a0ea
JA
1612 if (task_work_pending(current) ||
1613 wq_list_empty(&ctx->iopoll_list)) {
dac6a0ea 1614 mutex_unlock(&ctx->uring_lock);
9d54bd6a 1615 io_run_task_work();
dac6a0ea 1616 mutex_lock(&ctx->uring_lock);
dac6a0ea 1617 }
8f487ef2
PB
1618 /* some requests don't go through iopoll_list */
1619 if (tail != ctx->cached_cq_tail ||
5eef4e87 1620 wq_list_empty(&ctx->iopoll_list))
e9979b36 1621 break;
500f9fba 1622 }
5ba3c874 1623 ret = io_do_iopoll(ctx, !min);
9e4bef2b
JA
1624 if (unlikely(ret < 0))
1625 return ret;
dc314886
PB
1626
1627 if (task_sigpending(current))
1628 return -EINTR;
9e4bef2b 1629 if (need_resched())
5ba3c874 1630 break;
d487b43c 1631
5ba3c874 1632 nr_events += ret;
9e4bef2b 1633 } while (nr_events < min);
d487b43c 1634
9e4bef2b 1635 return 0;
def596e9 1636}
7012c815 1637
a282967c 1638void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
8ef12efe 1639{
8e5b3b89 1640 io_req_complete_defer(req);
8ef12efe
JA
1641}
1642
def596e9
JA
1643/*
1644 * After the iocb has been issued, it's safe to be found on the poll list.
1645 * Adding the kiocb to the list AFTER submission ensures that we don't
f39c8a5b 1646 * find it from a io_do_iopoll() thread before the issuer is done
def596e9
JA
1647 * accessing the kiocb cookie.
1648 */
9882131c 1649static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
def596e9
JA
1650{
1651 struct io_ring_ctx *ctx = req->ctx;
3b44b371 1652 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
cb3d8972
PB
1653
1654 /* workqueue context doesn't hold uring_lock, grab it now */
3b44b371 1655 if (unlikely(needs_lock))
cb3d8972 1656 mutex_lock(&ctx->uring_lock);
def596e9
JA
1657
1658 /*
1659 * Track whether we have multiple files in our lists. This will impact
1660 * how we do polling eventually, not spinning if we're on potentially
1661 * different devices.
1662 */
5eef4e87 1663 if (wq_list_empty(&ctx->iopoll_list)) {
915b3dde
HX
1664 ctx->poll_multi_queue = false;
1665 } else if (!ctx->poll_multi_queue) {
def596e9
JA
1666 struct io_kiocb *list_req;
1667
5eef4e87
PB
1668 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1669 comp_list);
30da1b45 1670 if (list_req->file != req->file)
915b3dde 1671 ctx->poll_multi_queue = true;
def596e9
JA
1672 }
1673
1674 /*
1675 * For fast devices, IO may have already completed. If it has, add
1676 * it to the front so we find it first.
1677 */
65a6543d 1678 if (READ_ONCE(req->iopoll_completed))
5eef4e87 1679 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
def596e9 1680 else
5eef4e87 1681 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
bdcd3eab 1682
3b44b371 1683 if (unlikely(needs_lock)) {
cb3d8972
PB
1684 /*
1685 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1686 * in sq thread task context or in io worker task context. If
1687 * current task context is sq thread, we don't need to check
1688 * whether should wake up sq thread.
1689 */
1690 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1691 wq_has_sleeper(&ctx->sq_data->wait))
1692 wake_up(&ctx->sq_data->wait);
1693
1694 mutex_unlock(&ctx->uring_lock);
1695 }
def596e9
JA
1696}
1697
4bcb982c 1698io_req_flags_t io_file_get_flags(struct file *file)
88459b50 1699{
4bcb982c 1700 io_req_flags_t res = 0;
af197f50 1701
53cfd5ce 1702 if (S_ISREG(file_inode(file)->i_mode))
8487f083 1703 res |= REQ_F_ISREG;
b9a6c945 1704 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
8487f083 1705 res |= REQ_F_SUPPORT_NOWAIT;
88459b50 1706 return res;
2b188cc1
JA
1707}
1708
99f15d8d 1709bool io_alloc_async_data(struct io_kiocb *req)
3d9932a8 1710{
f30bd4d0
BL
1711 WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size);
1712 req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL);
d886e185
PB
1713 if (req->async_data) {
1714 req->flags |= REQ_F_ASYNC_DATA;
1715 return false;
1716 }
1717 return true;
3d9932a8
XW
1718}
1719
f3b44f92 1720int io_req_prep_async(struct io_kiocb *req)
f67676d1 1721{
f30bd4d0 1722 const struct io_cold_def *cdef = &io_cold_defs[req->opcode];
a7dd2782 1723 const struct io_issue_def *def = &io_issue_defs[req->opcode];
0702e536
JA
1724
1725 /* assign early for deferred execution for non-fixed file */
54aa7f23 1726 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file)
0702e536 1727 req->file = io_file_get_normal(req, req->cqe.fd);
f30bd4d0 1728 if (!cdef->prep_async)
0702e536
JA
1729 return 0;
1730 if (WARN_ON_ONCE(req_has_async_data(req)))
1731 return -EFAULT;
f30bd4d0 1732 if (!def->manual_alloc) {
59169439
PB
1733 if (io_alloc_async_data(req))
1734 return -EAGAIN;
1735 }
f30bd4d0 1736 return cdef->prep_async(req);
bfe76559
PB
1737}
1738
9cf7c104
PB
1739static u32 io_get_sequence(struct io_kiocb *req)
1740{
a3dbdf54 1741 u32 seq = req->ctx->cached_sq_head;
963c6abb 1742 struct io_kiocb *cur;
9cf7c104 1743
a3dbdf54 1744 /* need original cached_sq_head, but it was increased for each req */
963c6abb 1745 io_for_each_link(cur, req)
a3dbdf54
PB
1746 seq--;
1747 return seq;
9cf7c104
PB
1748}
1749
c072481d 1750static __cold void io_drain_req(struct io_kiocb *req)
e276ae34 1751 __must_hold(&ctx->uring_lock)
de0617e4 1752{
a197f664 1753 struct io_ring_ctx *ctx = req->ctx;
27dc8338 1754 struct io_defer_entry *de;
f67676d1 1755 int ret;
e0eb71dc 1756 u32 seq = io_get_sequence(req);
3c19966d 1757
9d858b21 1758 /* Still need defer if there is pending req in defer list. */
e302f104 1759 spin_lock(&ctx->completion_lock);
5e371265 1760 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
e302f104 1761 spin_unlock(&ctx->completion_lock);
e0eb71dc 1762queue:
10c66904 1763 ctx->drain_active = false;
e0eb71dc
PB
1764 io_req_task_queue(req);
1765 return;
10c66904 1766 }
e302f104 1767 spin_unlock(&ctx->completion_lock);
9cf7c104 1768
cbdcb435 1769 io_prep_async_link(req);
27dc8338 1770 de = kmalloc(sizeof(*de), GFP_KERNEL);
76cc33d7 1771 if (!de) {
1b48773f 1772 ret = -ENOMEM;
ef5c600a
DY
1773 io_req_defer_failed(req, ret);
1774 return;
76cc33d7 1775 }
2d28390a 1776
79ebeaee 1777 spin_lock(&ctx->completion_lock);
9cf7c104 1778 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
79ebeaee 1779 spin_unlock(&ctx->completion_lock);
27dc8338 1780 kfree(de);
e0eb71dc 1781 goto queue;
de0617e4
JA
1782 }
1783
48863ffd 1784 trace_io_uring_defer(req);
27dc8338 1785 de->req = req;
9cf7c104 1786 de->seq = seq;
27dc8338 1787 list_add_tail(&de->list, &ctx->defer_list);
79ebeaee 1788 spin_unlock(&ctx->completion_lock);
de0617e4
JA
1789}
1790
f4992544
JA
1791static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1792 unsigned int issue_flags)
6bf9c47a 1793{
f4992544 1794 if (req->file || !def->needs_file)
6bf9c47a
JA
1795 return true;
1796
1797 if (req->flags & REQ_F_FIXED_FILE)
cef216fc 1798 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
6bf9c47a 1799 else
cef216fc 1800 req->file = io_file_get_normal(req, req->cqe.fd);
6bf9c47a 1801
772f5e00 1802 return !!req->file;
6bf9c47a
JA
1803}
1804
889fca73 1805static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
2b188cc1 1806{
a7dd2782 1807 const struct io_issue_def *def = &io_issue_defs[req->opcode];
5730b27e 1808 const struct cred *creds = NULL;
d625c6ee 1809 int ret;
2b188cc1 1810
f4992544 1811 if (unlikely(!io_assign_file(req, def, issue_flags)))
70152140
JA
1812 return -EBADF;
1813
6878b40e 1814 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
c10d1f98 1815 creds = override_creds(req->creds);
5730b27e 1816
fcde59fe 1817 if (!def->audit_skip)
5bd2182d
PM
1818 audit_uring_entry(req->opcode);
1819
0702e536 1820 ret = def->issue(req, issue_flags);
2b188cc1 1821
fcde59fe 1822 if (!def->audit_skip)
5bd2182d
PM
1823 audit_uring_exit(!ret, ret);
1824
5730b27e
JA
1825 if (creds)
1826 revert_creds(creds);
97b388d7 1827
75d7b3ae
PB
1828 if (ret == IOU_OK) {
1829 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
9da070b1 1830 io_req_complete_defer(req);
75d7b3ae 1831 else
1bec951c 1832 io_req_complete_post(req, issue_flags);
97b388d7 1833
9b43ef3d
PB
1834 return 0;
1835 }
def596e9 1836
e0b23d99
PB
1837 if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1838 ret = 0;
1839 io_arm_ltimeout(req);
def596e9 1840
e0b23d99
PB
1841 /* If the op doesn't have a file, we're not polling for it */
1842 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1843 io_iopoll_req_issued(req, issue_flags);
1844 }
1845 return ret;
2b188cc1
JA
1846}
1847
a282967c 1848int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
329061d3 1849{
a282967c 1850 io_tw_lock(req->ctx, ts);
9a692451
DY
1851 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1852 IO_URING_F_COMPLETE_DEFER);
329061d3
JA
1853}
1854
c9f06aa7 1855struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
ebc11b6c
PB
1856{
1857 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
247f97a5 1858 struct io_kiocb *nxt = NULL;
ebc11b6c 1859
247f97a5
PB
1860 if (req_ref_put_and_test(req)) {
1861 if (req->flags & IO_REQ_LINK_FLAGS)
1862 nxt = io_req_find_next(req);
1863 io_free_req(req);
1864 }
1865 return nxt ? &nxt->work : NULL;
ebc11b6c
PB
1866}
1867
c9f06aa7 1868void io_wq_submit_work(struct io_wq_work *work)
2b188cc1
JA
1869{
1870 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
a7dd2782 1871 const struct io_issue_def *def = &io_issue_defs[req->opcode];
e6aeb272 1872 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
d01905db 1873 bool needs_poll = false;
6bf9c47a 1874 int ret = 0, err = -ECANCELED;
2b188cc1 1875
23a6c9ac 1876 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
48dcd38d
PB
1877 if (!(req->flags & REQ_F_REFCOUNT))
1878 __io_req_set_refcount(req, 2);
1879 else
1880 req_ref_get(req);
5d5901a3 1881
cb2d344c 1882 io_arm_ltimeout(req);
6bf9c47a 1883
dadebc35 1884 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
d01905db 1885 if (work->flags & IO_WQ_WORK_CANCEL) {
0f8da75b 1886fail:
6bf9c47a 1887 io_req_task_queue_fail(req, err);
d01905db
PB
1888 return;
1889 }
f4992544 1890 if (!io_assign_file(req, def, issue_flags)) {
0f8da75b
PB
1891 err = -EBADF;
1892 work->flags |= IO_WQ_WORK_CANCEL;
1893 goto fail;
1894 }
31b51510 1895
e0e4ab52
PB
1896 /*
1897 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1898 * submitter task context. Final request completions are handed to the
1899 * right context, however this is not the case of auxiliary CQEs,
1900 * which is the main mean of operation for multishot requests.
1901 * Don't allow any multishot execution from io-wq. It's more restrictive
1902 * than necessary and also cleaner.
1903 */
1904 if (req->flags & REQ_F_APOLL_MULTISHOT) {
1905 err = -EBADFD;
1906 if (!io_file_can_poll(req))
1907 goto fail;
bee1d5be
JA
1908 if (req->file->f_flags & O_NONBLOCK ||
1909 req->file->f_mode & FMODE_NOWAIT) {
1910 err = -ECANCELED;
1911 if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1912 goto fail;
1913 return;
1914 } else {
1915 req->flags &= ~REQ_F_APOLL_MULTISHOT;
1916 }
e0e4ab52
PB
1917 }
1918
d01905db 1919 if (req->flags & REQ_F_FORCE_ASYNC) {
afb7f56f
PB
1920 bool opcode_poll = def->pollin || def->pollout;
1921
95041b93 1922 if (opcode_poll && io_file_can_poll(req)) {
afb7f56f 1923 needs_poll = true;
d01905db 1924 issue_flags |= IO_URING_F_NONBLOCK;
afb7f56f 1925 }
561fb04a 1926 }
31b51510 1927
d01905db
PB
1928 do {
1929 ret = io_issue_sqe(req, issue_flags);
1930 if (ret != -EAGAIN)
1931 break;
a9be2022
JA
1932
1933 /*
1934 * If REQ_F_NOWAIT is set, then don't wait or retry with
1935 * poll. -EAGAIN is final for that case.
1936 */
1937 if (req->flags & REQ_F_NOWAIT)
1938 break;
1939
d01905db
PB
1940 /*
1941 * We can get EAGAIN for iopolled IO even though we're
1942 * forcing a sync submission from here, since we can't
1943 * wait for request slots on the block side.
1944 */
1945 if (!needs_poll) {
e0deb6a0
PB
1946 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1947 break;
45500dc4
PB
1948 if (io_wq_worker_stopped())
1949 break;
d01905db
PB
1950 cond_resched();
1951 continue;
90fa0288
HX
1952 }
1953
4d9237e3 1954 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
d01905db
PB
1955 return;
1956 /* aborted or ready, in either case retry blocking */
1957 needs_poll = false;
1958 issue_flags &= ~IO_URING_F_NONBLOCK;
1959 } while (1);
31b51510 1960
a3df7698 1961 /* avoid locking problems by failing it from a clean context */
97b388d7 1962 if (ret < 0)
a3df7698 1963 io_req_task_queue_fail(req, ret);
2b188cc1
JA
1964}
1965
531113bb
JA
1966inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1967 unsigned int issue_flags)
09bb8394 1968{
5106dd6e 1969 struct io_ring_ctx *ctx = req->ctx;
4bfb0c9a 1970 struct io_fixed_file *slot;
5106dd6e 1971 struct file *file = NULL;
09bb8394 1972
93f052cb 1973 io_ring_submit_lock(ctx, issue_flags);
5106dd6e 1974
ac177053 1975 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
5106dd6e 1976 goto out;
ac177053 1977 fd = array_index_nospec(fd, ctx->nr_user_files);
4bfb0c9a 1978 slot = io_fixed_file_slot(&ctx->file_table, fd);
3f302388
JA
1979 if (!req->rsrc_node)
1980 __io_req_set_rsrc_node(req, ctx);
4bfb0c9a 1981 req->flags |= io_slot_flags(slot);
3f302388 1982 file = io_slot_file(slot);
5106dd6e 1983out:
93f052cb 1984 io_ring_submit_unlock(ctx, issue_flags);
ac177053
PB
1985 return file;
1986}
d44f554e 1987
531113bb 1988struct file *io_file_get_normal(struct io_kiocb *req, int fd)
ac177053 1989{
62906e89 1990 struct file *file = fget(fd);
ac177053 1991
48863ffd 1992 trace_io_uring_file_get(req, fd);
09bb8394 1993
ac177053 1994 /* we don't allow fixed io_uring files */
e5550a14 1995 if (file && io_is_uring_fops(file))
9cae36a0 1996 io_req_track_inflight(req);
8371adf5 1997 return file;
09bb8394
JA
1998}
1999
7bfa9bad 2000static void io_queue_async(struct io_kiocb *req, int ret)
d475a9a6
PB
2001 __must_hold(&req->ctx->uring_lock)
2002{
7bfa9bad
PB
2003 struct io_kiocb *linked_timeout;
2004
2005 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
973fc83f 2006 io_req_defer_failed(req, ret);
7bfa9bad
PB
2007 return;
2008 }
2009
2010 linked_timeout = io_prep_linked_timeout(req);
d475a9a6 2011
4d9237e3 2012 switch (io_arm_poll_handler(req, 0)) {
d475a9a6 2013 case IO_APOLL_READY:
336d28a8 2014 io_kbuf_recycle(req, 0);
d475a9a6
PB
2015 io_req_task_queue(req);
2016 break;
2017 case IO_APOLL_ABORTED:
6436c770 2018 io_kbuf_recycle(req, 0);
6e6b8c62 2019 io_queue_iowq(req);
d475a9a6 2020 break;
b1c62645 2021 case IO_APOLL_OK:
b1c62645 2022 break;
d475a9a6
PB
2023 }
2024
2025 if (linked_timeout)
2026 io_queue_linked_timeout(linked_timeout);
2027}
2028
cbc2e203 2029static inline void io_queue_sqe(struct io_kiocb *req)
282cdc86 2030 __must_hold(&req->ctx->uring_lock)
2b188cc1 2031{
e0c5c576 2032 int ret;
2b188cc1 2033
c5eef2b9 2034 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
193155c8 2035
491381ce
JA
2036 /*
2037 * We async punt it if the file wasn't marked NOWAIT, or if the file
2038 * doesn't support non-blocking read/write attempts
2039 */
e0b23d99 2040 if (unlikely(ret))
7bfa9bad 2041 io_queue_async(req, ret);
2b188cc1
JA
2042}
2043
4652fe3f 2044static void io_queue_sqe_fallback(struct io_kiocb *req)
282cdc86 2045 __must_hold(&req->ctx->uring_lock)
4fe2c963 2046{
17b147f6
PB
2047 if (unlikely(req->flags & REQ_F_FAIL)) {
2048 /*
2049 * We don't submit, fail them all, for that replace hardlinks
2050 * with normal links. Extra REQ_F_LINK is tolerated.
2051 */
2052 req->flags &= ~REQ_F_HARDLINK;
2053 req->flags |= REQ_F_LINK;
973fc83f 2054 io_req_defer_failed(req, req->cqe.res);
76cc33d7
PB
2055 } else {
2056 int ret = io_req_prep_async(req);
2057
ef5c600a 2058 if (unlikely(ret)) {
973fc83f 2059 io_req_defer_failed(req, ret);
ef5c600a
DY
2060 return;
2061 }
2062
2063 if (unlikely(req->ctx->drain_active))
2064 io_drain_req(req);
76cc33d7 2065 else
6e6b8c62 2066 io_queue_iowq(req);
ce35a47a 2067 }
4fe2c963
JL
2068}
2069
b16fed66
PB
2070/*
2071 * Check SQE restrictions (opcode and flags).
2072 *
2073 * Returns 'true' if SQE is allowed, 'false' otherwise.
2074 */
2075static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2076 struct io_kiocb *req,
2077 unsigned int sqe_flags)
4fe2c963 2078{
b16fed66
PB
2079 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2080 return false;
2081
2082 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2083 ctx->restrictions.sqe_flags_required)
2084 return false;
2085
2086 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2087 ctx->restrictions.sqe_flags_required))
2088 return false;
2089
2090 return true;
4fe2c963
JL
2091}
2092
22b2ca31
PB
2093static void io_init_req_drain(struct io_kiocb *req)
2094{
2095 struct io_ring_ctx *ctx = req->ctx;
2096 struct io_kiocb *head = ctx->submit_state.link.head;
2097
2098 ctx->drain_active = true;
2099 if (head) {
2100 /*
2101 * If we need to drain a request in the middle of a link, drain
2102 * the head request and the next request/link after the current
2103 * link. Considering sequential execution of links,
b6c7db32 2104 * REQ_F_IO_DRAIN will be maintained for every request of our
22b2ca31
PB
2105 * link.
2106 */
b6c7db32 2107 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
22b2ca31
PB
2108 ctx->drain_next = true;
2109 }
2110}
2111
e21e1c45
JA
2112static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2113{
2114 /* ensure per-opcode data is cleared if we fail before prep */
2115 memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2116 return err;
2117}
2118
b16fed66
PB
2119static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2120 const struct io_uring_sqe *sqe)
282cdc86 2121 __must_hold(&ctx->uring_lock)
b16fed66 2122{
a7dd2782 2123 const struct io_issue_def *def;
b16fed66 2124 unsigned int sqe_flags;
fc0ae024 2125 int personality;
4a04d1d1 2126 u8 opcode;
b16fed66 2127
864ea921 2128 /* req is partially pre-initialised, see io_preinit_req() */
4a04d1d1 2129 req->opcode = opcode = READ_ONCE(sqe->opcode);
b16fed66 2130 /* same numerical values with corresponding REQ_F_*, safe to copy */
4bcb982c
JA
2131 sqe_flags = READ_ONCE(sqe->flags);
2132 req->flags = (io_req_flags_t) sqe_flags;
cef216fc 2133 req->cqe.user_data = READ_ONCE(sqe->user_data);
b16fed66 2134 req->file = NULL;
c1bdf8ed 2135 req->rsrc_node = NULL;
b16fed66 2136 req->task = current;
b16fed66 2137
4a04d1d1
PB
2138 if (unlikely(opcode >= IORING_OP_LAST)) {
2139 req->opcode = 0;
e21e1c45 2140 return io_init_fail_req(req, -EINVAL);
4a04d1d1 2141 }
a7dd2782 2142 def = &io_issue_defs[opcode];
68fe256a
PB
2143 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2144 /* enforce forwards compatibility on users */
2145 if (sqe_flags & ~SQE_VALID_FLAGS)
e21e1c45 2146 return io_init_fail_req(req, -EINVAL);
4e906702 2147 if (sqe_flags & IOSQE_BUFFER_SELECT) {
fcde59fe 2148 if (!def->buffer_select)
e21e1c45 2149 return io_init_fail_req(req, -EOPNOTSUPP);
4e906702
JA
2150 req->buf_index = READ_ONCE(sqe->buf_group);
2151 }
5562a8d7
PB
2152 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2153 ctx->drain_disabled = true;
2154 if (sqe_flags & IOSQE_IO_DRAIN) {
2155 if (ctx->drain_disabled)
e21e1c45 2156 return io_init_fail_req(req, -EOPNOTSUPP);
22b2ca31 2157 io_init_req_drain(req);
5562a8d7 2158 }
2a56a9bd
PB
2159 }
2160 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2161 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
e21e1c45 2162 return io_init_fail_req(req, -EACCES);
2a56a9bd
PB
2163 /* knock it to the slow queue path, will be drained there */
2164 if (ctx->drain_active)
2165 req->flags |= REQ_F_FORCE_ASYNC;
2166 /* if there is no link, we're at "next" request and need to drain */
2167 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2168 ctx->drain_next = false;
2169 ctx->drain_active = true;
b6c7db32 2170 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2a56a9bd 2171 }
68fe256a 2172 }
b16fed66 2173
fcde59fe 2174 if (!def->ioprio && sqe->ioprio)
e21e1c45 2175 return io_init_fail_req(req, -EINVAL);
fcde59fe 2176 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
e21e1c45 2177 return io_init_fail_req(req, -EINVAL);
73911426 2178
fcde59fe 2179 if (def->needs_file) {
6d63416d
PB
2180 struct io_submit_state *state = &ctx->submit_state;
2181
cef216fc 2182 req->cqe.fd = READ_ONCE(sqe->fd);
6bf9c47a 2183
6d63416d
PB
2184 /*
2185 * Plug now if we have more than 2 IO left after this, and the
2186 * target is potentially a read/write to block based storage.
2187 */
fcde59fe 2188 if (state->need_plug && def->plug) {
6d63416d
PB
2189 state->plug_started = true;
2190 state->need_plug = false;
5ca7a8b3 2191 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
6d63416d 2192 }
b16fed66 2193 }
863e0560 2194
003e8dcc
JA
2195 personality = READ_ONCE(sqe->personality);
2196 if (personality) {
cdab10bf
LT
2197 int ret;
2198
c10d1f98
PB
2199 req->creds = xa_load(&ctx->personalities, personality);
2200 if (!req->creds)
e21e1c45 2201 return io_init_fail_req(req, -EINVAL);
c10d1f98 2202 get_cred(req->creds);
cdc1404a
PM
2203 ret = security_uring_override_creds(req->creds);
2204 if (ret) {
2205 put_cred(req->creds);
e21e1c45 2206 return io_init_fail_req(req, ret);
cdc1404a 2207 }
b8e64b53 2208 req->flags |= REQ_F_CREDS;
003e8dcc 2209 }
b16fed66 2210
0702e536 2211 return def->prep(req, sqe);
b16fed66
PB
2212}
2213
df3becde
PB
2214static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2215 struct io_kiocb *req, int ret)
2216{
2217 struct io_ring_ctx *ctx = req->ctx;
2218 struct io_submit_link *link = &ctx->submit_state.link;
2219 struct io_kiocb *head = link->head;
2220
48863ffd 2221 trace_io_uring_req_failed(sqe, req, ret);
df3becde
PB
2222
2223 /*
2224 * Avoid breaking links in the middle as it renders links with SQPOLL
2225 * unusable. Instead of failing eagerly, continue assembling the link if
2226 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2227 * should find the flag and handle the rest.
2228 */
2229 req_fail_link_node(req, ret);
2230 if (head && !(head->flags & REQ_F_FAIL))
2231 req_fail_link_node(head, -ECANCELED);
2232
2233 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2234 if (head) {
2235 link->last->link = req;
2236 link->head = NULL;
2237 req = head;
2238 }
2239 io_queue_sqe_fallback(req);
2240 return ret;
2241 }
2242
2243 if (head)
2244 link->last->link = req;
2245 else
2246 link->head = req;
2247 link->last = req;
2248 return 0;
2249}
2250
2251static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
a1ab7b35 2252 const struct io_uring_sqe *sqe)
282cdc86 2253 __must_hold(&ctx->uring_lock)
9e645e11 2254{
a1ab7b35 2255 struct io_submit_link *link = &ctx->submit_state.link;
ef4ff581 2256 int ret;
9e645e11 2257
a6b8cadc 2258 ret = io_init_req(ctx, req, sqe);
df3becde
PB
2259 if (unlikely(ret))
2260 return io_submit_fail_init(sqe, req, ret);
441b8a78 2261
2ad57931 2262 trace_io_uring_submit_req(req);
a6b8cadc 2263
9e645e11
JA
2264 /*
2265 * If we already have a head request, queue this one for async
2266 * submittal once the head completes. If we don't have a head but
2267 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2268 * submitted sync once the chain is complete. If none of those
2269 * conditions are true (normal request), then just queue it.
2270 */
924a07e4 2271 if (unlikely(link->head)) {
df3becde
PB
2272 ret = io_req_prep_async(req);
2273 if (unlikely(ret))
2274 return io_submit_fail_init(sqe, req, ret);
2275
48863ffd 2276 trace_io_uring_link(req, link->head);
f2f87370 2277 link->last->link = req;
863e0560 2278 link->last = req;
32fe525b 2279
da1a08c5 2280 if (req->flags & IO_REQ_LINK_FLAGS)
f15a3431 2281 return 0;
df3becde
PB
2282 /* last request of the link, flush it */
2283 req = link->head;
f15a3431 2284 link->head = NULL;
924a07e4
PB
2285 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2286 goto fallback;
2287
2288 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2289 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2290 if (req->flags & IO_REQ_LINK_FLAGS) {
2291 link->head = req;
2292 link->last = req;
2293 } else {
2294fallback:
2295 io_queue_sqe_fallback(req);
2296 }
f15a3431 2297 return 0;
9e645e11 2298 }
2e6e1fde 2299
f15a3431 2300 io_queue_sqe(req);
1d4240cc 2301 return 0;
9e645e11
JA
2302}
2303
9a56a232
JA
2304/*
2305 * Batched submission is done, ensure local IO is flushed out.
2306 */
553deffd 2307static void io_submit_state_end(struct io_ring_ctx *ctx)
9a56a232 2308{
553deffd
PB
2309 struct io_submit_state *state = &ctx->submit_state;
2310
e126391c
PB
2311 if (unlikely(state->link.head))
2312 io_queue_sqe_fallback(state->link.head);
553deffd 2313 /* flush only after queuing links as they can generate completions */
c450178d 2314 io_submit_flush_completions(ctx);
27926b68
JA
2315 if (state->plug_started)
2316 blk_finish_plug(&state->plug);
9a56a232
JA
2317}
2318
2319/*
2320 * Start submission side cache.
2321 */
2322static void io_submit_state_start(struct io_submit_state *state,
ba88ff11 2323 unsigned int max_ios)
9a56a232 2324{
27926b68 2325 state->plug_started = false;
4b628aeb 2326 state->need_plug = max_ios > 2;
5ca7a8b3 2327 state->submit_nr = max_ios;
a1ab7b35
PB
2328 /* set only head, no need to init link_last in advance */
2329 state->link.head = NULL;
9a56a232
JA
2330}
2331
2b188cc1
JA
2332static void io_commit_sqring(struct io_ring_ctx *ctx)
2333{
75b28aff 2334 struct io_rings *rings = ctx->rings;
2b188cc1 2335
caf582c6
PB
2336 /*
2337 * Ensure any loads from the SQEs are done at this point,
2338 * since once we write the new head, the application could
2339 * write new data to them.
2340 */
2341 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
2342}
2343
2b188cc1 2344/*
dd9ae8a0 2345 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2b188cc1
JA
2346 * that is mapped by userspace. This means that care needs to be taken to
2347 * ensure that reads are stable, as we cannot rely on userspace always
2348 * being a good citizen. If members of the sqe are validated and then later
2349 * used, it's important that those reads are done through READ_ONCE() to
2350 * prevent a re-load down the line.
2351 */
b5083dfa 2352static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2b188cc1 2353{
2af89abd
PB
2354 unsigned mask = ctx->sq_entries - 1;
2355 unsigned head = ctx->cached_sq_head++ & mask;
2356
2357 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
2358 head = READ_ONCE(ctx->sq_array[head]);
2359 if (unlikely(head >= ctx->sq_entries)) {
2360 /* drop invalid entries */
2361 spin_lock(&ctx->completion_lock);
2362 ctx->cq_extra--;
2363 spin_unlock(&ctx->completion_lock);
2364 WRITE_ONCE(ctx->rings->sq_dropped,
2365 READ_ONCE(ctx->rings->sq_dropped) + 1);
2366 return false;
2367 }
2368 }
2b188cc1
JA
2369
2370 /*
2371 * The cached sq head (or cq tail) serves two purposes:
2372 *
2373 * 1) allows us to batch the cost of updating the user visible
2374 * head updates.
2375 * 2) allows the kernel side to track the head on its own, even
2376 * though the application is the one updating it.
2377 */
2b188cc1 2378
2af89abd
PB
2379 /* double index for 128-byte SQEs, twice as long */
2380 if (ctx->flags & IORING_SETUP_SQE128)
2381 head <<= 1;
2382 *sqe = &ctx->sq_sqes[head];
2383 return true;
709b302f
PB
2384}
2385
17437f31 2386int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
282cdc86 2387 __must_hold(&ctx->uring_lock)
6c271ce2 2388{
69629809 2389 unsigned int entries = io_sqring_entries(ctx);
8e6971a8
PB
2390 unsigned int left;
2391 int ret;
6c271ce2 2392
51d48dab 2393 if (unlikely(!entries))
69629809 2394 return 0;
ee7d46d9 2395 /* make sure SQ entry isn't read before tail */
e3ef728f 2396 ret = left = min(nr, entries);
8e6971a8
PB
2397 io_get_task_refs(left);
2398 io_submit_state_start(&ctx->submit_state, left);
6c271ce2 2399
69629809 2400 do {
3529d8c2 2401 const struct io_uring_sqe *sqe;
196be95c 2402 struct io_kiocb *req;
fb5ccc98 2403
c8576f3e 2404 if (unlikely(!io_alloc_req(ctx, &req)))
fb5ccc98 2405 break;
b5083dfa 2406 if (unlikely(!io_get_sqe(ctx, &sqe))) {
fa05457a 2407 io_req_add_to_cache(req, ctx);
4fccfcbb
PB
2408 break;
2409 }
6c271ce2 2410
1cd15904
PB
2411 /*
2412 * Continue submitting even for sqe failure if the
2413 * ring was setup with IORING_SETUP_SUBMIT_ALL
2414 */
2415 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2416 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2417 left--;
2418 break;
bcbb7bf6 2419 }
1cd15904 2420 } while (--left);
9466f437 2421
8e6971a8
PB
2422 if (unlikely(left)) {
2423 ret -= left;
2424 /* try again if it submitted nothing and can't allocate a req */
2425 if (!ret && io_req_cache_empty(ctx))
2426 ret = -EAGAIN;
2427 current->io_uring->cached_refs += left;
9466f437 2428 }
6c271ce2 2429
553deffd 2430 io_submit_state_end(ctx);
ae9428ca
PB
2431 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2432 io_commit_sqring(ctx);
8e6971a8 2433 return ret;
6c271ce2
JA
2434}
2435
bda52162
JA
2436static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2437 int wake_flags, void *key)
2438{
bd550173 2439 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
bda52162 2440
6c503150
PB
2441 /*
2442 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2443 * the task, and the next invocation will do it.
2444 */
bd550173 2445 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
6c503150
PB
2446 return autoremove_wake_function(curr, mode, wake_flags, key);
2447 return -1;
bda52162
JA
2448}
2449
c0e0d6ba 2450int io_run_task_work_sig(struct io_ring_ctx *ctx)
af9c1a44 2451{
1414d629 2452 if (!llist_empty(&ctx->work_llist)) {
2f413956 2453 __set_current_state(TASK_RUNNING);
9fe3eaea 2454 if (io_run_local_work(ctx, INT_MAX) > 0)
d246c759 2455 return 0;
1414d629
PB
2456 }
2457 if (io_run_task_work() > 0)
d246c759 2458 return 0;
c5020bc8
OL
2459 if (task_sigpending(current))
2460 return -EINTR;
2461 return 0;
af9c1a44
JA
2462}
2463
7b72d661
JA
2464static bool current_pending_io(void)
2465{
2466 struct io_uring_task *tctx = current->io_uring;
2467
2468 if (!tctx)
2469 return false;
2470 return percpu_counter_read_positive(&tctx->inflight);
2471}
2472
eeb60b9a
PB
2473/* when returns >0, the caller should retry */
2474static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
d33a39e5 2475 struct io_wait_queue *iowq)
eeb60b9a 2476{
6f0974ec 2477 int ret;
8a796565 2478
3fcf19d5
PB
2479 if (unlikely(READ_ONCE(ctx->check_cq)))
2480 return 1;
846072f1
PB
2481 if (unlikely(!llist_empty(&ctx->work_llist)))
2482 return 1;
2483 if (unlikely(test_thread_flag(TIF_NOTIFY_SIGNAL)))
2484 return 1;
2485 if (unlikely(task_sigpending(current)))
2486 return -EINTR;
2487 if (unlikely(io_should_wake(iowq)))
2488 return 0;
8a796565
AF
2489
2490 /*
7b72d661
JA
2491 * Mark us as being in io_wait if we have pending requests, so cpufreq
2492 * can take into account that the task is waiting for IO - turns out
2493 * to be important for low QD IO.
8a796565 2494 */
7b72d661
JA
2495 if (current_pending_io())
2496 current->in_iowait = 1;
8a796565 2497 ret = 0;
d33a39e5 2498 if (iowq->timeout == KTIME_MAX)
46ae7eef 2499 schedule();
d33a39e5 2500 else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS))
8a796565 2501 ret = -ETIME;
6f0974ec 2502 current->in_iowait = 0;
8a796565 2503 return ret;
eeb60b9a
PB
2504}
2505
2b188cc1
JA
2506/*
2507 * Wait until events become available, if we don't already have some. The
2508 * application must reap them itself, as they reside on the shared cq ring.
2509 */
2510static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
c73ebb68
HX
2511 const sigset_t __user *sig, size_t sigsz,
2512 struct __kernel_timespec __user *uts)
2b188cc1 2513{
90291099 2514 struct io_wait_queue iowq;
75b28aff 2515 struct io_rings *rings = ctx->rings;
c1d5a224 2516 int ret;
2b188cc1 2517
76de6749
PB
2518 if (!io_allowed_run_tw(ctx))
2519 return -EEXIST;
140102ae 2520 if (!llist_empty(&ctx->work_llist))
9fe3eaea 2521 io_run_local_work(ctx, min_events);
f36ba6cf
PB
2522 io_run_task_work();
2523 io_cqring_overflow_flush(ctx);
2524 /* if user messes with these they will just get an early return */
2525 if (__io_cqring_events_user(ctx) >= min_events)
2526 return 0;
2b188cc1 2527
90291099
PB
2528 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2529 iowq.wq.private = current;
2530 INIT_LIST_HEAD(&iowq.wq.entry);
2531 iowq.ctx = ctx;
bda52162 2532 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5fd46178 2533 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
d33a39e5
PB
2534 iowq.timeout = KTIME_MAX;
2535
2536 if (uts) {
2537 struct timespec64 ts;
2538
2539 if (get_timespec64(&ts, uts))
2540 return -EFAULT;
8d0c12a8 2541
d33a39e5 2542 iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8d0c12a8 2543 io_napi_adjust_timeout(ctx, &iowq, &ts);
d33a39e5 2544 }
90291099 2545
978e5c19
AI
2546 if (sig) {
2547#ifdef CONFIG_COMPAT
2548 if (in_compat_syscall())
2549 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2550 sigsz);
2551 else
2552#endif
2553 ret = set_user_sigmask(sig, sigsz);
2554
2555 if (ret)
2556 return ret;
2557 }
2558
8d0c12a8
SR
2559 io_napi_busy_loop(ctx, &iowq);
2560
c826bd7a 2561 trace_io_uring_cqring_wait(ctx, min_events);
bda52162 2562 do {
9fe3eaea 2563 int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail);
3fcf19d5
PB
2564 unsigned long check_cq;
2565
130bd686 2566 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
8751d154 2567 atomic_set(&ctx->cq_wait_nr, nr_wait);
130bd686
PB
2568 set_current_state(TASK_INTERRUPTIBLE);
2569 } else {
2570 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2571 TASK_INTERRUPTIBLE);
2572 }
2573
d33a39e5 2574 ret = io_cqring_wait_schedule(ctx, &iowq);
130bd686 2575 __set_current_state(TASK_RUNNING);
b4bc35cf 2576 atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
d80c0f00 2577
846072f1
PB
2578 /*
2579 * Run task_work after scheduling and before io_should_wake().
2580 * If we got woken because of task_work being processed, run it
2581 * now rather than let the caller do another wait loop.
2582 */
2583 io_run_task_work();
2584 if (!llist_empty(&ctx->work_llist))
9fe3eaea 2585 io_run_local_work(ctx, nr_wait);
3fcf19d5 2586
6ff1407e
JA
2587 /*
2588 * Non-local task_work will be run on exit to userspace, but
2589 * if we're using DEFER_TASKRUN, then we could have waited
2590 * with a timeout for a number of requests. If the timeout
2591 * hits, we could have some requests ready to process. Ensure
2592 * this break is _after_ we have run task_work, to avoid
2593 * deferring running potentially pending requests until the
2594 * next time we wait for events.
2595 */
2596 if (ret < 0)
2597 break;
2598
3fcf19d5
PB
2599 check_cq = READ_ONCE(ctx->check_cq);
2600 if (unlikely(check_cq)) {
2601 /* let the caller flush overflows, retry */
326a9e48 2602 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3fcf19d5 2603 io_cqring_do_overflow_flush(ctx);
3fcf19d5
PB
2604 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2605 ret = -EBADR;
2606 break;
2607 }
2608 }
2609
846072f1
PB
2610 if (io_should_wake(&iowq)) {
2611 ret = 0;
35d90f95 2612 break;
846072f1 2613 }
ca0a2651 2614 cond_resched();
846072f1 2615 } while (1);
bda52162 2616
130bd686
PB
2617 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2618 finish_wait(&ctx->cq_wait, &iowq.wq);
b7db41c9 2619 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 2620
75b28aff 2621 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
2622}
2623
edecf168 2624void io_mem_free(void *ptr)
b9bd2bea 2625{
73572984
JA
2626 if (!ptr)
2627 return;
b9bd2bea 2628
99a9e0b8 2629 folio_put(virt_to_folio(ptr));
b9bd2bea
PB
2630}
2631
03d89a2d
JA
2632static void io_pages_free(struct page ***pages, int npages)
2633{
2c5c0ba1 2634 struct page **page_array = *pages;
03d89a2d
JA
2635 int i;
2636
8b51a395
JA
2637 if (!page_array)
2638 return;
2639
03d89a2d
JA
2640 for (i = 0; i < npages; i++)
2641 unpin_user_page(page_array[i]);
2642 kvfree(page_array);
2643 *pages = NULL;
2644}
2645
2646static void *__io_uaddr_map(struct page ***pages, unsigned short *npages,
2647 unsigned long uaddr, size_t size)
2648{
2649 struct page **page_array;
2650 unsigned int nr_pages;
820d070f 2651 void *page_addr;
67d1189d 2652 int ret, i, pinned;
03d89a2d
JA
2653
2654 *npages = 0;
2655
2656 if (uaddr & (PAGE_SIZE - 1) || !size)
2657 return ERR_PTR(-EINVAL);
2658
2659 nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2660 if (nr_pages > USHRT_MAX)
2661 return ERR_PTR(-EINVAL);
2662 page_array = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
2663 if (!page_array)
2664 return ERR_PTR(-ENOMEM);
2665
67d1189d
GKB
2666
2667 pinned = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
2668 page_array);
2669 if (pinned != nr_pages) {
2670 ret = (pinned < 0) ? pinned : -EFAULT;
2671 goto free_pages;
03d89a2d 2672 }
223ef474 2673
820d070f 2674 page_addr = page_address(page_array[0]);
223ef474 2675 for (i = 0; i < nr_pages; i++) {
820d070f
JA
2676 ret = -EINVAL;
2677
2678 /*
2679 * Can't support mapping user allocated ring memory on 32-bit
2680 * archs where it could potentially reside in highmem. Just
2681 * fail those with -EINVAL, just like we did on kernels that
2682 * didn't support this feature.
2683 */
2684 if (PageHighMem(page_array[i]))
67d1189d 2685 goto free_pages;
820d070f
JA
2686
2687 /*
2688 * No support for discontig pages for now, should either be a
2689 * single normal page, or a huge page. Later on we can add
2690 * support for remapping discontig pages, for now we will
2691 * just fail them with EINVAL.
2692 */
2693 if (page_address(page_array[i]) != page_addr)
67d1189d 2694 goto free_pages;
820d070f 2695 page_addr += PAGE_SIZE;
223ef474
JA
2696 }
2697
03d89a2d
JA
2698 *pages = page_array;
2699 *npages = nr_pages;
2700 return page_to_virt(page_array[0]);
67d1189d
GKB
2701
2702free_pages:
2703 io_pages_free(&page_array, pinned > 0 ? pinned : 0);
2704 return ERR_PTR(ret);
03d89a2d
JA
2705}
2706
2707static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2708 size_t size)
2709{
2710 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2711 size);
2712}
2713
2714static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2715 size_t size)
2716{
2717 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2718 size);
2719}
2720
9c189eee
JA
2721static void io_rings_free(struct io_ring_ctx *ctx)
2722{
03d89a2d
JA
2723 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2724 io_mem_free(ctx->rings);
2725 io_mem_free(ctx->sq_sqes);
03d89a2d
JA
2726 } else {
2727 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
8b51a395 2728 ctx->n_ring_pages = 0;
03d89a2d 2729 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
8b51a395 2730 ctx->n_sqe_pages = 0;
03d89a2d 2731 }
cef59d1e
PB
2732
2733 ctx->rings = NULL;
2734 ctx->sq_sqes = NULL;
9c189eee
JA
2735}
2736
edecf168 2737void *io_mem_alloc(size_t size)
b9bd2bea 2738{
73572984 2739 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
e27cef86 2740 void *ret;
b9bd2bea 2741
e27cef86
JA
2742 ret = (void *) __get_free_pages(gfp, get_order(size));
2743 if (ret)
2744 return ret;
2745 return ERR_PTR(-ENOMEM);
b9bd2bea
PB
2746}
2747
73572984
JA
2748static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2749 unsigned int cq_entries, size_t *sq_offset)
6b06314c 2750{
73572984
JA
2751 struct io_rings *rings;
2752 size_t off, sq_array_size;
6b06314c 2753
73572984
JA
2754 off = struct_size(rings, cqes, cq_entries);
2755 if (off == SIZE_MAX)
2756 return SIZE_MAX;
2757 if (ctx->flags & IORING_SETUP_CQE32) {
2758 if (check_shl_overflow(off, 1, &off))
2759 return SIZE_MAX;
2760 }
ab409402 2761
73572984
JA
2762#ifdef CONFIG_SMP
2763 off = ALIGN(off, SMP_CACHE_BYTES);
2764 if (off == 0)
2765 return SIZE_MAX;
2766#endif
82fbcfa9 2767
2af89abd
PB
2768 if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
2769 if (sq_offset)
2770 *sq_offset = SIZE_MAX;
2771 return off;
2772 }
2773
73572984
JA
2774 if (sq_offset)
2775 *sq_offset = off;
82fbcfa9 2776
73572984
JA
2777 sq_array_size = array_size(sizeof(u32), sq_entries);
2778 if (sq_array_size == SIZE_MAX)
2779 return SIZE_MAX;
6b06314c 2780
73572984
JA
2781 if (check_add_overflow(off, sq_array_size, &off))
2782 return SIZE_MAX;
8bad28d8 2783
73572984 2784 return off;
8bad28d8
HX
2785}
2786
73572984 2787static void io_req_caches_free(struct io_ring_ctx *ctx)
2b188cc1 2788{
c8576f3e 2789 struct io_kiocb *req;
37f0e767 2790 int nr = 0;
bf019da7 2791
9a4fdbd8 2792 mutex_lock(&ctx->uring_lock);
34f0bc42 2793 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
9a4fdbd8 2794
88ab95be 2795 while (!io_req_cache_empty(ctx)) {
c8576f3e 2796 req = io_extract_req(ctx);
c2b6c6bc 2797 kmem_cache_free(req_cachep, req);
37f0e767 2798 nr++;
c2b6c6bc 2799 }
37f0e767
PB
2800 if (nr)
2801 percpu_ref_put_many(&ctx->refs, nr);
9a4fdbd8
JA
2802 mutex_unlock(&ctx->uring_lock);
2803}
2804
9eae8655
PB
2805static void io_rsrc_node_cache_free(struct io_cache_entry *entry)
2806{
2807 kfree(container_of(entry, struct io_rsrc_node, cache));
2808}
2809
c072481d 2810static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2b188cc1 2811{
37d1e2e3 2812 io_sq_thread_finish(ctx);
43597aac 2813 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
0b222eeb
PB
2814 if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
2815 return;
43597aac 2816
8bad28d8 2817 mutex_lock(&ctx->uring_lock);
43597aac 2818 if (ctx->buf_data)
bd54b6fe 2819 __io_sqe_buffers_unregister(ctx);
43597aac 2820 if (ctx->file_data)
08480400 2821 __io_sqe_files_unregister(ctx);
a85381d8 2822 io_cqring_overflow_kill(ctx);
9b402849 2823 io_eventfd_unregister(ctx);
9b797a37 2824 io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free);
43e0bbbd 2825 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
194bb58c 2826 io_futex_cache_free(ctx);
5a2e745d 2827 io_destroy_buffers(ctx);
b4a72c05 2828 mutex_unlock(&ctx->uring_lock);
07db298a
PB
2829 if (ctx->sq_creds)
2830 put_cred(ctx->sq_creds);
97bbdc06
PB
2831 if (ctx->submitter_task)
2832 put_task_struct(ctx->submitter_task);
def596e9 2833
a7f0ed5a
PB
2834 /* there are no registered resources left, nobody uses it */
2835 if (ctx->rsrc_node)
9eae8655 2836 io_rsrc_node_destroy(ctx, ctx->rsrc_node);
a7f0ed5a
PB
2837
2838 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
ef9dd637 2839 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2b188cc1 2840
9eae8655 2841 io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free);
42b6419d
PB
2842 if (ctx->mm_account) {
2843 mmdrop(ctx->mm_account);
2844 ctx->mm_account = NULL;
2845 }
9c189eee 2846 io_rings_free(ctx);
c392cbec 2847 io_kbuf_mmap_list_free(ctx);
2b188cc1
JA
2848
2849 percpu_ref_exit(&ctx->refs);
2b188cc1 2850 free_uid(ctx->user);
4010fec4 2851 io_req_caches_free(ctx);
e941894e
JA
2852 if (ctx->hash_map)
2853 io_wq_put_hash(ctx->hash_map);
8d0c12a8 2854 io_napi_free(ctx);
e6f89be6 2855 kfree(ctx->cancel_table.hbs);
9ca9fb24 2856 kfree(ctx->cancel_table_locked.hbs);
9cfc7e94 2857 xa_destroy(&ctx->io_bl_xa);
2b188cc1
JA
2858 kfree(ctx);
2859}
2860
bca39f39
PB
2861static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2862{
2863 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2864 poll_wq_task_work);
2865
2866 mutex_lock(&ctx->uring_lock);
2867 ctx->poll_activated = true;
2868 mutex_unlock(&ctx->uring_lock);
2869
2870 /*
2871 * Wake ups for some events between start of polling and activation
2872 * might've been lost due to loose synchronisation.
2873 */
2874 wake_up_all(&ctx->poll_wq);
2875 percpu_ref_put(&ctx->refs);
2876}
2877
c4320315 2878__cold void io_activate_pollwq(struct io_ring_ctx *ctx)
bca39f39
PB
2879{
2880 spin_lock(&ctx->completion_lock);
2881 /* already activated or in progress */
2882 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2883 goto out;
2884 if (WARN_ON_ONCE(!ctx->task_complete))
2885 goto out;
2886 if (!ctx->submitter_task)
2887 goto out;
2888 /*
2889 * with ->submitter_task only the submitter task completes requests, we
2890 * only need to sync with it, which is done by injecting a tw
2891 */
2892 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2893 percpu_ref_get(&ctx->refs);
2894 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2895 percpu_ref_put(&ctx->refs);
2896out:
2897 spin_unlock(&ctx->completion_lock);
2898}
2899
2b188cc1
JA
2900static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2901{
2902 struct io_ring_ctx *ctx = file->private_data;
2903 __poll_t mask = 0;
2904
bca39f39
PB
2905 if (unlikely(!ctx->poll_activated))
2906 io_activate_pollwq(ctx);
2907
7b235dd8 2908 poll_wait(file, &ctx->poll_wq, wait);
4f7067c3
SB
2909 /*
2910 * synchronizes with barrier from wq_has_sleeper call in
2911 * io_commit_cqring
2912 */
2b188cc1 2913 smp_rmb();
90554200 2914 if (!io_sqring_full(ctx))
2b188cc1 2915 mask |= EPOLLOUT | EPOLLWRNORM;
ed670c3f
HX
2916
2917 /*
2918 * Don't flush cqring overflow list here, just do a simple check.
2919 * Otherwise there could possible be ABBA deadlock:
2920 * CPU0 CPU1
2921 * ---- ----
2922 * lock(&ctx->uring_lock);
2923 * lock(&ep->mtx);
2924 * lock(&ctx->uring_lock);
2925 * lock(&ep->mtx);
2926 *
2927 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10d8bc35 2928 * pushes them to do the flush.
ed670c3f 2929 */
b4c98d59 2930
c10bb646 2931 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2b188cc1
JA
2932 mask |= EPOLLIN | EPOLLRDNORM;
2933
2934 return mask;
2935}
2936
d56d938b
PB
2937struct io_tctx_exit {
2938 struct callback_head task_work;
2939 struct completion completion;
baf186c4 2940 struct io_ring_ctx *ctx;
d56d938b
PB
2941};
2942
c072481d 2943static __cold void io_tctx_exit_cb(struct callback_head *cb)
d56d938b
PB
2944{
2945 struct io_uring_task *tctx = current->io_uring;
2946 struct io_tctx_exit *work;
2947
2948 work = container_of(cb, struct io_tctx_exit, task_work);
2949 /*
8d664282 2950 * When @in_cancel, we're in cancellation and it's racy to remove the
d56d938b 2951 * node. It'll be removed by the end of cancellation, just ignore it.
998b30c3
HM
2952 * tctx can be NULL if the queueing of this task_work raced with
2953 * work cancelation off the exec path.
d56d938b 2954 */
8d664282 2955 if (tctx && !atomic_read(&tctx->in_cancel))
eef51daa 2956 io_uring_del_tctx_node((unsigned long)work->ctx);
d56d938b
PB
2957 complete(&work->completion);
2958}
2959
c072481d 2960static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
28090c13
PB
2961{
2962 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2963
2964 return req->ctx == data;
2965}
2966
c072481d 2967static __cold void io_ring_exit_work(struct work_struct *work)
85faa7b8 2968{
d56d938b 2969 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
b5bb3a24 2970 unsigned long timeout = jiffies + HZ * 60 * 5;
58d3be2c 2971 unsigned long interval = HZ / 20;
d56d938b
PB
2972 struct io_tctx_exit exit;
2973 struct io_tctx_node *node;
2974 int ret;
85faa7b8 2975
56952e91
JA
2976 /*
2977 * If we're doing polled IO and end up having requests being
2978 * submitted async (out-of-line), then completions can come in while
2979 * we're waiting for refs to drop. We need to reap these manually,
2980 * as nobody else will be looking for them.
2981 */
b2edc0a7 2982 do {
a85381d8
PB
2983 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2984 mutex_lock(&ctx->uring_lock);
2985 io_cqring_overflow_kill(ctx);
2986 mutex_unlock(&ctx->uring_lock);
2987 }
2988
c0e0d6ba
DY
2989 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2990 io_move_task_work_from_local(ctx);
2991
affa87db
PB
2992 while (io_uring_try_cancel_requests(ctx, NULL, true))
2993 cond_resched();
2994
28090c13
PB
2995 if (ctx->sq_data) {
2996 struct io_sq_data *sqd = ctx->sq_data;
2997 struct task_struct *tsk;
2998
2999 io_sq_thread_park(sqd);
3000 tsk = sqd->thread;
3001 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
3002 io_wq_cancel_cb(tsk->io_uring->io_wq,
3003 io_cancel_ctx_cb, ctx, true);
3004 io_sq_thread_unpark(sqd);
3005 }
b5bb3a24 3006
37f0e767
PB
3007 io_req_caches_free(ctx);
3008
58d3be2c
PB
3009 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
3010 /* there is little hope left, don't run it too often */
3011 interval = HZ * 60;
3012 }
4826c594
JA
3013 /*
3014 * This is really an uninterruptible wait, as it has to be
3015 * complete. But it's also run from a kworker, which doesn't
3016 * take signals, so it's fine to make it interruptible. This
3017 * avoids scenarios where we knowingly can wait much longer
3018 * on completions, for example if someone does a SIGSTOP on
3019 * a task that needs to finish task_work to make this loop
3020 * complete. That's a synthetic situation that should not
3021 * cause a stuck task backtrace, and hence a potential panic
3022 * on stuck tasks if that is enabled.
3023 */
3024 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
d56d938b 3025
7f00651a
PB
3026 init_completion(&exit.completion);
3027 init_task_work(&exit.task_work, io_tctx_exit_cb);
3028 exit.ctx = ctx;
f7b32e78 3029
d56d938b
PB
3030 mutex_lock(&ctx->uring_lock);
3031 while (!list_empty(&ctx->tctx_list)) {
b5bb3a24
PB
3032 WARN_ON_ONCE(time_after(jiffies, timeout));
3033
d56d938b
PB
3034 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
3035 ctx_node);
7f00651a
PB
3036 /* don't spin on a single task if cancellation failed */
3037 list_rotate_left(&ctx->tctx_list);
d56d938b
PB
3038 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
3039 if (WARN_ON_ONCE(ret))
3040 continue;
d56d938b
PB
3041
3042 mutex_unlock(&ctx->uring_lock);
4826c594
JA
3043 /*
3044 * See comment above for
3045 * wait_for_completion_interruptible_timeout() on why this
3046 * wait is marked as interruptible.
3047 */
3048 wait_for_completion_interruptible(&exit.completion);
d56d938b
PB
3049 mutex_lock(&ctx->uring_lock);
3050 }
3051 mutex_unlock(&ctx->uring_lock);
79ebeaee
JA
3052 spin_lock(&ctx->completion_lock);
3053 spin_unlock(&ctx->completion_lock);
d56d938b 3054
d73a572d
PB
3055 /* pairs with RCU read section in io_req_local_work_add() */
3056 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3057 synchronize_rcu();
3058
85faa7b8
JA
3059 io_ring_ctx_free(ctx);
3060}
3061
c072481d 3062static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2b188cc1 3063{
61cf9370
MWO
3064 unsigned long index;
3065 struct creds *creds;
3066
2b188cc1
JA
3067 mutex_lock(&ctx->uring_lock);
3068 percpu_ref_kill(&ctx->refs);
61cf9370
MWO
3069 xa_for_each(&ctx->personalities, index, creds)
3070 io_unregister_personality(ctx, index);
9ca9fb24
PB
3071 if (ctx->rings)
3072 io_poll_remove_all(ctx, NULL, true);
2b188cc1
JA
3073 mutex_unlock(&ctx->uring_lock);
3074
02bac94b
PB
3075 /*
3076 * If we failed setting up the ctx, we might not have any rings
3077 * and therefore did not submit any requests
3078 */
3079 if (ctx->rings)
60053be8 3080 io_kill_timeouts(ctx, NULL, true);
309fc03a 3081
dfbe5561
JA
3082 flush_delayed_work(&ctx->fallback_work);
3083
85faa7b8 3084 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
fc666777
JA
3085 /*
3086 * Use system_unbound_wq to avoid spawning tons of event kworkers
3087 * if we're exiting a ton of rings at the same time. It just adds
3088 * noise and overhead, there's no discernable change in runtime
3089 * over using system_wq.
3090 */
73eaa2b5 3091 queue_work(iou_wq, &ctx->exit_work);
2b188cc1
JA
3092}
3093
3094static int io_uring_release(struct inode *inode, struct file *file)
3095{
3096 struct io_ring_ctx *ctx = file->private_data;
3097
3098 file->private_data = NULL;
3099 io_ring_ctx_wait_and_kill(ctx);
3100 return 0;
3101}
3102
f6edbabb
PB
3103struct io_task_cancel {
3104 struct task_struct *task;
3dd0c97a 3105 bool all;
f6edbabb 3106};
f254ac04 3107
f6edbabb 3108static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
b711d4ea 3109{
9a472ef7 3110 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
f6edbabb 3111 struct io_task_cancel *cancel = data;
9a472ef7 3112
6af3f48b 3113 return io_match_task_safe(req, cancel->task, cancel->all);
b711d4ea
JA
3114}
3115
c072481d
PB
3116static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3117 struct task_struct *task,
3118 bool cancel_all)
b7ddce3c 3119{
e1915f76 3120 struct io_defer_entry *de;
b7ddce3c
PB
3121 LIST_HEAD(list);
3122
79ebeaee 3123 spin_lock(&ctx->completion_lock);
b7ddce3c 3124 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
6af3f48b 3125 if (io_match_task_safe(de->req, task, cancel_all)) {
b7ddce3c
PB
3126 list_cut_position(&list, &ctx->defer_list, &de->list);
3127 break;
3128 }
3129 }
79ebeaee 3130 spin_unlock(&ctx->completion_lock);
e1915f76
PB
3131 if (list_empty(&list))
3132 return false;
b7ddce3c
PB
3133
3134 while (!list_empty(&list)) {
3135 de = list_first_entry(&list, struct io_defer_entry, list);
3136 list_del_init(&de->list);
e276ae34 3137 io_req_task_queue_fail(de->req, -ECANCELED);
b7ddce3c
PB
3138 kfree(de);
3139 }
e1915f76 3140 return true;
b7ddce3c
PB
3141}
3142
c072481d 3143static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
1b00764f
PB
3144{
3145 struct io_tctx_node *node;
3146 enum io_wq_cancel cret;
3147 bool ret = false;
3148
3149 mutex_lock(&ctx->uring_lock);
3150 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3151 struct io_uring_task *tctx = node->task->io_uring;
3152
3153 /*
3154 * io_wq will stay alive while we hold uring_lock, because it's
3155 * killed after ctx nodes, which requires to take the lock.
3156 */
3157 if (!tctx || !tctx->io_wq)
3158 continue;
3159 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3160 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3161 }
3162 mutex_unlock(&ctx->uring_lock);
3163
3164 return ret;
3165}
3166
affa87db 3167static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
c072481d
PB
3168 struct task_struct *task,
3169 bool cancel_all)
9936c7c2 3170{
3dd0c97a 3171 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
1b00764f 3172 struct io_uring_task *tctx = task ? task->io_uring : NULL;
affa87db
PB
3173 enum io_wq_cancel cret;
3174 bool ret = false;
9936c7c2 3175
360cd42c
PB
3176 /* set it so io_req_local_work_add() would wake us up */
3177 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3178 atomic_set(&ctx->cq_wait_nr, 1);
3179 smp_mb();
3180 }
3181
60053be8
PB
3182 /* failed during ring init, it couldn't have issued any requests */
3183 if (!ctx->rings)
affa87db 3184 return false;
60053be8 3185
affa87db
PB
3186 if (!task) {
3187 ret |= io_uring_try_cancel_iowq(ctx);
3188 } else if (tctx && tctx->io_wq) {
3189 /*
3190 * Cancels requests of all rings, not only @ctx, but
3191 * it's fine as the task is in exit/exec.
3192 */
3193 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3194 &cancel, true);
3195 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3196 }
9936c7c2 3197
affa87db
PB
3198 /* SQPOLL thread does its own polling */
3199 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3200 (ctx->sq_data && ctx->sq_data->thread == current)) {
3201 while (!wq_list_empty(&ctx->iopoll_list)) {
3202 io_iopoll_try_reap_events(ctx);
3203 ret = true;
fcc926bb 3204 cond_resched();
9936c7c2 3205 }
9936c7c2 3206 }
affa87db 3207
140102ae
PB
3208 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3209 io_allowed_defer_tw_run(ctx))
9fe3eaea 3210 ret |= io_run_local_work(ctx, INT_MAX) > 0;
affa87db
PB
3211 ret |= io_cancel_defer_files(ctx, task, cancel_all);
3212 mutex_lock(&ctx->uring_lock);
3213 ret |= io_poll_remove_all(ctx, task, cancel_all);
f31ecf67 3214 ret |= io_waitid_remove_all(ctx, task, cancel_all);
194bb58c 3215 ret |= io_futex_remove_all(ctx, task, cancel_all);
93b8cc60 3216 ret |= io_uring_try_cancel_uring_cmd(ctx, task, cancel_all);
affa87db
PB
3217 mutex_unlock(&ctx->uring_lock);
3218 ret |= io_kill_timeouts(ctx, task, cancel_all);
3219 if (task)
c0e0d6ba 3220 ret |= io_run_task_work() > 0;
affa87db 3221 return ret;
9936c7c2
PB
3222}
3223
3f48cf18 3224static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
521d6a73 3225{
3f48cf18 3226 if (tracked)
9cae36a0 3227 return atomic_read(&tctx->inflight_tracked);
521d6a73
PB
3228 return percpu_counter_sum(&tctx->inflight);
3229}
3230
78cc687b
PB
3231/*
3232 * Find any io_uring ctx that this task has registered or done IO on, and cancel
78a78060 3233 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
78cc687b 3234 */
17437f31 3235__cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
0e9ddb39 3236{
521d6a73 3237 struct io_uring_task *tctx = current->io_uring;
734551df 3238 struct io_ring_ctx *ctx;
360cd42c
PB
3239 struct io_tctx_node *node;
3240 unsigned long index;
0e9ddb39
PB
3241 s64 inflight;
3242 DEFINE_WAIT(wait);
fdaf083c 3243
78cc687b
PB
3244 WARN_ON_ONCE(sqd && sqd->thread != current);
3245
6d042ffb
PO
3246 if (!current->io_uring)
3247 return;
17a91051
PB
3248 if (tctx->io_wq)
3249 io_wq_exit_start(tctx->io_wq);
3250
8d664282 3251 atomic_inc(&tctx->in_cancel);
0e9ddb39 3252 do {
affa87db
PB
3253 bool loop = false;
3254
e9dbe221 3255 io_uring_drop_tctx_refs(current);
0e9ddb39 3256 /* read completions before cancelations */
78cc687b 3257 inflight = tctx_inflight(tctx, !cancel_all);
0e9ddb39
PB
3258 if (!inflight)
3259 break;
fdaf083c 3260
78cc687b 3261 if (!sqd) {
78cc687b
PB
3262 xa_for_each(&tctx->xa, index, node) {
3263 /* sqpoll task will cancel all its requests */
3264 if (node->ctx->sq_data)
3265 continue;
affa87db
PB
3266 loop |= io_uring_try_cancel_requests(node->ctx,
3267 current, cancel_all);
78cc687b
PB
3268 }
3269 } else {
3270 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
affa87db
PB
3271 loop |= io_uring_try_cancel_requests(ctx,
3272 current,
3273 cancel_all);
3274 }
3275
3276 if (loop) {
3277 cond_resched();
3278 continue;
78cc687b 3279 }
17a91051 3280
78a78060
JA
3281 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3282 io_run_task_work();
e9dbe221 3283 io_uring_drop_tctx_refs(current);
360cd42c
PB
3284 xa_for_each(&tctx->xa, index, node) {
3285 if (!llist_empty(&node->ctx->work_llist)) {
3286 WARN_ON_ONCE(node->ctx->submitter_task &&
3287 node->ctx->submitter_task != current);
3288 goto end_wait;
3289 }
3290 }
0f212204 3291 /*
a1bb3cd5
PB
3292 * If we've seen completions, retry without waiting. This
3293 * avoids a race where a completion comes in before we did
3294 * prepare_to_wait().
0f212204 3295 */
3dd0c97a 3296 if (inflight == tctx_inflight(tctx, !cancel_all))
a1bb3cd5 3297 schedule();
360cd42c 3298end_wait:
f57555ed 3299 finish_wait(&tctx->wait, &wait);
d8a6df10 3300 } while (1);
de7f1d9e 3301
8452d4a6 3302 io_uring_clean_tctx(tctx);
3dd0c97a 3303 if (cancel_all) {
3cc7fdb9
PB
3304 /*
3305 * We shouldn't run task_works after cancel, so just leave
8d664282 3306 * ->in_cancel set for normal exit.
3cc7fdb9 3307 */
8d664282 3308 atomic_dec(&tctx->in_cancel);
3f48cf18
PB
3309 /* for exec all current's requests should be gone, kill tctx */
3310 __io_uring_free(current);
3311 }
44e728b8
PB
3312}
3313
f552a27a 3314void __io_uring_cancel(bool cancel_all)
78cc687b 3315{
f552a27a 3316 io_uring_cancel_generic(cancel_all, NULL);
78cc687b
PB
3317}
3318
6c5c240e
RP
3319static void *io_uring_validate_mmap_request(struct file *file,
3320 loff_t pgoff, size_t sz)
2b188cc1 3321{
2b188cc1 3322 struct io_ring_ctx *ctx = file->private_data;
6c5c240e 3323 loff_t offset = pgoff << PAGE_SHIFT;
2b188cc1
JA
3324 struct page *page;
3325 void *ptr;
3326
c56e022c 3327 switch (offset & IORING_OFF_MMAP_MASK) {
2b188cc1 3328 case IORING_OFF_SQ_RING:
75b28aff 3329 case IORING_OFF_CQ_RING:
6f007b14
JA
3330 /* Don't allow mmap if the ring was setup without it */
3331 if (ctx->flags & IORING_SETUP_NO_MMAP)
3332 return ERR_PTR(-EINVAL);
75b28aff 3333 ptr = ctx->rings;
2b188cc1
JA
3334 break;
3335 case IORING_OFF_SQES:
6f007b14
JA
3336 /* Don't allow mmap if the ring was setup without it */
3337 if (ctx->flags & IORING_SETUP_NO_MMAP)
3338 return ERR_PTR(-EINVAL);
2b188cc1
JA
3339 ptr = ctx->sq_sqes;
3340 break;
c56e022c 3341 case IORING_OFF_PBUF_RING: {
561e4f94 3342 struct io_buffer_list *bl;
c56e022c
JA
3343 unsigned int bgid;
3344
3345 bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT;
561e4f94
JA
3346 bl = io_pbuf_get_bl(ctx, bgid);
3347 if (IS_ERR(bl))
3348 return bl;
3349 ptr = bl->buf_ring;
3350 io_put_bl(ctx, bl);
c56e022c
JA
3351 break;
3352 }
2b188cc1 3353 default:
6c5c240e 3354 return ERR_PTR(-EINVAL);
2b188cc1
JA
3355 }
3356
3357 page = virt_to_head_page(ptr);
a50b854e 3358 if (sz > page_size(page))
6c5c240e
RP
3359 return ERR_PTR(-EINVAL);
3360
3361 return ptr;
3362}
3363
3364#ifdef CONFIG_MMU
3365
c072481d 3366static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6c5c240e
RP
3367{
3368 size_t sz = vma->vm_end - vma->vm_start;
3369 unsigned long pfn;
3370 void *ptr;
3371
3372 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
3373 if (IS_ERR(ptr))
3374 return PTR_ERR(ptr);
2b188cc1
JA
3375
3376 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3377 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3378}
3379
d808459b
HD
3380static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp,
3381 unsigned long addr, unsigned long len,
3382 unsigned long pgoff, unsigned long flags)
3383{
d808459b
HD
3384 void *ptr;
3385
3386 /*
3387 * Do not allow to map to user-provided address to avoid breaking the
3388 * aliasing rules. Userspace is not able to guess the offset address of
3389 * kernel kmalloc()ed memory area.
3390 */
3391 if (addr)
3392 return -EINVAL;
3393
3394 ptr = io_uring_validate_mmap_request(filp, pgoff, len);
3395 if (IS_ERR(ptr))
3396 return -ENOMEM;
3397
32832a40
HD
3398 /*
3399 * Some architectures have strong cache aliasing requirements.
3400 * For such architectures we need a coherent mapping which aliases
3401 * kernel memory *and* userspace memory. To achieve that:
3402 * - use a NULL file pointer to reference physical memory, and
3403 * - use the kernel virtual address of the shared io_uring context
3404 * (instead of the userspace-provided address, which has to be 0UL
3405 * anyway).
56675f8b
HD
3406 * - use the same pgoff which the get_unmapped_area() uses to
3407 * calculate the page colouring.
32832a40
HD
3408 * For architectures without such aliasing requirements, the
3409 * architecture will return any suitable mapping because addr is 0.
3410 */
3411 filp = NULL;
3412 flags |= MAP_SHARED;
3413 pgoff = 0; /* has been translated to ptr above */
d808459b 3414#ifdef SHM_COLOUR
32832a40 3415 addr = (uintptr_t) ptr;
56675f8b 3416 pgoff = addr >> PAGE_SHIFT;
d808459b 3417#else
32832a40 3418 addr = 0UL;
d808459b 3419#endif
32832a40 3420 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
d808459b
HD
3421}
3422
6c5c240e
RP
3423#else /* !CONFIG_MMU */
3424
3425static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3426{
fc4f4be9 3427 return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL;
6c5c240e
RP
3428}
3429
3430static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
3431{
3432 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
3433}
3434
3435static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3436 unsigned long addr, unsigned long len,
3437 unsigned long pgoff, unsigned long flags)
3438{
3439 void *ptr;
3440
3441 ptr = io_uring_validate_mmap_request(file, pgoff, len);
3442 if (IS_ERR(ptr))
3443 return PTR_ERR(ptr);
3444
3445 return (unsigned long) ptr;
3446}
3447
3448#endif /* !CONFIG_MMU */
3449
f81440d3
PB
3450static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3451{
3452 if (flags & IORING_ENTER_EXT_ARG) {
3453 struct io_uring_getevents_arg arg;
3454
3455 if (argsz != sizeof(arg))
3456 return -EINVAL;
3457 if (copy_from_user(&arg, argp, sizeof(arg)))
3458 return -EFAULT;
3459 }
3460 return 0;
3461}
3462
c73ebb68
HX
3463static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3464 struct __kernel_timespec __user **ts,
3465 const sigset_t __user **sig)
3466{
3467 struct io_uring_getevents_arg arg;
3468
3469 /*
3470 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3471 * is just a pointer to the sigset_t.
3472 */
3473 if (!(flags & IORING_ENTER_EXT_ARG)) {
3474 *sig = (const sigset_t __user *) argp;
3475 *ts = NULL;
3476 return 0;
3477 }
3478
3479 /*
3480 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3481 * timespec and sigset_t pointers if good.
3482 */
3483 if (*argsz != sizeof(arg))
3484 return -EINVAL;
3485 if (copy_from_user(&arg, argp, sizeof(arg)))
3486 return -EFAULT;
d2347b96
DY
3487 if (arg.pad)
3488 return -EINVAL;
c73ebb68
HX
3489 *sig = u64_to_user_ptr(arg.sigmask);
3490 *argsz = arg.sigmask_sz;
3491 *ts = u64_to_user_ptr(arg.ts);
3492 return 0;
3493}
3494
2b188cc1 3495SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
c73ebb68
HX
3496 u32, min_complete, u32, flags, const void __user *, argp,
3497 size_t, argsz)
2b188cc1
JA
3498{
3499 struct io_ring_ctx *ctx;
73363c26 3500 struct file *file;
33f993da 3501 long ret;
2b188cc1 3502
33f993da 3503 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
e7a6c00d
JA
3504 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3505 IORING_ENTER_REGISTERED_RING)))
2b188cc1
JA
3506 return -EINVAL;
3507
e7a6c00d
JA
3508 /*
3509 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3510 * need only dereference our task private array to find it.
3511 */
3512 if (flags & IORING_ENTER_REGISTERED_RING) {
3513 struct io_uring_task *tctx = current->io_uring;
3514
3273c440 3515 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
e7a6c00d
JA
3516 return -EINVAL;
3517 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
73363c26
JA
3518 file = tctx->registered_rings[fd];
3519 if (unlikely(!file))
3273c440 3520 return -EBADF;
e7a6c00d 3521 } else {
73363c26
JA
3522 file = fget(fd);
3523 if (unlikely(!file))
3273c440
PB
3524 return -EBADF;
3525 ret = -EOPNOTSUPP;
73363c26 3526 if (unlikely(!io_is_uring_fops(file)))
fbb8bb02 3527 goto out;
e7a6c00d 3528 }
2b188cc1 3529
73363c26 3530 ctx = file->private_data;
7e84e1c7 3531 ret = -EBADFD;
33f993da 3532 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
7e84e1c7
SG
3533 goto out;
3534
6c271ce2
JA
3535 /*
3536 * For SQ polling, the thread will do all submissions and completions.
3537 * Just return the requested submit count, and wake the thread if
3538 * we were asked to.
3539 */
b2a9eada 3540 ret = 0;
6c271ce2 3541 if (ctx->flags & IORING_SETUP_SQPOLL) {
90f67366 3542 io_cqring_overflow_flush(ctx);
89448c47 3543
21f96522
JA
3544 if (unlikely(ctx->sq_data->thread == NULL)) {
3545 ret = -EOWNERDEAD;
04147488 3546 goto out;
21f96522 3547 }
6c271ce2 3548 if (flags & IORING_ENTER_SQ_WAKEUP)
534ca6d6 3549 wake_up(&ctx->sq_data->wait);
88b80534
QF
3550 if (flags & IORING_ENTER_SQ_WAIT)
3551 io_sqpoll_wait_sq(ctx);
3552
3e813c90 3553 ret = to_submit;
b2a9eada 3554 } else if (to_submit) {
eef51daa 3555 ret = io_uring_add_tctx_node(ctx);
0f212204
JA
3556 if (unlikely(ret))
3557 goto out;
7c504e65 3558
2b188cc1 3559 mutex_lock(&ctx->uring_lock);
3e813c90
DY
3560 ret = io_submit_sqes(ctx, to_submit);
3561 if (ret != to_submit) {
d487b43c 3562 mutex_unlock(&ctx->uring_lock);
7c504e65 3563 goto out;
d487b43c 3564 }
44f87745
PB
3565 if (flags & IORING_ENTER_GETEVENTS) {
3566 if (ctx->syscall_iopoll)
3567 goto iopoll_locked;
3568 /*
3569 * Ignore errors, we'll soon call io_cqring_wait() and
3570 * it should handle ownership problems if any.
3571 */
3572 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
9fe3eaea 3573 (void)io_run_local_work_locked(ctx, min_complete);
44f87745 3574 }
d487b43c 3575 mutex_unlock(&ctx->uring_lock);
2b188cc1 3576 }
c0e0d6ba 3577
2b188cc1 3578 if (flags & IORING_ENTER_GETEVENTS) {
3e813c90 3579 int ret2;
c0e0d6ba 3580
773697b6 3581 if (ctx->syscall_iopoll) {
d487b43c
PB
3582 /*
3583 * We disallow the app entering submit/complete with
3584 * polling, but we still need to lock the ring to
3585 * prevent racing with polled issue that got punted to
3586 * a workqueue.
3587 */
3588 mutex_lock(&ctx->uring_lock);
3589iopoll_locked:
3e813c90
DY
3590 ret2 = io_validate_ext_arg(flags, argp, argsz);
3591 if (likely(!ret2)) {
3592 min_complete = min(min_complete,
3593 ctx->cq_entries);
3594 ret2 = io_iopoll_check(ctx, min_complete);
d487b43c
PB
3595 }
3596 mutex_unlock(&ctx->uring_lock);
def596e9 3597 } else {
f81440d3
PB
3598 const sigset_t __user *sig;
3599 struct __kernel_timespec __user *ts;
3600
3e813c90
DY
3601 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3602 if (likely(!ret2)) {
3603 min_complete = min(min_complete,
3604 ctx->cq_entries);
3605 ret2 = io_cqring_wait(ctx, min_complete, sig,
3606 argsz, ts);
3607 }
def596e9 3608 }
c73ebb68 3609
155bc950 3610 if (!ret) {
3e813c90 3611 ret = ret2;
2b188cc1 3612
155bc950
DY
3613 /*
3614 * EBADR indicates that one or more CQE were dropped.
3615 * Once the user has been informed we can clear the bit
3616 * as they are obviously ok with those drops.
3617 */
3618 if (unlikely(ret2 == -EBADR))
3619 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3620 &ctx->check_cq);
def596e9 3621 }
2b188cc1 3622 }
7c504e65 3623out:
73363c26
JA
3624 if (!(flags & IORING_ENTER_REGISTERED_RING))
3625 fput(file);
3e813c90 3626 return ret;
2b188cc1
JA
3627}
3628
3629static const struct file_operations io_uring_fops = {
3630 .release = io_uring_release,
3631 .mmap = io_uring_mmap,
6c5c240e
RP
3632#ifndef CONFIG_MMU
3633 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3634 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
d808459b
HD
3635#else
3636 .get_unmapped_area = io_uring_mmu_get_unmapped_area,
6c5c240e 3637#endif
2b188cc1 3638 .poll = io_uring_poll,
bebdb65e 3639#ifdef CONFIG_PROC_FS
87ce955b 3640 .show_fdinfo = io_uring_show_fdinfo,
bebdb65e 3641#endif
2b188cc1
JA
3642};
3643
92ac8bea
JA
3644bool io_is_uring_fops(struct file *file)
3645{
3646 return file->f_op == &io_uring_fops;
3647}
3648
c072481d
PB
3649static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3650 struct io_uring_params *p)
2b188cc1 3651{
75b28aff
HV
3652 struct io_rings *rings;
3653 size_t size, sq_array_offset;
e27cef86 3654 void *ptr;
2b188cc1 3655
bd740481
JA
3656 /* make sure these are sane, as we already accounted them */
3657 ctx->sq_entries = p->sq_entries;
3658 ctx->cq_entries = p->cq_entries;
3659
baf9cb64 3660 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
75b28aff
HV
3661 if (size == SIZE_MAX)
3662 return -EOVERFLOW;
3663
03d89a2d
JA
3664 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3665 rings = io_mem_alloc(size);
3666 else
3667 rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3668
e27cef86
JA
3669 if (IS_ERR(rings))
3670 return PTR_ERR(rings);
2b188cc1 3671
75b28aff 3672 ctx->rings = rings;
2af89abd
PB
3673 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3674 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
75b28aff
HV
3675 rings->sq_ring_mask = p->sq_entries - 1;
3676 rings->cq_ring_mask = p->cq_entries - 1;
3677 rings->sq_ring_entries = p->sq_entries;
3678 rings->cq_ring_entries = p->cq_entries;
2b188cc1 3679
ebdeb7c0
JA
3680 if (p->flags & IORING_SETUP_SQE128)
3681 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3682 else
3683 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
eb065d30 3684 if (size == SIZE_MAX) {
9c189eee 3685 io_rings_free(ctx);
2b188cc1 3686 return -EOVERFLOW;
eb065d30 3687 }
2b188cc1 3688
03d89a2d
JA
3689 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3690 ptr = io_mem_alloc(size);
3691 else
3692 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3693
e27cef86 3694 if (IS_ERR(ptr)) {
9c189eee 3695 io_rings_free(ctx);
e27cef86 3696 return PTR_ERR(ptr);
eb065d30 3697 }
2b188cc1 3698
e27cef86 3699 ctx->sq_sqes = ptr;
2b188cc1
JA
3700 return 0;
3701}
3702
6e76ac59 3703static int io_uring_install_fd(struct file *file)
9faadcc8 3704{
6e76ac59 3705 int fd;
9faadcc8
PB
3706
3707 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3708 if (fd < 0)
3709 return fd;
9faadcc8
PB
3710 fd_install(fd, file);
3711 return fd;
3712}
3713
2b188cc1
JA
3714/*
3715 * Allocate an anonymous fd, this is what constitutes the application
3716 * visible backing of an io_uring instance. The application mmaps this
6e5e6d27 3717 * fd to gain access to the SQ/CQ ring details.
2b188cc1 3718 */
9faadcc8 3719static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
2b188cc1 3720{
4f0b9194 3721 /* Create a new inode so that the LSM can block the creation. */
09d1c6a8 3722 return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
91a9ab7c 3723 O_RDWR | O_CLOEXEC, NULL);
2b188cc1
JA
3724}
3725
c072481d
PB
3726static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3727 struct io_uring_params __user *params)
2b188cc1 3728{
2b188cc1 3729 struct io_ring_ctx *ctx;
6e76ac59 3730 struct io_uring_task *tctx;
9faadcc8 3731 struct file *file;
2b188cc1
JA
3732 int ret;
3733
8110c1a6 3734 if (!entries)
2b188cc1 3735 return -EINVAL;
8110c1a6
JA
3736 if (entries > IORING_MAX_ENTRIES) {
3737 if (!(p->flags & IORING_SETUP_CLAMP))
3738 return -EINVAL;
3739 entries = IORING_MAX_ENTRIES;
3740 }
2b188cc1 3741
6e76ac59
JT
3742 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3743 && !(p->flags & IORING_SETUP_NO_MMAP))
3744 return -EINVAL;
3745
2b188cc1
JA
3746 /*
3747 * Use twice as many entries for the CQ ring. It's possible for the
3748 * application to drive a higher depth than the size of the SQ ring,
3749 * since the sqes are only used at submission time. This allows for
33a107f0
JA
3750 * some flexibility in overcommitting a bit. If the application has
3751 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3752 * of CQ ring entries manually.
2b188cc1
JA
3753 */
3754 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
3755 if (p->flags & IORING_SETUP_CQSIZE) {
3756 /*
3757 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3758 * to a power-of-two, if it isn't already. We do NOT impose
3759 * any cq vs sq ring sizing.
3760 */
eb2667b3 3761 if (!p->cq_entries)
33a107f0 3762 return -EINVAL;
8110c1a6
JA
3763 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3764 if (!(p->flags & IORING_SETUP_CLAMP))
3765 return -EINVAL;
3766 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3767 }
eb2667b3
JQ
3768 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3769 if (p->cq_entries < p->sq_entries)
3770 return -EINVAL;
33a107f0
JA
3771 } else {
3772 p->cq_entries = 2 * p->sq_entries;
3773 }
2b188cc1 3774
2b188cc1 3775 ctx = io_ring_ctx_alloc(p);
62e398be 3776 if (!ctx)
2b188cc1 3777 return -ENOMEM;
773697b6 3778
e6aeb272
PB
3779 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3780 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3781 !(ctx->flags & IORING_SETUP_SQPOLL))
3782 ctx->task_complete = true;
3783
ec26c225
PB
3784 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3785 ctx->lockless_cq = true;
3786
bca39f39
PB
3787 /*
3788 * lazy poll_wq activation relies on ->task_complete for synchronisation
3789 * purposes, see io_activate_pollwq()
3790 */
3791 if (!ctx->task_complete)
3792 ctx->poll_activated = true;
3793
773697b6
PB
3794 /*
3795 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3796 * space applications don't need to do io completion events
3797 * polling again, they can rely on io_sq_thread to do polling
3798 * work, which can reduce cpu usage and uring_lock contention.
3799 */
3800 if (ctx->flags & IORING_SETUP_IOPOLL &&
3801 !(ctx->flags & IORING_SETUP_SQPOLL))
3802 ctx->syscall_iopoll = 1;
3803
2b188cc1 3804 ctx->compat = in_compat_syscall();
6adc2272 3805 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
62e398be 3806 ctx->user = get_uid(current_user());
2aede0e4 3807
9f010507 3808 /*
e1169f06
JA
3809 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3810 * COOP_TASKRUN is set, then IPIs are never needed by the app.
9f010507 3811 */
e1169f06
JA
3812 ret = -EINVAL;
3813 if (ctx->flags & IORING_SETUP_SQPOLL) {
3814 /* IPI related flags don't make sense with SQPOLL */
ef060ea9 3815 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
c0e0d6ba
DY
3816 IORING_SETUP_TASKRUN_FLAG |
3817 IORING_SETUP_DEFER_TASKRUN))
e1169f06 3818 goto err;
9f010507 3819 ctx->notify_method = TWA_SIGNAL_NO_IPI;
e1169f06
JA
3820 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3821 ctx->notify_method = TWA_SIGNAL_NO_IPI;
3822 } else {
c0e0d6ba
DY
3823 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
3824 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
ef060ea9 3825 goto err;
9f010507 3826 ctx->notify_method = TWA_SIGNAL;
e1169f06 3827 }
9f010507 3828
c0e0d6ba
DY
3829 /*
3830 * For DEFER_TASKRUN we require the completion task to be the same as the
3831 * submission task. This implies that there is only one submitter, so enforce
3832 * that.
3833 */
3834 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
3835 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
3836 goto err;
3837 }
3838
2aede0e4
JA
3839 /*
3840 * This is just grabbed for accounting purposes. When a process exits,
3841 * the mm is exited and dropped before the files, hence we need to hang
3842 * on to this mm purely for the purposes of being able to unaccount
3843 * memory (locked/pinned vm). It's not used for anything else.
3844 */
6b7898eb 3845 mmgrab(current->mm);
2aede0e4 3846 ctx->mm_account = current->mm;
6b7898eb 3847
2b188cc1
JA
3848 ret = io_allocate_scq_urings(ctx, p);
3849 if (ret)
3850 goto err;
3851
7e84e1c7 3852 ret = io_sq_offload_create(ctx, p);
2b188cc1
JA
3853 if (ret)
3854 goto err;
2933ae6e
PB
3855
3856 ret = io_rsrc_init(ctx);
47b228ce
PB
3857 if (ret)
3858 goto err;
2b188cc1 3859
75b28aff
HV
3860 p->sq_off.head = offsetof(struct io_rings, sq.head);
3861 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3862 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3863 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3864 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3865 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
2af89abd
PB
3866 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3867 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9b1b58ca 3868 p->sq_off.resv1 = 0;
03d89a2d
JA
3869 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3870 p->sq_off.user_addr = 0;
2b188cc1 3871
75b28aff
HV
3872 p->cq_off.head = offsetof(struct io_rings, cq.head);
3873 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3874 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3875 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3876 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3877 p->cq_off.cqes = offsetof(struct io_rings, cqes);
0d9b5b3a 3878 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9b1b58ca 3879 p->cq_off.resv1 = 0;
03d89a2d
JA
3880 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3881 p->cq_off.user_addr = 0;
ac90f249 3882
7f13657d
XW
3883 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3884 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
5769a351 3885 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
c73ebb68 3886 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9690557e 3887 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
c4212f3e 3888 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
7d3fd88d 3889 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING;
7f13657d
XW
3890
3891 if (copy_to_user(params, p, sizeof(*p))) {
3892 ret = -EFAULT;
3893 goto err;
3894 }
d1719f70 3895
7cae596b
DY
3896 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
3897 && !(ctx->flags & IORING_SETUP_R_DISABLED))
8579538c 3898 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
7cae596b 3899
9faadcc8
PB
3900 file = io_uring_get_file(ctx);
3901 if (IS_ERR(file)) {
3902 ret = PTR_ERR(file);
3903 goto err;
3904 }
3905
6e76ac59
JT
3906 ret = __io_uring_add_tctx_node(ctx);
3907 if (ret)
3908 goto err_fput;
3909 tctx = current->io_uring;
3910
044c1ab3
JA
3911 /*
3912 * Install ring fd as the very last thing, so we don't risk someone
3913 * having closed it before we finish setup
3914 */
6e76ac59
JT
3915 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3916 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
3917 else
3918 ret = io_uring_install_fd(file);
3919 if (ret < 0)
3920 goto err_fput;
044c1ab3 3921
c826bd7a 3922 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
3923 return ret;
3924err:
3925 io_ring_ctx_wait_and_kill(ctx);
3926 return ret;
6e76ac59
JT
3927err_fput:
3928 fput(file);
3929 return ret;
2b188cc1
JA
3930}
3931
3932/*
3933 * Sets up an aio uring context, and returns the fd. Applications asks for a
3934 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3935 * params structure passed in.
3936 */
3937static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3938{
3939 struct io_uring_params p;
2b188cc1
JA
3940 int i;
3941
3942 if (copy_from_user(&p, params, sizeof(p)))
3943 return -EFAULT;
3944 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3945 if (p.resv[i])
3946 return -EINVAL;
3947 }
3948
6c271ce2 3949 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8110c1a6 3950 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
7e84e1c7 3951 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
e1169f06 3952 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
ebdeb7c0 3953 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
97bbdc06 3954 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
03d89a2d 3955 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
2af89abd
PB
3956 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
3957 IORING_SETUP_NO_SQARRAY))
2b188cc1
JA
3958 return -EINVAL;
3959
ef060ea9 3960 return io_uring_create(entries, &p, params);
2b188cc1
JA
3961}
3962
76d3ccec
MR
3963static inline bool io_uring_allowed(void)
3964{
3965 int disabled = READ_ONCE(sysctl_io_uring_disabled);
3966 kgid_t io_uring_group;
3967
3968 if (disabled == 2)
3969 return false;
3970
3971 if (disabled == 0 || capable(CAP_SYS_ADMIN))
3972 return true;
3973
3974 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
3975 if (!gid_valid(io_uring_group))
3976 return false;
3977
3978 return in_group_p(io_uring_group);
3979}
3980
2b188cc1
JA
3981SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3982 struct io_uring_params __user *, params)
3983{
76d3ccec
MR
3984 if (!io_uring_allowed())
3985 return -EPERM;
3986
2b188cc1
JA
3987 return io_uring_setup(entries, params);
3988}
3989
3990static int __init io_uring_init(void)
3991{
9c71d39a 3992#define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
d7f62e82 3993 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9c71d39a 3994 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
d7f62e82
SM
3995} while (0)
3996
3997#define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9c71d39a
SM
3998 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
3999#define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
4000 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
d7f62e82
SM
4001 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
4002 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
4003 BUILD_BUG_SQE_ELEM(1, __u8, flags);
4004 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
4005 BUILD_BUG_SQE_ELEM(4, __s32, fd);
4006 BUILD_BUG_SQE_ELEM(8, __u64, off);
4007 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9c71d39a
SM
4008 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
4009 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
d7f62e82 4010 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7d67af2c 4011 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
d7f62e82
SM
4012 BUILD_BUG_SQE_ELEM(24, __u32, len);
4013 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
4014 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
4015 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
4016 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
5769a351
JX
4017 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
4018 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
d7f62e82
SM
4019 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
4020 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
4021 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
4022 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
4023 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
4024 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
4025 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
4026 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7d67af2c 4027 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9c71d39a
SM
4028 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
4029 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
4030 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
4031 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
4032 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
d7f62e82
SM
4033 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
4034 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
16340eab 4035 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
d7f62e82 4036 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7d67af2c 4037 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
b9445598 4038 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
b48c312b
PB
4039 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
4040 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
e9621e2b 4041 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
9c71d39a
SM
4042 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
4043 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
d7f62e82 4044
b0d658ec
PB
4045 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
4046 sizeof(struct io_uring_rsrc_update));
4047 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
4048 sizeof(struct io_uring_rsrc_update2));
90499ad0
PB
4049
4050 /* ->buf_index is u16 */
c7fb1942
JA
4051 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
4052 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
4053 offsetof(struct io_uring_buf_ring, tail));
90499ad0 4054
b0d658ec
PB
4055 /* should fit into one byte */
4056 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
68fe256a
PB
4057 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4058 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
b0d658ec 4059
4bcb982c 4060 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
16340eab 4061
3a4b89a2
JA
4062 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4063
528ce678
ML
4064 /* top 8bits are for internal use */
4065 BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
4066
d9b57aa3 4067 io_uring_optable_init();
0702e536 4068
b97f96e2
JA
4069 /*
4070 * Allow user copy in the per-command field, which starts after the
4071 * file in io_kiocb and until the opcode field. The openat2 handling
4072 * requires copying in user memory into the io_kiocb object in that
4073 * range, and HARDENED_USERCOPY will complain if we haven't
4074 * correctly annotated this range.
4075 */
4076 req_cachep = kmem_cache_create_usercopy("io_kiocb",
4077 sizeof(struct io_kiocb), 0,
4078 SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4079 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU,
4080 offsetof(struct io_kiocb, cmd.data),
4081 sizeof_field(struct io_kiocb, cmd.data), NULL);
a6e959bd
KC
4082 io_buf_cachep = KMEM_CACHE(io_buffer,
4083 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT);
b97f96e2 4084
73eaa2b5
JA
4085 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
4086
76d3ccec
MR
4087#ifdef CONFIG_SYSCTL
4088 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
4089#endif
4090
2b188cc1
JA
4091 return 0;
4092};
4093__initcall(io_uring_init);