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