xref: /linux/io_uring/io_uring.c (revision 23acda7c221a76ff711d65f4ca90029d43b249a0)
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
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
14  * through a control-dependency in io_get_cqe (smp_store_release to
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.
29  *
30  * Also see the examples in the liburing library:
31  *
32  *	git://git.kernel.org/pub/scm/linux/kernel/git/axboe/liburing.git
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
40  * Copyright (c) 2018-2019 Christoph Hellwig
41  */
42 #include <linux/kernel.h>
43 #include <linux/errno.h>
44 #include <linux/syscalls.h>
45 #include <linux/refcount.h>
46 #include <linux/bits.h>
47 
48 #include <linux/sched/signal.h>
49 #include <linux/fs.h>
50 #include <linux/mm.h>
51 #include <linux/percpu.h>
52 #include <linux/slab.h>
53 #include <linux/anon_inodes.h>
54 #include <linux/uaccess.h>
55 #include <linux/nospec.h>
56 #include <linux/task_work.h>
57 #include <linux/io_uring.h>
58 #include <linux/io_uring/cmd.h>
59 #include <linux/audit.h>
60 #include <linux/security.h>
61 #include <linux/jump_label.h>
62 
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/io_uring.h>
65 
66 #include <uapi/linux/io_uring.h>
67 
68 #include "io-wq.h"
69 
70 #include "filetable.h"
71 #include "io_uring.h"
72 #include "opdef.h"
73 #include "refs.h"
74 #include "tctx.h"
75 #include "register.h"
76 #include "sqpoll.h"
77 #include "fdinfo.h"
78 #include "kbuf.h"
79 #include "rsrc.h"
80 #include "cancel.h"
81 #include "net.h"
82 #include "notif.h"
83 #include "waitid.h"
84 #include "futex.h"
85 #include "napi.h"
86 #include "uring_cmd.h"
87 #include "msg_ring.h"
88 #include "memmap.h"
89 #include "zcrx.h"
90 #include "bpf-ops.h"
91 
92 #include "timeout.h"
93 #include "poll.h"
94 #include "rw.h"
95 #include "alloc_cache.h"
96 #include "eventfd.h"
97 #include "wait.h"
98 #include "bpf_filter.h"
99 #include "loop.h"
100 
101 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
102 			  IOSQE_IO_HARDLINK | IOSQE_ASYNC)
103 
104 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
105 
106 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
107 				REQ_F_INFLIGHT | REQ_F_CREDS | REQ_F_ASYNC_DATA)
108 
109 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | IO_REQ_LINK_FLAGS | \
110 				 REQ_F_REISSUE | REQ_F_POLLED | \
111 				 IO_REQ_CLEAN_FLAGS)
112 
113 #define IO_TCTX_REFS_CACHE_NR	(1U << 10)
114 
115 #define IO_COMPL_BATCH			32
116 #define IO_REQ_ALLOC_BATCH		8
117 
118 /* requests with any of those set should undergo io_disarm_next() */
119 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
120 
121 static void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags);
122 static void __io_req_caches_free(struct io_ring_ctx *ctx);
123 
124 static __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(io_key_has_sqarray, HZ);
125 
126 struct kmem_cache *req_cachep;
127 static struct workqueue_struct *iou_wq __ro_after_init;
128 
129 static int __read_mostly sysctl_io_uring_disabled;
130 static int __read_mostly sysctl_io_uring_group = -1;
131 
132 #ifdef CONFIG_SYSCTL
133 static const struct ctl_table kernel_io_uring_disabled_table[] = {
134 	{
135 		.procname	= "io_uring_disabled",
136 		.data		= &sysctl_io_uring_disabled,
137 		.maxlen		= sizeof(sysctl_io_uring_disabled),
138 		.mode		= 0644,
139 		.proc_handler	= proc_dointvec_minmax,
140 		.extra1		= SYSCTL_ZERO,
141 		.extra2		= SYSCTL_TWO,
142 	},
143 	{
144 		.procname	= "io_uring_group",
145 		.data		= &sysctl_io_uring_group,
146 		.maxlen		= sizeof(gid_t),
147 		.mode		= 0644,
148 		.proc_handler	= proc_dointvec,
149 	},
150 };
151 #endif
152 
153 static void io_poison_cached_req(struct io_kiocb *req)
154 {
155 	req->ctx = IO_URING_PTR_POISON;
156 	req->tctx = IO_URING_PTR_POISON;
157 	req->file = IO_URING_PTR_POISON;
158 	req->creds = IO_URING_PTR_POISON;
159 	req->io_task_work.func = IO_URING_PTR_POISON;
160 	req->apoll = IO_URING_PTR_POISON;
161 }
162 
163 static void io_poison_req(struct io_kiocb *req)
164 {
165 	io_poison_cached_req(req);
166 	req->async_data = IO_URING_PTR_POISON;
167 	req->kbuf = IO_URING_PTR_POISON;
168 	req->comp_list.next = IO_URING_PTR_POISON;
169 	req->file_node = IO_URING_PTR_POISON;
170 	req->link = IO_URING_PTR_POISON;
171 }
172 
173 static inline void req_fail_link_node(struct io_kiocb *req, int res)
174 {
175 	req_set_fail(req);
176 	io_req_set_res(req, res, 0);
177 }
178 
179 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
180 {
181 	if (IS_ENABLED(CONFIG_KASAN))
182 		io_poison_cached_req(req);
183 	wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
184 }
185 
186 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
187 {
188 	struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
189 
190 	complete(&ctx->ref_comp);
191 }
192 
193 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
194 {
195 	unsigned int hash_buckets;
196 	int i;
197 
198 	do {
199 		hash_buckets = 1U << bits;
200 		table->hbs = kvmalloc_objs(table->hbs[0], hash_buckets,
201 					   GFP_KERNEL_ACCOUNT);
202 		if (table->hbs)
203 			break;
204 		if (bits == 1)
205 			return -ENOMEM;
206 		bits--;
207 	} while (1);
208 
209 	table->hash_bits = bits;
210 	for (i = 0; i < hash_buckets; i++)
211 		INIT_HLIST_HEAD(&table->hbs[i].list);
212 	return 0;
213 }
214 
215 static void io_free_alloc_caches(struct io_ring_ctx *ctx)
216 {
217 	io_alloc_cache_free(&ctx->apoll_cache, kfree);
218 	io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
219 	io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
220 	io_alloc_cache_free(&ctx->cmd_cache, io_cmd_cache_free);
221 	io_futex_cache_free(ctx);
222 	io_rsrc_cache_free(ctx);
223 }
224 
225 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
226 {
227 	struct io_ring_ctx *ctx;
228 	int hash_bits;
229 	bool ret;
230 
231 	ctx = kzalloc_obj(*ctx);
232 	if (!ctx)
233 		return NULL;
234 
235 	xa_init(&ctx->io_bl_xa);
236 
237 	/*
238 	 * Use 5 bits less than the max cq entries, that should give us around
239 	 * 32 entries per hash list if totally full and uniformly spread, but
240 	 * don't keep too many buckets to not overconsume memory.
241 	 */
242 	hash_bits = ilog2(p->cq_entries) - 5;
243 	hash_bits = clamp(hash_bits, 1, 8);
244 	if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
245 		goto err;
246 	if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
247 			    0, GFP_KERNEL))
248 		goto err;
249 
250 	ctx->flags = p->flags;
251 	ctx->hybrid_poll_time = LLONG_MAX;
252 	atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
253 	init_waitqueue_head(&ctx->sqo_sq_wait);
254 	INIT_LIST_HEAD(&ctx->sqd_list);
255 	INIT_LIST_HEAD(&ctx->cq_overflow_list);
256 	ret = io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX,
257 			    sizeof(struct async_poll), 0);
258 	ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
259 			    sizeof(struct io_async_msghdr),
260 			    offsetof(struct io_async_msghdr, clear));
261 	ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX,
262 			    sizeof(struct io_async_rw),
263 			    offsetof(struct io_async_rw, clear));
264 	ret |= io_alloc_cache_init(&ctx->cmd_cache, IO_ALLOC_CACHE_MAX,
265 			    sizeof(struct io_async_cmd),
266 			    sizeof(struct io_async_cmd));
267 	ret |= io_futex_cache_init(ctx);
268 	ret |= io_rsrc_cache_init(ctx);
269 	if (ret)
270 		goto free_ref;
271 	init_completion(&ctx->ref_comp);
272 	xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
273 	mutex_init(&ctx->uring_lock);
274 	init_waitqueue_head(&ctx->cq_wait);
275 	init_waitqueue_head(&ctx->poll_wq);
276 	spin_lock_init(&ctx->completion_lock);
277 	raw_spin_lock_init(&ctx->timeout_lock);
278 	INIT_LIST_HEAD(&ctx->iopoll_list);
279 	INIT_LIST_HEAD(&ctx->defer_list);
280 	INIT_LIST_HEAD(&ctx->timeout_list);
281 	INIT_LIST_HEAD(&ctx->ltimeout_list);
282 	init_llist_head(&ctx->work_llist);
283 	INIT_LIST_HEAD(&ctx->tctx_list);
284 	mutex_init(&ctx->tctx_lock);
285 	ctx->submit_state.free_list.next = NULL;
286 	INIT_HLIST_HEAD(&ctx->waitid_list);
287 	xa_init_flags(&ctx->zcrx_ctxs, XA_FLAGS_ALLOC);
288 #ifdef CONFIG_FUTEX
289 	INIT_HLIST_HEAD(&ctx->futex_list);
290 #endif
291 	INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
292 	INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
293 	INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
294 	io_napi_init(ctx);
295 	mutex_init(&ctx->mmap_lock);
296 
297 	return ctx;
298 
299 free_ref:
300 	percpu_ref_exit(&ctx->refs);
301 err:
302 	io_free_alloc_caches(ctx);
303 	kvfree(ctx->cancel_table.hbs);
304 	xa_destroy(&ctx->io_bl_xa);
305 	kfree(ctx);
306 	return NULL;
307 }
308 
309 static void io_clean_op(struct io_kiocb *req)
310 {
311 	if (unlikely(req->flags & REQ_F_BUFFER_SELECTED))
312 		io_kbuf_drop_legacy(req);
313 
314 	if (req->flags & REQ_F_NEED_CLEANUP) {
315 		const struct io_cold_def *def = &io_cold_defs[req->opcode];
316 
317 		if (def->cleanup)
318 			def->cleanup(req);
319 	}
320 	if (req->flags & REQ_F_INFLIGHT)
321 		atomic_dec(&req->tctx->inflight_tracked);
322 	if (req->flags & REQ_F_CREDS)
323 		put_cred(req->creds);
324 	if (req->flags & REQ_F_ASYNC_DATA) {
325 		kfree(req->async_data);
326 		req->async_data = NULL;
327 	}
328 	req->flags &= ~IO_REQ_CLEAN_FLAGS;
329 }
330 
331 /*
332  * Mark the request as inflight, so that file cancelation will find it.
333  * Can be used if the file is an io_uring instance, or if the request itself
334  * relies on ->mm being alive for the duration of the request.
335  */
336 inline void io_req_track_inflight(struct io_kiocb *req)
337 {
338 	if (!(req->flags & REQ_F_INFLIGHT)) {
339 		req->flags |= REQ_F_INFLIGHT;
340 		atomic_inc(&req->tctx->inflight_tracked);
341 	}
342 }
343 
344 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
345 {
346 	if (WARN_ON_ONCE(!req->link))
347 		return NULL;
348 
349 	req->flags &= ~REQ_F_ARM_LTIMEOUT;
350 	req->flags |= REQ_F_LINK_TIMEOUT;
351 
352 	/* linked timeouts should have two refs once prep'ed */
353 	io_req_set_refcount(req);
354 	__io_req_set_refcount(req->link, 2);
355 	return req->link;
356 }
357 
358 static void io_prep_async_work(struct io_kiocb *req)
359 {
360 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
361 
362 	if (!(req->flags & REQ_F_CREDS)) {
363 		req->flags |= REQ_F_CREDS;
364 		req->creds = get_current_cred();
365 	}
366 
367 	req->work.list.next = NULL;
368 	atomic_set(&req->work.flags, 0);
369 	if (req->flags & REQ_F_FORCE_ASYNC)
370 		atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
371 
372 	if (req->file && !(req->flags & REQ_F_FIXED_FILE))
373 		req->flags |= io_file_get_flags(req->file);
374 
375 	if (req->file && (req->flags & REQ_F_ISREG)) {
376 		bool should_hash = def->hash_reg_file;
377 
378 		/* don't serialize this request if the fs doesn't need it */
379 		if (should_hash && (req->file->f_flags & O_DIRECT) &&
380 		    (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
381 			should_hash = false;
382 		if (should_hash || (req->flags & REQ_F_IOPOLL))
383 			io_wq_hash_work(&req->work, file_inode(req->file));
384 	} else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
385 		if (def->unbound_nonreg_file)
386 			atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
387 	}
388 }
389 
390 static void io_prep_async_link(struct io_kiocb *req)
391 {
392 	struct io_kiocb *cur;
393 
394 	if (req->flags & REQ_F_LINK_TIMEOUT) {
395 		struct io_ring_ctx *ctx = req->ctx;
396 
397 		raw_spin_lock_irq(&ctx->timeout_lock);
398 		io_for_each_link(cur, req)
399 			io_prep_async_work(cur);
400 		raw_spin_unlock_irq(&ctx->timeout_lock);
401 	} else {
402 		io_for_each_link(cur, req)
403 			io_prep_async_work(cur);
404 	}
405 }
406 
407 static void io_queue_iowq(struct io_kiocb *req)
408 {
409 	struct io_uring_task *tctx = req->tctx;
410 
411 	BUG_ON(!tctx);
412 
413 	if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
414 		io_req_task_queue_fail(req, -ECANCELED);
415 		return;
416 	}
417 
418 	/* init ->work of the whole link before punting */
419 	io_prep_async_link(req);
420 
421 	/*
422 	 * Not expected to happen, but if we do have a bug where this _can_
423 	 * happen, catch it here and ensure the request is marked as
424 	 * canceled. That will make io-wq go through the usual work cancel
425 	 * procedure rather than attempt to run this request (or create a new
426 	 * worker for it).
427 	 */
428 	if (WARN_ON_ONCE(!same_thread_group(tctx->task, current)))
429 		atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
430 
431 	trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
432 	io_wq_enqueue(tctx->io_wq, &req->work);
433 }
434 
435 static void io_req_queue_iowq_tw(struct io_tw_req tw_req, io_tw_token_t tw)
436 {
437 	io_queue_iowq(tw_req.req);
438 }
439 
440 void io_req_queue_iowq(struct io_kiocb *req)
441 {
442 	req->io_task_work.func = io_req_queue_iowq_tw;
443 	io_req_task_work_add(req);
444 }
445 
446 unsigned io_linked_nr(struct io_kiocb *req)
447 {
448 	struct io_kiocb *tmp;
449 	unsigned nr = 0;
450 
451 	io_for_each_link(tmp, req)
452 		nr++;
453 	return nr;
454 }
455 
456 static __cold noinline void io_queue_deferred(struct io_ring_ctx *ctx)
457 {
458 	bool drain_seen = false, first = true;
459 
460 	lockdep_assert_held(&ctx->uring_lock);
461 	__io_req_caches_free(ctx);
462 
463 	while (!list_empty(&ctx->defer_list)) {
464 		struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
465 						struct io_defer_entry, list);
466 
467 		drain_seen |= de->req->flags & REQ_F_IO_DRAIN;
468 		if ((drain_seen || first) && ctx->nr_req_allocated != ctx->nr_drained)
469 			return;
470 
471 		list_del_init(&de->list);
472 		ctx->nr_drained -= io_linked_nr(de->req);
473 		io_req_task_queue(de->req);
474 		kfree(de);
475 		first = false;
476 	}
477 }
478 
479 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
480 {
481 	if (ctx->int_flags & IO_RING_F_POLL_ACTIVATED)
482 		io_poll_wq_wake(ctx);
483 	if (ctx->int_flags & IO_RING_F_OFF_TIMEOUT_USED)
484 		io_flush_timeouts(ctx);
485 	if (ctx->int_flags & IO_RING_F_HAS_EVFD)
486 		io_eventfd_signal(ctx, true);
487 }
488 
489 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
490 {
491 	if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ))
492 		spin_lock(&ctx->completion_lock);
493 }
494 
495 static inline void io_cq_lock(struct io_ring_ctx *ctx)
496 	__acquires(ctx->completion_lock)
497 {
498 	spin_lock(&ctx->completion_lock);
499 }
500 
501 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
502 {
503 	io_commit_cqring(ctx);
504 	if (!(ctx->int_flags & IO_RING_F_TASK_COMPLETE)) {
505 		if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ))
506 			spin_unlock(&ctx->completion_lock);
507 		/* IOPOLL rings only need to wake up if it's also SQPOLL */
508 		if (!(ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL))
509 			io_cqring_wake(ctx);
510 	}
511 	io_commit_cqring_flush(ctx);
512 }
513 
514 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
515 	__releases(ctx->completion_lock)
516 {
517 	io_commit_cqring(ctx);
518 	spin_unlock(&ctx->completion_lock);
519 	io_cqring_wake(ctx);
520 	io_commit_cqring_flush(ctx);
521 }
522 
523 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
524 {
525 	lockdep_assert_held(&ctx->uring_lock);
526 
527 	/* don't abort if we're dying, entries must get freed */
528 	if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
529 		return;
530 
531 	io_cq_lock(ctx);
532 	while (!list_empty(&ctx->cq_overflow_list)) {
533 		size_t cqe_size = sizeof(struct io_uring_cqe);
534 		struct io_uring_cqe *cqe;
535 		struct io_overflow_cqe *ocqe;
536 		bool is_cqe32 = false;
537 
538 		ocqe = list_first_entry(&ctx->cq_overflow_list,
539 					struct io_overflow_cqe, list);
540 		if (ocqe->cqe.flags & IORING_CQE_F_32 ||
541 		    ctx->flags & IORING_SETUP_CQE32) {
542 			is_cqe32 = true;
543 			cqe_size <<= 1;
544 		}
545 		if (ctx->flags & IORING_SETUP_CQE32)
546 			is_cqe32 = false;
547 
548 		if (!dying) {
549 			if (!io_get_cqe_overflow(ctx, &cqe, true, is_cqe32))
550 				break;
551 			memcpy(cqe, &ocqe->cqe, cqe_size);
552 		}
553 		list_del(&ocqe->list);
554 		kfree(ocqe);
555 
556 		/*
557 		 * For silly syzbot cases that deliberately overflow by huge
558 		 * amounts, check if we need to resched and drop and
559 		 * reacquire the locks if so. Nothing real would ever hit this.
560 		 * Ideally we'd have a non-posting unlock for this, but hard
561 		 * to care for a non-real case.
562 		 */
563 		if (need_resched()) {
564 			ctx->cqe_sentinel = ctx->cqe_cached;
565 			io_cq_unlock_post(ctx);
566 			mutex_unlock(&ctx->uring_lock);
567 			cond_resched();
568 			mutex_lock(&ctx->uring_lock);
569 			io_cq_lock(ctx);
570 		}
571 	}
572 
573 	if (list_empty(&ctx->cq_overflow_list)) {
574 		clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
575 		atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
576 	}
577 	io_cq_unlock_post(ctx);
578 }
579 
580 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
581 {
582 	if (ctx->rings)
583 		__io_cqring_overflow_flush(ctx, true);
584 }
585 
586 void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
587 {
588 	mutex_lock(&ctx->uring_lock);
589 	__io_cqring_overflow_flush(ctx, false);
590 	mutex_unlock(&ctx->uring_lock);
591 }
592 
593 void io_cqring_overflow_flush_locked(struct io_ring_ctx *ctx)
594 {
595 	__io_cqring_overflow_flush(ctx, false);
596 }
597 
598 /* must to be called somewhat shortly after putting a request */
599 static inline void io_put_task(struct io_kiocb *req)
600 {
601 	struct io_uring_task *tctx = req->tctx;
602 
603 	if (likely(tctx->task == current)) {
604 		tctx->cached_refs++;
605 	} else {
606 		percpu_counter_sub(&tctx->inflight, 1);
607 		if (unlikely(atomic_read(&tctx->in_cancel)))
608 			wake_up(&tctx->wait);
609 		put_task_struct(tctx->task);
610 	}
611 }
612 
613 void io_task_refs_refill(struct io_uring_task *tctx)
614 {
615 	unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
616 
617 	percpu_counter_add(&tctx->inflight, refill);
618 	refcount_add(refill, &current->usage);
619 	tctx->cached_refs += refill;
620 }
621 
622 __cold void io_uring_drop_tctx_refs(struct task_struct *task)
623 {
624 	struct io_uring_task *tctx = task->io_uring;
625 	unsigned int refs = tctx->cached_refs;
626 
627 	if (refs) {
628 		tctx->cached_refs = 0;
629 		percpu_counter_sub(&tctx->inflight, refs);
630 		put_task_struct_many(task, refs);
631 	}
632 }
633 
634 static __cold bool io_cqring_add_overflow(struct io_ring_ctx *ctx,
635 					  struct io_overflow_cqe *ocqe)
636 {
637 	lockdep_assert_held(&ctx->completion_lock);
638 
639 	if (!ocqe) {
640 		struct io_rings *r = ctx->rings;
641 
642 		/*
643 		 * If we're in ring overflow flush mode, or in task cancel mode,
644 		 * or cannot allocate an overflow entry, then we need to drop it
645 		 * on the floor.
646 		 */
647 		WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
648 		set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
649 		return false;
650 	}
651 	if (list_empty(&ctx->cq_overflow_list)) {
652 		set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
653 		atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
654 
655 	}
656 	list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
657 	return true;
658 }
659 
660 static struct io_overflow_cqe *io_alloc_ocqe(struct io_ring_ctx *ctx,
661 					     struct io_cqe *cqe,
662 					     struct io_big_cqe *big_cqe, gfp_t gfp)
663 {
664 	struct io_overflow_cqe *ocqe;
665 	size_t ocq_size = sizeof(struct io_overflow_cqe);
666 	bool is_cqe32 = false;
667 
668 	if (cqe->flags & IORING_CQE_F_32 || ctx->flags & IORING_SETUP_CQE32) {
669 		is_cqe32 = true;
670 		ocq_size += sizeof(struct io_uring_cqe);
671 	}
672 
673 	ocqe = kzalloc(ocq_size, gfp | __GFP_ACCOUNT);
674 	trace_io_uring_cqe_overflow(ctx, cqe->user_data, cqe->res, cqe->flags, ocqe);
675 	if (ocqe) {
676 		ocqe->cqe.user_data = cqe->user_data;
677 		ocqe->cqe.res = cqe->res;
678 		ocqe->cqe.flags = cqe->flags;
679 		if (is_cqe32 && big_cqe) {
680 			ocqe->cqe.big_cqe[0] = big_cqe->extra1;
681 			ocqe->cqe.big_cqe[1] = big_cqe->extra2;
682 		}
683 	}
684 	if (big_cqe)
685 		big_cqe->extra1 = big_cqe->extra2 = 0;
686 	return ocqe;
687 }
688 
689 /*
690  * Fill an empty dummy CQE, in case alignment is off for posting a 32b CQE
691  * because the ring is a single 16b entry away from wrapping.
692  */
693 static bool io_fill_nop_cqe(struct io_ring_ctx *ctx, unsigned int off)
694 {
695 	if (__io_cqring_events(ctx) < ctx->cq_entries) {
696 		struct io_uring_cqe *cqe = &ctx->rings->cqes[off];
697 
698 		cqe->user_data = 0;
699 		cqe->res = 0;
700 		cqe->flags = IORING_CQE_F_SKIP;
701 		ctx->cached_cq_tail++;
702 		return true;
703 	}
704 	return false;
705 }
706 
707 /*
708  * writes to the cq entry need to come after reading head; the
709  * control dependency is enough as we're using WRITE_ONCE to
710  * fill the cq entry
711  */
712 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow, bool cqe32)
713 {
714 	struct io_rings *rings = ctx->rings;
715 	unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
716 	unsigned int free, queued, len;
717 
718 	/*
719 	 * Posting into the CQ when there are pending overflowed CQEs may break
720 	 * ordering guarantees, which will affect links, F_MORE users and more.
721 	 * Force overflow the completion.
722 	 */
723 	if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
724 		return false;
725 
726 	/*
727 	 * Post dummy CQE if a 32b CQE is needed and there's only room for a
728 	 * 16b CQE before the ring wraps.
729 	 */
730 	if (cqe32 && off + 1 == ctx->cq_entries) {
731 		if (!io_fill_nop_cqe(ctx, off))
732 			return false;
733 		off = 0;
734 	}
735 
736 	/* userspace may cheat modifying the tail, be safe and do min */
737 	queued = min(__io_cqring_events(ctx), ctx->cq_entries);
738 	free = ctx->cq_entries - queued;
739 	/* we need a contiguous range, limit based on the current array offset */
740 	len = min(free, ctx->cq_entries - off);
741 	if (len < (cqe32 + 1))
742 		return false;
743 
744 	if (ctx->flags & IORING_SETUP_CQE32) {
745 		off <<= 1;
746 		len <<= 1;
747 	}
748 
749 	ctx->cqe_cached = &rings->cqes[off];
750 	ctx->cqe_sentinel = ctx->cqe_cached + len;
751 	return true;
752 }
753 
754 static bool io_fill_cqe_aux32(struct io_ring_ctx *ctx,
755 			      struct io_uring_cqe src_cqe[2])
756 {
757 	struct io_uring_cqe *cqe;
758 
759 	if (WARN_ON_ONCE(!(ctx->flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED))))
760 		return false;
761 	if (unlikely(!io_get_cqe(ctx, &cqe, true)))
762 		return false;
763 
764 	memcpy(cqe, src_cqe, 2 * sizeof(*cqe));
765 	trace_io_uring_complete(ctx, NULL, cqe);
766 	return true;
767 }
768 
769 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
770 			      u32 cflags)
771 {
772 	bool cqe32 = cflags & IORING_CQE_F_32;
773 	struct io_uring_cqe *cqe;
774 
775 	if (likely(io_get_cqe(ctx, &cqe, cqe32))) {
776 		WRITE_ONCE(cqe->user_data, user_data);
777 		WRITE_ONCE(cqe->res, res);
778 		WRITE_ONCE(cqe->flags, cflags);
779 
780 		if (cqe32) {
781 			WRITE_ONCE(cqe->big_cqe[0], 0);
782 			WRITE_ONCE(cqe->big_cqe[1], 0);
783 		}
784 
785 		trace_io_uring_complete(ctx, NULL, cqe);
786 		return true;
787 	}
788 	return false;
789 }
790 
791 static inline struct io_cqe io_init_cqe(u64 user_data, s32 res, u32 cflags)
792 {
793 	return (struct io_cqe) { .user_data = user_data, .res = res, .flags = cflags };
794 }
795 
796 static __cold void io_cqe_overflow(struct io_ring_ctx *ctx, struct io_cqe *cqe,
797 				   struct io_big_cqe *big_cqe)
798 {
799 	struct io_overflow_cqe *ocqe;
800 
801 	ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_KERNEL);
802 	spin_lock(&ctx->completion_lock);
803 	io_cqring_add_overflow(ctx, ocqe);
804 	spin_unlock(&ctx->completion_lock);
805 }
806 
807 static __cold bool io_cqe_overflow_locked(struct io_ring_ctx *ctx,
808 					  struct io_cqe *cqe,
809 					  struct io_big_cqe *big_cqe)
810 {
811 	struct io_overflow_cqe *ocqe;
812 
813 	ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_NOWAIT);
814 	return io_cqring_add_overflow(ctx, ocqe);
815 }
816 
817 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
818 {
819 	bool filled;
820 
821 	io_cq_lock(ctx);
822 	filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
823 	if (unlikely(!filled)) {
824 		struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
825 
826 		filled = io_cqe_overflow_locked(ctx, &cqe, NULL);
827 	}
828 	io_cq_unlock_post(ctx);
829 	return filled;
830 }
831 
832 /*
833  * Must be called from inline task_work so we know a flush will happen later,
834  * and obviously with ctx->uring_lock held (tw always has that).
835  */
836 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
837 {
838 	lockdep_assert_held(&ctx->uring_lock);
839 	lockdep_assert(ctx->int_flags & IO_RING_F_LOCKLESS_CQ);
840 
841 	if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
842 		struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
843 
844 		io_cqe_overflow(ctx, &cqe, NULL);
845 	}
846 	ctx->submit_state.cq_flush = true;
847 }
848 
849 /*
850  * A helper for multishot requests posting additional CQEs.
851  * Should only be used from a task_work including IO_URING_F_MULTISHOT.
852  */
853 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
854 {
855 	struct io_ring_ctx *ctx = req->ctx;
856 	bool posted;
857 
858 	/*
859 	 * If multishot has already posted deferred completions, ensure that
860 	 * those are flushed first before posting this one. If not, CQEs
861 	 * could get reordered.
862 	 */
863 	if (!wq_list_empty(&ctx->submit_state.compl_reqs))
864 		__io_submit_flush_completions(ctx);
865 
866 	lockdep_assert(!io_wq_current_is_worker());
867 	lockdep_assert_held(&ctx->uring_lock);
868 
869 	if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) {
870 		spin_lock(&ctx->completion_lock);
871 		posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
872 		spin_unlock(&ctx->completion_lock);
873 	} else {
874 		posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
875 	}
876 
877 	ctx->submit_state.cq_flush = true;
878 	return posted;
879 }
880 
881 /*
882  * A helper for multishot requests posting additional CQEs.
883  * Should only be used from a task_work including IO_URING_F_MULTISHOT.
884  */
885 bool io_req_post_cqe32(struct io_kiocb *req, struct io_uring_cqe cqe[2])
886 {
887 	struct io_ring_ctx *ctx = req->ctx;
888 	bool posted;
889 
890 	lockdep_assert(!io_wq_current_is_worker());
891 	lockdep_assert_held(&ctx->uring_lock);
892 
893 	cqe[0].user_data = req->cqe.user_data;
894 	if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) {
895 		spin_lock(&ctx->completion_lock);
896 		posted = io_fill_cqe_aux32(ctx, cqe);
897 		spin_unlock(&ctx->completion_lock);
898 	} else {
899 		posted = io_fill_cqe_aux32(ctx, cqe);
900 	}
901 
902 	ctx->submit_state.cq_flush = true;
903 	return posted;
904 }
905 
906 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
907 {
908 	struct io_ring_ctx *ctx = req->ctx;
909 	bool completed = true;
910 
911 	/*
912 	 * All execution paths but io-wq use the deferred completions by
913 	 * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
914 	 */
915 	if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
916 		return;
917 
918 	/*
919 	 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
920 	 * the submitter task context, IOPOLL protects with uring_lock.
921 	 */
922 	if ((ctx->int_flags & IO_RING_F_LOCKLESS_CQ) || (req->flags & REQ_F_REISSUE)) {
923 defer_complete:
924 		req->io_task_work.func = io_req_task_complete;
925 		io_req_task_work_add(req);
926 		return;
927 	}
928 
929 	io_cq_lock(ctx);
930 	if (!(req->flags & REQ_F_CQE_SKIP))
931 		completed = io_fill_cqe_req(ctx, req);
932 	io_cq_unlock_post(ctx);
933 
934 	if (!completed)
935 		goto defer_complete;
936 
937 	/*
938 	 * We don't free the request here because we know it's called from
939 	 * io-wq only, which holds a reference, so it cannot be the last put.
940 	 */
941 	req_ref_put(req);
942 }
943 
944 void io_req_defer_failed(struct io_kiocb *req, s32 res)
945 	__must_hold(&ctx->uring_lock)
946 {
947 	const struct io_cold_def *def = &io_cold_defs[req->opcode];
948 
949 	lockdep_assert_held(&req->ctx->uring_lock);
950 
951 	req_set_fail(req);
952 	io_req_set_res(req, res, io_put_kbuf(req, res, NULL));
953 	if (def->fail)
954 		def->fail(req);
955 	io_req_complete_defer(req);
956 }
957 
958 /*
959  * A request might get retired back into the request caches even before opcode
960  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
961  * Because of that, io_alloc_req() should be called only under ->uring_lock
962  * and with extra caution to not get a request that is still worked on.
963  */
964 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
965 	__must_hold(&ctx->uring_lock)
966 {
967 	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO;
968 	void *reqs[IO_REQ_ALLOC_BATCH];
969 	int ret;
970 
971 	ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
972 
973 	/*
974 	 * Bulk alloc is all-or-nothing. If we fail to get a batch,
975 	 * retry single alloc to be on the safe side.
976 	 */
977 	if (unlikely(ret <= 0)) {
978 		reqs[0] = kmem_cache_alloc(req_cachep, gfp);
979 		if (!reqs[0])
980 			return false;
981 		ret = 1;
982 	}
983 
984 	percpu_ref_get_many(&ctx->refs, ret);
985 	ctx->nr_req_allocated += ret;
986 
987 	while (ret--) {
988 		struct io_kiocb *req = reqs[ret];
989 
990 		io_req_add_to_cache(req, ctx);
991 	}
992 	return true;
993 }
994 
995 __cold void io_free_req(struct io_kiocb *req)
996 {
997 	/* refs were already put, restore them for io_req_task_complete() */
998 	req->flags &= ~REQ_F_REFCOUNT;
999 	/* we only want to free it, don't post CQEs */
1000 	req->flags |= REQ_F_CQE_SKIP;
1001 	req->io_task_work.func = io_req_task_complete;
1002 	io_req_task_work_add(req);
1003 }
1004 
1005 static void __io_req_find_next_prep(struct io_kiocb *req)
1006 {
1007 	struct io_ring_ctx *ctx = req->ctx;
1008 
1009 	spin_lock(&ctx->completion_lock);
1010 	io_disarm_next(req);
1011 	spin_unlock(&ctx->completion_lock);
1012 }
1013 
1014 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1015 {
1016 	struct io_kiocb *nxt;
1017 
1018 	/*
1019 	 * If LINK is set, we have dependent requests in this chain. If we
1020 	 * didn't fail this request, queue the first one up, moving any other
1021 	 * dependencies to the next request. In case of failure, fail the rest
1022 	 * of the chain.
1023 	 */
1024 	if (unlikely(req->flags & IO_DISARM_MASK))
1025 		__io_req_find_next_prep(req);
1026 	nxt = req->link;
1027 	req->link = NULL;
1028 	return nxt;
1029 }
1030 
1031 static void io_req_task_cancel(struct io_tw_req tw_req, io_tw_token_t tw)
1032 {
1033 	struct io_kiocb *req = tw_req.req;
1034 
1035 	io_tw_lock(req->ctx, tw);
1036 	io_req_defer_failed(req, req->cqe.res);
1037 }
1038 
1039 void io_req_task_submit(struct io_tw_req tw_req, io_tw_token_t tw)
1040 {
1041 	struct io_kiocb *req = tw_req.req;
1042 	struct io_ring_ctx *ctx = req->ctx;
1043 
1044 	io_tw_lock(ctx, tw);
1045 	if (unlikely(tw.cancel))
1046 		io_req_defer_failed(req, -EFAULT);
1047 	else if (req->flags & REQ_F_FORCE_ASYNC)
1048 		io_queue_iowq(req);
1049 	else
1050 		io_queue_sqe(req, 0);
1051 }
1052 
1053 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1054 {
1055 	io_req_set_res(req, ret, 0);
1056 	req->io_task_work.func = io_req_task_cancel;
1057 	io_req_task_work_add(req);
1058 }
1059 
1060 void io_req_task_queue(struct io_kiocb *req)
1061 {
1062 	req->io_task_work.func = io_req_task_submit;
1063 	io_req_task_work_add(req);
1064 }
1065 
1066 void io_queue_next(struct io_kiocb *req)
1067 {
1068 	struct io_kiocb *nxt = io_req_find_next(req);
1069 
1070 	if (nxt)
1071 		io_req_task_queue(nxt);
1072 }
1073 
1074 static inline void io_req_put_rsrc_nodes(struct io_kiocb *req)
1075 {
1076 	struct io_ring_ctx *ctx = req->ctx;
1077 
1078 	if (req->file_node) {
1079 		io_put_rsrc_node(ctx, req->file_node);
1080 		req->file_node = NULL;
1081 	}
1082 	if (req->flags & REQ_F_BUF_NODE)
1083 		io_put_rsrc_node(ctx, req->buf_node);
1084 }
1085 
1086 static void io_free_batch_list(struct io_ring_ctx *ctx,
1087 			       struct io_wq_work_node *node)
1088 	__must_hold(&ctx->uring_lock)
1089 {
1090 	do {
1091 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1092 						    comp_list);
1093 
1094 		if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1095 			if (req->flags & REQ_F_REISSUE) {
1096 				node = req->comp_list.next;
1097 				req->flags &= ~REQ_F_REISSUE;
1098 				io_queue_iowq(req);
1099 				continue;
1100 			}
1101 			if (req->flags & REQ_F_REFCOUNT) {
1102 				node = req->comp_list.next;
1103 				if (!req_ref_put_and_test(req))
1104 					continue;
1105 			}
1106 			if ((req->flags & REQ_F_POLLED) && req->apoll) {
1107 				struct async_poll *apoll = req->apoll;
1108 
1109 				if (apoll->double_poll)
1110 					kfree(apoll->double_poll);
1111 				io_cache_free(&ctx->apoll_cache, apoll);
1112 				req->flags &= ~REQ_F_POLLED;
1113 			}
1114 			if (req->flags & IO_REQ_LINK_FLAGS)
1115 				io_queue_next(req);
1116 			if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1117 				io_clean_op(req);
1118 		}
1119 		io_put_file(req);
1120 		io_req_put_rsrc_nodes(req);
1121 		io_put_task(req);
1122 
1123 		node = req->comp_list.next;
1124 		io_req_add_to_cache(req, ctx);
1125 	} while (node);
1126 }
1127 
1128 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1129 	__must_hold(&ctx->uring_lock)
1130 {
1131 	struct io_submit_state *state = &ctx->submit_state;
1132 	struct io_wq_work_node *node;
1133 
1134 	__io_cq_lock(ctx);
1135 	__wq_list_for_each(node, &state->compl_reqs) {
1136 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1137 					    comp_list);
1138 
1139 		/*
1140 		 * Requests marked with REQUEUE should not post a CQE, they
1141 		 * will go through the io-wq retry machinery and post one
1142 		 * later.
1143 		 */
1144 		if (!(req->flags & (REQ_F_CQE_SKIP | REQ_F_REISSUE)) &&
1145 		    unlikely(!io_fill_cqe_req(ctx, req))) {
1146 			if (ctx->int_flags & IO_RING_F_LOCKLESS_CQ)
1147 				io_cqe_overflow(ctx, &req->cqe, &req->big_cqe);
1148 			else
1149 				io_cqe_overflow_locked(ctx, &req->cqe, &req->big_cqe);
1150 		}
1151 	}
1152 	__io_cq_unlock_post(ctx);
1153 
1154 	if (!wq_list_empty(&state->compl_reqs)) {
1155 		io_free_batch_list(ctx, state->compl_reqs.first);
1156 		INIT_WQ_LIST(&state->compl_reqs);
1157 	}
1158 
1159 	if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_ACTIVE))
1160 		io_queue_deferred(ctx);
1161 
1162 	ctx->submit_state.cq_flush = false;
1163 }
1164 
1165 /*
1166  * We can't just wait for polled events to come to us, we have to actively
1167  * find and complete them.
1168  */
1169 __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1170 {
1171 	if (!(ctx->flags & IORING_SETUP_IOPOLL))
1172 		return;
1173 
1174 	mutex_lock(&ctx->uring_lock);
1175 	while (!list_empty(&ctx->iopoll_list)) {
1176 		/* let it sleep and repeat later if can't complete a request */
1177 		if (io_do_iopoll(ctx, true) == 0)
1178 			break;
1179 		/*
1180 		 * Ensure we allow local-to-the-cpu processing to take place,
1181 		 * in this case we need to ensure that we reap all events.
1182 		 * Also let task_work, etc. to progress by releasing the mutex
1183 		 */
1184 		if (need_resched()) {
1185 			mutex_unlock(&ctx->uring_lock);
1186 			cond_resched();
1187 			mutex_lock(&ctx->uring_lock);
1188 		}
1189 	}
1190 	mutex_unlock(&ctx->uring_lock);
1191 
1192 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
1193 		io_move_task_work_from_local(ctx);
1194 }
1195 
1196 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned int min_events)
1197 {
1198 	unsigned long check_cq;
1199 
1200 	min_events = min(min_events, ctx->cq_entries);
1201 
1202 	lockdep_assert_held(&ctx->uring_lock);
1203 
1204 	if (!io_allowed_run_tw(ctx))
1205 		return -EEXIST;
1206 
1207 	check_cq = READ_ONCE(ctx->check_cq);
1208 	if (unlikely(check_cq)) {
1209 		if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1210 			__io_cqring_overflow_flush(ctx, false);
1211 		/*
1212 		 * Similarly do not spin if we have not informed the user of any
1213 		 * dropped CQE.
1214 		 */
1215 		if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1216 			return -EBADR;
1217 	}
1218 	/*
1219 	 * Don't enter poll loop if we already have events pending.
1220 	 * If we do, we can potentially be spinning for commands that
1221 	 * already triggered a CQE (eg in error).
1222 	 */
1223 	if (io_cqring_events(ctx))
1224 		return 0;
1225 
1226 	do {
1227 		int ret = 0;
1228 
1229 		/*
1230 		 * If a submit got punted to a workqueue, we can have the
1231 		 * application entering polling for a command before it gets
1232 		 * issued. That app will hold the uring_lock for the duration
1233 		 * of the poll right here, so we need to take a breather every
1234 		 * now and then to ensure that the issue has a chance to add
1235 		 * the poll to the issued list. Otherwise we can spin here
1236 		 * forever, while the workqueue is stuck trying to acquire the
1237 		 * very same mutex.
1238 		 */
1239 		if (list_empty(&ctx->iopoll_list) || io_task_work_pending(ctx)) {
1240 			(void) io_run_local_work_locked(ctx, min_events);
1241 
1242 			if (task_work_pending(current) || list_empty(&ctx->iopoll_list)) {
1243 				mutex_unlock(&ctx->uring_lock);
1244 				io_run_task_work();
1245 				mutex_lock(&ctx->uring_lock);
1246 			}
1247 			/* some requests don't go through iopoll_list */
1248 			if (list_empty(&ctx->iopoll_list))
1249 				break;
1250 		}
1251 		ret = io_do_iopoll(ctx, !min_events);
1252 		if (unlikely(ret < 0))
1253 			return ret;
1254 
1255 		if (task_sigpending(current))
1256 			return -EINTR;
1257 		if (need_resched())
1258 			break;
1259 	} while (io_cqring_events(ctx) < min_events);
1260 
1261 	return 0;
1262 }
1263 
1264 void io_req_task_complete(struct io_tw_req tw_req, io_tw_token_t tw)
1265 {
1266 	io_req_complete_defer(tw_req.req);
1267 }
1268 
1269 /*
1270  * After the iocb has been issued, it's safe to be found on the poll list.
1271  * Adding the kiocb to the list AFTER submission ensures that we don't
1272  * find it from a io_do_iopoll() thread before the issuer is done
1273  * accessing the kiocb cookie.
1274  */
1275 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1276 {
1277 	struct io_ring_ctx *ctx = req->ctx;
1278 	const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1279 
1280 	/* workqueue context doesn't hold uring_lock, grab it now */
1281 	if (unlikely(needs_lock))
1282 		mutex_lock(&ctx->uring_lock);
1283 
1284 	/*
1285 	 * Track whether we have multiple files in our lists. This will impact
1286 	 * how we do polling eventually, not spinning if we're on potentially
1287 	 * different devices.
1288 	 */
1289 	if (list_empty(&ctx->iopoll_list)) {
1290 		ctx->poll_multi_queue = false;
1291 	} else if (!ctx->poll_multi_queue) {
1292 		struct io_kiocb *list_req;
1293 
1294 		list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb, iopoll_node);
1295 		if (list_req->file != req->file)
1296 			ctx->poll_multi_queue = true;
1297 	}
1298 
1299 	list_add_tail(&req->iopoll_node, &ctx->iopoll_list);
1300 
1301 	if (unlikely(needs_lock)) {
1302 		/*
1303 		 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1304 		 * in sq thread task context or in io worker task context. If
1305 		 * current task context is sq thread, we don't need to check
1306 		 * whether should wake up sq thread.
1307 		 */
1308 		if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1309 		    wq_has_sleeper(&ctx->sq_data->wait))
1310 			wake_up(&ctx->sq_data->wait);
1311 
1312 		mutex_unlock(&ctx->uring_lock);
1313 	}
1314 }
1315 
1316 io_req_flags_t io_file_get_flags(struct file *file)
1317 {
1318 	io_req_flags_t res = 0;
1319 
1320 	BUILD_BUG_ON(REQ_F_ISREG_BIT != REQ_F_SUPPORT_NOWAIT_BIT + 1);
1321 
1322 	if (S_ISREG(file_inode(file)->i_mode))
1323 		res |= REQ_F_ISREG;
1324 	if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1325 		res |= REQ_F_SUPPORT_NOWAIT;
1326 	return res;
1327 }
1328 
1329 static __cold void io_drain_req(struct io_kiocb *req)
1330 	__must_hold(&ctx->uring_lock)
1331 {
1332 	struct io_ring_ctx *ctx = req->ctx;
1333 	bool drain = req->flags & IOSQE_IO_DRAIN;
1334 	struct io_defer_entry *de;
1335 
1336 	de = kmalloc_obj(*de, GFP_KERNEL_ACCOUNT);
1337 	if (!de) {
1338 		io_req_defer_failed(req, -ENOMEM);
1339 		return;
1340 	}
1341 
1342 	io_prep_async_link(req);
1343 	trace_io_uring_defer(req);
1344 	de->req = req;
1345 
1346 	ctx->nr_drained += io_linked_nr(req);
1347 	list_add_tail(&de->list, &ctx->defer_list);
1348 	io_queue_deferred(ctx);
1349 	if (!drain && list_empty(&ctx->defer_list))
1350 		ctx->int_flags &= ~IO_RING_F_DRAIN_ACTIVE;
1351 }
1352 
1353 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1354 			   unsigned int issue_flags)
1355 {
1356 	if (req->file || !def->needs_file)
1357 		return true;
1358 
1359 	if (req->flags & REQ_F_FIXED_FILE)
1360 		req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1361 	else
1362 		req->file = io_file_get_normal(req, req->cqe.fd);
1363 
1364 	return !!req->file;
1365 }
1366 
1367 #define REQ_ISSUE_SLOW_FLAGS	(REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)
1368 
1369 static inline int __io_issue_sqe(struct io_kiocb *req,
1370 				 unsigned int issue_flags,
1371 				 const struct io_issue_def *def)
1372 {
1373 	const struct cred *creds = NULL;
1374 	struct io_kiocb *link = NULL;
1375 	int ret;
1376 
1377 	if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) {
1378 		if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
1379 			creds = override_creds(req->creds);
1380 		if (req->flags & REQ_F_ARM_LTIMEOUT)
1381 			link = __io_prep_linked_timeout(req);
1382 	}
1383 
1384 	if (!def->audit_skip)
1385 		audit_uring_entry(req->opcode);
1386 
1387 	ret = def->issue(req, issue_flags);
1388 
1389 	if (!def->audit_skip)
1390 		audit_uring_exit(!ret, ret);
1391 
1392 	if (unlikely(creds || link)) {
1393 		if (creds)
1394 			revert_creds(creds);
1395 		if (link)
1396 			io_queue_linked_timeout(link);
1397 	}
1398 
1399 	return ret;
1400 }
1401 
1402 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1403 {
1404 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1405 	int ret;
1406 
1407 	if (unlikely(!io_assign_file(req, def, issue_flags)))
1408 		return -EBADF;
1409 
1410 	ret = __io_issue_sqe(req, issue_flags, def);
1411 
1412 	if (ret == IOU_COMPLETE) {
1413 		if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1414 			io_req_complete_defer(req);
1415 		else
1416 			io_req_complete_post(req, issue_flags);
1417 
1418 		return 0;
1419 	}
1420 
1421 	if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1422 		ret = 0;
1423 
1424 		if (req->flags & REQ_F_IOPOLL)
1425 			io_iopoll_req_issued(req, issue_flags);
1426 	}
1427 	return ret;
1428 }
1429 
1430 int io_poll_issue(struct io_kiocb *req, io_tw_token_t tw)
1431 {
1432 	const unsigned int issue_flags = IO_URING_F_NONBLOCK |
1433 					 IO_URING_F_MULTISHOT |
1434 					 IO_URING_F_COMPLETE_DEFER;
1435 	int ret;
1436 
1437 	io_tw_lock(req->ctx, tw);
1438 
1439 	WARN_ON_ONCE(!req->file);
1440 	if (WARN_ON_ONCE(req->flags & REQ_F_IOPOLL))
1441 		return -EFAULT;
1442 
1443 	ret = __io_issue_sqe(req, issue_flags, &io_issue_defs[req->opcode]);
1444 
1445 	WARN_ON_ONCE(ret == IOU_ISSUE_SKIP_COMPLETE);
1446 	return ret;
1447 }
1448 
1449 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1450 {
1451 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1452 	struct io_kiocb *nxt = NULL;
1453 
1454 	if (req_ref_put_and_test_atomic(req)) {
1455 		if (req->flags & IO_REQ_LINK_FLAGS)
1456 			nxt = io_req_find_next(req);
1457 		io_free_req(req);
1458 	}
1459 	return nxt ? &nxt->work : NULL;
1460 }
1461 
1462 void io_wq_submit_work(struct io_wq_work *work)
1463 {
1464 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1465 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1466 	unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1467 	bool needs_poll = false;
1468 	int ret = 0, err = -ECANCELED;
1469 
1470 	/* one will be dropped by io_wq_free_work() after returning to io-wq */
1471 	if (!(req->flags & REQ_F_REFCOUNT))
1472 		__io_req_set_refcount(req, 2);
1473 	else
1474 		req_ref_get(req);
1475 
1476 	/* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1477 	if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
1478 fail:
1479 		io_req_task_queue_fail(req, err);
1480 		return;
1481 	}
1482 	if (!io_assign_file(req, def, issue_flags)) {
1483 		err = -EBADF;
1484 		atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1485 		goto fail;
1486 	}
1487 
1488 	/*
1489 	 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1490 	 * submitter task context. Final request completions are handed to the
1491 	 * right context, however this is not the case of auxiliary CQEs,
1492 	 * which is the main mean of operation for multishot requests.
1493 	 * Don't allow any multishot execution from io-wq. It's more restrictive
1494 	 * than necessary and also cleaner.
1495 	 */
1496 	if (req->flags & (REQ_F_MULTISHOT|REQ_F_APOLL_MULTISHOT)) {
1497 		err = -EBADFD;
1498 		if (!io_file_can_poll(req))
1499 			goto fail;
1500 		if (req->file->f_flags & O_NONBLOCK ||
1501 		    req->file->f_mode & FMODE_NOWAIT) {
1502 			err = -ECANCELED;
1503 			if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1504 				goto fail;
1505 			return;
1506 		} else {
1507 			req->flags &= ~(REQ_F_APOLL_MULTISHOT|REQ_F_MULTISHOT);
1508 		}
1509 	}
1510 
1511 	if (req->flags & REQ_F_FORCE_ASYNC) {
1512 		bool opcode_poll = def->pollin || def->pollout;
1513 
1514 		if (opcode_poll && io_file_can_poll(req)) {
1515 			needs_poll = true;
1516 			issue_flags |= IO_URING_F_NONBLOCK;
1517 		}
1518 	}
1519 
1520 	do {
1521 		ret = io_issue_sqe(req, issue_flags);
1522 		if (ret != -EAGAIN)
1523 			break;
1524 
1525 		/*
1526 		 * If REQ_F_NOWAIT is set, then don't wait or retry with
1527 		 * poll. -EAGAIN is final for that case.
1528 		 */
1529 		if (req->flags & REQ_F_NOWAIT)
1530 			break;
1531 
1532 		/*
1533 		 * We can get EAGAIN for iopolled IO even though we're
1534 		 * forcing a sync submission from here, since we can't
1535 		 * wait for request slots on the block side.
1536 		 */
1537 		if (!needs_poll) {
1538 			if (!(req->flags & REQ_F_IOPOLL))
1539 				break;
1540 			if (io_wq_worker_stopped())
1541 				break;
1542 			cond_resched();
1543 			continue;
1544 		}
1545 
1546 		if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1547 			return;
1548 		/* aborted or ready, in either case retry blocking */
1549 		needs_poll = false;
1550 		issue_flags &= ~IO_URING_F_NONBLOCK;
1551 	} while (1);
1552 
1553 	/* avoid locking problems by failing it from a clean context */
1554 	if (ret)
1555 		io_req_task_queue_fail(req, ret);
1556 }
1557 
1558 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1559 				      unsigned int issue_flags)
1560 {
1561 	struct io_ring_ctx *ctx = req->ctx;
1562 	struct io_rsrc_node *node;
1563 	struct file *file = NULL;
1564 
1565 	io_ring_submit_lock(ctx, issue_flags);
1566 	node = io_rsrc_node_lookup(&ctx->file_table.data, fd);
1567 	if (node) {
1568 		node->refs++;
1569 		req->file_node = node;
1570 		req->flags |= io_slot_flags(node);
1571 		file = io_slot_file(node);
1572 	}
1573 	io_ring_submit_unlock(ctx, issue_flags);
1574 	return file;
1575 }
1576 
1577 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1578 {
1579 	struct file *file = fget(fd);
1580 
1581 	trace_io_uring_file_get(req, fd);
1582 
1583 	/* we don't allow fixed io_uring files */
1584 	if (file && io_is_uring_fops(file))
1585 		io_req_track_inflight(req);
1586 	return file;
1587 }
1588 
1589 static int io_req_sqe_copy(struct io_kiocb *req, unsigned int issue_flags)
1590 {
1591 	const struct io_cold_def *def = &io_cold_defs[req->opcode];
1592 
1593 	if (req->flags & REQ_F_SQE_COPIED)
1594 		return 0;
1595 	req->flags |= REQ_F_SQE_COPIED;
1596 	if (!def->sqe_copy)
1597 		return 0;
1598 	if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_INLINE)))
1599 		return -EFAULT;
1600 	def->sqe_copy(req);
1601 	return 0;
1602 }
1603 
1604 static void io_queue_async(struct io_kiocb *req, unsigned int issue_flags, int ret)
1605 	__must_hold(&req->ctx->uring_lock)
1606 {
1607 	if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1608 fail:
1609 		io_req_defer_failed(req, ret);
1610 		return;
1611 	}
1612 
1613 	ret = io_req_sqe_copy(req, issue_flags);
1614 	if (unlikely(ret))
1615 		goto fail;
1616 
1617 	switch (io_arm_poll_handler(req, 0)) {
1618 	case IO_APOLL_READY:
1619 		io_req_task_queue(req);
1620 		break;
1621 	case IO_APOLL_ABORTED:
1622 		io_queue_iowq(req);
1623 		break;
1624 	case IO_APOLL_OK:
1625 		break;
1626 	}
1627 }
1628 
1629 static inline void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags)
1630 	__must_hold(&req->ctx->uring_lock)
1631 {
1632 	unsigned int issue_flags = IO_URING_F_NONBLOCK |
1633 				   IO_URING_F_COMPLETE_DEFER | extra_flags;
1634 	int ret;
1635 
1636 	ret = io_issue_sqe(req, issue_flags);
1637 
1638 	/*
1639 	 * We async punt it if the file wasn't marked NOWAIT, or if the file
1640 	 * doesn't support non-blocking read/write attempts
1641 	 */
1642 	if (unlikely(ret))
1643 		io_queue_async(req, issue_flags, ret);
1644 }
1645 
1646 static void io_queue_sqe_fallback(struct io_kiocb *req)
1647 	__must_hold(&req->ctx->uring_lock)
1648 {
1649 	if (unlikely(req->flags & REQ_F_FAIL)) {
1650 		/*
1651 		 * We don't submit, fail them all, for that replace hardlinks
1652 		 * with normal links. Extra REQ_F_LINK is tolerated.
1653 		 */
1654 		req->flags &= ~REQ_F_HARDLINK;
1655 		req->flags |= REQ_F_LINK;
1656 		io_req_defer_failed(req, req->cqe.res);
1657 	} else {
1658 		/* can't fail with IO_URING_F_INLINE */
1659 		io_req_sqe_copy(req, IO_URING_F_INLINE);
1660 		if (unlikely(req->ctx->int_flags & IO_RING_F_DRAIN_ACTIVE))
1661 			io_drain_req(req);
1662 		else
1663 			io_queue_iowq(req);
1664 	}
1665 }
1666 
1667 /*
1668  * Check SQE restrictions (opcode and flags).
1669  *
1670  * Returns 'true' if SQE is allowed, 'false' otherwise.
1671  */
1672 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
1673 					struct io_kiocb *req,
1674 					unsigned int sqe_flags)
1675 {
1676 	if (!(ctx->int_flags & IO_RING_F_OP_RESTRICTED))
1677 		return true;
1678 	if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
1679 		return false;
1680 
1681 	if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
1682 	    ctx->restrictions.sqe_flags_required)
1683 		return false;
1684 
1685 	if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
1686 			  ctx->restrictions.sqe_flags_required))
1687 		return false;
1688 
1689 	return true;
1690 }
1691 
1692 static void io_init_drain(struct io_ring_ctx *ctx)
1693 {
1694 	struct io_kiocb *head = ctx->submit_state.link.head;
1695 
1696 	ctx->int_flags |= IO_RING_F_DRAIN_ACTIVE;
1697 	if (head) {
1698 		/*
1699 		 * If we need to drain a request in the middle of a link, drain
1700 		 * the head request and the next request/link after the current
1701 		 * link. Considering sequential execution of links,
1702 		 * REQ_F_IO_DRAIN will be maintained for every request of our
1703 		 * link.
1704 		 */
1705 		head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1706 		ctx->int_flags |= IO_RING_F_DRAIN_NEXT;
1707 	}
1708 }
1709 
1710 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
1711 {
1712 	/* ensure per-opcode data is cleared if we fail before prep */
1713 	memset(&req->cmd.data, 0, sizeof(req->cmd.data));
1714 	return err;
1715 }
1716 
1717 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
1718 		       const struct io_uring_sqe *sqe, unsigned int *left)
1719 	__must_hold(&ctx->uring_lock)
1720 {
1721 	const struct io_issue_def *def;
1722 	unsigned int sqe_flags;
1723 	int personality;
1724 	u8 opcode;
1725 
1726 	req->ctx = ctx;
1727 	req->opcode = opcode = READ_ONCE(sqe->opcode);
1728 	/* same numerical values with corresponding REQ_F_*, safe to copy */
1729 	sqe_flags = READ_ONCE(sqe->flags);
1730 	req->flags = (__force io_req_flags_t) sqe_flags;
1731 	req->cqe.user_data = READ_ONCE(sqe->user_data);
1732 	req->file = NULL;
1733 	req->tctx = current->io_uring;
1734 	req->cancel_seq_set = false;
1735 	req->async_data = NULL;
1736 
1737 	if (unlikely(opcode >= IORING_OP_LAST)) {
1738 		req->opcode = 0;
1739 		return io_init_fail_req(req, -EINVAL);
1740 	}
1741 	opcode = array_index_nospec(opcode, IORING_OP_LAST);
1742 
1743 	def = &io_issue_defs[opcode];
1744 	if (def->is_128 && !(ctx->flags & IORING_SETUP_SQE128)) {
1745 		/*
1746 		 * A 128b op on a non-128b SQ requires mixed SQE support as
1747 		 * well as 2 contiguous entries.
1748 		 */
1749 		if (!(ctx->flags & IORING_SETUP_SQE_MIXED) || *left < 2 ||
1750 		    (unsigned)(sqe - ctx->sq_sqes) >= ctx->sq_entries - 1)
1751 			return io_init_fail_req(req, -EINVAL);
1752 		/*
1753 		 * A 128b operation on a mixed SQ uses two entries, so we have
1754 		 * to increment the head and cached refs, and decrement what's
1755 		 * left.
1756 		 */
1757 		current->io_uring->cached_refs++;
1758 		ctx->cached_sq_head++;
1759 		(*left)--;
1760 	}
1761 
1762 	if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
1763 		/* enforce forwards compatibility on users */
1764 		if (sqe_flags & ~SQE_VALID_FLAGS)
1765 			return io_init_fail_req(req, -EINVAL);
1766 		if (sqe_flags & IOSQE_BUFFER_SELECT) {
1767 			if (!def->buffer_select)
1768 				return io_init_fail_req(req, -EOPNOTSUPP);
1769 			req->buf_index = READ_ONCE(sqe->buf_group);
1770 		}
1771 		if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
1772 			ctx->int_flags |= IO_RING_F_DRAIN_DISABLED;
1773 		if (sqe_flags & IOSQE_IO_DRAIN) {
1774 			if (ctx->int_flags & IO_RING_F_DRAIN_DISABLED)
1775 				return io_init_fail_req(req, -EOPNOTSUPP);
1776 			io_init_drain(ctx);
1777 		}
1778 	}
1779 	if (unlikely(ctx->int_flags & (IO_RING_F_OP_RESTRICTED | IO_RING_F_DRAIN_ACTIVE | IO_RING_F_DRAIN_NEXT))) {
1780 		if (!io_check_restriction(ctx, req, sqe_flags))
1781 			return io_init_fail_req(req, -EACCES);
1782 		/* knock it to the slow queue path, will be drained there */
1783 		if (ctx->int_flags & IO_RING_F_DRAIN_ACTIVE)
1784 			req->flags |= REQ_F_FORCE_ASYNC;
1785 		/* if there is no link, we're at "next" request and need to drain */
1786 		if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_NEXT) && !ctx->submit_state.link.head) {
1787 			ctx->int_flags &= ~IO_RING_F_DRAIN_NEXT;
1788 			ctx->int_flags |= IO_RING_F_DRAIN_ACTIVE;
1789 			req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1790 		}
1791 	}
1792 
1793 	if (!def->ioprio && sqe->ioprio)
1794 		return io_init_fail_req(req, -EINVAL);
1795 	if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
1796 		return io_init_fail_req(req, -EINVAL);
1797 
1798 	if (def->needs_file) {
1799 		struct io_submit_state *state = &ctx->submit_state;
1800 
1801 		req->cqe.fd = READ_ONCE(sqe->fd);
1802 
1803 		/*
1804 		 * Plug now if we have more than 2 IO left after this, and the
1805 		 * target is potentially a read/write to block based storage.
1806 		 */
1807 		if (state->need_plug && def->plug) {
1808 			state->plug_started = true;
1809 			state->need_plug = false;
1810 			blk_start_plug_nr_ios(&state->plug, state->submit_nr);
1811 		}
1812 	}
1813 
1814 	personality = READ_ONCE(sqe->personality);
1815 	if (personality) {
1816 		int ret;
1817 
1818 		req->creds = xa_load(&ctx->personalities, personality);
1819 		if (!req->creds)
1820 			return io_init_fail_req(req, -EINVAL);
1821 		get_cred(req->creds);
1822 		ret = security_uring_override_creds(req->creds);
1823 		if (ret) {
1824 			put_cred(req->creds);
1825 			return io_init_fail_req(req, ret);
1826 		}
1827 		req->flags |= REQ_F_CREDS;
1828 	}
1829 
1830 	return def->prep(req, sqe);
1831 }
1832 
1833 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
1834 				      struct io_kiocb *req, int ret)
1835 {
1836 	struct io_ring_ctx *ctx = req->ctx;
1837 	struct io_submit_link *link = &ctx->submit_state.link;
1838 	struct io_kiocb *head = link->head;
1839 
1840 	trace_io_uring_req_failed(sqe, req, ret);
1841 
1842 	/*
1843 	 * Avoid breaking links in the middle as it renders links with SQPOLL
1844 	 * unusable. Instead of failing eagerly, continue assembling the link if
1845 	 * applicable and mark the head with REQ_F_FAIL. The link flushing code
1846 	 * should find the flag and handle the rest.
1847 	 */
1848 	req_fail_link_node(req, ret);
1849 	if (head && !(head->flags & REQ_F_FAIL))
1850 		req_fail_link_node(head, -ECANCELED);
1851 
1852 	if (!(req->flags & IO_REQ_LINK_FLAGS)) {
1853 		if (head) {
1854 			link->last->link = req;
1855 			link->head = NULL;
1856 			req = head;
1857 		}
1858 		io_queue_sqe_fallback(req);
1859 		return ret;
1860 	}
1861 
1862 	if (head)
1863 		link->last->link = req;
1864 	else
1865 		link->head = req;
1866 	link->last = req;
1867 	return 0;
1868 }
1869 
1870 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1871 			 const struct io_uring_sqe *sqe, unsigned int *left)
1872 	__must_hold(&ctx->uring_lock)
1873 {
1874 	struct io_submit_link *link = &ctx->submit_state.link;
1875 	int ret;
1876 
1877 	ret = io_init_req(ctx, req, sqe, left);
1878 	if (unlikely(ret))
1879 		return io_submit_fail_init(sqe, req, ret);
1880 
1881 	if (unlikely(ctx->bpf_filters)) {
1882 		ret = io_uring_run_bpf_filters(ctx->bpf_filters, req);
1883 		if (ret)
1884 			return io_submit_fail_init(sqe, req, ret);
1885 	}
1886 
1887 	trace_io_uring_submit_req(req);
1888 
1889 	/*
1890 	 * If we already have a head request, queue this one for async
1891 	 * submittal once the head completes. If we don't have a head but
1892 	 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
1893 	 * submitted sync once the chain is complete. If none of those
1894 	 * conditions are true (normal request), then just queue it.
1895 	 */
1896 	if (unlikely(link->head)) {
1897 		trace_io_uring_link(req, link->last);
1898 		io_req_sqe_copy(req, IO_URING_F_INLINE);
1899 		link->last->link = req;
1900 		link->last = req;
1901 
1902 		if (req->flags & IO_REQ_LINK_FLAGS)
1903 			return 0;
1904 		/* last request of the link, flush it */
1905 		req = link->head;
1906 		link->head = NULL;
1907 		if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
1908 			goto fallback;
1909 
1910 	} else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
1911 					  REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
1912 		if (req->flags & IO_REQ_LINK_FLAGS) {
1913 			link->head = req;
1914 			link->last = req;
1915 		} else {
1916 fallback:
1917 			io_queue_sqe_fallback(req);
1918 		}
1919 		return 0;
1920 	}
1921 
1922 	io_queue_sqe(req, IO_URING_F_INLINE);
1923 	return 0;
1924 }
1925 
1926 /*
1927  * Batched submission is done, ensure local IO is flushed out.
1928  */
1929 static void io_submit_state_end(struct io_ring_ctx *ctx)
1930 {
1931 	struct io_submit_state *state = &ctx->submit_state;
1932 
1933 	if (unlikely(state->link.head))
1934 		io_queue_sqe_fallback(state->link.head);
1935 	/* flush only after queuing links as they can generate completions */
1936 	io_submit_flush_completions(ctx);
1937 	if (state->plug_started)
1938 		blk_finish_plug(&state->plug);
1939 }
1940 
1941 /*
1942  * Start submission side cache.
1943  */
1944 static void io_submit_state_start(struct io_submit_state *state,
1945 				  unsigned int max_ios)
1946 {
1947 	state->plug_started = false;
1948 	state->need_plug = max_ios > 2;
1949 	state->submit_nr = max_ios;
1950 	/* set only head, no need to init link_last in advance */
1951 	state->link.head = NULL;
1952 }
1953 
1954 static void io_commit_sqring(struct io_ring_ctx *ctx)
1955 {
1956 	struct io_rings *rings = ctx->rings;
1957 
1958 	if (ctx->flags & IORING_SETUP_SQ_REWIND) {
1959 		ctx->cached_sq_head = 0;
1960 	} else {
1961 		/*
1962 		 * Ensure any loads from the SQEs are done at this point,
1963 		 * since once we write the new head, the application could
1964 		 * write new data to them.
1965 		 */
1966 		smp_store_release(&rings->sq.head, ctx->cached_sq_head);
1967 	}
1968 }
1969 
1970 /*
1971  * Fetch an sqe, if one is available. Note this returns a pointer to memory
1972  * that is mapped by userspace. This means that care needs to be taken to
1973  * ensure that reads are stable, as we cannot rely on userspace always
1974  * being a good citizen. If members of the sqe are validated and then later
1975  * used, it's important that those reads are done through READ_ONCE() to
1976  * prevent a re-load down the line.
1977  */
1978 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
1979 {
1980 	unsigned mask = ctx->sq_entries - 1;
1981 	unsigned head = ctx->cached_sq_head++ & mask;
1982 
1983 	if (static_branch_unlikely(&io_key_has_sqarray.key) &&
1984 	    (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) {
1985 		head = READ_ONCE(ctx->sq_array[head]);
1986 		if (unlikely(head >= ctx->sq_entries)) {
1987 			WRITE_ONCE(ctx->rings->sq_dropped,
1988 				   READ_ONCE(ctx->rings->sq_dropped) + 1);
1989 			return false;
1990 		}
1991 		head = array_index_nospec(head, ctx->sq_entries);
1992 	}
1993 
1994 	/*
1995 	 * The cached sq head (or cq tail) serves two purposes:
1996 	 *
1997 	 * 1) allows us to batch the cost of updating the user visible
1998 	 *    head updates.
1999 	 * 2) allows the kernel side to track the head on its own, even
2000 	 *    though the application is the one updating it.
2001 	 */
2002 
2003 	/* double index for 128-byte SQEs, twice as long */
2004 	if (ctx->flags & IORING_SETUP_SQE128)
2005 		head <<= 1;
2006 	*sqe = &ctx->sq_sqes[head];
2007 	return true;
2008 }
2009 
2010 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2011 	__must_hold(&ctx->uring_lock)
2012 {
2013 	unsigned int entries;
2014 	unsigned int left;
2015 	int ret;
2016 
2017 	if (ctx->flags & IORING_SETUP_SQ_REWIND)
2018 		entries = ctx->sq_entries;
2019 	else
2020 		entries = __io_sqring_entries(ctx);
2021 
2022 	entries = min(nr, entries);
2023 	if (unlikely(!entries))
2024 		return 0;
2025 
2026 	ret = left = entries;
2027 	io_get_task_refs(left);
2028 	io_submit_state_start(&ctx->submit_state, left);
2029 
2030 	do {
2031 		const struct io_uring_sqe *sqe;
2032 		struct io_kiocb *req;
2033 
2034 		if (unlikely(!io_alloc_req(ctx, &req)))
2035 			break;
2036 		if (unlikely(!io_get_sqe(ctx, &sqe))) {
2037 			io_req_add_to_cache(req, ctx);
2038 			break;
2039 		}
2040 
2041 		/*
2042 		 * Continue submitting even for sqe failure if the
2043 		 * ring was setup with IORING_SETUP_SUBMIT_ALL
2044 		 */
2045 		if (unlikely(io_submit_sqe(ctx, req, sqe, &left)) &&
2046 		    !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2047 			left--;
2048 			break;
2049 		}
2050 	} while (--left);
2051 
2052 	if (unlikely(left)) {
2053 		ret -= left;
2054 		/* try again if it submitted nothing and can't allocate a req */
2055 		if (!ret && io_req_cache_empty(ctx))
2056 			ret = -EAGAIN;
2057 		current->io_uring->cached_refs += left;
2058 	}
2059 
2060 	io_submit_state_end(ctx);
2061 	 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2062 	io_commit_sqring(ctx);
2063 	return ret;
2064 }
2065 
2066 static void io_rings_free(struct io_ring_ctx *ctx)
2067 {
2068 	io_free_region(ctx->user, &ctx->sq_region);
2069 	io_free_region(ctx->user, &ctx->ring_region);
2070 	ctx->rings = NULL;
2071 	RCU_INIT_POINTER(ctx->rings_rcu, NULL);
2072 	ctx->sq_sqes = NULL;
2073 }
2074 
2075 static int rings_size(unsigned int flags, unsigned int sq_entries,
2076 		      unsigned int cq_entries, struct io_rings_layout *rl)
2077 {
2078 	struct io_rings *rings;
2079 	size_t sqe_size;
2080 	size_t off;
2081 
2082 	if (flags & IORING_SETUP_CQE_MIXED) {
2083 		if (cq_entries < 2)
2084 			return -EOVERFLOW;
2085 	}
2086 	if (flags & IORING_SETUP_SQE_MIXED) {
2087 		if (sq_entries < 2)
2088 			return -EOVERFLOW;
2089 	}
2090 
2091 	rl->sq_array_offset = SIZE_MAX;
2092 
2093 	sqe_size = sizeof(struct io_uring_sqe);
2094 	if (flags & IORING_SETUP_SQE128)
2095 		sqe_size *= 2;
2096 
2097 	rl->sq_size = array_size(sqe_size, sq_entries);
2098 	if (rl->sq_size == SIZE_MAX)
2099 		return -EOVERFLOW;
2100 
2101 	off = struct_size(rings, cqes, cq_entries);
2102 	if (flags & IORING_SETUP_CQE32)
2103 		off = size_mul(off, 2);
2104 	if (off == SIZE_MAX)
2105 		return -EOVERFLOW;
2106 
2107 #ifdef CONFIG_SMP
2108 	off = ALIGN(off, SMP_CACHE_BYTES);
2109 	if (off == 0)
2110 		return -EOVERFLOW;
2111 #endif
2112 
2113 	if (!(flags & IORING_SETUP_NO_SQARRAY)) {
2114 		size_t sq_array_size;
2115 
2116 		rl->sq_array_offset = off;
2117 
2118 		sq_array_size = array_size(sizeof(u32), sq_entries);
2119 		off = size_add(off, sq_array_size);
2120 		if (off == SIZE_MAX)
2121 			return -EOVERFLOW;
2122 	}
2123 
2124 	rl->rings_size = off;
2125 	return 0;
2126 }
2127 
2128 static __cold void __io_req_caches_free(struct io_ring_ctx *ctx)
2129 {
2130 	struct io_kiocb *req;
2131 	int nr = 0;
2132 
2133 	while (!io_req_cache_empty(ctx)) {
2134 		req = io_extract_req(ctx);
2135 		io_poison_req(req);
2136 		kmem_cache_free(req_cachep, req);
2137 		nr++;
2138 	}
2139 	if (nr) {
2140 		ctx->nr_req_allocated -= nr;
2141 		percpu_ref_put_many(&ctx->refs, nr);
2142 	}
2143 }
2144 
2145 static __cold void io_req_caches_free(struct io_ring_ctx *ctx)
2146 {
2147 	guard(mutex)(&ctx->uring_lock);
2148 	__io_req_caches_free(ctx);
2149 }
2150 
2151 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2152 {
2153 	io_unregister_bpf_ops(ctx);
2154 	io_sq_thread_finish(ctx);
2155 
2156 	mutex_lock(&ctx->uring_lock);
2157 	io_sqe_buffers_unregister(ctx);
2158 	io_sqe_files_unregister(ctx);
2159 	io_unregister_zcrx(ctx);
2160 	io_cqring_overflow_kill(ctx);
2161 	io_eventfd_unregister(ctx);
2162 	io_free_alloc_caches(ctx);
2163 	io_destroy_buffers(ctx);
2164 	io_free_region(ctx->user, &ctx->param_region);
2165 	mutex_unlock(&ctx->uring_lock);
2166 	if (ctx->sq_creds)
2167 		put_cred(ctx->sq_creds);
2168 	if (ctx->submitter_task)
2169 		put_task_struct(ctx->submitter_task);
2170 
2171 	WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2172 
2173 	if (ctx->mm_account) {
2174 		mmdrop(ctx->mm_account);
2175 		ctx->mm_account = NULL;
2176 	}
2177 	io_rings_free(ctx);
2178 
2179 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2180 		static_branch_slow_dec_deferred(&io_key_has_sqarray);
2181 
2182 	percpu_ref_exit(&ctx->refs);
2183 	free_uid(ctx->user);
2184 	io_req_caches_free(ctx);
2185 
2186 	if (ctx->restrictions.bpf_filters) {
2187 		WARN_ON_ONCE(ctx->bpf_filters !=
2188 			     ctx->restrictions.bpf_filters->filters);
2189 	} else {
2190 		WARN_ON_ONCE(ctx->bpf_filters);
2191 	}
2192 	io_put_bpf_filters(&ctx->restrictions);
2193 
2194 	WARN_ON_ONCE(ctx->nr_req_allocated);
2195 
2196 	if (ctx->hash_map)
2197 		io_wq_put_hash(ctx->hash_map);
2198 	io_napi_free(ctx);
2199 	kvfree(ctx->cancel_table.hbs);
2200 	xa_destroy(&ctx->io_bl_xa);
2201 	kfree(ctx);
2202 }
2203 
2204 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2205 {
2206 	struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2207 					       poll_wq_task_work);
2208 
2209 	mutex_lock(&ctx->uring_lock);
2210 	ctx->int_flags |= IO_RING_F_POLL_ACTIVATED;
2211 	mutex_unlock(&ctx->uring_lock);
2212 
2213 	/*
2214 	 * Wake ups for some events between start of polling and activation
2215 	 * might've been lost due to loose synchronisation.
2216 	 */
2217 	wake_up_all(&ctx->poll_wq);
2218 	percpu_ref_put(&ctx->refs);
2219 }
2220 
2221 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2222 {
2223 	spin_lock(&ctx->completion_lock);
2224 	/* already activated or in progress */
2225 	if ((ctx->int_flags & IO_RING_F_POLL_ACTIVATED) || ctx->poll_wq_task_work.func)
2226 		goto out;
2227 	if (WARN_ON_ONCE(!(ctx->int_flags & IO_RING_F_TASK_COMPLETE)))
2228 		goto out;
2229 	if (!ctx->submitter_task)
2230 		goto out;
2231 	/*
2232 	 * with ->submitter_task only the submitter task completes requests, we
2233 	 * only need to sync with it, which is done by injecting a tw
2234 	 */
2235 	init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2236 	percpu_ref_get(&ctx->refs);
2237 	if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2238 		percpu_ref_put(&ctx->refs);
2239 out:
2240 	spin_unlock(&ctx->completion_lock);
2241 }
2242 
2243 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2244 {
2245 	struct io_ring_ctx *ctx = file->private_data;
2246 	__poll_t mask = 0;
2247 
2248 	if (unlikely(!(data_race(ctx->int_flags) & IO_RING_F_POLL_ACTIVATED)))
2249 		io_activate_pollwq(ctx);
2250 	/*
2251 	 * provides mb() which pairs with barrier from wq_has_sleeper
2252 	 * call in io_commit_cqring
2253 	 */
2254 	poll_wait(file, &ctx->poll_wq, wait);
2255 
2256 	rcu_read_lock();
2257 
2258 	if (!__io_sqring_full(ctx))
2259 		mask |= EPOLLOUT | EPOLLWRNORM;
2260 
2261 	/*
2262 	 * Don't flush cqring overflow list here, just do a simple check.
2263 	 * Otherwise there could possible be ABBA deadlock:
2264 	 *      CPU0                    CPU1
2265 	 *      ----                    ----
2266 	 * lock(&ctx->uring_lock);
2267 	 *                              lock(&ep->mtx);
2268 	 *                              lock(&ctx->uring_lock);
2269 	 * lock(&ep->mtx);
2270 	 *
2271 	 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2272 	 * pushes them to do the flush.
2273 	 */
2274 
2275 	if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2276 		mask |= EPOLLIN | EPOLLRDNORM;
2277 
2278 	rcu_read_unlock();
2279 	return mask;
2280 }
2281 
2282 struct io_tctx_exit {
2283 	struct callback_head		task_work;
2284 	struct completion		completion;
2285 	struct io_ring_ctx		*ctx;
2286 };
2287 
2288 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2289 {
2290 	struct io_uring_task *tctx = current->io_uring;
2291 	struct io_tctx_exit *work;
2292 
2293 	work = container_of(cb, struct io_tctx_exit, task_work);
2294 	/*
2295 	 * When @in_cancel, we're in cancellation and it's racy to remove the
2296 	 * node. It'll be removed by the end of cancellation, just ignore it.
2297 	 * tctx can be NULL if the queueing of this task_work raced with
2298 	 * work cancelation off the exec path.
2299 	 */
2300 	if (tctx && !atomic_read(&tctx->in_cancel))
2301 		io_uring_del_tctx_node((unsigned long)work->ctx);
2302 	complete(&work->completion);
2303 }
2304 
2305 static __cold void io_ring_exit_work(struct work_struct *work)
2306 {
2307 	struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2308 	unsigned long timeout = jiffies + IO_URING_EXIT_WAIT_MAX;
2309 	unsigned long interval = HZ / 20;
2310 	struct io_tctx_exit exit;
2311 	struct io_tctx_node *node;
2312 	int ret;
2313 
2314 	mutex_lock(&ctx->uring_lock);
2315 	io_terminate_zcrx(ctx);
2316 	mutex_unlock(&ctx->uring_lock);
2317 
2318 	/*
2319 	 * If we're doing polled IO and end up having requests being
2320 	 * submitted async (out-of-line), then completions can come in while
2321 	 * we're waiting for refs to drop. We need to reap these manually,
2322 	 * as nobody else will be looking for them.
2323 	 */
2324 	do {
2325 		if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2326 			mutex_lock(&ctx->uring_lock);
2327 			io_cqring_overflow_kill(ctx);
2328 			mutex_unlock(&ctx->uring_lock);
2329 		}
2330 
2331 		/* The SQPOLL thread never reaches this path */
2332 		do {
2333 			if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2334 				io_move_task_work_from_local(ctx);
2335 			cond_resched();
2336 		} while (io_uring_try_cancel_requests(ctx, NULL, true, false));
2337 
2338 		if (ctx->sq_data) {
2339 			struct io_sq_data *sqd = ctx->sq_data;
2340 			struct task_struct *tsk;
2341 
2342 			io_sq_thread_park(sqd);
2343 			tsk = sqpoll_task_locked(sqd);
2344 			if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2345 				io_wq_cancel_cb(tsk->io_uring->io_wq,
2346 						io_cancel_ctx_cb, ctx, true);
2347 			io_sq_thread_unpark(sqd);
2348 		}
2349 
2350 		io_req_caches_free(ctx);
2351 
2352 		if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2353 			/* there is little hope left, don't run it too often */
2354 			interval = HZ * 60;
2355 		}
2356 		/*
2357 		 * This is really an uninterruptible wait, as it has to be
2358 		 * complete. But it's also run from a kworker, which doesn't
2359 		 * take signals, so it's fine to make it interruptible. This
2360 		 * avoids scenarios where we knowingly can wait much longer
2361 		 * on completions, for example if someone does a SIGSTOP on
2362 		 * a task that needs to finish task_work to make this loop
2363 		 * complete. That's a synthetic situation that should not
2364 		 * cause a stuck task backtrace, and hence a potential panic
2365 		 * on stuck tasks if that is enabled.
2366 		 */
2367 	} while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
2368 
2369 	init_completion(&exit.completion);
2370 	init_task_work(&exit.task_work, io_tctx_exit_cb);
2371 	exit.ctx = ctx;
2372 
2373 	mutex_lock(&ctx->uring_lock);
2374 	mutex_lock(&ctx->tctx_lock);
2375 	while (!list_empty(&ctx->tctx_list)) {
2376 		WARN_ON_ONCE(time_after(jiffies, timeout));
2377 
2378 		node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2379 					ctx_node);
2380 		/* don't spin on a single task if cancellation failed */
2381 		list_rotate_left(&ctx->tctx_list);
2382 		ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2383 		if (WARN_ON_ONCE(ret))
2384 			continue;
2385 
2386 		mutex_unlock(&ctx->tctx_lock);
2387 		mutex_unlock(&ctx->uring_lock);
2388 		/*
2389 		 * See comment above for
2390 		 * wait_for_completion_interruptible_timeout() on why this
2391 		 * wait is marked as interruptible.
2392 		 */
2393 		wait_for_completion_interruptible(&exit.completion);
2394 		mutex_lock(&ctx->uring_lock);
2395 		mutex_lock(&ctx->tctx_lock);
2396 	}
2397 	mutex_unlock(&ctx->tctx_lock);
2398 	mutex_unlock(&ctx->uring_lock);
2399 	spin_lock(&ctx->completion_lock);
2400 	spin_unlock(&ctx->completion_lock);
2401 
2402 	/* pairs with RCU read section in io_req_local_work_add() */
2403 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2404 		synchronize_rcu();
2405 
2406 	io_ring_ctx_free(ctx);
2407 }
2408 
2409 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2410 {
2411 	unsigned long index;
2412 	struct cred *creds;
2413 
2414 	mutex_lock(&ctx->uring_lock);
2415 	percpu_ref_kill(&ctx->refs);
2416 	xa_for_each(&ctx->personalities, index, creds)
2417 		io_unregister_personality(ctx, index);
2418 	mutex_unlock(&ctx->uring_lock);
2419 
2420 	flush_delayed_work(&ctx->fallback_work);
2421 
2422 	INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2423 	/*
2424 	 * Use system_dfl_wq to avoid spawning tons of event kworkers
2425 	 * if we're exiting a ton of rings at the same time. It just adds
2426 	 * noise and overhead, there's no discernable change in runtime
2427 	 * over using system_percpu_wq.
2428 	 */
2429 	queue_work(iou_wq, &ctx->exit_work);
2430 }
2431 
2432 static int io_uring_release(struct inode *inode, struct file *file)
2433 {
2434 	struct io_ring_ctx *ctx = file->private_data;
2435 
2436 	file->private_data = NULL;
2437 	io_ring_ctx_wait_and_kill(ctx);
2438 	return 0;
2439 }
2440 
2441 static struct io_uring_reg_wait *io_get_ext_arg_reg(struct io_ring_ctx *ctx,
2442 			const struct io_uring_getevents_arg __user *uarg)
2443 {
2444 	unsigned long size = sizeof(struct io_uring_reg_wait);
2445 	unsigned long offset = (uintptr_t)uarg;
2446 	unsigned long end;
2447 
2448 	if (unlikely(offset % sizeof(long)))
2449 		return ERR_PTR(-EFAULT);
2450 
2451 	/* also protects from NULL ->cq_wait_arg as the size would be 0 */
2452 	if (unlikely(check_add_overflow(offset, size, &end) ||
2453 		     end > ctx->cq_wait_size))
2454 		return ERR_PTR(-EFAULT);
2455 
2456 	offset = array_index_nospec(offset, ctx->cq_wait_size - size);
2457 	return ctx->cq_wait_arg + offset;
2458 }
2459 
2460 static int io_validate_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
2461 			       const void __user *argp, size_t argsz)
2462 {
2463 	struct io_uring_getevents_arg arg;
2464 
2465 	if (!(flags & IORING_ENTER_EXT_ARG))
2466 		return 0;
2467 	if (flags & IORING_ENTER_EXT_ARG_REG)
2468 		return -EINVAL;
2469 	if (argsz != sizeof(arg))
2470 		return -EINVAL;
2471 	if (copy_from_user(&arg, argp, sizeof(arg)))
2472 		return -EFAULT;
2473 	return 0;
2474 }
2475 
2476 static int io_get_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
2477 			  const void __user *argp, struct ext_arg *ext_arg)
2478 {
2479 	const struct io_uring_getevents_arg __user *uarg = argp;
2480 	struct io_uring_getevents_arg arg;
2481 
2482 	ext_arg->iowait = !(flags & IORING_ENTER_NO_IOWAIT);
2483 
2484 	/*
2485 	 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
2486 	 * is just a pointer to the sigset_t.
2487 	 */
2488 	if (!(flags & IORING_ENTER_EXT_ARG)) {
2489 		ext_arg->sig = (const sigset_t __user *) argp;
2490 		return 0;
2491 	}
2492 
2493 	if (flags & IORING_ENTER_EXT_ARG_REG) {
2494 		struct io_uring_reg_wait *w;
2495 
2496 		if (ext_arg->argsz != sizeof(struct io_uring_reg_wait))
2497 			return -EINVAL;
2498 		w = io_get_ext_arg_reg(ctx, argp);
2499 		if (IS_ERR(w))
2500 			return PTR_ERR(w);
2501 
2502 		if (w->flags & ~IORING_REG_WAIT_TS)
2503 			return -EINVAL;
2504 		ext_arg->min_time = READ_ONCE(w->min_wait_usec) * NSEC_PER_USEC;
2505 		ext_arg->sig = u64_to_user_ptr(READ_ONCE(w->sigmask));
2506 		ext_arg->argsz = READ_ONCE(w->sigmask_sz);
2507 		if (w->flags & IORING_REG_WAIT_TS) {
2508 			ext_arg->ts.tv_sec = READ_ONCE(w->ts.tv_sec);
2509 			ext_arg->ts.tv_nsec = READ_ONCE(w->ts.tv_nsec);
2510 			ext_arg->ts_set = true;
2511 		}
2512 		return 0;
2513 	}
2514 
2515 	/*
2516 	 * EXT_ARG is set - ensure we agree on the size of it and copy in our
2517 	 * timespec and sigset_t pointers if good.
2518 	 */
2519 	if (ext_arg->argsz != sizeof(arg))
2520 		return -EINVAL;
2521 #ifdef CONFIG_64BIT
2522 	if (!user_access_begin(uarg, sizeof(*uarg)))
2523 		return -EFAULT;
2524 	unsafe_get_user(arg.sigmask, &uarg->sigmask, uaccess_end);
2525 	unsafe_get_user(arg.sigmask_sz, &uarg->sigmask_sz, uaccess_end);
2526 	unsafe_get_user(arg.min_wait_usec, &uarg->min_wait_usec, uaccess_end);
2527 	unsafe_get_user(arg.ts, &uarg->ts, uaccess_end);
2528 	user_access_end();
2529 #else
2530 	if (copy_from_user(&arg, uarg, sizeof(arg)))
2531 		return -EFAULT;
2532 #endif
2533 	ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC;
2534 	ext_arg->sig = u64_to_user_ptr(arg.sigmask);
2535 	ext_arg->argsz = arg.sigmask_sz;
2536 	if (arg.ts) {
2537 		if (get_timespec64(&ext_arg->ts, u64_to_user_ptr(arg.ts)))
2538 			return -EFAULT;
2539 		ext_arg->ts_set = true;
2540 	}
2541 	return 0;
2542 #ifdef CONFIG_64BIT
2543 uaccess_end:
2544 	user_access_end();
2545 	return -EFAULT;
2546 #endif
2547 }
2548 
2549 /*
2550  * Given an 'fd' value, return the ctx associated with if. If 'registered' is
2551  * true, then the registered index is used. Otherwise, the normal fd table.
2552  * Caller must call fput() on the returned file if it isn't a registered file,
2553  * unless it's an ERR_PTR.
2554  */
2555 struct file *io_uring_ctx_get_file(unsigned int fd, bool registered)
2556 {
2557 	struct file *file;
2558 
2559 	if (registered) {
2560 		/*
2561 		 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
2562 		 * need only dereference our task private array to find it.
2563 		 */
2564 		struct io_uring_task *tctx = current->io_uring;
2565 
2566 		if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
2567 			return ERR_PTR(-EINVAL);
2568 		fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
2569 		file = tctx->registered_rings[fd];
2570 	} else {
2571 		file = fget(fd);
2572 	}
2573 
2574 	if (unlikely(!file))
2575 		return ERR_PTR(-EBADF);
2576 	if (io_is_uring_fops(file))
2577 		return file;
2578 	fput(file);
2579 	return ERR_PTR(-EOPNOTSUPP);
2580 }
2581 
2582 
2583 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2584 		u32, min_complete, u32, flags, const void __user *, argp,
2585 		size_t, argsz)
2586 {
2587 	struct io_ring_ctx *ctx;
2588 	struct file *file;
2589 	long ret;
2590 
2591 	if (unlikely(flags & ~IORING_ENTER_FLAGS))
2592 		return -EINVAL;
2593 
2594 	file = io_uring_ctx_get_file(fd, flags & IORING_ENTER_REGISTERED_RING);
2595 	if (IS_ERR(file))
2596 		return PTR_ERR(file);
2597 	ctx = file->private_data;
2598 	ret = -EBADFD;
2599 	/*
2600 	 * Keep IORING_SETUP_R_DISABLED check before submitter_task load
2601 	 * in io_uring_add_tctx_node() -> __io_uring_add_tctx_node_from_submit()
2602 	 */
2603 	if (unlikely(smp_load_acquire(&ctx->flags) & IORING_SETUP_R_DISABLED))
2604 		goto out;
2605 
2606 	if (io_has_loop_ops(ctx)) {
2607 		ret = io_run_loop(ctx);
2608 		goto out;
2609 	}
2610 
2611 	/*
2612 	 * For SQ polling, the thread will do all submissions and completions.
2613 	 * Just return the requested submit count, and wake the thread if
2614 	 * we were asked to.
2615 	 */
2616 	ret = 0;
2617 	if (ctx->flags & IORING_SETUP_SQPOLL) {
2618 		if (unlikely(ctx->sq_data->thread == NULL)) {
2619 			ret = -EOWNERDEAD;
2620 			goto out;
2621 		}
2622 		if (flags & IORING_ENTER_SQ_WAKEUP)
2623 			wake_up(&ctx->sq_data->wait);
2624 		if (flags & IORING_ENTER_SQ_WAIT)
2625 			io_sqpoll_wait_sq(ctx);
2626 
2627 		ret = to_submit;
2628 	} else if (to_submit) {
2629 		ret = io_uring_add_tctx_node(ctx);
2630 		if (unlikely(ret))
2631 			goto out;
2632 
2633 		mutex_lock(&ctx->uring_lock);
2634 		ret = io_submit_sqes(ctx, to_submit);
2635 		if (ret != to_submit) {
2636 			mutex_unlock(&ctx->uring_lock);
2637 			goto out;
2638 		}
2639 		if (flags & IORING_ENTER_GETEVENTS) {
2640 			if (ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL)
2641 				goto iopoll_locked;
2642 			/*
2643 			 * Ignore errors, we'll soon call io_cqring_wait() and
2644 			 * it should handle ownership problems if any.
2645 			 */
2646 			if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2647 				(void)io_run_local_work_locked(ctx, min_complete);
2648 		}
2649 		mutex_unlock(&ctx->uring_lock);
2650 	}
2651 
2652 	if (flags & IORING_ENTER_GETEVENTS) {
2653 		int ret2;
2654 
2655 		if (ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL) {
2656 			/*
2657 			 * We disallow the app entering submit/complete with
2658 			 * polling, but we still need to lock the ring to
2659 			 * prevent racing with polled issue that got punted to
2660 			 * a workqueue.
2661 			 */
2662 			mutex_lock(&ctx->uring_lock);
2663 iopoll_locked:
2664 			ret2 = io_validate_ext_arg(ctx, flags, argp, argsz);
2665 			if (likely(!ret2))
2666 				ret2 = io_iopoll_check(ctx, min_complete);
2667 			mutex_unlock(&ctx->uring_lock);
2668 		} else {
2669 			struct ext_arg ext_arg = { .argsz = argsz };
2670 
2671 			ret2 = io_get_ext_arg(ctx, flags, argp, &ext_arg);
2672 			if (likely(!ret2))
2673 				ret2 = io_cqring_wait(ctx, min_complete, flags,
2674 						      &ext_arg);
2675 		}
2676 
2677 		if (!ret) {
2678 			ret = ret2;
2679 
2680 			/*
2681 			 * EBADR indicates that one or more CQE were dropped.
2682 			 * Once the user has been informed we can clear the bit
2683 			 * as they are obviously ok with those drops.
2684 			 */
2685 			if (unlikely(ret2 == -EBADR))
2686 				clear_bit(IO_CHECK_CQ_DROPPED_BIT,
2687 					  &ctx->check_cq);
2688 		}
2689 	}
2690 out:
2691 	if (!(flags & IORING_ENTER_REGISTERED_RING))
2692 		fput(file);
2693 	return ret;
2694 }
2695 
2696 static const struct file_operations io_uring_fops = {
2697 	.release	= io_uring_release,
2698 	.mmap		= io_uring_mmap,
2699 	.get_unmapped_area = io_uring_get_unmapped_area,
2700 #ifndef CONFIG_MMU
2701 	.mmap_capabilities = io_uring_nommu_mmap_capabilities,
2702 #endif
2703 	.poll		= io_uring_poll,
2704 #ifdef CONFIG_PROC_FS
2705 	.show_fdinfo	= io_uring_show_fdinfo,
2706 #endif
2707 };
2708 
2709 bool io_is_uring_fops(struct file *file)
2710 {
2711 	return file->f_op == &io_uring_fops;
2712 }
2713 
2714 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2715 					 struct io_ctx_config *config)
2716 {
2717 	struct io_uring_params *p = &config->p;
2718 	struct io_rings_layout *rl = &config->layout;
2719 	struct io_uring_region_desc rd;
2720 	struct io_rings *rings;
2721 	int ret;
2722 
2723 	/* make sure these are sane, as we already accounted them */
2724 	ctx->sq_entries = p->sq_entries;
2725 	ctx->cq_entries = p->cq_entries;
2726 
2727 	memset(&rd, 0, sizeof(rd));
2728 	rd.size = PAGE_ALIGN(rl->rings_size);
2729 	if (ctx->flags & IORING_SETUP_NO_MMAP) {
2730 		rd.user_addr = p->cq_off.user_addr;
2731 		rd.flags |= IORING_MEM_REGION_TYPE_USER;
2732 	}
2733 	ret = io_create_region(ctx, &ctx->ring_region, &rd, IORING_OFF_CQ_RING);
2734 	if (ret)
2735 		return ret;
2736 	ctx->rings = rings = io_region_get_ptr(&ctx->ring_region);
2737 	rcu_assign_pointer(ctx->rings_rcu, rings);
2738 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2739 		ctx->sq_array = (u32 *)((char *)rings + rl->sq_array_offset);
2740 
2741 	memset(&rd, 0, sizeof(rd));
2742 	rd.size = PAGE_ALIGN(rl->sq_size);
2743 	if (ctx->flags & IORING_SETUP_NO_MMAP) {
2744 		rd.user_addr = p->sq_off.user_addr;
2745 		rd.flags |= IORING_MEM_REGION_TYPE_USER;
2746 	}
2747 	ret = io_create_region(ctx, &ctx->sq_region, &rd, IORING_OFF_SQES);
2748 	if (ret) {
2749 		io_rings_free(ctx);
2750 		return ret;
2751 	}
2752 	ctx->sq_sqes = io_region_get_ptr(&ctx->sq_region);
2753 
2754 	memset(rings, 0, sizeof(*rings));
2755 	WRITE_ONCE(rings->sq_ring_mask, ctx->sq_entries - 1);
2756 	WRITE_ONCE(rings->cq_ring_mask, ctx->cq_entries - 1);
2757 	WRITE_ONCE(rings->sq_ring_entries, ctx->sq_entries);
2758 	WRITE_ONCE(rings->cq_ring_entries, ctx->cq_entries);
2759 	return 0;
2760 }
2761 
2762 static int io_uring_install_fd(struct file *file)
2763 {
2764 	int fd;
2765 
2766 	fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2767 	if (fd < 0)
2768 		return fd;
2769 	fd_install(fd, file);
2770 	return fd;
2771 }
2772 
2773 /*
2774  * Allocate an anonymous fd, this is what constitutes the application
2775  * visible backing of an io_uring instance. The application mmaps this
2776  * fd to gain access to the SQ/CQ ring details.
2777  */
2778 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
2779 {
2780 	/* Create a new inode so that the LSM can block the creation.  */
2781 	return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
2782 					 O_RDWR | O_CLOEXEC, NULL);
2783 }
2784 
2785 static int io_uring_sanitise_params(struct io_uring_params *p)
2786 {
2787 	unsigned flags = p->flags;
2788 
2789 	if (flags & ~IORING_SETUP_FLAGS)
2790 		return -EINVAL;
2791 
2792 	if (flags & IORING_SETUP_SQ_REWIND) {
2793 		if ((flags & IORING_SETUP_SQPOLL) ||
2794 		    !(flags & IORING_SETUP_NO_SQARRAY))
2795 			return -EINVAL;
2796 	}
2797 
2798 	/* There is no way to mmap rings without a real fd */
2799 	if ((flags & IORING_SETUP_REGISTERED_FD_ONLY) &&
2800 	    !(flags & IORING_SETUP_NO_MMAP))
2801 		return -EINVAL;
2802 
2803 	if (flags & IORING_SETUP_SQPOLL) {
2804 		/* IPI related flags don't make sense with SQPOLL */
2805 		if (flags & (IORING_SETUP_COOP_TASKRUN |
2806 			     IORING_SETUP_TASKRUN_FLAG |
2807 			     IORING_SETUP_DEFER_TASKRUN))
2808 			return -EINVAL;
2809 	}
2810 
2811 	if (flags & IORING_SETUP_TASKRUN_FLAG) {
2812 		if (!(flags & (IORING_SETUP_COOP_TASKRUN |
2813 			       IORING_SETUP_DEFER_TASKRUN)))
2814 			return -EINVAL;
2815 	}
2816 
2817 	/* HYBRID_IOPOLL only valid with IOPOLL */
2818 	if ((flags & IORING_SETUP_HYBRID_IOPOLL) && !(flags & IORING_SETUP_IOPOLL))
2819 		return -EINVAL;
2820 
2821 	/*
2822 	 * For DEFER_TASKRUN we require the completion task to be the same as
2823 	 * the submission task. This implies that there is only one submitter.
2824 	 */
2825 	if ((flags & IORING_SETUP_DEFER_TASKRUN) &&
2826 	    !(flags & IORING_SETUP_SINGLE_ISSUER))
2827 		return -EINVAL;
2828 
2829 	/*
2830 	 * Nonsensical to ask for CQE32 and mixed CQE support, it's not
2831 	 * supported to post 16b CQEs on a ring setup with CQE32.
2832 	 */
2833 	if ((flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)) ==
2834 	    (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED))
2835 		return -EINVAL;
2836 	/*
2837 	 * Nonsensical to ask for SQE128 and mixed SQE support, it's not
2838 	 * supported to post 64b SQEs on a ring setup with SQE128.
2839 	 */
2840 	if ((flags & (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED)) ==
2841 	    (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED))
2842 		return -EINVAL;
2843 
2844 	return 0;
2845 }
2846 
2847 static int io_uring_fill_params(struct io_uring_params *p)
2848 {
2849 	unsigned entries = p->sq_entries;
2850 
2851 	if (!entries)
2852 		return -EINVAL;
2853 	if (entries > IORING_MAX_ENTRIES) {
2854 		if (!(p->flags & IORING_SETUP_CLAMP))
2855 			return -EINVAL;
2856 		entries = IORING_MAX_ENTRIES;
2857 	}
2858 
2859 	/*
2860 	 * Use twice as many entries for the CQ ring. It's possible for the
2861 	 * application to drive a higher depth than the size of the SQ ring,
2862 	 * since the sqes are only used at submission time. This allows for
2863 	 * some flexibility in overcommitting a bit. If the application has
2864 	 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
2865 	 * of CQ ring entries manually.
2866 	 */
2867 	p->sq_entries = roundup_pow_of_two(entries);
2868 	if (p->flags & IORING_SETUP_CQSIZE) {
2869 		/*
2870 		 * If IORING_SETUP_CQSIZE is set, we do the same roundup
2871 		 * to a power-of-two, if it isn't already. We do NOT impose
2872 		 * any cq vs sq ring sizing.
2873 		 */
2874 		if (!p->cq_entries)
2875 			return -EINVAL;
2876 		if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
2877 			if (!(p->flags & IORING_SETUP_CLAMP))
2878 				return -EINVAL;
2879 			p->cq_entries = IORING_MAX_CQ_ENTRIES;
2880 		}
2881 		p->cq_entries = roundup_pow_of_two(p->cq_entries);
2882 		if (p->cq_entries < p->sq_entries)
2883 			return -EINVAL;
2884 	} else {
2885 		p->cq_entries = 2 * p->sq_entries;
2886 	}
2887 
2888 	return 0;
2889 }
2890 
2891 int io_prepare_config(struct io_ctx_config *config)
2892 {
2893 	struct io_uring_params *p = &config->p;
2894 	int ret;
2895 
2896 	ret = io_uring_sanitise_params(p);
2897 	if (ret)
2898 		return ret;
2899 
2900 	ret = io_uring_fill_params(p);
2901 	if (ret)
2902 		return ret;
2903 
2904 	ret = rings_size(p->flags, p->sq_entries, p->cq_entries,
2905 			 &config->layout);
2906 	if (ret)
2907 		return ret;
2908 
2909 	p->sq_off.head = offsetof(struct io_rings, sq.head);
2910 	p->sq_off.tail = offsetof(struct io_rings, sq.tail);
2911 	p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
2912 	p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
2913 	p->sq_off.flags = offsetof(struct io_rings, sq_flags);
2914 	p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
2915 	p->sq_off.resv1 = 0;
2916 	if (!(p->flags & IORING_SETUP_NO_MMAP))
2917 		p->sq_off.user_addr = 0;
2918 
2919 	p->cq_off.head = offsetof(struct io_rings, cq.head);
2920 	p->cq_off.tail = offsetof(struct io_rings, cq.tail);
2921 	p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
2922 	p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
2923 	p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
2924 	p->cq_off.cqes = offsetof(struct io_rings, cqes);
2925 	p->cq_off.flags = offsetof(struct io_rings, cq_flags);
2926 	p->cq_off.resv1 = 0;
2927 	if (!(p->flags & IORING_SETUP_NO_MMAP))
2928 		p->cq_off.user_addr = 0;
2929 	if (!(p->flags & IORING_SETUP_NO_SQARRAY))
2930 		p->sq_off.array = config->layout.sq_array_offset;
2931 
2932 	return 0;
2933 }
2934 
2935 void io_restriction_clone(struct io_restriction *dst, struct io_restriction *src)
2936 {
2937 	memcpy(&dst->register_op, &src->register_op, sizeof(dst->register_op));
2938 	memcpy(&dst->sqe_op, &src->sqe_op, sizeof(dst->sqe_op));
2939 	dst->sqe_flags_allowed = src->sqe_flags_allowed;
2940 	dst->sqe_flags_required = src->sqe_flags_required;
2941 	dst->op_registered = src->op_registered;
2942 	dst->reg_registered = src->reg_registered;
2943 
2944 	io_bpf_filter_clone(dst, src);
2945 }
2946 
2947 static void io_ctx_restriction_clone(struct io_ring_ctx *ctx,
2948 				     struct io_restriction *src)
2949 {
2950 	struct io_restriction *dst = &ctx->restrictions;
2951 
2952 	io_restriction_clone(dst, src);
2953 	if (dst->bpf_filters)
2954 		WRITE_ONCE(ctx->bpf_filters, dst->bpf_filters->filters);
2955 	if (dst->op_registered)
2956 		ctx->int_flags |= IO_RING_F_OP_RESTRICTED;
2957 	if (dst->reg_registered)
2958 		ctx->int_flags |= IO_RING_F_REG_RESTRICTED;
2959 }
2960 
2961 static __cold int io_uring_create(struct io_ctx_config *config)
2962 {
2963 	struct io_uring_params *p = &config->p;
2964 	struct io_ring_ctx *ctx;
2965 	struct io_uring_task *tctx;
2966 	struct file *file;
2967 	int ret;
2968 
2969 	ret = io_prepare_config(config);
2970 	if (ret)
2971 		return ret;
2972 
2973 	ctx = io_ring_ctx_alloc(p);
2974 	if (!ctx)
2975 		return -ENOMEM;
2976 
2977 	ctx->clockid = CLOCK_MONOTONIC;
2978 	ctx->clock_offset = 0;
2979 
2980 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2981 		static_branch_deferred_inc(&io_key_has_sqarray);
2982 
2983 	if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
2984 	    !(ctx->flags & IORING_SETUP_IOPOLL))
2985 		ctx->int_flags |= IO_RING_F_TASK_COMPLETE;
2986 
2987 	if ((ctx->int_flags & IO_RING_F_TASK_COMPLETE) ||
2988 	    (ctx->flags & IORING_SETUP_IOPOLL))
2989 		ctx->int_flags |= IO_RING_F_LOCKLESS_CQ;
2990 
2991 	/*
2992 	 * lazy poll_wq activation relies on ->task_complete for synchronisation
2993 	 * purposes, see io_activate_pollwq()
2994 	 */
2995 	if (!(ctx->int_flags & IO_RING_F_TASK_COMPLETE))
2996 		ctx->int_flags |= IO_RING_F_POLL_ACTIVATED;
2997 
2998 	/*
2999 	 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3000 	 * space applications don't need to do io completion events
3001 	 * polling again, they can rely on io_sq_thread to do polling
3002 	 * work, which can reduce cpu usage and uring_lock contention.
3003 	 */
3004 	if (ctx->flags & IORING_SETUP_IOPOLL &&
3005 	    !(ctx->flags & IORING_SETUP_SQPOLL))
3006 		ctx->int_flags |= IO_RING_F_SYSCALL_IOPOLL;
3007 
3008 	if (in_compat_syscall())
3009 		ctx->int_flags |= IO_RING_F_COMPAT;
3010 	if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3011 		ctx->user = get_uid(current_user());
3012 
3013 	/*
3014 	 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3015 	 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3016 	 */
3017 	if (ctx->flags & (IORING_SETUP_SQPOLL|IORING_SETUP_COOP_TASKRUN))
3018 		ctx->notify_method = TWA_SIGNAL_NO_IPI;
3019 	else
3020 		ctx->notify_method = TWA_SIGNAL;
3021 
3022 	/*
3023 	 * If the current task has restrictions enabled, then copy them to
3024 	 * our newly created ring and mark it as registered.
3025 	 */
3026 	if (current->io_uring_restrict)
3027 		io_ctx_restriction_clone(ctx, current->io_uring_restrict);
3028 
3029 	/*
3030 	 * This is just grabbed for accounting purposes. When a process exits,
3031 	 * the mm is exited and dropped before the files, hence we need to hang
3032 	 * on to this mm purely for the purposes of being able to unaccount
3033 	 * memory (locked/pinned vm). It's not used for anything else.
3034 	 */
3035 	mmgrab(current->mm);
3036 	ctx->mm_account = current->mm;
3037 
3038 	ret = io_allocate_scq_urings(ctx, config);
3039 	if (ret)
3040 		goto err;
3041 
3042 	ret = io_sq_offload_create(ctx, p);
3043 	if (ret)
3044 		goto err;
3045 
3046 	p->features = IORING_FEAT_FLAGS;
3047 
3048 	if (copy_to_user(config->uptr, p, sizeof(*p))) {
3049 		ret = -EFAULT;
3050 		goto err;
3051 	}
3052 
3053 	if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
3054 	    && !(ctx->flags & IORING_SETUP_R_DISABLED))
3055 		ctx->submitter_task = get_task_struct(current);
3056 
3057 	file = io_uring_get_file(ctx);
3058 	if (IS_ERR(file)) {
3059 		ret = PTR_ERR(file);
3060 		goto err;
3061 	}
3062 
3063 	ret = __io_uring_add_tctx_node(ctx);
3064 	if (ret)
3065 		goto err_fput;
3066 	tctx = current->io_uring;
3067 
3068 	/*
3069 	 * Install ring fd as the very last thing, so we don't risk someone
3070 	 * having closed it before we finish setup
3071 	 */
3072 	if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3073 		ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
3074 	else
3075 		ret = io_uring_install_fd(file);
3076 	if (ret < 0)
3077 		goto err_fput;
3078 
3079 	trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3080 	return ret;
3081 err:
3082 	io_ring_ctx_wait_and_kill(ctx);
3083 	return ret;
3084 err_fput:
3085 	fput(file);
3086 	return ret;
3087 }
3088 
3089 /*
3090  * Sets up an aio uring context, and returns the fd. Applications asks for a
3091  * ring size, we return the actual sq/cq ring sizes (among other things) in the
3092  * params structure passed in.
3093  */
3094 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3095 {
3096 	struct io_ctx_config config;
3097 
3098 	memset(&config, 0, sizeof(config));
3099 
3100 	if (copy_from_user(&config.p, params, sizeof(config.p)))
3101 		return -EFAULT;
3102 
3103 	if (!mem_is_zero(&config.p.resv, sizeof(config.p.resv)))
3104 		return -EINVAL;
3105 
3106 	config.p.sq_entries = entries;
3107 	config.uptr = params;
3108 	return io_uring_create(&config);
3109 }
3110 
3111 static inline int io_uring_allowed(void)
3112 {
3113 	int disabled = READ_ONCE(sysctl_io_uring_disabled);
3114 	kgid_t io_uring_group;
3115 
3116 	if (disabled == 2)
3117 		return -EPERM;
3118 
3119 	if (disabled == 0 || capable(CAP_SYS_ADMIN))
3120 		goto allowed_lsm;
3121 
3122 	io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
3123 	if (!gid_valid(io_uring_group))
3124 		return -EPERM;
3125 
3126 	if (!in_group_p(io_uring_group))
3127 		return -EPERM;
3128 
3129 allowed_lsm:
3130 	return security_uring_allowed();
3131 }
3132 
3133 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3134 		struct io_uring_params __user *, params)
3135 {
3136 	int ret;
3137 
3138 	ret = io_uring_allowed();
3139 	if (ret)
3140 		return ret;
3141 
3142 	return io_uring_setup(entries, params);
3143 }
3144 
3145 static int __init io_uring_init(void)
3146 {
3147 	struct kmem_cache_args kmem_args = {
3148 		.useroffset = offsetof(struct io_kiocb, cmd.data),
3149 		.usersize = sizeof_field(struct io_kiocb, cmd.data),
3150 		.freeptr_offset = offsetof(struct io_kiocb, work),
3151 		.use_freeptr_offset = true,
3152 	};
3153 
3154 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
3155 	BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
3156 	BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
3157 } while (0)
3158 
3159 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
3160 	__BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
3161 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
3162 	__BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
3163 	BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
3164 	BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
3165 	BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
3166 	BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
3167 	BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
3168 	BUILD_BUG_SQE_ELEM(8,  __u64,  off);
3169 	BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
3170 	BUILD_BUG_SQE_ELEM(8,  __u32,  cmd_op);
3171 	BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
3172 	BUILD_BUG_SQE_ELEM(16, __u64,  addr);
3173 	BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
3174 	BUILD_BUG_SQE_ELEM(24, __u32,  len);
3175 	BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
3176 	BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
3177 	BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
3178 	BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
3179 	BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
3180 	BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
3181 	BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
3182 	BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
3183 	BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
3184 	BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
3185 	BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
3186 	BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
3187 	BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
3188 	BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
3189 	BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
3190 	BUILD_BUG_SQE_ELEM(28, __u32,  rename_flags);
3191 	BUILD_BUG_SQE_ELEM(28, __u32,  unlink_flags);
3192 	BUILD_BUG_SQE_ELEM(28, __u32,  hardlink_flags);
3193 	BUILD_BUG_SQE_ELEM(28, __u32,  xattr_flags);
3194 	BUILD_BUG_SQE_ELEM(28, __u32,  msg_ring_flags);
3195 	BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
3196 	BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
3197 	BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
3198 	BUILD_BUG_SQE_ELEM(42, __u16,  personality);
3199 	BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
3200 	BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
3201 	BUILD_BUG_SQE_ELEM(44, __u16,  addr_len);
3202 	BUILD_BUG_SQE_ELEM(44, __u8,   write_stream);
3203 	BUILD_BUG_SQE_ELEM(45, __u8,   __pad4[0]);
3204 	BUILD_BUG_SQE_ELEM(46, __u16,  __pad3[0]);
3205 	BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
3206 	BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
3207 	BUILD_BUG_SQE_ELEM(48, __u64, attr_ptr);
3208 	BUILD_BUG_SQE_ELEM(56, __u64, attr_type_mask);
3209 	BUILD_BUG_SQE_ELEM(56, __u64,  __pad2);
3210 
3211 	BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3212 		     sizeof(struct io_uring_rsrc_update));
3213 	BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3214 		     sizeof(struct io_uring_rsrc_update2));
3215 
3216 	/* ->buf_index is u16 */
3217 	BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3218 	BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3219 		     offsetof(struct io_uring_buf_ring, tail));
3220 
3221 	/* should fit into one byte */
3222 	BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
3223 	BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
3224 	BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
3225 
3226 	BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
3227 
3228 	BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
3229 
3230 	/* top 8bits are for internal use */
3231 	BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
3232 
3233 	io_uring_optable_init();
3234 
3235 	/* imu->dir is u8 */
3236 	BUILD_BUG_ON((IO_IMU_DEST | IO_IMU_SOURCE) > U8_MAX);
3237 
3238 	/*
3239 	 * Allow user copy in the per-command field, which starts after the
3240 	 * file in io_kiocb and until the opcode field. The openat2 handling
3241 	 * requires copying in user memory into the io_kiocb object in that
3242 	 * range, and HARDENED_USERCOPY will complain if we haven't
3243 	 * correctly annotated this range.
3244 	 */
3245 	req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
3246 				SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
3247 				SLAB_TYPESAFE_BY_RCU);
3248 
3249 	iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
3250 	BUG_ON(!iou_wq);
3251 
3252 #ifdef CONFIG_SYSCTL
3253 	register_sysctl_init("kernel", kernel_io_uring_disabled_table);
3254 #endif
3255 
3256 	return 0;
3257 };
3258 __initcall(io_uring_init);
3259