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