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