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