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