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