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