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