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