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