xref: /linux/io_uring/io_uring.c (revision 3186a8e55ae3428ec1e06af09075e20885376e4e)
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 	u32			seq;
133 };
134 
135 /* requests with any of those set should undergo io_disarm_next() */
136 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
137 
138 /*
139  * No waiters. It's larger than any valid value of the tw counter
140  * so that tests against ->cq_wait_nr would fail and skip wake_up().
141  */
142 #define IO_CQ_WAKE_INIT		(-1U)
143 /* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
144 #define IO_CQ_WAKE_FORCE	(IO_CQ_WAKE_INIT >> 1)
145 
146 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
147 					 struct io_uring_task *tctx,
148 					 bool cancel_all,
149 					 bool is_sqpoll_thread);
150 
151 static void io_queue_sqe(struct io_kiocb *req);
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 #ifdef CONFIG_FUTEX
363 	INIT_HLIST_HEAD(&ctx->futex_list);
364 #endif
365 	INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
366 	INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
367 	INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
368 	io_napi_init(ctx);
369 	mutex_init(&ctx->mmap_lock);
370 
371 	return ctx;
372 
373 free_ref:
374 	percpu_ref_exit(&ctx->refs);
375 err:
376 	io_free_alloc_caches(ctx);
377 	kvfree(ctx->cancel_table.hbs);
378 	xa_destroy(&ctx->io_bl_xa);
379 	kfree(ctx);
380 	return NULL;
381 }
382 
383 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
384 {
385 	struct io_rings *r = ctx->rings;
386 
387 	WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
388 	ctx->cq_extra--;
389 }
390 
391 static bool req_need_defer(struct io_kiocb *req, u32 seq)
392 {
393 	if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
394 		struct io_ring_ctx *ctx = req->ctx;
395 
396 		return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
397 	}
398 
399 	return false;
400 }
401 
402 static void io_clean_op(struct io_kiocb *req)
403 {
404 	if (unlikely(req->flags & REQ_F_BUFFER_SELECTED))
405 		io_kbuf_drop_legacy(req);
406 
407 	if (req->flags & REQ_F_NEED_CLEANUP) {
408 		const struct io_cold_def *def = &io_cold_defs[req->opcode];
409 
410 		if (def->cleanup)
411 			def->cleanup(req);
412 	}
413 	if ((req->flags & REQ_F_POLLED) && req->apoll) {
414 		kfree(req->apoll->double_poll);
415 		kfree(req->apoll);
416 		req->apoll = NULL;
417 	}
418 	if (req->flags & REQ_F_INFLIGHT)
419 		atomic_dec(&req->tctx->inflight_tracked);
420 	if (req->flags & REQ_F_CREDS)
421 		put_cred(req->creds);
422 	if (req->flags & REQ_F_ASYNC_DATA) {
423 		kfree(req->async_data);
424 		req->async_data = NULL;
425 	}
426 	req->flags &= ~IO_REQ_CLEAN_FLAGS;
427 }
428 
429 static inline void io_req_track_inflight(struct io_kiocb *req)
430 {
431 	if (!(req->flags & REQ_F_INFLIGHT)) {
432 		req->flags |= REQ_F_INFLIGHT;
433 		atomic_inc(&req->tctx->inflight_tracked);
434 	}
435 }
436 
437 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
438 {
439 	if (WARN_ON_ONCE(!req->link))
440 		return NULL;
441 
442 	req->flags &= ~REQ_F_ARM_LTIMEOUT;
443 	req->flags |= REQ_F_LINK_TIMEOUT;
444 
445 	/* linked timeouts should have two refs once prep'ed */
446 	io_req_set_refcount(req);
447 	__io_req_set_refcount(req->link, 2);
448 	return req->link;
449 }
450 
451 static void io_prep_async_work(struct io_kiocb *req)
452 {
453 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
454 	struct io_ring_ctx *ctx = req->ctx;
455 
456 	if (!(req->flags & REQ_F_CREDS)) {
457 		req->flags |= REQ_F_CREDS;
458 		req->creds = get_current_cred();
459 	}
460 
461 	req->work.list.next = NULL;
462 	atomic_set(&req->work.flags, 0);
463 	if (req->flags & REQ_F_FORCE_ASYNC)
464 		atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
465 
466 	if (req->file && !(req->flags & REQ_F_FIXED_FILE))
467 		req->flags |= io_file_get_flags(req->file);
468 
469 	if (req->file && (req->flags & REQ_F_ISREG)) {
470 		bool should_hash = def->hash_reg_file;
471 
472 		/* don't serialize this request if the fs doesn't need it */
473 		if (should_hash && (req->file->f_flags & O_DIRECT) &&
474 		    (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
475 			should_hash = false;
476 		if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
477 			io_wq_hash_work(&req->work, file_inode(req->file));
478 	} else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
479 		if (def->unbound_nonreg_file)
480 			atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
481 	}
482 }
483 
484 static void io_prep_async_link(struct io_kiocb *req)
485 {
486 	struct io_kiocb *cur;
487 
488 	if (req->flags & REQ_F_LINK_TIMEOUT) {
489 		struct io_ring_ctx *ctx = req->ctx;
490 
491 		raw_spin_lock_irq(&ctx->timeout_lock);
492 		io_for_each_link(cur, req)
493 			io_prep_async_work(cur);
494 		raw_spin_unlock_irq(&ctx->timeout_lock);
495 	} else {
496 		io_for_each_link(cur, req)
497 			io_prep_async_work(cur);
498 	}
499 }
500 
501 static void io_queue_iowq(struct io_kiocb *req)
502 {
503 	struct io_uring_task *tctx = req->tctx;
504 
505 	BUG_ON(!tctx);
506 
507 	if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
508 		io_req_task_queue_fail(req, -ECANCELED);
509 		return;
510 	}
511 
512 	/* init ->work of the whole link before punting */
513 	io_prep_async_link(req);
514 
515 	/*
516 	 * Not expected to happen, but if we do have a bug where this _can_
517 	 * happen, catch it here and ensure the request is marked as
518 	 * canceled. That will make io-wq go through the usual work cancel
519 	 * procedure rather than attempt to run this request (or create a new
520 	 * worker for it).
521 	 */
522 	if (WARN_ON_ONCE(!same_thread_group(tctx->task, current)))
523 		atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
524 
525 	trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
526 	io_wq_enqueue(tctx->io_wq, &req->work);
527 }
528 
529 static void io_req_queue_iowq_tw(struct io_kiocb *req, io_tw_token_t tw)
530 {
531 	io_queue_iowq(req);
532 }
533 
534 void io_req_queue_iowq(struct io_kiocb *req)
535 {
536 	req->io_task_work.func = io_req_queue_iowq_tw;
537 	io_req_task_work_add(req);
538 }
539 
540 static __cold noinline void io_queue_deferred(struct io_ring_ctx *ctx)
541 {
542 	spin_lock(&ctx->completion_lock);
543 	while (!list_empty(&ctx->defer_list)) {
544 		struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
545 						struct io_defer_entry, list);
546 
547 		if (req_need_defer(de->req, de->seq))
548 			break;
549 		list_del_init(&de->list);
550 		io_req_task_queue(de->req);
551 		kfree(de);
552 	}
553 	spin_unlock(&ctx->completion_lock);
554 }
555 
556 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
557 {
558 	if (ctx->poll_activated)
559 		io_poll_wq_wake(ctx);
560 	if (ctx->off_timeout_used)
561 		io_flush_timeouts(ctx);
562 	if (ctx->drain_active)
563 		io_queue_deferred(ctx);
564 	if (ctx->has_evfd)
565 		io_eventfd_flush_signal(ctx);
566 }
567 
568 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
569 {
570 	if (!ctx->lockless_cq)
571 		spin_lock(&ctx->completion_lock);
572 }
573 
574 static inline void io_cq_lock(struct io_ring_ctx *ctx)
575 	__acquires(ctx->completion_lock)
576 {
577 	spin_lock(&ctx->completion_lock);
578 }
579 
580 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
581 {
582 	io_commit_cqring(ctx);
583 	if (!ctx->task_complete) {
584 		if (!ctx->lockless_cq)
585 			spin_unlock(&ctx->completion_lock);
586 		/* IOPOLL rings only need to wake up if it's also SQPOLL */
587 		if (!ctx->syscall_iopoll)
588 			io_cqring_wake(ctx);
589 	}
590 	io_commit_cqring_flush(ctx);
591 }
592 
593 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
594 	__releases(ctx->completion_lock)
595 {
596 	io_commit_cqring(ctx);
597 	spin_unlock(&ctx->completion_lock);
598 	io_cqring_wake(ctx);
599 	io_commit_cqring_flush(ctx);
600 }
601 
602 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
603 {
604 	size_t cqe_size = sizeof(struct io_uring_cqe);
605 
606 	lockdep_assert_held(&ctx->uring_lock);
607 
608 	/* don't abort if we're dying, entries must get freed */
609 	if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
610 		return;
611 
612 	if (ctx->flags & IORING_SETUP_CQE32)
613 		cqe_size <<= 1;
614 
615 	io_cq_lock(ctx);
616 	while (!list_empty(&ctx->cq_overflow_list)) {
617 		struct io_uring_cqe *cqe;
618 		struct io_overflow_cqe *ocqe;
619 
620 		ocqe = list_first_entry(&ctx->cq_overflow_list,
621 					struct io_overflow_cqe, list);
622 
623 		if (!dying) {
624 			if (!io_get_cqe_overflow(ctx, &cqe, true))
625 				break;
626 			memcpy(cqe, &ocqe->cqe, cqe_size);
627 		}
628 		list_del(&ocqe->list);
629 		kfree(ocqe);
630 
631 		/*
632 		 * For silly syzbot cases that deliberately overflow by huge
633 		 * amounts, check if we need to resched and drop and
634 		 * reacquire the locks if so. Nothing real would ever hit this.
635 		 * Ideally we'd have a non-posting unlock for this, but hard
636 		 * to care for a non-real case.
637 		 */
638 		if (need_resched()) {
639 			io_cq_unlock_post(ctx);
640 			mutex_unlock(&ctx->uring_lock);
641 			cond_resched();
642 			mutex_lock(&ctx->uring_lock);
643 			io_cq_lock(ctx);
644 		}
645 	}
646 
647 	if (list_empty(&ctx->cq_overflow_list)) {
648 		clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
649 		atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
650 	}
651 	io_cq_unlock_post(ctx);
652 }
653 
654 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
655 {
656 	if (ctx->rings)
657 		__io_cqring_overflow_flush(ctx, true);
658 }
659 
660 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
661 {
662 	mutex_lock(&ctx->uring_lock);
663 	__io_cqring_overflow_flush(ctx, false);
664 	mutex_unlock(&ctx->uring_lock);
665 }
666 
667 /* must to be called somewhat shortly after putting a request */
668 static inline void io_put_task(struct io_kiocb *req)
669 {
670 	struct io_uring_task *tctx = req->tctx;
671 
672 	if (likely(tctx->task == current)) {
673 		tctx->cached_refs++;
674 	} else {
675 		percpu_counter_sub(&tctx->inflight, 1);
676 		if (unlikely(atomic_read(&tctx->in_cancel)))
677 			wake_up(&tctx->wait);
678 		put_task_struct(tctx->task);
679 	}
680 }
681 
682 void io_task_refs_refill(struct io_uring_task *tctx)
683 {
684 	unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
685 
686 	percpu_counter_add(&tctx->inflight, refill);
687 	refcount_add(refill, &current->usage);
688 	tctx->cached_refs += refill;
689 }
690 
691 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
692 {
693 	struct io_uring_task *tctx = task->io_uring;
694 	unsigned int refs = tctx->cached_refs;
695 
696 	if (refs) {
697 		tctx->cached_refs = 0;
698 		percpu_counter_sub(&tctx->inflight, refs);
699 		put_task_struct_many(task, refs);
700 	}
701 }
702 
703 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
704 				     s32 res, u32 cflags, u64 extra1, u64 extra2)
705 {
706 	struct io_overflow_cqe *ocqe;
707 	size_t ocq_size = sizeof(struct io_overflow_cqe);
708 	bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
709 
710 	lockdep_assert_held(&ctx->completion_lock);
711 
712 	if (is_cqe32)
713 		ocq_size += sizeof(struct io_uring_cqe);
714 
715 	ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
716 	trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
717 	if (!ocqe) {
718 		/*
719 		 * If we're in ring overflow flush mode, or in task cancel mode,
720 		 * or cannot allocate an overflow entry, then we need to drop it
721 		 * on the floor.
722 		 */
723 		io_account_cq_overflow(ctx);
724 		set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
725 		return false;
726 	}
727 	if (list_empty(&ctx->cq_overflow_list)) {
728 		set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
729 		atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
730 
731 	}
732 	ocqe->cqe.user_data = user_data;
733 	ocqe->cqe.res = res;
734 	ocqe->cqe.flags = cflags;
735 	if (is_cqe32) {
736 		ocqe->cqe.big_cqe[0] = extra1;
737 		ocqe->cqe.big_cqe[1] = extra2;
738 	}
739 	list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
740 	return true;
741 }
742 
743 static void io_req_cqe_overflow(struct io_kiocb *req)
744 {
745 	io_cqring_event_overflow(req->ctx, req->cqe.user_data,
746 				req->cqe.res, req->cqe.flags,
747 				req->big_cqe.extra1, req->big_cqe.extra2);
748 	memset(&req->big_cqe, 0, sizeof(req->big_cqe));
749 }
750 
751 /*
752  * writes to the cq entry need to come after reading head; the
753  * control dependency is enough as we're using WRITE_ONCE to
754  * fill the cq entry
755  */
756 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
757 {
758 	struct io_rings *rings = ctx->rings;
759 	unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
760 	unsigned int free, queued, len;
761 
762 	/*
763 	 * Posting into the CQ when there are pending overflowed CQEs may break
764 	 * ordering guarantees, which will affect links, F_MORE users and more.
765 	 * Force overflow the completion.
766 	 */
767 	if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
768 		return false;
769 
770 	/* userspace may cheat modifying the tail, be safe and do min */
771 	queued = min(__io_cqring_events(ctx), ctx->cq_entries);
772 	free = ctx->cq_entries - queued;
773 	/* we need a contiguous range, limit based on the current array offset */
774 	len = min(free, ctx->cq_entries - off);
775 	if (!len)
776 		return false;
777 
778 	if (ctx->flags & IORING_SETUP_CQE32) {
779 		off <<= 1;
780 		len <<= 1;
781 	}
782 
783 	ctx->cqe_cached = &rings->cqes[off];
784 	ctx->cqe_sentinel = ctx->cqe_cached + len;
785 	return true;
786 }
787 
788 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
789 			      u32 cflags)
790 {
791 	struct io_uring_cqe *cqe;
792 
793 	ctx->cq_extra++;
794 
795 	/*
796 	 * If we can't get a cq entry, userspace overflowed the
797 	 * submission (by quite a lot). Increment the overflow count in
798 	 * the ring.
799 	 */
800 	if (likely(io_get_cqe(ctx, &cqe))) {
801 		WRITE_ONCE(cqe->user_data, user_data);
802 		WRITE_ONCE(cqe->res, res);
803 		WRITE_ONCE(cqe->flags, cflags);
804 
805 		if (ctx->flags & IORING_SETUP_CQE32) {
806 			WRITE_ONCE(cqe->big_cqe[0], 0);
807 			WRITE_ONCE(cqe->big_cqe[1], 0);
808 		}
809 
810 		trace_io_uring_complete(ctx, NULL, cqe);
811 		return true;
812 	}
813 	return false;
814 }
815 
816 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
817 {
818 	bool filled;
819 
820 	io_cq_lock(ctx);
821 	filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
822 	if (!filled)
823 		filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
824 	io_cq_unlock_post(ctx);
825 	return filled;
826 }
827 
828 /*
829  * Must be called from inline task_work so we now a flush will happen later,
830  * and obviously with ctx->uring_lock held (tw always has that).
831  */
832 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
833 {
834 	if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
835 		spin_lock(&ctx->completion_lock);
836 		io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
837 		spin_unlock(&ctx->completion_lock);
838 	}
839 	ctx->submit_state.cq_flush = true;
840 }
841 
842 /*
843  * A helper for multishot requests posting additional CQEs.
844  * Should only be used from a task_work including IO_URING_F_MULTISHOT.
845  */
846 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
847 {
848 	struct io_ring_ctx *ctx = req->ctx;
849 	bool posted;
850 
851 	/*
852 	 * If multishot has already posted deferred completions, ensure that
853 	 * those are flushed first before posting this one. If not, CQEs
854 	 * could get reordered.
855 	 */
856 	if (!wq_list_empty(&ctx->submit_state.compl_reqs))
857 		__io_submit_flush_completions(ctx);
858 
859 	lockdep_assert(!io_wq_current_is_worker());
860 	lockdep_assert_held(&ctx->uring_lock);
861 
862 	if (!ctx->lockless_cq) {
863 		spin_lock(&ctx->completion_lock);
864 		posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
865 		spin_unlock(&ctx->completion_lock);
866 	} else {
867 		posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
868 	}
869 
870 	ctx->submit_state.cq_flush = true;
871 	return posted;
872 }
873 
874 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
875 {
876 	struct io_ring_ctx *ctx = req->ctx;
877 	bool completed = true;
878 
879 	/*
880 	 * All execution paths but io-wq use the deferred completions by
881 	 * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
882 	 */
883 	if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
884 		return;
885 
886 	/*
887 	 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
888 	 * the submitter task context, IOPOLL protects with uring_lock.
889 	 */
890 	if (ctx->lockless_cq || (req->flags & REQ_F_REISSUE)) {
891 defer_complete:
892 		req->io_task_work.func = io_req_task_complete;
893 		io_req_task_work_add(req);
894 		return;
895 	}
896 
897 	io_cq_lock(ctx);
898 	if (!(req->flags & REQ_F_CQE_SKIP))
899 		completed = io_fill_cqe_req(ctx, req);
900 	io_cq_unlock_post(ctx);
901 
902 	if (!completed)
903 		goto defer_complete;
904 
905 	/*
906 	 * We don't free the request here because we know it's called from
907 	 * io-wq only, which holds a reference, so it cannot be the last put.
908 	 */
909 	req_ref_put(req);
910 }
911 
912 void io_req_defer_failed(struct io_kiocb *req, s32 res)
913 	__must_hold(&ctx->uring_lock)
914 {
915 	const struct io_cold_def *def = &io_cold_defs[req->opcode];
916 
917 	lockdep_assert_held(&req->ctx->uring_lock);
918 
919 	req_set_fail(req);
920 	io_req_set_res(req, res, io_put_kbuf(req, res, IO_URING_F_UNLOCKED));
921 	if (def->fail)
922 		def->fail(req);
923 	io_req_complete_defer(req);
924 }
925 
926 /*
927  * Don't initialise the fields below on every allocation, but do that in
928  * advance and keep them valid across allocations.
929  */
930 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
931 {
932 	req->ctx = ctx;
933 	req->buf_node = NULL;
934 	req->file_node = NULL;
935 	req->link = NULL;
936 	req->async_data = NULL;
937 	/* not necessary, but safer to zero */
938 	memset(&req->cqe, 0, sizeof(req->cqe));
939 	memset(&req->big_cqe, 0, sizeof(req->big_cqe));
940 }
941 
942 /*
943  * A request might get retired back into the request caches even before opcode
944  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
945  * Because of that, io_alloc_req() should be called only under ->uring_lock
946  * and with extra caution to not get a request that is still worked on.
947  */
948 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
949 	__must_hold(&ctx->uring_lock)
950 {
951 	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
952 	void *reqs[IO_REQ_ALLOC_BATCH];
953 	int ret;
954 
955 	ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
956 
957 	/*
958 	 * Bulk alloc is all-or-nothing. If we fail to get a batch,
959 	 * retry single alloc to be on the safe side.
960 	 */
961 	if (unlikely(ret <= 0)) {
962 		reqs[0] = kmem_cache_alloc(req_cachep, gfp);
963 		if (!reqs[0])
964 			return false;
965 		ret = 1;
966 	}
967 
968 	percpu_ref_get_many(&ctx->refs, ret);
969 	while (ret--) {
970 		struct io_kiocb *req = reqs[ret];
971 
972 		io_preinit_req(req, ctx);
973 		io_req_add_to_cache(req, ctx);
974 	}
975 	return true;
976 }
977 
978 __cold void io_free_req(struct io_kiocb *req)
979 {
980 	/* refs were already put, restore them for io_req_task_complete() */
981 	req->flags &= ~REQ_F_REFCOUNT;
982 	/* we only want to free it, don't post CQEs */
983 	req->flags |= REQ_F_CQE_SKIP;
984 	req->io_task_work.func = io_req_task_complete;
985 	io_req_task_work_add(req);
986 }
987 
988 static void __io_req_find_next_prep(struct io_kiocb *req)
989 {
990 	struct io_ring_ctx *ctx = req->ctx;
991 
992 	spin_lock(&ctx->completion_lock);
993 	io_disarm_next(req);
994 	spin_unlock(&ctx->completion_lock);
995 }
996 
997 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
998 {
999 	struct io_kiocb *nxt;
1000 
1001 	/*
1002 	 * If LINK is set, we have dependent requests in this chain. If we
1003 	 * didn't fail this request, queue the first one up, moving any other
1004 	 * dependencies to the next request. In case of failure, fail the rest
1005 	 * of the chain.
1006 	 */
1007 	if (unlikely(req->flags & IO_DISARM_MASK))
1008 		__io_req_find_next_prep(req);
1009 	nxt = req->link;
1010 	req->link = NULL;
1011 	return nxt;
1012 }
1013 
1014 static void ctx_flush_and_put(struct io_ring_ctx *ctx, io_tw_token_t tw)
1015 {
1016 	if (!ctx)
1017 		return;
1018 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1019 		atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1020 
1021 	io_submit_flush_completions(ctx);
1022 	mutex_unlock(&ctx->uring_lock);
1023 	percpu_ref_put(&ctx->refs);
1024 }
1025 
1026 /*
1027  * Run queued task_work, returning the number of entries processed in *count.
1028  * If more entries than max_entries are available, stop processing once this
1029  * is reached and return the rest of the list.
1030  */
1031 struct llist_node *io_handle_tw_list(struct llist_node *node,
1032 				     unsigned int *count,
1033 				     unsigned int max_entries)
1034 {
1035 	struct io_ring_ctx *ctx = NULL;
1036 	struct io_tw_state ts = { };
1037 
1038 	do {
1039 		struct llist_node *next = node->next;
1040 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1041 						    io_task_work.node);
1042 
1043 		if (req->ctx != ctx) {
1044 			ctx_flush_and_put(ctx, ts);
1045 			ctx = req->ctx;
1046 			mutex_lock(&ctx->uring_lock);
1047 			percpu_ref_get(&ctx->refs);
1048 		}
1049 		INDIRECT_CALL_2(req->io_task_work.func,
1050 				io_poll_task_func, io_req_rw_complete,
1051 				req, ts);
1052 		node = next;
1053 		(*count)++;
1054 		if (unlikely(need_resched())) {
1055 			ctx_flush_and_put(ctx, ts);
1056 			ctx = NULL;
1057 			cond_resched();
1058 		}
1059 	} while (node && *count < max_entries);
1060 
1061 	ctx_flush_and_put(ctx, ts);
1062 	return node;
1063 }
1064 
1065 static __cold void __io_fallback_tw(struct llist_node *node, bool sync)
1066 {
1067 	struct io_ring_ctx *last_ctx = NULL;
1068 	struct io_kiocb *req;
1069 
1070 	while (node) {
1071 		req = container_of(node, struct io_kiocb, io_task_work.node);
1072 		node = node->next;
1073 		if (last_ctx != req->ctx) {
1074 			if (last_ctx) {
1075 				if (sync)
1076 					flush_delayed_work(&last_ctx->fallback_work);
1077 				percpu_ref_put(&last_ctx->refs);
1078 			}
1079 			last_ctx = req->ctx;
1080 			percpu_ref_get(&last_ctx->refs);
1081 		}
1082 		if (llist_add(&req->io_task_work.node, &last_ctx->fallback_llist))
1083 			schedule_delayed_work(&last_ctx->fallback_work, 1);
1084 	}
1085 
1086 	if (last_ctx) {
1087 		if (sync)
1088 			flush_delayed_work(&last_ctx->fallback_work);
1089 		percpu_ref_put(&last_ctx->refs);
1090 	}
1091 }
1092 
1093 static void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1094 {
1095 	struct llist_node *node = llist_del_all(&tctx->task_list);
1096 
1097 	__io_fallback_tw(node, sync);
1098 }
1099 
1100 struct llist_node *tctx_task_work_run(struct io_uring_task *tctx,
1101 				      unsigned int max_entries,
1102 				      unsigned int *count)
1103 {
1104 	struct llist_node *node;
1105 
1106 	if (unlikely(current->flags & PF_EXITING)) {
1107 		io_fallback_tw(tctx, true);
1108 		return NULL;
1109 	}
1110 
1111 	node = llist_del_all(&tctx->task_list);
1112 	if (node) {
1113 		node = llist_reverse_order(node);
1114 		node = io_handle_tw_list(node, count, max_entries);
1115 	}
1116 
1117 	/* relaxed read is enough as only the task itself sets ->in_cancel */
1118 	if (unlikely(atomic_read(&tctx->in_cancel)))
1119 		io_uring_drop_tctx_refs(current);
1120 
1121 	trace_io_uring_task_work_run(tctx, *count);
1122 	return node;
1123 }
1124 
1125 void tctx_task_work(struct callback_head *cb)
1126 {
1127 	struct io_uring_task *tctx;
1128 	struct llist_node *ret;
1129 	unsigned int count = 0;
1130 
1131 	tctx = container_of(cb, struct io_uring_task, task_work);
1132 	ret = tctx_task_work_run(tctx, UINT_MAX, &count);
1133 	/* can't happen */
1134 	WARN_ON_ONCE(ret);
1135 }
1136 
1137 static void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1138 {
1139 	struct io_ring_ctx *ctx = req->ctx;
1140 	unsigned nr_wait, nr_tw, nr_tw_prev;
1141 	struct llist_node *head;
1142 
1143 	/* See comment above IO_CQ_WAKE_INIT */
1144 	BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
1145 
1146 	/*
1147 	 * We don't know how many reuqests is there in the link and whether
1148 	 * they can even be queued lazily, fall back to non-lazy.
1149 	 */
1150 	if (req->flags & IO_REQ_LINK_FLAGS)
1151 		flags &= ~IOU_F_TWQ_LAZY_WAKE;
1152 
1153 	guard(rcu)();
1154 
1155 	head = READ_ONCE(ctx->work_llist.first);
1156 	do {
1157 		nr_tw_prev = 0;
1158 		if (head) {
1159 			struct io_kiocb *first_req = container_of(head,
1160 							struct io_kiocb,
1161 							io_task_work.node);
1162 			/*
1163 			 * Might be executed at any moment, rely on
1164 			 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1165 			 */
1166 			nr_tw_prev = READ_ONCE(first_req->nr_tw);
1167 		}
1168 
1169 		/*
1170 		 * Theoretically, it can overflow, but that's fine as one of
1171 		 * previous adds should've tried to wake the task.
1172 		 */
1173 		nr_tw = nr_tw_prev + 1;
1174 		if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1175 			nr_tw = IO_CQ_WAKE_FORCE;
1176 
1177 		req->nr_tw = nr_tw;
1178 		req->io_task_work.node.next = head;
1179 	} while (!try_cmpxchg(&ctx->work_llist.first, &head,
1180 			      &req->io_task_work.node));
1181 
1182 	/*
1183 	 * cmpxchg implies a full barrier, which pairs with the barrier
1184 	 * in set_current_state() on the io_cqring_wait() side. It's used
1185 	 * to ensure that either we see updated ->cq_wait_nr, or waiters
1186 	 * going to sleep will observe the work added to the list, which
1187 	 * is similar to the wait/wawke task state sync.
1188 	 */
1189 
1190 	if (!head) {
1191 		if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1192 			atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1193 		if (ctx->has_evfd)
1194 			io_eventfd_signal(ctx);
1195 	}
1196 
1197 	nr_wait = atomic_read(&ctx->cq_wait_nr);
1198 	/* not enough or no one is waiting */
1199 	if (nr_tw < nr_wait)
1200 		return;
1201 	/* the previous add has already woken it up */
1202 	if (nr_tw_prev >= nr_wait)
1203 		return;
1204 	wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1205 }
1206 
1207 static void io_req_normal_work_add(struct io_kiocb *req)
1208 {
1209 	struct io_uring_task *tctx = req->tctx;
1210 	struct io_ring_ctx *ctx = req->ctx;
1211 
1212 	/* task_work already pending, we're done */
1213 	if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1214 		return;
1215 
1216 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1217 		atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1218 
1219 	/* SQPOLL doesn't need the task_work added, it'll run it itself */
1220 	if (ctx->flags & IORING_SETUP_SQPOLL) {
1221 		__set_notify_signal(tctx->task);
1222 		return;
1223 	}
1224 
1225 	if (likely(!task_work_add(tctx->task, &tctx->task_work, ctx->notify_method)))
1226 		return;
1227 
1228 	io_fallback_tw(tctx, false);
1229 }
1230 
1231 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1232 {
1233 	if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN)
1234 		io_req_local_work_add(req, flags);
1235 	else
1236 		io_req_normal_work_add(req);
1237 }
1238 
1239 void io_req_task_work_add_remote(struct io_kiocb *req, unsigned flags)
1240 {
1241 	if (WARN_ON_ONCE(!(req->ctx->flags & IORING_SETUP_DEFER_TASKRUN)))
1242 		return;
1243 	__io_req_task_work_add(req, flags);
1244 }
1245 
1246 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1247 {
1248 	struct llist_node *node = llist_del_all(&ctx->work_llist);
1249 
1250 	__io_fallback_tw(node, false);
1251 	node = llist_del_all(&ctx->retry_llist);
1252 	__io_fallback_tw(node, false);
1253 }
1254 
1255 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1256 				       int min_events)
1257 {
1258 	if (!io_local_work_pending(ctx))
1259 		return false;
1260 	if (events < min_events)
1261 		return true;
1262 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1263 		atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1264 	return false;
1265 }
1266 
1267 static int __io_run_local_work_loop(struct llist_node **node,
1268 				    io_tw_token_t tw,
1269 				    int events)
1270 {
1271 	int ret = 0;
1272 
1273 	while (*node) {
1274 		struct llist_node *next = (*node)->next;
1275 		struct io_kiocb *req = container_of(*node, struct io_kiocb,
1276 						    io_task_work.node);
1277 		INDIRECT_CALL_2(req->io_task_work.func,
1278 				io_poll_task_func, io_req_rw_complete,
1279 				req, tw);
1280 		*node = next;
1281 		if (++ret >= events)
1282 			break;
1283 	}
1284 
1285 	return ret;
1286 }
1287 
1288 static int __io_run_local_work(struct io_ring_ctx *ctx, io_tw_token_t tw,
1289 			       int min_events, int max_events)
1290 {
1291 	struct llist_node *node;
1292 	unsigned int loops = 0;
1293 	int ret = 0;
1294 
1295 	if (WARN_ON_ONCE(ctx->submitter_task != current))
1296 		return -EEXIST;
1297 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1298 		atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1299 again:
1300 	min_events -= ret;
1301 	ret = __io_run_local_work_loop(&ctx->retry_llist.first, tw, max_events);
1302 	if (ctx->retry_llist.first)
1303 		goto retry_done;
1304 
1305 	/*
1306 	 * llists are in reverse order, flip it back the right way before
1307 	 * running the pending items.
1308 	 */
1309 	node = llist_reverse_order(llist_del_all(&ctx->work_llist));
1310 	ret += __io_run_local_work_loop(&node, tw, max_events - ret);
1311 	ctx->retry_llist.first = node;
1312 	loops++;
1313 
1314 	if (io_run_local_work_continue(ctx, ret, min_events))
1315 		goto again;
1316 retry_done:
1317 	io_submit_flush_completions(ctx);
1318 	if (io_run_local_work_continue(ctx, ret, min_events))
1319 		goto again;
1320 
1321 	trace_io_uring_local_work_run(ctx, ret, loops);
1322 	return ret;
1323 }
1324 
1325 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1326 					   int min_events)
1327 {
1328 	struct io_tw_state ts = {};
1329 
1330 	if (!io_local_work_pending(ctx))
1331 		return 0;
1332 	return __io_run_local_work(ctx, ts, min_events,
1333 					max(IO_LOCAL_TW_DEFAULT_MAX, min_events));
1334 }
1335 
1336 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events,
1337 			     int max_events)
1338 {
1339 	struct io_tw_state ts = {};
1340 	int ret;
1341 
1342 	mutex_lock(&ctx->uring_lock);
1343 	ret = __io_run_local_work(ctx, ts, min_events, max_events);
1344 	mutex_unlock(&ctx->uring_lock);
1345 	return ret;
1346 }
1347 
1348 static void io_req_task_cancel(struct io_kiocb *req, io_tw_token_t tw)
1349 {
1350 	io_tw_lock(req->ctx, tw);
1351 	io_req_defer_failed(req, req->cqe.res);
1352 }
1353 
1354 void io_req_task_submit(struct io_kiocb *req, io_tw_token_t tw)
1355 {
1356 	io_tw_lock(req->ctx, tw);
1357 	if (unlikely(io_should_terminate_tw()))
1358 		io_req_defer_failed(req, -EFAULT);
1359 	else if (req->flags & REQ_F_FORCE_ASYNC)
1360 		io_queue_iowq(req);
1361 	else
1362 		io_queue_sqe(req);
1363 }
1364 
1365 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1366 {
1367 	io_req_set_res(req, ret, 0);
1368 	req->io_task_work.func = io_req_task_cancel;
1369 	io_req_task_work_add(req);
1370 }
1371 
1372 void io_req_task_queue(struct io_kiocb *req)
1373 {
1374 	req->io_task_work.func = io_req_task_submit;
1375 	io_req_task_work_add(req);
1376 }
1377 
1378 void io_queue_next(struct io_kiocb *req)
1379 {
1380 	struct io_kiocb *nxt = io_req_find_next(req);
1381 
1382 	if (nxt)
1383 		io_req_task_queue(nxt);
1384 }
1385 
1386 static void io_free_batch_list(struct io_ring_ctx *ctx,
1387 			       struct io_wq_work_node *node)
1388 	__must_hold(&ctx->uring_lock)
1389 {
1390 	do {
1391 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1392 						    comp_list);
1393 
1394 		if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1395 			if (req->flags & REQ_F_REISSUE) {
1396 				node = req->comp_list.next;
1397 				req->flags &= ~REQ_F_REISSUE;
1398 				io_queue_iowq(req);
1399 				continue;
1400 			}
1401 			if (req->flags & REQ_F_REFCOUNT) {
1402 				node = req->comp_list.next;
1403 				if (!req_ref_put_and_test(req))
1404 					continue;
1405 			}
1406 			if ((req->flags & REQ_F_POLLED) && req->apoll) {
1407 				struct async_poll *apoll = req->apoll;
1408 
1409 				if (apoll->double_poll)
1410 					kfree(apoll->double_poll);
1411 				io_cache_free(&ctx->apoll_cache, apoll);
1412 				req->flags &= ~REQ_F_POLLED;
1413 			}
1414 			if (req->flags & IO_REQ_LINK_FLAGS)
1415 				io_queue_next(req);
1416 			if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1417 				io_clean_op(req);
1418 		}
1419 		io_put_file(req);
1420 		io_req_put_rsrc_nodes(req);
1421 		io_put_task(req);
1422 
1423 		node = req->comp_list.next;
1424 		io_req_add_to_cache(req, ctx);
1425 	} while (node);
1426 }
1427 
1428 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1429 	__must_hold(&ctx->uring_lock)
1430 {
1431 	struct io_submit_state *state = &ctx->submit_state;
1432 	struct io_wq_work_node *node;
1433 
1434 	__io_cq_lock(ctx);
1435 	__wq_list_for_each(node, &state->compl_reqs) {
1436 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1437 					    comp_list);
1438 
1439 		/*
1440 		 * Requests marked with REQUEUE should not post a CQE, they
1441 		 * will go through the io-wq retry machinery and post one
1442 		 * later.
1443 		 */
1444 		if (!(req->flags & (REQ_F_CQE_SKIP | REQ_F_REISSUE)) &&
1445 		    unlikely(!io_fill_cqe_req(ctx, req))) {
1446 			if (ctx->lockless_cq) {
1447 				spin_lock(&ctx->completion_lock);
1448 				io_req_cqe_overflow(req);
1449 				spin_unlock(&ctx->completion_lock);
1450 			} else {
1451 				io_req_cqe_overflow(req);
1452 			}
1453 		}
1454 	}
1455 	__io_cq_unlock_post(ctx);
1456 
1457 	if (!wq_list_empty(&state->compl_reqs)) {
1458 		io_free_batch_list(ctx, state->compl_reqs.first);
1459 		INIT_WQ_LIST(&state->compl_reqs);
1460 	}
1461 	ctx->submit_state.cq_flush = false;
1462 }
1463 
1464 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1465 {
1466 	/* See comment at the top of this file */
1467 	smp_rmb();
1468 	return __io_cqring_events(ctx);
1469 }
1470 
1471 /*
1472  * We can't just wait for polled events to come to us, we have to actively
1473  * find and complete them.
1474  */
1475 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1476 {
1477 	if (!(ctx->flags & IORING_SETUP_IOPOLL))
1478 		return;
1479 
1480 	mutex_lock(&ctx->uring_lock);
1481 	while (!wq_list_empty(&ctx->iopoll_list)) {
1482 		/* let it sleep and repeat later if can't complete a request */
1483 		if (io_do_iopoll(ctx, true) == 0)
1484 			break;
1485 		/*
1486 		 * Ensure we allow local-to-the-cpu processing to take place,
1487 		 * in this case we need to ensure that we reap all events.
1488 		 * Also let task_work, etc. to progress by releasing the mutex
1489 		 */
1490 		if (need_resched()) {
1491 			mutex_unlock(&ctx->uring_lock);
1492 			cond_resched();
1493 			mutex_lock(&ctx->uring_lock);
1494 		}
1495 	}
1496 	mutex_unlock(&ctx->uring_lock);
1497 }
1498 
1499 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned int min_events)
1500 {
1501 	unsigned int nr_events = 0;
1502 	unsigned long check_cq;
1503 
1504 	min_events = min(min_events, ctx->cq_entries);
1505 
1506 	lockdep_assert_held(&ctx->uring_lock);
1507 
1508 	if (!io_allowed_run_tw(ctx))
1509 		return -EEXIST;
1510 
1511 	check_cq = READ_ONCE(ctx->check_cq);
1512 	if (unlikely(check_cq)) {
1513 		if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1514 			__io_cqring_overflow_flush(ctx, false);
1515 		/*
1516 		 * Similarly do not spin if we have not informed the user of any
1517 		 * dropped CQE.
1518 		 */
1519 		if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1520 			return -EBADR;
1521 	}
1522 	/*
1523 	 * Don't enter poll loop if we already have events pending.
1524 	 * If we do, we can potentially be spinning for commands that
1525 	 * already triggered a CQE (eg in error).
1526 	 */
1527 	if (io_cqring_events(ctx))
1528 		return 0;
1529 
1530 	do {
1531 		int ret = 0;
1532 
1533 		/*
1534 		 * If a submit got punted to a workqueue, we can have the
1535 		 * application entering polling for a command before it gets
1536 		 * issued. That app will hold the uring_lock for the duration
1537 		 * of the poll right here, so we need to take a breather every
1538 		 * now and then to ensure that the issue has a chance to add
1539 		 * the poll to the issued list. Otherwise we can spin here
1540 		 * forever, while the workqueue is stuck trying to acquire the
1541 		 * very same mutex.
1542 		 */
1543 		if (wq_list_empty(&ctx->iopoll_list) ||
1544 		    io_task_work_pending(ctx)) {
1545 			u32 tail = ctx->cached_cq_tail;
1546 
1547 			(void) io_run_local_work_locked(ctx, min_events);
1548 
1549 			if (task_work_pending(current) ||
1550 			    wq_list_empty(&ctx->iopoll_list)) {
1551 				mutex_unlock(&ctx->uring_lock);
1552 				io_run_task_work();
1553 				mutex_lock(&ctx->uring_lock);
1554 			}
1555 			/* some requests don't go through iopoll_list */
1556 			if (tail != ctx->cached_cq_tail ||
1557 			    wq_list_empty(&ctx->iopoll_list))
1558 				break;
1559 		}
1560 		ret = io_do_iopoll(ctx, !min_events);
1561 		if (unlikely(ret < 0))
1562 			return ret;
1563 
1564 		if (task_sigpending(current))
1565 			return -EINTR;
1566 		if (need_resched())
1567 			break;
1568 
1569 		nr_events += ret;
1570 	} while (nr_events < min_events);
1571 
1572 	return 0;
1573 }
1574 
1575 void io_req_task_complete(struct io_kiocb *req, io_tw_token_t tw)
1576 {
1577 	io_req_complete_defer(req);
1578 }
1579 
1580 /*
1581  * After the iocb has been issued, it's safe to be found on the poll list.
1582  * Adding the kiocb to the list AFTER submission ensures that we don't
1583  * find it from a io_do_iopoll() thread before the issuer is done
1584  * accessing the kiocb cookie.
1585  */
1586 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1587 {
1588 	struct io_ring_ctx *ctx = req->ctx;
1589 	const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1590 
1591 	/* workqueue context doesn't hold uring_lock, grab it now */
1592 	if (unlikely(needs_lock))
1593 		mutex_lock(&ctx->uring_lock);
1594 
1595 	/*
1596 	 * Track whether we have multiple files in our lists. This will impact
1597 	 * how we do polling eventually, not spinning if we're on potentially
1598 	 * different devices.
1599 	 */
1600 	if (wq_list_empty(&ctx->iopoll_list)) {
1601 		ctx->poll_multi_queue = false;
1602 	} else if (!ctx->poll_multi_queue) {
1603 		struct io_kiocb *list_req;
1604 
1605 		list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1606 					comp_list);
1607 		if (list_req->file != req->file)
1608 			ctx->poll_multi_queue = true;
1609 	}
1610 
1611 	/*
1612 	 * For fast devices, IO may have already completed. If it has, add
1613 	 * it to the front so we find it first.
1614 	 */
1615 	if (READ_ONCE(req->iopoll_completed))
1616 		wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1617 	else
1618 		wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1619 
1620 	if (unlikely(needs_lock)) {
1621 		/*
1622 		 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1623 		 * in sq thread task context or in io worker task context. If
1624 		 * current task context is sq thread, we don't need to check
1625 		 * whether should wake up sq thread.
1626 		 */
1627 		if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1628 		    wq_has_sleeper(&ctx->sq_data->wait))
1629 			wake_up(&ctx->sq_data->wait);
1630 
1631 		mutex_unlock(&ctx->uring_lock);
1632 	}
1633 }
1634 
1635 io_req_flags_t io_file_get_flags(struct file *file)
1636 {
1637 	io_req_flags_t res = 0;
1638 
1639 	BUILD_BUG_ON(REQ_F_ISREG_BIT != REQ_F_SUPPORT_NOWAIT_BIT + 1);
1640 
1641 	if (S_ISREG(file_inode(file)->i_mode))
1642 		res |= REQ_F_ISREG;
1643 	if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1644 		res |= REQ_F_SUPPORT_NOWAIT;
1645 	return res;
1646 }
1647 
1648 static u32 io_get_sequence(struct io_kiocb *req)
1649 {
1650 	u32 seq = req->ctx->cached_sq_head;
1651 	struct io_kiocb *cur;
1652 
1653 	/* need original cached_sq_head, but it was increased for each req */
1654 	io_for_each_link(cur, req)
1655 		seq--;
1656 	return seq;
1657 }
1658 
1659 static __cold void io_drain_req(struct io_kiocb *req)
1660 	__must_hold(&ctx->uring_lock)
1661 {
1662 	struct io_ring_ctx *ctx = req->ctx;
1663 	struct io_defer_entry *de;
1664 	int ret;
1665 	u32 seq = io_get_sequence(req);
1666 
1667 	/* Still need defer if there is pending req in defer list. */
1668 	spin_lock(&ctx->completion_lock);
1669 	if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1670 		spin_unlock(&ctx->completion_lock);
1671 queue:
1672 		ctx->drain_active = false;
1673 		io_req_task_queue(req);
1674 		return;
1675 	}
1676 	spin_unlock(&ctx->completion_lock);
1677 
1678 	io_prep_async_link(req);
1679 	de = kmalloc(sizeof(*de), GFP_KERNEL);
1680 	if (!de) {
1681 		ret = -ENOMEM;
1682 		io_req_defer_failed(req, ret);
1683 		return;
1684 	}
1685 
1686 	spin_lock(&ctx->completion_lock);
1687 	if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1688 		spin_unlock(&ctx->completion_lock);
1689 		kfree(de);
1690 		goto queue;
1691 	}
1692 
1693 	trace_io_uring_defer(req);
1694 	de->req = req;
1695 	de->seq = seq;
1696 	list_add_tail(&de->list, &ctx->defer_list);
1697 	spin_unlock(&ctx->completion_lock);
1698 }
1699 
1700 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1701 			   unsigned int issue_flags)
1702 {
1703 	if (req->file || !def->needs_file)
1704 		return true;
1705 
1706 	if (req->flags & REQ_F_FIXED_FILE)
1707 		req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1708 	else
1709 		req->file = io_file_get_normal(req, req->cqe.fd);
1710 
1711 	return !!req->file;
1712 }
1713 
1714 #define REQ_ISSUE_SLOW_FLAGS	(REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)
1715 
1716 static inline int __io_issue_sqe(struct io_kiocb *req,
1717 				 unsigned int issue_flags,
1718 				 const struct io_issue_def *def)
1719 {
1720 	const struct cred *creds = NULL;
1721 	struct io_kiocb *link = NULL;
1722 	int ret;
1723 
1724 	if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) {
1725 		if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
1726 			creds = override_creds(req->creds);
1727 		if (req->flags & REQ_F_ARM_LTIMEOUT)
1728 			link = __io_prep_linked_timeout(req);
1729 	}
1730 
1731 	if (!def->audit_skip)
1732 		audit_uring_entry(req->opcode);
1733 
1734 	ret = def->issue(req, issue_flags);
1735 
1736 	if (!def->audit_skip)
1737 		audit_uring_exit(!ret, ret);
1738 
1739 	if (unlikely(creds || link)) {
1740 		if (creds)
1741 			revert_creds(creds);
1742 		if (link)
1743 			io_queue_linked_timeout(link);
1744 	}
1745 
1746 	return ret;
1747 }
1748 
1749 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1750 {
1751 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1752 	int ret;
1753 
1754 	if (unlikely(!io_assign_file(req, def, issue_flags)))
1755 		return -EBADF;
1756 
1757 	ret = __io_issue_sqe(req, issue_flags, def);
1758 
1759 	if (ret == IOU_OK) {
1760 		if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1761 			io_req_complete_defer(req);
1762 		else
1763 			io_req_complete_post(req, issue_flags);
1764 
1765 		return 0;
1766 	}
1767 
1768 	if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1769 		ret = 0;
1770 
1771 		/* If the op doesn't have a file, we're not polling for it */
1772 		if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1773 			io_iopoll_req_issued(req, issue_flags);
1774 	}
1775 	return ret;
1776 }
1777 
1778 int io_poll_issue(struct io_kiocb *req, io_tw_token_t tw)
1779 {
1780 	const unsigned int issue_flags = IO_URING_F_NONBLOCK |
1781 					 IO_URING_F_MULTISHOT |
1782 					 IO_URING_F_COMPLETE_DEFER;
1783 	int ret;
1784 
1785 	io_tw_lock(req->ctx, tw);
1786 
1787 	WARN_ON_ONCE(!req->file);
1788 	if (WARN_ON_ONCE(req->ctx->flags & IORING_SETUP_IOPOLL))
1789 		return -EFAULT;
1790 
1791 	ret = __io_issue_sqe(req, issue_flags, &io_issue_defs[req->opcode]);
1792 
1793 	WARN_ON_ONCE(ret == IOU_ISSUE_SKIP_COMPLETE);
1794 	return ret;
1795 }
1796 
1797 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1798 {
1799 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1800 	struct io_kiocb *nxt = NULL;
1801 
1802 	if (req_ref_put_and_test_atomic(req)) {
1803 		if (req->flags & IO_REQ_LINK_FLAGS)
1804 			nxt = io_req_find_next(req);
1805 		io_free_req(req);
1806 	}
1807 	return nxt ? &nxt->work : NULL;
1808 }
1809 
1810 void io_wq_submit_work(struct io_wq_work *work)
1811 {
1812 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1813 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1814 	unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1815 	bool needs_poll = false;
1816 	int ret = 0, err = -ECANCELED;
1817 
1818 	/* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1819 	if (!(req->flags & REQ_F_REFCOUNT))
1820 		__io_req_set_refcount(req, 2);
1821 	else
1822 		req_ref_get(req);
1823 
1824 	/* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1825 	if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
1826 fail:
1827 		io_req_task_queue_fail(req, err);
1828 		return;
1829 	}
1830 	if (!io_assign_file(req, def, issue_flags)) {
1831 		err = -EBADF;
1832 		atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1833 		goto fail;
1834 	}
1835 
1836 	/*
1837 	 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1838 	 * submitter task context. Final request completions are handed to the
1839 	 * right context, however this is not the case of auxiliary CQEs,
1840 	 * which is the main mean of operation for multishot requests.
1841 	 * Don't allow any multishot execution from io-wq. It's more restrictive
1842 	 * than necessary and also cleaner.
1843 	 */
1844 	if (req->flags & (REQ_F_MULTISHOT|REQ_F_APOLL_MULTISHOT)) {
1845 		err = -EBADFD;
1846 		if (!io_file_can_poll(req))
1847 			goto fail;
1848 		if (req->file->f_flags & O_NONBLOCK ||
1849 		    req->file->f_mode & FMODE_NOWAIT) {
1850 			err = -ECANCELED;
1851 			if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1852 				goto fail;
1853 			return;
1854 		} else {
1855 			req->flags &= ~(REQ_F_APOLL_MULTISHOT|REQ_F_MULTISHOT);
1856 		}
1857 	}
1858 
1859 	if (req->flags & REQ_F_FORCE_ASYNC) {
1860 		bool opcode_poll = def->pollin || def->pollout;
1861 
1862 		if (opcode_poll && io_file_can_poll(req)) {
1863 			needs_poll = true;
1864 			issue_flags |= IO_URING_F_NONBLOCK;
1865 		}
1866 	}
1867 
1868 	do {
1869 		ret = io_issue_sqe(req, issue_flags);
1870 		if (ret != -EAGAIN)
1871 			break;
1872 
1873 		/*
1874 		 * If REQ_F_NOWAIT is set, then don't wait or retry with
1875 		 * poll. -EAGAIN is final for that case.
1876 		 */
1877 		if (req->flags & REQ_F_NOWAIT)
1878 			break;
1879 
1880 		/*
1881 		 * We can get EAGAIN for iopolled IO even though we're
1882 		 * forcing a sync submission from here, since we can't
1883 		 * wait for request slots on the block side.
1884 		 */
1885 		if (!needs_poll) {
1886 			if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1887 				break;
1888 			if (io_wq_worker_stopped())
1889 				break;
1890 			cond_resched();
1891 			continue;
1892 		}
1893 
1894 		if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1895 			return;
1896 		/* aborted or ready, in either case retry blocking */
1897 		needs_poll = false;
1898 		issue_flags &= ~IO_URING_F_NONBLOCK;
1899 	} while (1);
1900 
1901 	/* avoid locking problems by failing it from a clean context */
1902 	if (ret)
1903 		io_req_task_queue_fail(req, ret);
1904 }
1905 
1906 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1907 				      unsigned int issue_flags)
1908 {
1909 	struct io_ring_ctx *ctx = req->ctx;
1910 	struct io_rsrc_node *node;
1911 	struct file *file = NULL;
1912 
1913 	io_ring_submit_lock(ctx, issue_flags);
1914 	node = io_rsrc_node_lookup(&ctx->file_table.data, fd);
1915 	if (node) {
1916 		io_req_assign_rsrc_node(&req->file_node, node);
1917 		req->flags |= io_slot_flags(node);
1918 		file = io_slot_file(node);
1919 	}
1920 	io_ring_submit_unlock(ctx, issue_flags);
1921 	return file;
1922 }
1923 
1924 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1925 {
1926 	struct file *file = fget(fd);
1927 
1928 	trace_io_uring_file_get(req, fd);
1929 
1930 	/* we don't allow fixed io_uring files */
1931 	if (file && io_is_uring_fops(file))
1932 		io_req_track_inflight(req);
1933 	return file;
1934 }
1935 
1936 static void io_queue_async(struct io_kiocb *req, int ret)
1937 	__must_hold(&req->ctx->uring_lock)
1938 {
1939 	if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1940 		io_req_defer_failed(req, ret);
1941 		return;
1942 	}
1943 
1944 	switch (io_arm_poll_handler(req, 0)) {
1945 	case IO_APOLL_READY:
1946 		io_kbuf_recycle(req, 0);
1947 		io_req_task_queue(req);
1948 		break;
1949 	case IO_APOLL_ABORTED:
1950 		io_kbuf_recycle(req, 0);
1951 		io_queue_iowq(req);
1952 		break;
1953 	case IO_APOLL_OK:
1954 		break;
1955 	}
1956 }
1957 
1958 static inline void io_queue_sqe(struct io_kiocb *req)
1959 	__must_hold(&req->ctx->uring_lock)
1960 {
1961 	int ret;
1962 
1963 	ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
1964 
1965 	/*
1966 	 * We async punt it if the file wasn't marked NOWAIT, or if the file
1967 	 * doesn't support non-blocking read/write attempts
1968 	 */
1969 	if (unlikely(ret))
1970 		io_queue_async(req, ret);
1971 }
1972 
1973 static void io_queue_sqe_fallback(struct io_kiocb *req)
1974 	__must_hold(&req->ctx->uring_lock)
1975 {
1976 	if (unlikely(req->flags & REQ_F_FAIL)) {
1977 		/*
1978 		 * We don't submit, fail them all, for that replace hardlinks
1979 		 * with normal links. Extra REQ_F_LINK is tolerated.
1980 		 */
1981 		req->flags &= ~REQ_F_HARDLINK;
1982 		req->flags |= REQ_F_LINK;
1983 		io_req_defer_failed(req, req->cqe.res);
1984 	} else {
1985 		if (unlikely(req->ctx->drain_active))
1986 			io_drain_req(req);
1987 		else
1988 			io_queue_iowq(req);
1989 	}
1990 }
1991 
1992 /*
1993  * Check SQE restrictions (opcode and flags).
1994  *
1995  * Returns 'true' if SQE is allowed, 'false' otherwise.
1996  */
1997 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
1998 					struct io_kiocb *req,
1999 					unsigned int sqe_flags)
2000 {
2001 	if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2002 		return false;
2003 
2004 	if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2005 	    ctx->restrictions.sqe_flags_required)
2006 		return false;
2007 
2008 	if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2009 			  ctx->restrictions.sqe_flags_required))
2010 		return false;
2011 
2012 	return true;
2013 }
2014 
2015 static void io_init_drain(struct io_ring_ctx *ctx)
2016 {
2017 	struct io_kiocb *head = ctx->submit_state.link.head;
2018 
2019 	ctx->drain_active = true;
2020 	if (head) {
2021 		/*
2022 		 * If we need to drain a request in the middle of a link, drain
2023 		 * the head request and the next request/link after the current
2024 		 * link. Considering sequential execution of links,
2025 		 * REQ_F_IO_DRAIN will be maintained for every request of our
2026 		 * link.
2027 		 */
2028 		head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2029 		ctx->drain_next = true;
2030 	}
2031 }
2032 
2033 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2034 {
2035 	/* ensure per-opcode data is cleared if we fail before prep */
2036 	memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2037 	return err;
2038 }
2039 
2040 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2041 		       const struct io_uring_sqe *sqe)
2042 	__must_hold(&ctx->uring_lock)
2043 {
2044 	const struct io_issue_def *def;
2045 	unsigned int sqe_flags;
2046 	int personality;
2047 	u8 opcode;
2048 
2049 	/* req is partially pre-initialised, see io_preinit_req() */
2050 	req->opcode = opcode = READ_ONCE(sqe->opcode);
2051 	/* same numerical values with corresponding REQ_F_*, safe to copy */
2052 	sqe_flags = READ_ONCE(sqe->flags);
2053 	req->flags = (__force io_req_flags_t) sqe_flags;
2054 	req->cqe.user_data = READ_ONCE(sqe->user_data);
2055 	req->file = NULL;
2056 	req->tctx = current->io_uring;
2057 	req->cancel_seq_set = false;
2058 
2059 	if (unlikely(opcode >= IORING_OP_LAST)) {
2060 		req->opcode = 0;
2061 		return io_init_fail_req(req, -EINVAL);
2062 	}
2063 	opcode = array_index_nospec(opcode, IORING_OP_LAST);
2064 
2065 	def = &io_issue_defs[opcode];
2066 	if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2067 		/* enforce forwards compatibility on users */
2068 		if (sqe_flags & ~SQE_VALID_FLAGS)
2069 			return io_init_fail_req(req, -EINVAL);
2070 		if (sqe_flags & IOSQE_BUFFER_SELECT) {
2071 			if (!def->buffer_select)
2072 				return io_init_fail_req(req, -EOPNOTSUPP);
2073 			req->buf_index = READ_ONCE(sqe->buf_group);
2074 		}
2075 		if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2076 			ctx->drain_disabled = true;
2077 		if (sqe_flags & IOSQE_IO_DRAIN) {
2078 			if (ctx->drain_disabled)
2079 				return io_init_fail_req(req, -EOPNOTSUPP);
2080 			io_init_drain(ctx);
2081 		}
2082 	}
2083 	if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2084 		if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2085 			return io_init_fail_req(req, -EACCES);
2086 		/* knock it to the slow queue path, will be drained there */
2087 		if (ctx->drain_active)
2088 			req->flags |= REQ_F_FORCE_ASYNC;
2089 		/* if there is no link, we're at "next" request and need to drain */
2090 		if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2091 			ctx->drain_next = false;
2092 			ctx->drain_active = true;
2093 			req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2094 		}
2095 	}
2096 
2097 	if (!def->ioprio && sqe->ioprio)
2098 		return io_init_fail_req(req, -EINVAL);
2099 	if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2100 		return io_init_fail_req(req, -EINVAL);
2101 
2102 	if (def->needs_file) {
2103 		struct io_submit_state *state = &ctx->submit_state;
2104 
2105 		req->cqe.fd = READ_ONCE(sqe->fd);
2106 
2107 		/*
2108 		 * Plug now if we have more than 2 IO left after this, and the
2109 		 * target is potentially a read/write to block based storage.
2110 		 */
2111 		if (state->need_plug && def->plug) {
2112 			state->plug_started = true;
2113 			state->need_plug = false;
2114 			blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2115 		}
2116 	}
2117 
2118 	personality = READ_ONCE(sqe->personality);
2119 	if (personality) {
2120 		int ret;
2121 
2122 		req->creds = xa_load(&ctx->personalities, personality);
2123 		if (!req->creds)
2124 			return io_init_fail_req(req, -EINVAL);
2125 		get_cred(req->creds);
2126 		ret = security_uring_override_creds(req->creds);
2127 		if (ret) {
2128 			put_cred(req->creds);
2129 			return io_init_fail_req(req, ret);
2130 		}
2131 		req->flags |= REQ_F_CREDS;
2132 	}
2133 
2134 	return def->prep(req, sqe);
2135 }
2136 
2137 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2138 				      struct io_kiocb *req, int ret)
2139 {
2140 	struct io_ring_ctx *ctx = req->ctx;
2141 	struct io_submit_link *link = &ctx->submit_state.link;
2142 	struct io_kiocb *head = link->head;
2143 
2144 	trace_io_uring_req_failed(sqe, req, ret);
2145 
2146 	/*
2147 	 * Avoid breaking links in the middle as it renders links with SQPOLL
2148 	 * unusable. Instead of failing eagerly, continue assembling the link if
2149 	 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2150 	 * should find the flag and handle the rest.
2151 	 */
2152 	req_fail_link_node(req, ret);
2153 	if (head && !(head->flags & REQ_F_FAIL))
2154 		req_fail_link_node(head, -ECANCELED);
2155 
2156 	if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2157 		if (head) {
2158 			link->last->link = req;
2159 			link->head = NULL;
2160 			req = head;
2161 		}
2162 		io_queue_sqe_fallback(req);
2163 		return ret;
2164 	}
2165 
2166 	if (head)
2167 		link->last->link = req;
2168 	else
2169 		link->head = req;
2170 	link->last = req;
2171 	return 0;
2172 }
2173 
2174 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2175 			 const struct io_uring_sqe *sqe)
2176 	__must_hold(&ctx->uring_lock)
2177 {
2178 	struct io_submit_link *link = &ctx->submit_state.link;
2179 	int ret;
2180 
2181 	ret = io_init_req(ctx, req, sqe);
2182 	if (unlikely(ret))
2183 		return io_submit_fail_init(sqe, req, ret);
2184 
2185 	trace_io_uring_submit_req(req);
2186 
2187 	/*
2188 	 * If we already have a head request, queue this one for async
2189 	 * submittal once the head completes. If we don't have a head but
2190 	 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2191 	 * submitted sync once the chain is complete. If none of those
2192 	 * conditions are true (normal request), then just queue it.
2193 	 */
2194 	if (unlikely(link->head)) {
2195 		trace_io_uring_link(req, link->last);
2196 		link->last->link = req;
2197 		link->last = req;
2198 
2199 		if (req->flags & IO_REQ_LINK_FLAGS)
2200 			return 0;
2201 		/* last request of the link, flush it */
2202 		req = link->head;
2203 		link->head = NULL;
2204 		if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2205 			goto fallback;
2206 
2207 	} else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2208 					  REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2209 		if (req->flags & IO_REQ_LINK_FLAGS) {
2210 			link->head = req;
2211 			link->last = req;
2212 		} else {
2213 fallback:
2214 			io_queue_sqe_fallback(req);
2215 		}
2216 		return 0;
2217 	}
2218 
2219 	io_queue_sqe(req);
2220 	return 0;
2221 }
2222 
2223 /*
2224  * Batched submission is done, ensure local IO is flushed out.
2225  */
2226 static void io_submit_state_end(struct io_ring_ctx *ctx)
2227 {
2228 	struct io_submit_state *state = &ctx->submit_state;
2229 
2230 	if (unlikely(state->link.head))
2231 		io_queue_sqe_fallback(state->link.head);
2232 	/* flush only after queuing links as they can generate completions */
2233 	io_submit_flush_completions(ctx);
2234 	if (state->plug_started)
2235 		blk_finish_plug(&state->plug);
2236 }
2237 
2238 /*
2239  * Start submission side cache.
2240  */
2241 static void io_submit_state_start(struct io_submit_state *state,
2242 				  unsigned int max_ios)
2243 {
2244 	state->plug_started = false;
2245 	state->need_plug = max_ios > 2;
2246 	state->submit_nr = max_ios;
2247 	/* set only head, no need to init link_last in advance */
2248 	state->link.head = NULL;
2249 }
2250 
2251 static void io_commit_sqring(struct io_ring_ctx *ctx)
2252 {
2253 	struct io_rings *rings = ctx->rings;
2254 
2255 	/*
2256 	 * Ensure any loads from the SQEs are done at this point,
2257 	 * since once we write the new head, the application could
2258 	 * write new data to them.
2259 	 */
2260 	smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2261 }
2262 
2263 /*
2264  * Fetch an sqe, if one is available. Note this returns a pointer to memory
2265  * that is mapped by userspace. This means that care needs to be taken to
2266  * ensure that reads are stable, as we cannot rely on userspace always
2267  * being a good citizen. If members of the sqe are validated and then later
2268  * used, it's important that those reads are done through READ_ONCE() to
2269  * prevent a re-load down the line.
2270  */
2271 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2272 {
2273 	unsigned mask = ctx->sq_entries - 1;
2274 	unsigned head = ctx->cached_sq_head++ & mask;
2275 
2276 	if (static_branch_unlikely(&io_key_has_sqarray) &&
2277 	    (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) {
2278 		head = READ_ONCE(ctx->sq_array[head]);
2279 		if (unlikely(head >= ctx->sq_entries)) {
2280 			/* drop invalid entries */
2281 			spin_lock(&ctx->completion_lock);
2282 			ctx->cq_extra--;
2283 			spin_unlock(&ctx->completion_lock);
2284 			WRITE_ONCE(ctx->rings->sq_dropped,
2285 				   READ_ONCE(ctx->rings->sq_dropped) + 1);
2286 			return false;
2287 		}
2288 		head = array_index_nospec(head, ctx->sq_entries);
2289 	}
2290 
2291 	/*
2292 	 * The cached sq head (or cq tail) serves two purposes:
2293 	 *
2294 	 * 1) allows us to batch the cost of updating the user visible
2295 	 *    head updates.
2296 	 * 2) allows the kernel side to track the head on its own, even
2297 	 *    though the application is the one updating it.
2298 	 */
2299 
2300 	/* double index for 128-byte SQEs, twice as long */
2301 	if (ctx->flags & IORING_SETUP_SQE128)
2302 		head <<= 1;
2303 	*sqe = &ctx->sq_sqes[head];
2304 	return true;
2305 }
2306 
2307 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2308 	__must_hold(&ctx->uring_lock)
2309 {
2310 	unsigned int entries = io_sqring_entries(ctx);
2311 	unsigned int left;
2312 	int ret;
2313 
2314 	if (unlikely(!entries))
2315 		return 0;
2316 	/* make sure SQ entry isn't read before tail */
2317 	ret = left = min(nr, entries);
2318 	io_get_task_refs(left);
2319 	io_submit_state_start(&ctx->submit_state, left);
2320 
2321 	do {
2322 		const struct io_uring_sqe *sqe;
2323 		struct io_kiocb *req;
2324 
2325 		if (unlikely(!io_alloc_req(ctx, &req)))
2326 			break;
2327 		if (unlikely(!io_get_sqe(ctx, &sqe))) {
2328 			io_req_add_to_cache(req, ctx);
2329 			break;
2330 		}
2331 
2332 		/*
2333 		 * Continue submitting even for sqe failure if the
2334 		 * ring was setup with IORING_SETUP_SUBMIT_ALL
2335 		 */
2336 		if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2337 		    !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2338 			left--;
2339 			break;
2340 		}
2341 	} while (--left);
2342 
2343 	if (unlikely(left)) {
2344 		ret -= left;
2345 		/* try again if it submitted nothing and can't allocate a req */
2346 		if (!ret && io_req_cache_empty(ctx))
2347 			ret = -EAGAIN;
2348 		current->io_uring->cached_refs += left;
2349 	}
2350 
2351 	io_submit_state_end(ctx);
2352 	 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2353 	io_commit_sqring(ctx);
2354 	return ret;
2355 }
2356 
2357 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2358 			    int wake_flags, void *key)
2359 {
2360 	struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2361 
2362 	/*
2363 	 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2364 	 * the task, and the next invocation will do it.
2365 	 */
2366 	if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2367 		return autoremove_wake_function(curr, mode, wake_flags, key);
2368 	return -1;
2369 }
2370 
2371 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2372 {
2373 	if (io_local_work_pending(ctx)) {
2374 		__set_current_state(TASK_RUNNING);
2375 		if (io_run_local_work(ctx, INT_MAX, IO_LOCAL_TW_DEFAULT_MAX) > 0)
2376 			return 0;
2377 	}
2378 	if (io_run_task_work() > 0)
2379 		return 0;
2380 	if (task_sigpending(current))
2381 		return -EINTR;
2382 	return 0;
2383 }
2384 
2385 static bool current_pending_io(void)
2386 {
2387 	struct io_uring_task *tctx = current->io_uring;
2388 
2389 	if (!tctx)
2390 		return false;
2391 	return percpu_counter_read_positive(&tctx->inflight);
2392 }
2393 
2394 static enum hrtimer_restart io_cqring_timer_wakeup(struct hrtimer *timer)
2395 {
2396 	struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
2397 
2398 	WRITE_ONCE(iowq->hit_timeout, 1);
2399 	iowq->min_timeout = 0;
2400 	wake_up_process(iowq->wq.private);
2401 	return HRTIMER_NORESTART;
2402 }
2403 
2404 /*
2405  * Doing min_timeout portion. If we saw any timeouts, events, or have work,
2406  * wake up. If not, and we have a normal timeout, switch to that and keep
2407  * sleeping.
2408  */
2409 static enum hrtimer_restart io_cqring_min_timer_wakeup(struct hrtimer *timer)
2410 {
2411 	struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
2412 	struct io_ring_ctx *ctx = iowq->ctx;
2413 
2414 	/* no general timeout, or shorter (or equal), we are done */
2415 	if (iowq->timeout == KTIME_MAX ||
2416 	    ktime_compare(iowq->min_timeout, iowq->timeout) >= 0)
2417 		goto out_wake;
2418 	/* work we may need to run, wake function will see if we need to wake */
2419 	if (io_has_work(ctx))
2420 		goto out_wake;
2421 	/* got events since we started waiting, min timeout is done */
2422 	if (iowq->cq_min_tail != READ_ONCE(ctx->rings->cq.tail))
2423 		goto out_wake;
2424 	/* if we have any events and min timeout expired, we're done */
2425 	if (io_cqring_events(ctx))
2426 		goto out_wake;
2427 
2428 	/*
2429 	 * If using deferred task_work running and application is waiting on
2430 	 * more than one request, ensure we reset it now where we are switching
2431 	 * to normal sleeps. Any request completion post min_wait should wake
2432 	 * the task and return.
2433 	 */
2434 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2435 		atomic_set(&ctx->cq_wait_nr, 1);
2436 		smp_mb();
2437 		if (!llist_empty(&ctx->work_llist))
2438 			goto out_wake;
2439 	}
2440 
2441 	hrtimer_update_function(&iowq->t, io_cqring_timer_wakeup);
2442 	hrtimer_set_expires(timer, iowq->timeout);
2443 	return HRTIMER_RESTART;
2444 out_wake:
2445 	return io_cqring_timer_wakeup(timer);
2446 }
2447 
2448 static int io_cqring_schedule_timeout(struct io_wait_queue *iowq,
2449 				      clockid_t clock_id, ktime_t start_time)
2450 {
2451 	ktime_t timeout;
2452 
2453 	if (iowq->min_timeout) {
2454 		timeout = ktime_add_ns(iowq->min_timeout, start_time);
2455 		hrtimer_setup_on_stack(&iowq->t, io_cqring_min_timer_wakeup, clock_id,
2456 				       HRTIMER_MODE_ABS);
2457 	} else {
2458 		timeout = iowq->timeout;
2459 		hrtimer_setup_on_stack(&iowq->t, io_cqring_timer_wakeup, clock_id,
2460 				       HRTIMER_MODE_ABS);
2461 	}
2462 
2463 	hrtimer_set_expires_range_ns(&iowq->t, timeout, 0);
2464 	hrtimer_start_expires(&iowq->t, HRTIMER_MODE_ABS);
2465 
2466 	if (!READ_ONCE(iowq->hit_timeout))
2467 		schedule();
2468 
2469 	hrtimer_cancel(&iowq->t);
2470 	destroy_hrtimer_on_stack(&iowq->t);
2471 	__set_current_state(TASK_RUNNING);
2472 
2473 	return READ_ONCE(iowq->hit_timeout) ? -ETIME : 0;
2474 }
2475 
2476 struct ext_arg {
2477 	size_t argsz;
2478 	struct timespec64 ts;
2479 	const sigset_t __user *sig;
2480 	ktime_t min_time;
2481 	bool ts_set;
2482 	bool iowait;
2483 };
2484 
2485 static int __io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2486 				     struct io_wait_queue *iowq,
2487 				     struct ext_arg *ext_arg,
2488 				     ktime_t start_time)
2489 {
2490 	int ret = 0;
2491 
2492 	/*
2493 	 * Mark us as being in io_wait if we have pending requests, so cpufreq
2494 	 * can take into account that the task is waiting for IO - turns out
2495 	 * to be important for low QD IO.
2496 	 */
2497 	if (ext_arg->iowait && current_pending_io())
2498 		current->in_iowait = 1;
2499 	if (iowq->timeout != KTIME_MAX || iowq->min_timeout)
2500 		ret = io_cqring_schedule_timeout(iowq, ctx->clockid, start_time);
2501 	else
2502 		schedule();
2503 	current->in_iowait = 0;
2504 	return ret;
2505 }
2506 
2507 /* If this returns > 0, the caller should retry */
2508 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2509 					  struct io_wait_queue *iowq,
2510 					  struct ext_arg *ext_arg,
2511 					  ktime_t start_time)
2512 {
2513 	if (unlikely(READ_ONCE(ctx->check_cq)))
2514 		return 1;
2515 	if (unlikely(io_local_work_pending(ctx)))
2516 		return 1;
2517 	if (unlikely(task_work_pending(current)))
2518 		return 1;
2519 	if (unlikely(task_sigpending(current)))
2520 		return -EINTR;
2521 	if (unlikely(io_should_wake(iowq)))
2522 		return 0;
2523 
2524 	return __io_cqring_wait_schedule(ctx, iowq, ext_arg, start_time);
2525 }
2526 
2527 /*
2528  * Wait until events become available, if we don't already have some. The
2529  * application must reap them itself, as they reside on the shared cq ring.
2530  */
2531 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events, u32 flags,
2532 			  struct ext_arg *ext_arg)
2533 {
2534 	struct io_wait_queue iowq;
2535 	struct io_rings *rings = ctx->rings;
2536 	ktime_t start_time;
2537 	int ret;
2538 
2539 	min_events = min_t(int, min_events, ctx->cq_entries);
2540 
2541 	if (!io_allowed_run_tw(ctx))
2542 		return -EEXIST;
2543 	if (io_local_work_pending(ctx))
2544 		io_run_local_work(ctx, min_events,
2545 				  max(IO_LOCAL_TW_DEFAULT_MAX, min_events));
2546 	io_run_task_work();
2547 
2548 	if (unlikely(test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)))
2549 		io_cqring_do_overflow_flush(ctx);
2550 	if (__io_cqring_events_user(ctx) >= min_events)
2551 		return 0;
2552 
2553 	init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2554 	iowq.wq.private = current;
2555 	INIT_LIST_HEAD(&iowq.wq.entry);
2556 	iowq.ctx = ctx;
2557 	iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2558 	iowq.cq_min_tail = READ_ONCE(ctx->rings->cq.tail);
2559 	iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2560 	iowq.hit_timeout = 0;
2561 	iowq.min_timeout = ext_arg->min_time;
2562 	iowq.timeout = KTIME_MAX;
2563 	start_time = io_get_time(ctx);
2564 
2565 	if (ext_arg->ts_set) {
2566 		iowq.timeout = timespec64_to_ktime(ext_arg->ts);
2567 		if (!(flags & IORING_ENTER_ABS_TIMER))
2568 			iowq.timeout = ktime_add(iowq.timeout, start_time);
2569 	}
2570 
2571 	if (ext_arg->sig) {
2572 #ifdef CONFIG_COMPAT
2573 		if (in_compat_syscall())
2574 			ret = set_compat_user_sigmask((const compat_sigset_t __user *)ext_arg->sig,
2575 						      ext_arg->argsz);
2576 		else
2577 #endif
2578 			ret = set_user_sigmask(ext_arg->sig, ext_arg->argsz);
2579 
2580 		if (ret)
2581 			return ret;
2582 	}
2583 
2584 	io_napi_busy_loop(ctx, &iowq);
2585 
2586 	trace_io_uring_cqring_wait(ctx, min_events);
2587 	do {
2588 		unsigned long check_cq;
2589 		int nr_wait;
2590 
2591 		/* if min timeout has been hit, don't reset wait count */
2592 		if (!iowq.hit_timeout)
2593 			nr_wait = (int) iowq.cq_tail -
2594 					READ_ONCE(ctx->rings->cq.tail);
2595 		else
2596 			nr_wait = 1;
2597 
2598 		if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2599 			atomic_set(&ctx->cq_wait_nr, nr_wait);
2600 			set_current_state(TASK_INTERRUPTIBLE);
2601 		} else {
2602 			prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2603 							TASK_INTERRUPTIBLE);
2604 		}
2605 
2606 		ret = io_cqring_wait_schedule(ctx, &iowq, ext_arg, start_time);
2607 		__set_current_state(TASK_RUNNING);
2608 		atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
2609 
2610 		/*
2611 		 * Run task_work after scheduling and before io_should_wake().
2612 		 * If we got woken because of task_work being processed, run it
2613 		 * now rather than let the caller do another wait loop.
2614 		 */
2615 		if (io_local_work_pending(ctx))
2616 			io_run_local_work(ctx, nr_wait, nr_wait);
2617 		io_run_task_work();
2618 
2619 		/*
2620 		 * Non-local task_work will be run on exit to userspace, but
2621 		 * if we're using DEFER_TASKRUN, then we could have waited
2622 		 * with a timeout for a number of requests. If the timeout
2623 		 * hits, we could have some requests ready to process. Ensure
2624 		 * this break is _after_ we have run task_work, to avoid
2625 		 * deferring running potentially pending requests until the
2626 		 * next time we wait for events.
2627 		 */
2628 		if (ret < 0)
2629 			break;
2630 
2631 		check_cq = READ_ONCE(ctx->check_cq);
2632 		if (unlikely(check_cq)) {
2633 			/* let the caller flush overflows, retry */
2634 			if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2635 				io_cqring_do_overflow_flush(ctx);
2636 			if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2637 				ret = -EBADR;
2638 				break;
2639 			}
2640 		}
2641 
2642 		if (io_should_wake(&iowq)) {
2643 			ret = 0;
2644 			break;
2645 		}
2646 		cond_resched();
2647 	} while (1);
2648 
2649 	if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2650 		finish_wait(&ctx->cq_wait, &iowq.wq);
2651 	restore_saved_sigmask_unless(ret == -EINTR);
2652 
2653 	return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2654 }
2655 
2656 static void io_rings_free(struct io_ring_ctx *ctx)
2657 {
2658 	io_free_region(ctx, &ctx->sq_region);
2659 	io_free_region(ctx, &ctx->ring_region);
2660 	ctx->rings = NULL;
2661 	ctx->sq_sqes = NULL;
2662 }
2663 
2664 unsigned long rings_size(unsigned int flags, unsigned int sq_entries,
2665 			 unsigned int cq_entries, size_t *sq_offset)
2666 {
2667 	struct io_rings *rings;
2668 	size_t off, sq_array_size;
2669 
2670 	off = struct_size(rings, cqes, cq_entries);
2671 	if (off == SIZE_MAX)
2672 		return SIZE_MAX;
2673 	if (flags & IORING_SETUP_CQE32) {
2674 		if (check_shl_overflow(off, 1, &off))
2675 			return SIZE_MAX;
2676 	}
2677 
2678 #ifdef CONFIG_SMP
2679 	off = ALIGN(off, SMP_CACHE_BYTES);
2680 	if (off == 0)
2681 		return SIZE_MAX;
2682 #endif
2683 
2684 	if (flags & IORING_SETUP_NO_SQARRAY) {
2685 		*sq_offset = SIZE_MAX;
2686 		return off;
2687 	}
2688 
2689 	*sq_offset = off;
2690 
2691 	sq_array_size = array_size(sizeof(u32), sq_entries);
2692 	if (sq_array_size == SIZE_MAX)
2693 		return SIZE_MAX;
2694 
2695 	if (check_add_overflow(off, sq_array_size, &off))
2696 		return SIZE_MAX;
2697 
2698 	return off;
2699 }
2700 
2701 static void io_req_caches_free(struct io_ring_ctx *ctx)
2702 {
2703 	struct io_kiocb *req;
2704 	int nr = 0;
2705 
2706 	mutex_lock(&ctx->uring_lock);
2707 
2708 	while (!io_req_cache_empty(ctx)) {
2709 		req = io_extract_req(ctx);
2710 		kmem_cache_free(req_cachep, req);
2711 		nr++;
2712 	}
2713 	if (nr)
2714 		percpu_ref_put_many(&ctx->refs, nr);
2715 	mutex_unlock(&ctx->uring_lock);
2716 }
2717 
2718 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2719 {
2720 	io_sq_thread_finish(ctx);
2721 
2722 	mutex_lock(&ctx->uring_lock);
2723 	io_sqe_buffers_unregister(ctx);
2724 	io_sqe_files_unregister(ctx);
2725 	io_unregister_zcrx_ifqs(ctx);
2726 	io_cqring_overflow_kill(ctx);
2727 	io_eventfd_unregister(ctx);
2728 	io_free_alloc_caches(ctx);
2729 	io_destroy_buffers(ctx);
2730 	io_free_region(ctx, &ctx->param_region);
2731 	mutex_unlock(&ctx->uring_lock);
2732 	if (ctx->sq_creds)
2733 		put_cred(ctx->sq_creds);
2734 	if (ctx->submitter_task)
2735 		put_task_struct(ctx->submitter_task);
2736 
2737 	WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2738 
2739 	if (ctx->mm_account) {
2740 		mmdrop(ctx->mm_account);
2741 		ctx->mm_account = NULL;
2742 	}
2743 	io_rings_free(ctx);
2744 
2745 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2746 		static_branch_dec(&io_key_has_sqarray);
2747 
2748 	percpu_ref_exit(&ctx->refs);
2749 	free_uid(ctx->user);
2750 	io_req_caches_free(ctx);
2751 	if (ctx->hash_map)
2752 		io_wq_put_hash(ctx->hash_map);
2753 	io_napi_free(ctx);
2754 	kvfree(ctx->cancel_table.hbs);
2755 	xa_destroy(&ctx->io_bl_xa);
2756 	kfree(ctx);
2757 }
2758 
2759 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2760 {
2761 	struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2762 					       poll_wq_task_work);
2763 
2764 	mutex_lock(&ctx->uring_lock);
2765 	ctx->poll_activated = true;
2766 	mutex_unlock(&ctx->uring_lock);
2767 
2768 	/*
2769 	 * Wake ups for some events between start of polling and activation
2770 	 * might've been lost due to loose synchronisation.
2771 	 */
2772 	wake_up_all(&ctx->poll_wq);
2773 	percpu_ref_put(&ctx->refs);
2774 }
2775 
2776 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2777 {
2778 	spin_lock(&ctx->completion_lock);
2779 	/* already activated or in progress */
2780 	if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2781 		goto out;
2782 	if (WARN_ON_ONCE(!ctx->task_complete))
2783 		goto out;
2784 	if (!ctx->submitter_task)
2785 		goto out;
2786 	/*
2787 	 * with ->submitter_task only the submitter task completes requests, we
2788 	 * only need to sync with it, which is done by injecting a tw
2789 	 */
2790 	init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2791 	percpu_ref_get(&ctx->refs);
2792 	if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2793 		percpu_ref_put(&ctx->refs);
2794 out:
2795 	spin_unlock(&ctx->completion_lock);
2796 }
2797 
2798 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2799 {
2800 	struct io_ring_ctx *ctx = file->private_data;
2801 	__poll_t mask = 0;
2802 
2803 	if (unlikely(!ctx->poll_activated))
2804 		io_activate_pollwq(ctx);
2805 	/*
2806 	 * provides mb() which pairs with barrier from wq_has_sleeper
2807 	 * call in io_commit_cqring
2808 	 */
2809 	poll_wait(file, &ctx->poll_wq, wait);
2810 
2811 	if (!io_sqring_full(ctx))
2812 		mask |= EPOLLOUT | EPOLLWRNORM;
2813 
2814 	/*
2815 	 * Don't flush cqring overflow list here, just do a simple check.
2816 	 * Otherwise there could possible be ABBA deadlock:
2817 	 *      CPU0                    CPU1
2818 	 *      ----                    ----
2819 	 * lock(&ctx->uring_lock);
2820 	 *                              lock(&ep->mtx);
2821 	 *                              lock(&ctx->uring_lock);
2822 	 * lock(&ep->mtx);
2823 	 *
2824 	 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2825 	 * pushes them to do the flush.
2826 	 */
2827 
2828 	if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2829 		mask |= EPOLLIN | EPOLLRDNORM;
2830 
2831 	return mask;
2832 }
2833 
2834 struct io_tctx_exit {
2835 	struct callback_head		task_work;
2836 	struct completion		completion;
2837 	struct io_ring_ctx		*ctx;
2838 };
2839 
2840 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2841 {
2842 	struct io_uring_task *tctx = current->io_uring;
2843 	struct io_tctx_exit *work;
2844 
2845 	work = container_of(cb, struct io_tctx_exit, task_work);
2846 	/*
2847 	 * When @in_cancel, we're in cancellation and it's racy to remove the
2848 	 * node. It'll be removed by the end of cancellation, just ignore it.
2849 	 * tctx can be NULL if the queueing of this task_work raced with
2850 	 * work cancelation off the exec path.
2851 	 */
2852 	if (tctx && !atomic_read(&tctx->in_cancel))
2853 		io_uring_del_tctx_node((unsigned long)work->ctx);
2854 	complete(&work->completion);
2855 }
2856 
2857 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
2858 {
2859 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2860 
2861 	return req->ctx == data;
2862 }
2863 
2864 static __cold void io_ring_exit_work(struct work_struct *work)
2865 {
2866 	struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2867 	unsigned long timeout = jiffies + HZ * 60 * 5;
2868 	unsigned long interval = HZ / 20;
2869 	struct io_tctx_exit exit;
2870 	struct io_tctx_node *node;
2871 	int ret;
2872 
2873 	/*
2874 	 * If we're doing polled IO and end up having requests being
2875 	 * submitted async (out-of-line), then completions can come in while
2876 	 * we're waiting for refs to drop. We need to reap these manually,
2877 	 * as nobody else will be looking for them.
2878 	 */
2879 	do {
2880 		if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2881 			mutex_lock(&ctx->uring_lock);
2882 			io_cqring_overflow_kill(ctx);
2883 			mutex_unlock(&ctx->uring_lock);
2884 		}
2885 		if (ctx->ifq) {
2886 			mutex_lock(&ctx->uring_lock);
2887 			io_shutdown_zcrx_ifqs(ctx);
2888 			mutex_unlock(&ctx->uring_lock);
2889 		}
2890 
2891 		if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2892 			io_move_task_work_from_local(ctx);
2893 
2894 		/* The SQPOLL thread never reaches this path */
2895 		while (io_uring_try_cancel_requests(ctx, NULL, true, false))
2896 			cond_resched();
2897 
2898 		if (ctx->sq_data) {
2899 			struct io_sq_data *sqd = ctx->sq_data;
2900 			struct task_struct *tsk;
2901 
2902 			io_sq_thread_park(sqd);
2903 			tsk = sqd->thread;
2904 			if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2905 				io_wq_cancel_cb(tsk->io_uring->io_wq,
2906 						io_cancel_ctx_cb, ctx, true);
2907 			io_sq_thread_unpark(sqd);
2908 		}
2909 
2910 		io_req_caches_free(ctx);
2911 
2912 		if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2913 			/* there is little hope left, don't run it too often */
2914 			interval = HZ * 60;
2915 		}
2916 		/*
2917 		 * This is really an uninterruptible wait, as it has to be
2918 		 * complete. But it's also run from a kworker, which doesn't
2919 		 * take signals, so it's fine to make it interruptible. This
2920 		 * avoids scenarios where we knowingly can wait much longer
2921 		 * on completions, for example if someone does a SIGSTOP on
2922 		 * a task that needs to finish task_work to make this loop
2923 		 * complete. That's a synthetic situation that should not
2924 		 * cause a stuck task backtrace, and hence a potential panic
2925 		 * on stuck tasks if that is enabled.
2926 		 */
2927 	} while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
2928 
2929 	init_completion(&exit.completion);
2930 	init_task_work(&exit.task_work, io_tctx_exit_cb);
2931 	exit.ctx = ctx;
2932 
2933 	mutex_lock(&ctx->uring_lock);
2934 	while (!list_empty(&ctx->tctx_list)) {
2935 		WARN_ON_ONCE(time_after(jiffies, timeout));
2936 
2937 		node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2938 					ctx_node);
2939 		/* don't spin on a single task if cancellation failed */
2940 		list_rotate_left(&ctx->tctx_list);
2941 		ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2942 		if (WARN_ON_ONCE(ret))
2943 			continue;
2944 
2945 		mutex_unlock(&ctx->uring_lock);
2946 		/*
2947 		 * See comment above for
2948 		 * wait_for_completion_interruptible_timeout() on why this
2949 		 * wait is marked as interruptible.
2950 		 */
2951 		wait_for_completion_interruptible(&exit.completion);
2952 		mutex_lock(&ctx->uring_lock);
2953 	}
2954 	mutex_unlock(&ctx->uring_lock);
2955 	spin_lock(&ctx->completion_lock);
2956 	spin_unlock(&ctx->completion_lock);
2957 
2958 	/* pairs with RCU read section in io_req_local_work_add() */
2959 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2960 		synchronize_rcu();
2961 
2962 	io_ring_ctx_free(ctx);
2963 }
2964 
2965 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2966 {
2967 	unsigned long index;
2968 	struct creds *creds;
2969 
2970 	mutex_lock(&ctx->uring_lock);
2971 	percpu_ref_kill(&ctx->refs);
2972 	xa_for_each(&ctx->personalities, index, creds)
2973 		io_unregister_personality(ctx, index);
2974 	mutex_unlock(&ctx->uring_lock);
2975 
2976 	flush_delayed_work(&ctx->fallback_work);
2977 
2978 	INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2979 	/*
2980 	 * Use system_unbound_wq to avoid spawning tons of event kworkers
2981 	 * if we're exiting a ton of rings at the same time. It just adds
2982 	 * noise and overhead, there's no discernable change in runtime
2983 	 * over using system_wq.
2984 	 */
2985 	queue_work(iou_wq, &ctx->exit_work);
2986 }
2987 
2988 static int io_uring_release(struct inode *inode, struct file *file)
2989 {
2990 	struct io_ring_ctx *ctx = file->private_data;
2991 
2992 	file->private_data = NULL;
2993 	io_ring_ctx_wait_and_kill(ctx);
2994 	return 0;
2995 }
2996 
2997 struct io_task_cancel {
2998 	struct io_uring_task *tctx;
2999 	bool all;
3000 };
3001 
3002 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3003 {
3004 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3005 	struct io_task_cancel *cancel = data;
3006 
3007 	return io_match_task_safe(req, cancel->tctx, cancel->all);
3008 }
3009 
3010 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3011 					 struct io_uring_task *tctx,
3012 					 bool cancel_all)
3013 {
3014 	struct io_defer_entry *de;
3015 	LIST_HEAD(list);
3016 
3017 	spin_lock(&ctx->completion_lock);
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 	spin_unlock(&ctx->completion_lock);
3025 	if (list_empty(&list))
3026 		return false;
3027 
3028 	while (!list_empty(&list)) {
3029 		de = list_first_entry(&list, struct io_defer_entry, list);
3030 		list_del_init(&de->list);
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 	ret |= io_cancel_defer_files(ctx, tctx, cancel_all);
3106 	mutex_lock(&ctx->uring_lock);
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(46, __u16,  __pad3[0]);
3917 	BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
3918 	BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
3919 	BUILD_BUG_SQE_ELEM(48, __u64, attr_ptr);
3920 	BUILD_BUG_SQE_ELEM(56, __u64, attr_type_mask);
3921 	BUILD_BUG_SQE_ELEM(56, __u64,  __pad2);
3922 
3923 	BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3924 		     sizeof(struct io_uring_rsrc_update));
3925 	BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3926 		     sizeof(struct io_uring_rsrc_update2));
3927 
3928 	/* ->buf_index is u16 */
3929 	BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3930 	BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3931 		     offsetof(struct io_uring_buf_ring, tail));
3932 
3933 	/* should fit into one byte */
3934 	BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
3935 	BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
3936 	BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
3937 
3938 	BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
3939 
3940 	BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
3941 
3942 	/* top 8bits are for internal use */
3943 	BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
3944 
3945 	io_uring_optable_init();
3946 
3947 	/* imu->dir is u8 */
3948 	BUILD_BUG_ON((IO_IMU_DEST | IO_IMU_SOURCE) > U8_MAX);
3949 
3950 	/*
3951 	 * Allow user copy in the per-command field, which starts after the
3952 	 * file in io_kiocb and until the opcode field. The openat2 handling
3953 	 * requires copying in user memory into the io_kiocb object in that
3954 	 * range, and HARDENED_USERCOPY will complain if we haven't
3955 	 * correctly annotated this range.
3956 	 */
3957 	req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
3958 				SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
3959 				SLAB_TYPESAFE_BY_RCU);
3960 
3961 	iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
3962 	BUG_ON(!iou_wq);
3963 
3964 #ifdef CONFIG_SYSCTL
3965 	register_sysctl_init("kernel", kernel_io_uring_disabled_table);
3966 #endif
3967 
3968 	return 0;
3969 };
3970 __initcall(io_uring_init);
3971