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