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