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