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