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