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