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