xref: /openbmc/linux/io_uring/io_uring.c (revision 7994a484)
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/fdtable.h>
55 #include <linux/mm.h>
56 #include <linux/mman.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/bvec.h>
60 #include <linux/net.h>
61 #include <net/sock.h>
62 #include <net/af_unix.h>
63 #include <linux/anon_inodes.h>
64 #include <linux/sched/mm.h>
65 #include <linux/uaccess.h>
66 #include <linux/nospec.h>
67 #include <linux/highmem.h>
68 #include <linux/fsnotify.h>
69 #include <linux/fadvise.h>
70 #include <linux/task_work.h>
71 #include <linux/io_uring.h>
72 #include <linux/audit.h>
73 #include <linux/security.h>
74 #include <asm/shmparam.h>
75 
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
78 
79 #include <uapi/linux/io_uring.h>
80 
81 #include "io-wq.h"
82 
83 #include "io_uring.h"
84 #include "opdef.h"
85 #include "refs.h"
86 #include "tctx.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 
95 #include "timeout.h"
96 #include "poll.h"
97 #include "rw.h"
98 #include "alloc_cache.h"
99 
100 #define IORING_MAX_ENTRIES	32768
101 #define IORING_MAX_CQ_ENTRIES	(2 * IORING_MAX_ENTRIES)
102 
103 #define IORING_MAX_RESTRICTIONS	(IORING_RESTRICTION_LAST + \
104 				 IORING_REGISTER_LAST + IORING_OP_LAST)
105 
106 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
107 			  IOSQE_IO_HARDLINK | IOSQE_ASYNC)
108 
109 #define SQE_VALID_FLAGS	(SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
110 			IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
111 
112 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
113 				REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
114 				REQ_F_ASYNC_DATA)
115 
116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
117 				 IO_REQ_CLEAN_FLAGS)
118 
119 #define IO_TCTX_REFS_CACHE_NR	(1U << 10)
120 
121 #define IO_COMPL_BATCH			32
122 #define IO_REQ_ALLOC_BATCH		8
123 
124 enum {
125 	IO_CHECK_CQ_OVERFLOW_BIT,
126 	IO_CHECK_CQ_DROPPED_BIT,
127 };
128 
129 enum {
130 	IO_EVENTFD_OP_SIGNAL_BIT,
131 	IO_EVENTFD_OP_FREE_BIT,
132 };
133 
134 struct io_defer_entry {
135 	struct list_head	list;
136 	struct io_kiocb		*req;
137 	u32			seq;
138 };
139 
140 /* requests with any of those set should undergo io_disarm_next() */
141 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
142 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
143 
144 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
145 					 struct task_struct *task,
146 					 bool cancel_all);
147 
148 static void io_queue_sqe(struct io_kiocb *req);
149 
150 struct kmem_cache *req_cachep;
151 static struct workqueue_struct *iou_wq __ro_after_init;
152 
153 static int __read_mostly sysctl_io_uring_disabled;
154 static int __read_mostly sysctl_io_uring_group = -1;
155 
156 #ifdef CONFIG_SYSCTL
157 static struct ctl_table kernel_io_uring_disabled_table[] = {
158 	{
159 		.procname	= "io_uring_disabled",
160 		.data		= &sysctl_io_uring_disabled,
161 		.maxlen		= sizeof(sysctl_io_uring_disabled),
162 		.mode		= 0644,
163 		.proc_handler	= proc_dointvec_minmax,
164 		.extra1		= SYSCTL_ZERO,
165 		.extra2		= SYSCTL_TWO,
166 	},
167 	{
168 		.procname	= "io_uring_group",
169 		.data		= &sysctl_io_uring_group,
170 		.maxlen		= sizeof(gid_t),
171 		.mode		= 0644,
172 		.proc_handler	= proc_dointvec,
173 	},
174 	{},
175 };
176 #endif
177 
178 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
179 {
180 	if (!wq_list_empty(&ctx->submit_state.compl_reqs) ||
181 	    ctx->submit_state.cqes_count)
182 		__io_submit_flush_completions(ctx);
183 }
184 
185 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
186 {
187 	return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
188 }
189 
190 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
191 {
192 	return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
193 }
194 
195 static bool io_match_linked(struct io_kiocb *head)
196 {
197 	struct io_kiocb *req;
198 
199 	io_for_each_link(req, head) {
200 		if (req->flags & REQ_F_INFLIGHT)
201 			return true;
202 	}
203 	return false;
204 }
205 
206 /*
207  * As io_match_task() but protected against racing with linked timeouts.
208  * User must not hold timeout_lock.
209  */
210 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
211 			bool cancel_all)
212 {
213 	bool matched;
214 
215 	if (task && head->task != task)
216 		return false;
217 	if (cancel_all)
218 		return true;
219 
220 	if (head->flags & REQ_F_LINK_TIMEOUT) {
221 		struct io_ring_ctx *ctx = head->ctx;
222 
223 		/* protect against races with linked timeouts */
224 		spin_lock_irq(&ctx->timeout_lock);
225 		matched = io_match_linked(head);
226 		spin_unlock_irq(&ctx->timeout_lock);
227 	} else {
228 		matched = io_match_linked(head);
229 	}
230 	return matched;
231 }
232 
233 static inline void req_fail_link_node(struct io_kiocb *req, int res)
234 {
235 	req_set_fail(req);
236 	io_req_set_res(req, res, 0);
237 }
238 
239 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
240 {
241 	wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
242 }
243 
244 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
245 {
246 	struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
247 
248 	complete(&ctx->ref_comp);
249 }
250 
251 static __cold void io_fallback_req_func(struct work_struct *work)
252 {
253 	struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
254 						fallback_work.work);
255 	struct llist_node *node = llist_del_all(&ctx->fallback_llist);
256 	struct io_kiocb *req, *tmp;
257 	struct io_tw_state ts = { .locked = true, };
258 
259 	percpu_ref_get(&ctx->refs);
260 	mutex_lock(&ctx->uring_lock);
261 	llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
262 		req->io_task_work.func(req, &ts);
263 	if (WARN_ON_ONCE(!ts.locked))
264 		return;
265 	io_submit_flush_completions(ctx);
266 	mutex_unlock(&ctx->uring_lock);
267 	percpu_ref_put(&ctx->refs);
268 }
269 
270 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
271 {
272 	unsigned hash_buckets = 1U << bits;
273 	size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
274 
275 	table->hbs = kmalloc(hash_size, GFP_KERNEL);
276 	if (!table->hbs)
277 		return -ENOMEM;
278 
279 	table->hash_bits = bits;
280 	init_hash_table(table, hash_buckets);
281 	return 0;
282 }
283 
284 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
285 {
286 	struct io_ring_ctx *ctx;
287 	int hash_bits;
288 
289 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
290 	if (!ctx)
291 		return NULL;
292 
293 	xa_init(&ctx->io_bl_xa);
294 
295 	/*
296 	 * Use 5 bits less than the max cq entries, that should give us around
297 	 * 32 entries per hash list if totally full and uniformly spread, but
298 	 * don't keep too many buckets to not overconsume memory.
299 	 */
300 	hash_bits = ilog2(p->cq_entries) - 5;
301 	hash_bits = clamp(hash_bits, 1, 8);
302 	if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
303 		goto err;
304 	if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
305 		goto err;
306 	if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
307 			    0, GFP_KERNEL))
308 		goto err;
309 
310 	ctx->flags = p->flags;
311 	init_waitqueue_head(&ctx->sqo_sq_wait);
312 	INIT_LIST_HEAD(&ctx->sqd_list);
313 	INIT_LIST_HEAD(&ctx->cq_overflow_list);
314 	INIT_LIST_HEAD(&ctx->io_buffers_cache);
315 	INIT_HLIST_HEAD(&ctx->io_buf_list);
316 	io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
317 			    sizeof(struct io_rsrc_node));
318 	io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX,
319 			    sizeof(struct async_poll));
320 	io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
321 			    sizeof(struct io_async_msghdr));
322 	init_completion(&ctx->ref_comp);
323 	xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
324 	mutex_init(&ctx->uring_lock);
325 	init_waitqueue_head(&ctx->cq_wait);
326 	init_waitqueue_head(&ctx->poll_wq);
327 	init_waitqueue_head(&ctx->rsrc_quiesce_wq);
328 	spin_lock_init(&ctx->completion_lock);
329 	spin_lock_init(&ctx->timeout_lock);
330 	INIT_WQ_LIST(&ctx->iopoll_list);
331 	INIT_LIST_HEAD(&ctx->io_buffers_pages);
332 	INIT_LIST_HEAD(&ctx->io_buffers_comp);
333 	INIT_LIST_HEAD(&ctx->defer_list);
334 	INIT_LIST_HEAD(&ctx->timeout_list);
335 	INIT_LIST_HEAD(&ctx->ltimeout_list);
336 	INIT_LIST_HEAD(&ctx->rsrc_ref_list);
337 	init_llist_head(&ctx->work_llist);
338 	INIT_LIST_HEAD(&ctx->tctx_list);
339 	ctx->submit_state.free_list.next = NULL;
340 	INIT_WQ_LIST(&ctx->locked_free_list);
341 	INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
342 	INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
343 	return ctx;
344 err:
345 	kfree(ctx->cancel_table.hbs);
346 	kfree(ctx->cancel_table_locked.hbs);
347 	xa_destroy(&ctx->io_bl_xa);
348 	kfree(ctx);
349 	return NULL;
350 }
351 
352 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
353 {
354 	struct io_rings *r = ctx->rings;
355 
356 	WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
357 	ctx->cq_extra--;
358 }
359 
360 static bool req_need_defer(struct io_kiocb *req, u32 seq)
361 {
362 	if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
363 		struct io_ring_ctx *ctx = req->ctx;
364 
365 		return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
366 	}
367 
368 	return false;
369 }
370 
371 static void io_clean_op(struct io_kiocb *req)
372 {
373 	if (req->flags & REQ_F_BUFFER_SELECTED) {
374 		spin_lock(&req->ctx->completion_lock);
375 		io_put_kbuf_comp(req);
376 		spin_unlock(&req->ctx->completion_lock);
377 	}
378 
379 	if (req->flags & REQ_F_NEED_CLEANUP) {
380 		const struct io_cold_def *def = &io_cold_defs[req->opcode];
381 
382 		if (def->cleanup)
383 			def->cleanup(req);
384 	}
385 	if ((req->flags & REQ_F_POLLED) && req->apoll) {
386 		kfree(req->apoll->double_poll);
387 		kfree(req->apoll);
388 		req->apoll = NULL;
389 	}
390 	if (req->flags & REQ_F_INFLIGHT) {
391 		struct io_uring_task *tctx = req->task->io_uring;
392 
393 		atomic_dec(&tctx->inflight_tracked);
394 	}
395 	if (req->flags & REQ_F_CREDS)
396 		put_cred(req->creds);
397 	if (req->flags & REQ_F_ASYNC_DATA) {
398 		kfree(req->async_data);
399 		req->async_data = NULL;
400 	}
401 	req->flags &= ~IO_REQ_CLEAN_FLAGS;
402 }
403 
404 static inline void io_req_track_inflight(struct io_kiocb *req)
405 {
406 	if (!(req->flags & REQ_F_INFLIGHT)) {
407 		req->flags |= REQ_F_INFLIGHT;
408 		atomic_inc(&req->task->io_uring->inflight_tracked);
409 	}
410 }
411 
412 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
413 {
414 	if (WARN_ON_ONCE(!req->link))
415 		return NULL;
416 
417 	req->flags &= ~REQ_F_ARM_LTIMEOUT;
418 	req->flags |= REQ_F_LINK_TIMEOUT;
419 
420 	/* linked timeouts should have two refs once prep'ed */
421 	io_req_set_refcount(req);
422 	__io_req_set_refcount(req->link, 2);
423 	return req->link;
424 }
425 
426 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
427 {
428 	if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
429 		return NULL;
430 	return __io_prep_linked_timeout(req);
431 }
432 
433 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
434 {
435 	io_queue_linked_timeout(__io_prep_linked_timeout(req));
436 }
437 
438 static inline void io_arm_ltimeout(struct io_kiocb *req)
439 {
440 	if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
441 		__io_arm_ltimeout(req);
442 }
443 
444 static void io_prep_async_work(struct io_kiocb *req)
445 {
446 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
447 	struct io_ring_ctx *ctx = req->ctx;
448 
449 	if (!(req->flags & REQ_F_CREDS)) {
450 		req->flags |= REQ_F_CREDS;
451 		req->creds = get_current_cred();
452 	}
453 
454 	req->work.list.next = NULL;
455 	req->work.flags = 0;
456 	req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
457 	if (req->flags & REQ_F_FORCE_ASYNC)
458 		req->work.flags |= IO_WQ_WORK_CONCURRENT;
459 
460 	if (req->file && !(req->flags & REQ_F_FIXED_FILE))
461 		req->flags |= io_file_get_flags(req->file);
462 
463 	if (req->file && (req->flags & REQ_F_ISREG)) {
464 		bool should_hash = def->hash_reg_file;
465 
466 		/* don't serialize this request if the fs doesn't need it */
467 		if (should_hash && (req->file->f_flags & O_DIRECT) &&
468 		    (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE))
469 			should_hash = false;
470 		if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
471 			io_wq_hash_work(&req->work, file_inode(req->file));
472 	} else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
473 		if (def->unbound_nonreg_file)
474 			req->work.flags |= IO_WQ_WORK_UNBOUND;
475 	}
476 }
477 
478 static void io_prep_async_link(struct io_kiocb *req)
479 {
480 	struct io_kiocb *cur;
481 
482 	if (req->flags & REQ_F_LINK_TIMEOUT) {
483 		struct io_ring_ctx *ctx = req->ctx;
484 
485 		spin_lock_irq(&ctx->timeout_lock);
486 		io_for_each_link(cur, req)
487 			io_prep_async_work(cur);
488 		spin_unlock_irq(&ctx->timeout_lock);
489 	} else {
490 		io_for_each_link(cur, req)
491 			io_prep_async_work(cur);
492 	}
493 }
494 
495 void io_queue_iowq(struct io_kiocb *req, struct io_tw_state *ts_dont_use)
496 {
497 	struct io_kiocb *link = io_prep_linked_timeout(req);
498 	struct io_uring_task *tctx = req->task->io_uring;
499 
500 	BUG_ON(!tctx);
501 	BUG_ON(!tctx->io_wq);
502 
503 	/* init ->work of the whole link before punting */
504 	io_prep_async_link(req);
505 
506 	/*
507 	 * Not expected to happen, but if we do have a bug where this _can_
508 	 * happen, catch it here and ensure the request is marked as
509 	 * canceled. That will make io-wq go through the usual work cancel
510 	 * procedure rather than attempt to run this request (or create a new
511 	 * worker for it).
512 	 */
513 	if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
514 		req->work.flags |= IO_WQ_WORK_CANCEL;
515 
516 	trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
517 	io_wq_enqueue(tctx->io_wq, &req->work);
518 	if (link)
519 		io_queue_linked_timeout(link);
520 }
521 
522 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
523 {
524 	while (!list_empty(&ctx->defer_list)) {
525 		struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
526 						struct io_defer_entry, list);
527 
528 		if (req_need_defer(de->req, de->seq))
529 			break;
530 		list_del_init(&de->list);
531 		io_req_task_queue(de->req);
532 		kfree(de);
533 	}
534 }
535 
536 
537 static void io_eventfd_ops(struct rcu_head *rcu)
538 {
539 	struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
540 	int ops = atomic_xchg(&ev_fd->ops, 0);
541 
542 	if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT))
543 		eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE);
544 
545 	/* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback
546 	 * ordering in a race but if references are 0 we know we have to free
547 	 * it regardless.
548 	 */
549 	if (atomic_dec_and_test(&ev_fd->refs)) {
550 		eventfd_ctx_put(ev_fd->cq_ev_fd);
551 		kfree(ev_fd);
552 	}
553 }
554 
555 static void io_eventfd_signal(struct io_ring_ctx *ctx)
556 {
557 	struct io_ev_fd *ev_fd = NULL;
558 
559 	rcu_read_lock();
560 	/*
561 	 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
562 	 * and eventfd_signal
563 	 */
564 	ev_fd = rcu_dereference(ctx->io_ev_fd);
565 
566 	/*
567 	 * Check again if ev_fd exists incase an io_eventfd_unregister call
568 	 * completed between the NULL check of ctx->io_ev_fd at the start of
569 	 * the function and rcu_read_lock.
570 	 */
571 	if (unlikely(!ev_fd))
572 		goto out;
573 	if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
574 		goto out;
575 	if (ev_fd->eventfd_async && !io_wq_current_is_worker())
576 		goto out;
577 
578 	if (likely(eventfd_signal_allowed())) {
579 		eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE);
580 	} else {
581 		atomic_inc(&ev_fd->refs);
582 		if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops))
583 			call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops);
584 		else
585 			atomic_dec(&ev_fd->refs);
586 	}
587 
588 out:
589 	rcu_read_unlock();
590 }
591 
592 static void io_eventfd_flush_signal(struct io_ring_ctx *ctx)
593 {
594 	bool skip;
595 
596 	spin_lock(&ctx->completion_lock);
597 
598 	/*
599 	 * Eventfd should only get triggered when at least one event has been
600 	 * posted. Some applications rely on the eventfd notification count
601 	 * only changing IFF a new CQE has been added to the CQ ring. There's
602 	 * no depedency on 1:1 relationship between how many times this
603 	 * function is called (and hence the eventfd count) and number of CQEs
604 	 * posted to the CQ ring.
605 	 */
606 	skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail;
607 	ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
608 	spin_unlock(&ctx->completion_lock);
609 	if (skip)
610 		return;
611 
612 	io_eventfd_signal(ctx);
613 }
614 
615 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
616 {
617 	if (ctx->poll_activated)
618 		io_poll_wq_wake(ctx);
619 	if (ctx->off_timeout_used)
620 		io_flush_timeouts(ctx);
621 	if (ctx->drain_active) {
622 		spin_lock(&ctx->completion_lock);
623 		io_queue_deferred(ctx);
624 		spin_unlock(&ctx->completion_lock);
625 	}
626 	if (ctx->has_evfd)
627 		io_eventfd_flush_signal(ctx);
628 }
629 
630 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
631 {
632 	if (!ctx->lockless_cq)
633 		spin_lock(&ctx->completion_lock);
634 }
635 
636 static inline void io_cq_lock(struct io_ring_ctx *ctx)
637 	__acquires(ctx->completion_lock)
638 {
639 	spin_lock(&ctx->completion_lock);
640 }
641 
642 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
643 {
644 	io_commit_cqring(ctx);
645 	if (!ctx->task_complete) {
646 		if (!ctx->lockless_cq)
647 			spin_unlock(&ctx->completion_lock);
648 		/* IOPOLL rings only need to wake up if it's also SQPOLL */
649 		if (!ctx->syscall_iopoll)
650 			io_cqring_wake(ctx);
651 	}
652 	io_commit_cqring_flush(ctx);
653 }
654 
655 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
656 	__releases(ctx->completion_lock)
657 {
658 	io_commit_cqring(ctx);
659 	spin_unlock(&ctx->completion_lock);
660 	io_cqring_wake(ctx);
661 	io_commit_cqring_flush(ctx);
662 }
663 
664 /* Returns true if there are no backlogged entries after the flush */
665 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
666 {
667 	struct io_overflow_cqe *ocqe;
668 	LIST_HEAD(list);
669 
670 	spin_lock(&ctx->completion_lock);
671 	list_splice_init(&ctx->cq_overflow_list, &list);
672 	clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
673 	spin_unlock(&ctx->completion_lock);
674 
675 	while (!list_empty(&list)) {
676 		ocqe = list_first_entry(&list, struct io_overflow_cqe, list);
677 		list_del(&ocqe->list);
678 		kfree(ocqe);
679 	}
680 }
681 
682 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx)
683 {
684 	size_t cqe_size = sizeof(struct io_uring_cqe);
685 
686 	if (__io_cqring_events(ctx) == ctx->cq_entries)
687 		return;
688 
689 	if (ctx->flags & IORING_SETUP_CQE32)
690 		cqe_size <<= 1;
691 
692 	io_cq_lock(ctx);
693 	while (!list_empty(&ctx->cq_overflow_list)) {
694 		struct io_uring_cqe *cqe;
695 		struct io_overflow_cqe *ocqe;
696 
697 		if (!io_get_cqe_overflow(ctx, &cqe, true))
698 			break;
699 		ocqe = list_first_entry(&ctx->cq_overflow_list,
700 					struct io_overflow_cqe, list);
701 		memcpy(cqe, &ocqe->cqe, cqe_size);
702 		list_del(&ocqe->list);
703 		kfree(ocqe);
704 
705 		/*
706 		 * For silly syzbot cases that deliberately overflow by huge
707 		 * amounts, check if we need to resched and drop and
708 		 * reacquire the locks if so. Nothing real would ever hit this.
709 		 * Ideally we'd have a non-posting unlock for this, but hard
710 		 * to care for a non-real case.
711 		 */
712 		if (need_resched()) {
713 			io_cq_unlock_post(ctx);
714 			mutex_unlock(&ctx->uring_lock);
715 			cond_resched();
716 			mutex_lock(&ctx->uring_lock);
717 			io_cq_lock(ctx);
718 		}
719 	}
720 
721 	if (list_empty(&ctx->cq_overflow_list)) {
722 		clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
723 		atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
724 	}
725 	io_cq_unlock_post(ctx);
726 }
727 
728 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
729 {
730 	/* iopoll syncs against uring_lock, not completion_lock */
731 	if (ctx->flags & IORING_SETUP_IOPOLL)
732 		mutex_lock(&ctx->uring_lock);
733 	__io_cqring_overflow_flush(ctx);
734 	if (ctx->flags & IORING_SETUP_IOPOLL)
735 		mutex_unlock(&ctx->uring_lock);
736 }
737 
738 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx)
739 {
740 	if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
741 		io_cqring_do_overflow_flush(ctx);
742 }
743 
744 /* can be called by any task */
745 static void io_put_task_remote(struct task_struct *task)
746 {
747 	struct io_uring_task *tctx = task->io_uring;
748 
749 	percpu_counter_sub(&tctx->inflight, 1);
750 	if (unlikely(atomic_read(&tctx->in_cancel)))
751 		wake_up(&tctx->wait);
752 	put_task_struct(task);
753 }
754 
755 /* used by a task to put its own references */
756 static void io_put_task_local(struct task_struct *task)
757 {
758 	task->io_uring->cached_refs++;
759 }
760 
761 /* must to be called somewhat shortly after putting a request */
762 static inline void io_put_task(struct task_struct *task)
763 {
764 	if (likely(task == current))
765 		io_put_task_local(task);
766 	else
767 		io_put_task_remote(task);
768 }
769 
770 void io_task_refs_refill(struct io_uring_task *tctx)
771 {
772 	unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
773 
774 	percpu_counter_add(&tctx->inflight, refill);
775 	refcount_add(refill, &current->usage);
776 	tctx->cached_refs += refill;
777 }
778 
779 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
780 {
781 	struct io_uring_task *tctx = task->io_uring;
782 	unsigned int refs = tctx->cached_refs;
783 
784 	if (refs) {
785 		tctx->cached_refs = 0;
786 		percpu_counter_sub(&tctx->inflight, refs);
787 		put_task_struct_many(task, refs);
788 	}
789 }
790 
791 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
792 				     s32 res, u32 cflags, u64 extra1, u64 extra2)
793 {
794 	struct io_overflow_cqe *ocqe;
795 	size_t ocq_size = sizeof(struct io_overflow_cqe);
796 	bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
797 
798 	lockdep_assert_held(&ctx->completion_lock);
799 
800 	if (is_cqe32)
801 		ocq_size += sizeof(struct io_uring_cqe);
802 
803 	ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
804 	trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
805 	if (!ocqe) {
806 		/*
807 		 * If we're in ring overflow flush mode, or in task cancel mode,
808 		 * or cannot allocate an overflow entry, then we need to drop it
809 		 * on the floor.
810 		 */
811 		io_account_cq_overflow(ctx);
812 		set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
813 		return false;
814 	}
815 	if (list_empty(&ctx->cq_overflow_list)) {
816 		set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
817 		atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
818 
819 	}
820 	ocqe->cqe.user_data = user_data;
821 	ocqe->cqe.res = res;
822 	ocqe->cqe.flags = cflags;
823 	if (is_cqe32) {
824 		ocqe->cqe.big_cqe[0] = extra1;
825 		ocqe->cqe.big_cqe[1] = extra2;
826 	}
827 	list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
828 	return true;
829 }
830 
831 void io_req_cqe_overflow(struct io_kiocb *req)
832 {
833 	io_cqring_event_overflow(req->ctx, req->cqe.user_data,
834 				req->cqe.res, req->cqe.flags,
835 				req->big_cqe.extra1, req->big_cqe.extra2);
836 	memset(&req->big_cqe, 0, sizeof(req->big_cqe));
837 }
838 
839 /*
840  * writes to the cq entry need to come after reading head; the
841  * control dependency is enough as we're using WRITE_ONCE to
842  * fill the cq entry
843  */
844 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
845 {
846 	struct io_rings *rings = ctx->rings;
847 	unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
848 	unsigned int free, queued, len;
849 
850 	/*
851 	 * Posting into the CQ when there are pending overflowed CQEs may break
852 	 * ordering guarantees, which will affect links, F_MORE users and more.
853 	 * Force overflow the completion.
854 	 */
855 	if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
856 		return false;
857 
858 	/* userspace may cheat modifying the tail, be safe and do min */
859 	queued = min(__io_cqring_events(ctx), ctx->cq_entries);
860 	free = ctx->cq_entries - queued;
861 	/* we need a contiguous range, limit based on the current array offset */
862 	len = min(free, ctx->cq_entries - off);
863 	if (!len)
864 		return false;
865 
866 	if (ctx->flags & IORING_SETUP_CQE32) {
867 		off <<= 1;
868 		len <<= 1;
869 	}
870 
871 	ctx->cqe_cached = &rings->cqes[off];
872 	ctx->cqe_sentinel = ctx->cqe_cached + len;
873 	return true;
874 }
875 
876 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
877 			      u32 cflags)
878 {
879 	struct io_uring_cqe *cqe;
880 
881 	ctx->cq_extra++;
882 
883 	/*
884 	 * If we can't get a cq entry, userspace overflowed the
885 	 * submission (by quite a lot). Increment the overflow count in
886 	 * the ring.
887 	 */
888 	if (likely(io_get_cqe(ctx, &cqe))) {
889 		trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
890 
891 		WRITE_ONCE(cqe->user_data, user_data);
892 		WRITE_ONCE(cqe->res, res);
893 		WRITE_ONCE(cqe->flags, cflags);
894 
895 		if (ctx->flags & IORING_SETUP_CQE32) {
896 			WRITE_ONCE(cqe->big_cqe[0], 0);
897 			WRITE_ONCE(cqe->big_cqe[1], 0);
898 		}
899 		return true;
900 	}
901 	return false;
902 }
903 
904 static void __io_flush_post_cqes(struct io_ring_ctx *ctx)
905 	__must_hold(&ctx->uring_lock)
906 {
907 	struct io_submit_state *state = &ctx->submit_state;
908 	unsigned int i;
909 
910 	lockdep_assert_held(&ctx->uring_lock);
911 	for (i = 0; i < state->cqes_count; i++) {
912 		struct io_uring_cqe *cqe = &ctx->completion_cqes[i];
913 
914 		if (!io_fill_cqe_aux(ctx, cqe->user_data, cqe->res, cqe->flags)) {
915 			if (ctx->lockless_cq) {
916 				spin_lock(&ctx->completion_lock);
917 				io_cqring_event_overflow(ctx, cqe->user_data,
918 							cqe->res, cqe->flags, 0, 0);
919 				spin_unlock(&ctx->completion_lock);
920 			} else {
921 				io_cqring_event_overflow(ctx, cqe->user_data,
922 							cqe->res, cqe->flags, 0, 0);
923 			}
924 		}
925 	}
926 	state->cqes_count = 0;
927 }
928 
929 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags,
930 			      bool allow_overflow)
931 {
932 	bool filled;
933 
934 	io_cq_lock(ctx);
935 	filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
936 	if (!filled && allow_overflow)
937 		filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
938 
939 	io_cq_unlock_post(ctx);
940 	return filled;
941 }
942 
943 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
944 {
945 	return __io_post_aux_cqe(ctx, user_data, res, cflags, true);
946 }
947 
948 /*
949  * A helper for multishot requests posting additional CQEs.
950  * Should only be used from a task_work including IO_URING_F_MULTISHOT.
951  */
952 bool io_fill_cqe_req_aux(struct io_kiocb *req, bool defer, s32 res, u32 cflags)
953 {
954 	struct io_ring_ctx *ctx = req->ctx;
955 	u64 user_data = req->cqe.user_data;
956 	struct io_uring_cqe *cqe;
957 
958 	if (!defer)
959 		return __io_post_aux_cqe(ctx, user_data, res, cflags, false);
960 
961 	lockdep_assert_held(&ctx->uring_lock);
962 
963 	if (ctx->submit_state.cqes_count == ARRAY_SIZE(ctx->completion_cqes)) {
964 		__io_cq_lock(ctx);
965 		__io_flush_post_cqes(ctx);
966 		/* no need to flush - flush is deferred */
967 		__io_cq_unlock_post(ctx);
968 	}
969 
970 	/* For defered completions this is not as strict as it is otherwise,
971 	 * however it's main job is to prevent unbounded posted completions,
972 	 * and in that it works just as well.
973 	 */
974 	if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
975 		return false;
976 
977 	cqe = &ctx->completion_cqes[ctx->submit_state.cqes_count++];
978 	cqe->user_data = user_data;
979 	cqe->res = res;
980 	cqe->flags = cflags;
981 	return true;
982 }
983 
984 static void __io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
985 {
986 	struct io_ring_ctx *ctx = req->ctx;
987 	struct io_rsrc_node *rsrc_node = NULL;
988 
989 	io_cq_lock(ctx);
990 	if (!(req->flags & REQ_F_CQE_SKIP)) {
991 		if (!io_fill_cqe_req(ctx, req))
992 			io_req_cqe_overflow(req);
993 	}
994 
995 	/*
996 	 * If we're the last reference to this request, add to our locked
997 	 * free_list cache.
998 	 */
999 	if (req_ref_put_and_test(req)) {
1000 		if (req->flags & IO_REQ_LINK_FLAGS) {
1001 			if (req->flags & IO_DISARM_MASK)
1002 				io_disarm_next(req);
1003 			if (req->link) {
1004 				io_req_task_queue(req->link);
1005 				req->link = NULL;
1006 			}
1007 		}
1008 		io_put_kbuf_comp(req);
1009 		if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1010 			io_clean_op(req);
1011 		io_put_file(req);
1012 
1013 		rsrc_node = req->rsrc_node;
1014 		/*
1015 		 * Selected buffer deallocation in io_clean_op() assumes that
1016 		 * we don't hold ->completion_lock. Clean them here to avoid
1017 		 * deadlocks.
1018 		 */
1019 		io_put_task_remote(req->task);
1020 		wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1021 		ctx->locked_free_nr++;
1022 	}
1023 	io_cq_unlock_post(ctx);
1024 
1025 	if (rsrc_node) {
1026 		io_ring_submit_lock(ctx, issue_flags);
1027 		io_put_rsrc_node(ctx, rsrc_node);
1028 		io_ring_submit_unlock(ctx, issue_flags);
1029 	}
1030 }
1031 
1032 void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
1033 {
1034 	if (req->ctx->task_complete && req->ctx->submitter_task != current) {
1035 		req->io_task_work.func = io_req_task_complete;
1036 		io_req_task_work_add(req);
1037 	} else if (!(issue_flags & IO_URING_F_UNLOCKED) ||
1038 		   !(req->ctx->flags & IORING_SETUP_IOPOLL)) {
1039 		__io_req_complete_post(req, issue_flags);
1040 	} else {
1041 		struct io_ring_ctx *ctx = req->ctx;
1042 
1043 		mutex_lock(&ctx->uring_lock);
1044 		__io_req_complete_post(req, issue_flags & ~IO_URING_F_UNLOCKED);
1045 		mutex_unlock(&ctx->uring_lock);
1046 	}
1047 }
1048 
1049 void io_req_defer_failed(struct io_kiocb *req, s32 res)
1050 	__must_hold(&ctx->uring_lock)
1051 {
1052 	const struct io_cold_def *def = &io_cold_defs[req->opcode];
1053 
1054 	lockdep_assert_held(&req->ctx->uring_lock);
1055 
1056 	req_set_fail(req);
1057 	io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1058 	if (def->fail)
1059 		def->fail(req);
1060 	io_req_complete_defer(req);
1061 }
1062 
1063 /*
1064  * Don't initialise the fields below on every allocation, but do that in
1065  * advance and keep them valid across allocations.
1066  */
1067 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1068 {
1069 	req->ctx = ctx;
1070 	req->link = NULL;
1071 	req->async_data = NULL;
1072 	/* not necessary, but safer to zero */
1073 	memset(&req->cqe, 0, sizeof(req->cqe));
1074 	memset(&req->big_cqe, 0, sizeof(req->big_cqe));
1075 }
1076 
1077 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1078 					struct io_submit_state *state)
1079 {
1080 	spin_lock(&ctx->completion_lock);
1081 	wq_list_splice(&ctx->locked_free_list, &state->free_list);
1082 	ctx->locked_free_nr = 0;
1083 	spin_unlock(&ctx->completion_lock);
1084 }
1085 
1086 /*
1087  * A request might get retired back into the request caches even before opcode
1088  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1089  * Because of that, io_alloc_req() should be called only under ->uring_lock
1090  * and with extra caution to not get a request that is still worked on.
1091  */
1092 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1093 	__must_hold(&ctx->uring_lock)
1094 {
1095 	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1096 	void *reqs[IO_REQ_ALLOC_BATCH];
1097 	int ret, i;
1098 
1099 	/*
1100 	 * If we have more than a batch's worth of requests in our IRQ side
1101 	 * locked cache, grab the lock and move them over to our submission
1102 	 * side cache.
1103 	 */
1104 	if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1105 		io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1106 		if (!io_req_cache_empty(ctx))
1107 			return true;
1108 	}
1109 
1110 	ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1111 
1112 	/*
1113 	 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1114 	 * retry single alloc to be on the safe side.
1115 	 */
1116 	if (unlikely(ret <= 0)) {
1117 		reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1118 		if (!reqs[0])
1119 			return false;
1120 		ret = 1;
1121 	}
1122 
1123 	percpu_ref_get_many(&ctx->refs, ret);
1124 	for (i = 0; i < ret; i++) {
1125 		struct io_kiocb *req = reqs[i];
1126 
1127 		io_preinit_req(req, ctx);
1128 		io_req_add_to_cache(req, ctx);
1129 	}
1130 	return true;
1131 }
1132 
1133 __cold void io_free_req(struct io_kiocb *req)
1134 {
1135 	/* refs were already put, restore them for io_req_task_complete() */
1136 	req->flags &= ~REQ_F_REFCOUNT;
1137 	/* we only want to free it, don't post CQEs */
1138 	req->flags |= REQ_F_CQE_SKIP;
1139 	req->io_task_work.func = io_req_task_complete;
1140 	io_req_task_work_add(req);
1141 }
1142 
1143 static void __io_req_find_next_prep(struct io_kiocb *req)
1144 {
1145 	struct io_ring_ctx *ctx = req->ctx;
1146 
1147 	spin_lock(&ctx->completion_lock);
1148 	io_disarm_next(req);
1149 	spin_unlock(&ctx->completion_lock);
1150 }
1151 
1152 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1153 {
1154 	struct io_kiocb *nxt;
1155 
1156 	/*
1157 	 * If LINK is set, we have dependent requests in this chain. If we
1158 	 * didn't fail this request, queue the first one up, moving any other
1159 	 * dependencies to the next request. In case of failure, fail the rest
1160 	 * of the chain.
1161 	 */
1162 	if (unlikely(req->flags & IO_DISARM_MASK))
1163 		__io_req_find_next_prep(req);
1164 	nxt = req->link;
1165 	req->link = NULL;
1166 	return nxt;
1167 }
1168 
1169 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
1170 {
1171 	if (!ctx)
1172 		return;
1173 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1174 		atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1175 	if (ts->locked) {
1176 		io_submit_flush_completions(ctx);
1177 		mutex_unlock(&ctx->uring_lock);
1178 		ts->locked = false;
1179 	}
1180 	percpu_ref_put(&ctx->refs);
1181 }
1182 
1183 static unsigned int handle_tw_list(struct llist_node *node,
1184 				   struct io_ring_ctx **ctx,
1185 				   struct io_tw_state *ts)
1186 {
1187 	unsigned int count = 0;
1188 
1189 	do {
1190 		struct llist_node *next = node->next;
1191 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1192 						    io_task_work.node);
1193 
1194 		prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1195 
1196 		if (req->ctx != *ctx) {
1197 			ctx_flush_and_put(*ctx, ts);
1198 			*ctx = req->ctx;
1199 			/* if not contended, grab and improve batching */
1200 			ts->locked = mutex_trylock(&(*ctx)->uring_lock);
1201 			percpu_ref_get(&(*ctx)->refs);
1202 		}
1203 		INDIRECT_CALL_2(req->io_task_work.func,
1204 				io_poll_task_func, io_req_rw_complete,
1205 				req, ts);
1206 		node = next;
1207 		count++;
1208 		if (unlikely(need_resched())) {
1209 			ctx_flush_and_put(*ctx, ts);
1210 			*ctx = NULL;
1211 			cond_resched();
1212 		}
1213 	} while (node);
1214 
1215 	return count;
1216 }
1217 
1218 /**
1219  * io_llist_xchg - swap all entries in a lock-less list
1220  * @head:	the head of lock-less list to delete all entries
1221  * @new:	new entry as the head of the list
1222  *
1223  * If list is empty, return NULL, otherwise, return the pointer to the first entry.
1224  * The order of entries returned is from the newest to the oldest added one.
1225  */
1226 static inline struct llist_node *io_llist_xchg(struct llist_head *head,
1227 					       struct llist_node *new)
1228 {
1229 	return xchg(&head->first, new);
1230 }
1231 
1232 static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1233 {
1234 	struct llist_node *node = llist_del_all(&tctx->task_list);
1235 	struct io_ring_ctx *last_ctx = NULL;
1236 	struct io_kiocb *req;
1237 
1238 	while (node) {
1239 		req = container_of(node, struct io_kiocb, io_task_work.node);
1240 		node = node->next;
1241 		if (sync && last_ctx != req->ctx) {
1242 			if (last_ctx) {
1243 				flush_delayed_work(&last_ctx->fallback_work);
1244 				percpu_ref_put(&last_ctx->refs);
1245 			}
1246 			last_ctx = req->ctx;
1247 			percpu_ref_get(&last_ctx->refs);
1248 		}
1249 		if (llist_add(&req->io_task_work.node,
1250 			      &req->ctx->fallback_llist))
1251 			schedule_delayed_work(&req->ctx->fallback_work, 1);
1252 	}
1253 
1254 	if (last_ctx) {
1255 		flush_delayed_work(&last_ctx->fallback_work);
1256 		percpu_ref_put(&last_ctx->refs);
1257 	}
1258 }
1259 
1260 void tctx_task_work(struct callback_head *cb)
1261 {
1262 	struct io_tw_state ts = {};
1263 	struct io_ring_ctx *ctx = NULL;
1264 	struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1265 						  task_work);
1266 	struct llist_node *node;
1267 	unsigned int count = 0;
1268 
1269 	if (unlikely(current->flags & PF_EXITING)) {
1270 		io_fallback_tw(tctx, true);
1271 		return;
1272 	}
1273 
1274 	node = llist_del_all(&tctx->task_list);
1275 	if (node)
1276 		count = handle_tw_list(node, &ctx, &ts);
1277 
1278 	ctx_flush_and_put(ctx, &ts);
1279 
1280 	/* relaxed read is enough as only the task itself sets ->in_cancel */
1281 	if (unlikely(atomic_read(&tctx->in_cancel)))
1282 		io_uring_drop_tctx_refs(current);
1283 
1284 	trace_io_uring_task_work_run(tctx, count, 1);
1285 }
1286 
1287 static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1288 {
1289 	struct io_ring_ctx *ctx = req->ctx;
1290 	unsigned nr_wait, nr_tw, nr_tw_prev;
1291 	struct llist_node *first;
1292 
1293 	if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1294 		flags &= ~IOU_F_TWQ_LAZY_WAKE;
1295 
1296 	first = READ_ONCE(ctx->work_llist.first);
1297 	do {
1298 		nr_tw_prev = 0;
1299 		if (first) {
1300 			struct io_kiocb *first_req = container_of(first,
1301 							struct io_kiocb,
1302 							io_task_work.node);
1303 			/*
1304 			 * Might be executed at any moment, rely on
1305 			 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1306 			 */
1307 			nr_tw_prev = READ_ONCE(first_req->nr_tw);
1308 		}
1309 		nr_tw = nr_tw_prev + 1;
1310 		/* Large enough to fail the nr_wait comparison below */
1311 		if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1312 			nr_tw = INT_MAX;
1313 
1314 		req->nr_tw = nr_tw;
1315 		req->io_task_work.node.next = first;
1316 	} while (!try_cmpxchg(&ctx->work_llist.first, &first,
1317 			      &req->io_task_work.node));
1318 
1319 	if (!first) {
1320 		if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1321 			atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1322 		if (ctx->has_evfd)
1323 			io_eventfd_signal(ctx);
1324 	}
1325 
1326 	nr_wait = atomic_read(&ctx->cq_wait_nr);
1327 	/* no one is waiting */
1328 	if (!nr_wait)
1329 		return;
1330 	/* either not enough or the previous add has already woken it up */
1331 	if (nr_wait > nr_tw || nr_tw_prev >= nr_wait)
1332 		return;
1333 	/* pairs with set_current_state() in io_cqring_wait() */
1334 	smp_mb__after_atomic();
1335 	wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1336 }
1337 
1338 static void io_req_normal_work_add(struct io_kiocb *req)
1339 {
1340 	struct io_uring_task *tctx = req->task->io_uring;
1341 	struct io_ring_ctx *ctx = req->ctx;
1342 
1343 	/* task_work already pending, we're done */
1344 	if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1345 		return;
1346 
1347 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1348 		atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1349 
1350 	if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1351 		return;
1352 
1353 	io_fallback_tw(tctx, false);
1354 }
1355 
1356 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1357 {
1358 	if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
1359 		rcu_read_lock();
1360 		io_req_local_work_add(req, flags);
1361 		rcu_read_unlock();
1362 	} else {
1363 		io_req_normal_work_add(req);
1364 	}
1365 }
1366 
1367 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1368 {
1369 	struct llist_node *node;
1370 
1371 	node = llist_del_all(&ctx->work_llist);
1372 	while (node) {
1373 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1374 						    io_task_work.node);
1375 
1376 		node = node->next;
1377 		io_req_normal_work_add(req);
1378 	}
1379 }
1380 
1381 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1382 				       int min_events)
1383 {
1384 	if (llist_empty(&ctx->work_llist))
1385 		return false;
1386 	if (events < min_events)
1387 		return true;
1388 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1389 		atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1390 	return false;
1391 }
1392 
1393 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1394 			       int min_events)
1395 {
1396 	struct llist_node *node;
1397 	unsigned int loops = 0;
1398 	int ret = 0;
1399 
1400 	if (WARN_ON_ONCE(ctx->submitter_task != current))
1401 		return -EEXIST;
1402 	if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1403 		atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1404 again:
1405 	/*
1406 	 * llists are in reverse order, flip it back the right way before
1407 	 * running the pending items.
1408 	 */
1409 	node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
1410 	while (node) {
1411 		struct llist_node *next = node->next;
1412 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1413 						    io_task_work.node);
1414 		prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1415 		INDIRECT_CALL_2(req->io_task_work.func,
1416 				io_poll_task_func, io_req_rw_complete,
1417 				req, ts);
1418 		ret++;
1419 		node = next;
1420 	}
1421 	loops++;
1422 
1423 	if (io_run_local_work_continue(ctx, ret, min_events))
1424 		goto again;
1425 	if (ts->locked) {
1426 		io_submit_flush_completions(ctx);
1427 		if (io_run_local_work_continue(ctx, ret, min_events))
1428 			goto again;
1429 	}
1430 
1431 	trace_io_uring_local_work_run(ctx, ret, loops);
1432 	return ret;
1433 }
1434 
1435 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1436 					   int min_events)
1437 {
1438 	struct io_tw_state ts = { .locked = true, };
1439 	int ret;
1440 
1441 	if (llist_empty(&ctx->work_llist))
1442 		return 0;
1443 
1444 	ret = __io_run_local_work(ctx, &ts, min_events);
1445 	/* shouldn't happen! */
1446 	if (WARN_ON_ONCE(!ts.locked))
1447 		mutex_lock(&ctx->uring_lock);
1448 	return ret;
1449 }
1450 
1451 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
1452 {
1453 	struct io_tw_state ts = {};
1454 	int ret;
1455 
1456 	ts.locked = mutex_trylock(&ctx->uring_lock);
1457 	ret = __io_run_local_work(ctx, &ts, min_events);
1458 	if (ts.locked)
1459 		mutex_unlock(&ctx->uring_lock);
1460 
1461 	return ret;
1462 }
1463 
1464 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
1465 {
1466 	io_tw_lock(req->ctx, ts);
1467 	io_req_defer_failed(req, req->cqe.res);
1468 }
1469 
1470 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
1471 {
1472 	io_tw_lock(req->ctx, ts);
1473 	/* req->task == current here, checking PF_EXITING is safe */
1474 	if (unlikely(req->task->flags & PF_EXITING))
1475 		io_req_defer_failed(req, -EFAULT);
1476 	else if (req->flags & REQ_F_FORCE_ASYNC)
1477 		io_queue_iowq(req, ts);
1478 	else
1479 		io_queue_sqe(req);
1480 }
1481 
1482 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1483 {
1484 	io_req_set_res(req, ret, 0);
1485 	req->io_task_work.func = io_req_task_cancel;
1486 	io_req_task_work_add(req);
1487 }
1488 
1489 void io_req_task_queue(struct io_kiocb *req)
1490 {
1491 	req->io_task_work.func = io_req_task_submit;
1492 	io_req_task_work_add(req);
1493 }
1494 
1495 void io_queue_next(struct io_kiocb *req)
1496 {
1497 	struct io_kiocb *nxt = io_req_find_next(req);
1498 
1499 	if (nxt)
1500 		io_req_task_queue(nxt);
1501 }
1502 
1503 static void io_free_batch_list(struct io_ring_ctx *ctx,
1504 			       struct io_wq_work_node *node)
1505 	__must_hold(&ctx->uring_lock)
1506 {
1507 	do {
1508 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1509 						    comp_list);
1510 
1511 		if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1512 			if (req->flags & REQ_F_REFCOUNT) {
1513 				node = req->comp_list.next;
1514 				if (!req_ref_put_and_test(req))
1515 					continue;
1516 			}
1517 			if ((req->flags & REQ_F_POLLED) && req->apoll) {
1518 				struct async_poll *apoll = req->apoll;
1519 
1520 				if (apoll->double_poll)
1521 					kfree(apoll->double_poll);
1522 				if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache))
1523 					kfree(apoll);
1524 				req->flags &= ~REQ_F_POLLED;
1525 			}
1526 			if (req->flags & IO_REQ_LINK_FLAGS)
1527 				io_queue_next(req);
1528 			if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1529 				io_clean_op(req);
1530 		}
1531 		io_put_file(req);
1532 
1533 		io_req_put_rsrc_locked(req, ctx);
1534 
1535 		io_put_task(req->task);
1536 		node = req->comp_list.next;
1537 		io_req_add_to_cache(req, ctx);
1538 	} while (node);
1539 }
1540 
1541 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1542 	__must_hold(&ctx->uring_lock)
1543 {
1544 	struct io_submit_state *state = &ctx->submit_state;
1545 	struct io_wq_work_node *node;
1546 
1547 	__io_cq_lock(ctx);
1548 	/* must come first to preserve CQE ordering in failure cases */
1549 	if (state->cqes_count)
1550 		__io_flush_post_cqes(ctx);
1551 	__wq_list_for_each(node, &state->compl_reqs) {
1552 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1553 					    comp_list);
1554 
1555 		if (!(req->flags & REQ_F_CQE_SKIP) &&
1556 		    unlikely(!io_fill_cqe_req(ctx, req))) {
1557 			if (ctx->lockless_cq) {
1558 				spin_lock(&ctx->completion_lock);
1559 				io_req_cqe_overflow(req);
1560 				spin_unlock(&ctx->completion_lock);
1561 			} else {
1562 				io_req_cqe_overflow(req);
1563 			}
1564 		}
1565 	}
1566 	__io_cq_unlock_post(ctx);
1567 
1568 	if (!wq_list_empty(&ctx->submit_state.compl_reqs)) {
1569 		io_free_batch_list(ctx, state->compl_reqs.first);
1570 		INIT_WQ_LIST(&state->compl_reqs);
1571 	}
1572 }
1573 
1574 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1575 {
1576 	/* See comment at the top of this file */
1577 	smp_rmb();
1578 	return __io_cqring_events(ctx);
1579 }
1580 
1581 /*
1582  * We can't just wait for polled events to come to us, we have to actively
1583  * find and complete them.
1584  */
1585 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1586 {
1587 	if (!(ctx->flags & IORING_SETUP_IOPOLL))
1588 		return;
1589 
1590 	mutex_lock(&ctx->uring_lock);
1591 	while (!wq_list_empty(&ctx->iopoll_list)) {
1592 		/* let it sleep and repeat later if can't complete a request */
1593 		if (io_do_iopoll(ctx, true) == 0)
1594 			break;
1595 		/*
1596 		 * Ensure we allow local-to-the-cpu processing to take place,
1597 		 * in this case we need to ensure that we reap all events.
1598 		 * Also let task_work, etc. to progress by releasing the mutex
1599 		 */
1600 		if (need_resched()) {
1601 			mutex_unlock(&ctx->uring_lock);
1602 			cond_resched();
1603 			mutex_lock(&ctx->uring_lock);
1604 		}
1605 	}
1606 	mutex_unlock(&ctx->uring_lock);
1607 }
1608 
1609 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1610 {
1611 	unsigned int nr_events = 0;
1612 	unsigned long check_cq;
1613 
1614 	if (!io_allowed_run_tw(ctx))
1615 		return -EEXIST;
1616 
1617 	check_cq = READ_ONCE(ctx->check_cq);
1618 	if (unlikely(check_cq)) {
1619 		if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1620 			__io_cqring_overflow_flush(ctx);
1621 		/*
1622 		 * Similarly do not spin if we have not informed the user of any
1623 		 * dropped CQE.
1624 		 */
1625 		if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1626 			return -EBADR;
1627 	}
1628 	/*
1629 	 * Don't enter poll loop if we already have events pending.
1630 	 * If we do, we can potentially be spinning for commands that
1631 	 * already triggered a CQE (eg in error).
1632 	 */
1633 	if (io_cqring_events(ctx))
1634 		return 0;
1635 
1636 	do {
1637 		int ret = 0;
1638 
1639 		/*
1640 		 * If a submit got punted to a workqueue, we can have the
1641 		 * application entering polling for a command before it gets
1642 		 * issued. That app will hold the uring_lock for the duration
1643 		 * of the poll right here, so we need to take a breather every
1644 		 * now and then to ensure that the issue has a chance to add
1645 		 * the poll to the issued list. Otherwise we can spin here
1646 		 * forever, while the workqueue is stuck trying to acquire the
1647 		 * very same mutex.
1648 		 */
1649 		if (wq_list_empty(&ctx->iopoll_list) ||
1650 		    io_task_work_pending(ctx)) {
1651 			u32 tail = ctx->cached_cq_tail;
1652 
1653 			(void) io_run_local_work_locked(ctx, min);
1654 
1655 			if (task_work_pending(current) ||
1656 			    wq_list_empty(&ctx->iopoll_list)) {
1657 				mutex_unlock(&ctx->uring_lock);
1658 				io_run_task_work();
1659 				mutex_lock(&ctx->uring_lock);
1660 			}
1661 			/* some requests don't go through iopoll_list */
1662 			if (tail != ctx->cached_cq_tail ||
1663 			    wq_list_empty(&ctx->iopoll_list))
1664 				break;
1665 		}
1666 		ret = io_do_iopoll(ctx, !min);
1667 		if (unlikely(ret < 0))
1668 			return ret;
1669 
1670 		if (task_sigpending(current))
1671 			return -EINTR;
1672 		if (need_resched())
1673 			break;
1674 
1675 		nr_events += ret;
1676 	} while (nr_events < min);
1677 
1678 	return 0;
1679 }
1680 
1681 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
1682 {
1683 	if (ts->locked)
1684 		io_req_complete_defer(req);
1685 	else
1686 		io_req_complete_post(req, IO_URING_F_UNLOCKED);
1687 }
1688 
1689 /*
1690  * After the iocb has been issued, it's safe to be found on the poll list.
1691  * Adding the kiocb to the list AFTER submission ensures that we don't
1692  * find it from a io_do_iopoll() thread before the issuer is done
1693  * accessing the kiocb cookie.
1694  */
1695 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1696 {
1697 	struct io_ring_ctx *ctx = req->ctx;
1698 	const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1699 
1700 	/* workqueue context doesn't hold uring_lock, grab it now */
1701 	if (unlikely(needs_lock))
1702 		mutex_lock(&ctx->uring_lock);
1703 
1704 	/*
1705 	 * Track whether we have multiple files in our lists. This will impact
1706 	 * how we do polling eventually, not spinning if we're on potentially
1707 	 * different devices.
1708 	 */
1709 	if (wq_list_empty(&ctx->iopoll_list)) {
1710 		ctx->poll_multi_queue = false;
1711 	} else if (!ctx->poll_multi_queue) {
1712 		struct io_kiocb *list_req;
1713 
1714 		list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1715 					comp_list);
1716 		if (list_req->file != req->file)
1717 			ctx->poll_multi_queue = true;
1718 	}
1719 
1720 	/*
1721 	 * For fast devices, IO may have already completed. If it has, add
1722 	 * it to the front so we find it first.
1723 	 */
1724 	if (READ_ONCE(req->iopoll_completed))
1725 		wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1726 	else
1727 		wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1728 
1729 	if (unlikely(needs_lock)) {
1730 		/*
1731 		 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1732 		 * in sq thread task context or in io worker task context. If
1733 		 * current task context is sq thread, we don't need to check
1734 		 * whether should wake up sq thread.
1735 		 */
1736 		if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1737 		    wq_has_sleeper(&ctx->sq_data->wait))
1738 			wake_up(&ctx->sq_data->wait);
1739 
1740 		mutex_unlock(&ctx->uring_lock);
1741 	}
1742 }
1743 
1744 unsigned int io_file_get_flags(struct file *file)
1745 {
1746 	unsigned int res = 0;
1747 
1748 	if (S_ISREG(file_inode(file)->i_mode))
1749 		res |= REQ_F_ISREG;
1750 	if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1751 		res |= REQ_F_SUPPORT_NOWAIT;
1752 	return res;
1753 }
1754 
1755 bool io_alloc_async_data(struct io_kiocb *req)
1756 {
1757 	WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size);
1758 	req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL);
1759 	if (req->async_data) {
1760 		req->flags |= REQ_F_ASYNC_DATA;
1761 		return false;
1762 	}
1763 	return true;
1764 }
1765 
1766 int io_req_prep_async(struct io_kiocb *req)
1767 {
1768 	const struct io_cold_def *cdef = &io_cold_defs[req->opcode];
1769 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1770 
1771 	/* assign early for deferred execution for non-fixed file */
1772 	if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file)
1773 		req->file = io_file_get_normal(req, req->cqe.fd);
1774 	if (!cdef->prep_async)
1775 		return 0;
1776 	if (WARN_ON_ONCE(req_has_async_data(req)))
1777 		return -EFAULT;
1778 	if (!def->manual_alloc) {
1779 		if (io_alloc_async_data(req))
1780 			return -EAGAIN;
1781 	}
1782 	return cdef->prep_async(req);
1783 }
1784 
1785 static u32 io_get_sequence(struct io_kiocb *req)
1786 {
1787 	u32 seq = req->ctx->cached_sq_head;
1788 	struct io_kiocb *cur;
1789 
1790 	/* need original cached_sq_head, but it was increased for each req */
1791 	io_for_each_link(cur, req)
1792 		seq--;
1793 	return seq;
1794 }
1795 
1796 static __cold void io_drain_req(struct io_kiocb *req)
1797 	__must_hold(&ctx->uring_lock)
1798 {
1799 	struct io_ring_ctx *ctx = req->ctx;
1800 	struct io_defer_entry *de;
1801 	int ret;
1802 	u32 seq = io_get_sequence(req);
1803 
1804 	/* Still need defer if there is pending req in defer list. */
1805 	spin_lock(&ctx->completion_lock);
1806 	if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1807 		spin_unlock(&ctx->completion_lock);
1808 queue:
1809 		ctx->drain_active = false;
1810 		io_req_task_queue(req);
1811 		return;
1812 	}
1813 	spin_unlock(&ctx->completion_lock);
1814 
1815 	io_prep_async_link(req);
1816 	de = kmalloc(sizeof(*de), GFP_KERNEL);
1817 	if (!de) {
1818 		ret = -ENOMEM;
1819 		io_req_defer_failed(req, ret);
1820 		return;
1821 	}
1822 
1823 	spin_lock(&ctx->completion_lock);
1824 	if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1825 		spin_unlock(&ctx->completion_lock);
1826 		kfree(de);
1827 		goto queue;
1828 	}
1829 
1830 	trace_io_uring_defer(req);
1831 	de->req = req;
1832 	de->seq = seq;
1833 	list_add_tail(&de->list, &ctx->defer_list);
1834 	spin_unlock(&ctx->completion_lock);
1835 }
1836 
1837 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1838 			   unsigned int issue_flags)
1839 {
1840 	if (req->file || !def->needs_file)
1841 		return true;
1842 
1843 	if (req->flags & REQ_F_FIXED_FILE)
1844 		req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1845 	else
1846 		req->file = io_file_get_normal(req, req->cqe.fd);
1847 
1848 	return !!req->file;
1849 }
1850 
1851 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1852 {
1853 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1854 	const struct cred *creds = NULL;
1855 	int ret;
1856 
1857 	if (unlikely(!io_assign_file(req, def, issue_flags)))
1858 		return -EBADF;
1859 
1860 	if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
1861 		creds = override_creds(req->creds);
1862 
1863 	if (!def->audit_skip)
1864 		audit_uring_entry(req->opcode);
1865 
1866 	ret = def->issue(req, issue_flags);
1867 
1868 	if (!def->audit_skip)
1869 		audit_uring_exit(!ret, ret);
1870 
1871 	if (creds)
1872 		revert_creds(creds);
1873 
1874 	if (ret == IOU_OK) {
1875 		if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1876 			io_req_complete_defer(req);
1877 		else
1878 			io_req_complete_post(req, issue_flags);
1879 
1880 		return 0;
1881 	}
1882 
1883 	if (ret != IOU_ISSUE_SKIP_COMPLETE)
1884 		return ret;
1885 
1886 	/* If the op doesn't have a file, we're not polling for it */
1887 	if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1888 		io_iopoll_req_issued(req, issue_flags);
1889 
1890 	return 0;
1891 }
1892 
1893 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
1894 {
1895 	io_tw_lock(req->ctx, ts);
1896 	return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1897 				 IO_URING_F_COMPLETE_DEFER);
1898 }
1899 
1900 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1901 {
1902 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1903 	struct io_kiocb *nxt = NULL;
1904 
1905 	if (req_ref_put_and_test(req)) {
1906 		if (req->flags & IO_REQ_LINK_FLAGS)
1907 			nxt = io_req_find_next(req);
1908 		io_free_req(req);
1909 	}
1910 	return nxt ? &nxt->work : NULL;
1911 }
1912 
1913 void io_wq_submit_work(struct io_wq_work *work)
1914 {
1915 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1916 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1917 	unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1918 	bool needs_poll = false;
1919 	int ret = 0, err = -ECANCELED;
1920 
1921 	/* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1922 	if (!(req->flags & REQ_F_REFCOUNT))
1923 		__io_req_set_refcount(req, 2);
1924 	else
1925 		req_ref_get(req);
1926 
1927 	io_arm_ltimeout(req);
1928 
1929 	/* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1930 	if (work->flags & IO_WQ_WORK_CANCEL) {
1931 fail:
1932 		io_req_task_queue_fail(req, err);
1933 		return;
1934 	}
1935 	if (!io_assign_file(req, def, issue_flags)) {
1936 		err = -EBADF;
1937 		work->flags |= IO_WQ_WORK_CANCEL;
1938 		goto fail;
1939 	}
1940 
1941 	if (req->flags & REQ_F_FORCE_ASYNC) {
1942 		bool opcode_poll = def->pollin || def->pollout;
1943 
1944 		if (opcode_poll && file_can_poll(req->file)) {
1945 			needs_poll = true;
1946 			issue_flags |= IO_URING_F_NONBLOCK;
1947 		}
1948 	}
1949 
1950 	do {
1951 		ret = io_issue_sqe(req, issue_flags);
1952 		if (ret != -EAGAIN)
1953 			break;
1954 
1955 		/*
1956 		 * If REQ_F_NOWAIT is set, then don't wait or retry with
1957 		 * poll. -EAGAIN is final for that case.
1958 		 */
1959 		if (req->flags & REQ_F_NOWAIT)
1960 			break;
1961 
1962 		/*
1963 		 * We can get EAGAIN for iopolled IO even though we're
1964 		 * forcing a sync submission from here, since we can't
1965 		 * wait for request slots on the block side.
1966 		 */
1967 		if (!needs_poll) {
1968 			if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1969 				break;
1970 			if (io_wq_worker_stopped())
1971 				break;
1972 			cond_resched();
1973 			continue;
1974 		}
1975 
1976 		if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1977 			return;
1978 		/* aborted or ready, in either case retry blocking */
1979 		needs_poll = false;
1980 		issue_flags &= ~IO_URING_F_NONBLOCK;
1981 	} while (1);
1982 
1983 	/* avoid locking problems by failing it from a clean context */
1984 	if (ret < 0)
1985 		io_req_task_queue_fail(req, ret);
1986 }
1987 
1988 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1989 				      unsigned int issue_flags)
1990 {
1991 	struct io_ring_ctx *ctx = req->ctx;
1992 	struct io_fixed_file *slot;
1993 	struct file *file = NULL;
1994 
1995 	io_ring_submit_lock(ctx, issue_flags);
1996 
1997 	if (unlikely((unsigned int)fd >= ctx->nr_user_files))
1998 		goto out;
1999 	fd = array_index_nospec(fd, ctx->nr_user_files);
2000 	slot = io_fixed_file_slot(&ctx->file_table, fd);
2001 	file = io_slot_file(slot);
2002 	req->flags |= io_slot_flags(slot);
2003 	io_req_set_rsrc_node(req, ctx, 0);
2004 out:
2005 	io_ring_submit_unlock(ctx, issue_flags);
2006 	return file;
2007 }
2008 
2009 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
2010 {
2011 	struct file *file = fget(fd);
2012 
2013 	trace_io_uring_file_get(req, fd);
2014 
2015 	/* we don't allow fixed io_uring files */
2016 	if (file && io_is_uring_fops(file))
2017 		io_req_track_inflight(req);
2018 	return file;
2019 }
2020 
2021 static void io_queue_async(struct io_kiocb *req, int ret)
2022 	__must_hold(&req->ctx->uring_lock)
2023 {
2024 	struct io_kiocb *linked_timeout;
2025 
2026 	if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
2027 		io_req_defer_failed(req, ret);
2028 		return;
2029 	}
2030 
2031 	linked_timeout = io_prep_linked_timeout(req);
2032 
2033 	switch (io_arm_poll_handler(req, 0)) {
2034 	case IO_APOLL_READY:
2035 		io_kbuf_recycle(req, 0);
2036 		io_req_task_queue(req);
2037 		break;
2038 	case IO_APOLL_ABORTED:
2039 		io_kbuf_recycle(req, 0);
2040 		io_queue_iowq(req, NULL);
2041 		break;
2042 	case IO_APOLL_OK:
2043 		break;
2044 	}
2045 
2046 	if (linked_timeout)
2047 		io_queue_linked_timeout(linked_timeout);
2048 }
2049 
2050 static inline void io_queue_sqe(struct io_kiocb *req)
2051 	__must_hold(&req->ctx->uring_lock)
2052 {
2053 	int ret;
2054 
2055 	ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
2056 
2057 	/*
2058 	 * We async punt it if the file wasn't marked NOWAIT, or if the file
2059 	 * doesn't support non-blocking read/write attempts
2060 	 */
2061 	if (likely(!ret))
2062 		io_arm_ltimeout(req);
2063 	else
2064 		io_queue_async(req, ret);
2065 }
2066 
2067 static void io_queue_sqe_fallback(struct io_kiocb *req)
2068 	__must_hold(&req->ctx->uring_lock)
2069 {
2070 	if (unlikely(req->flags & REQ_F_FAIL)) {
2071 		/*
2072 		 * We don't submit, fail them all, for that replace hardlinks
2073 		 * with normal links. Extra REQ_F_LINK is tolerated.
2074 		 */
2075 		req->flags &= ~REQ_F_HARDLINK;
2076 		req->flags |= REQ_F_LINK;
2077 		io_req_defer_failed(req, req->cqe.res);
2078 	} else {
2079 		int ret = io_req_prep_async(req);
2080 
2081 		if (unlikely(ret)) {
2082 			io_req_defer_failed(req, ret);
2083 			return;
2084 		}
2085 
2086 		if (unlikely(req->ctx->drain_active))
2087 			io_drain_req(req);
2088 		else
2089 			io_queue_iowq(req, NULL);
2090 	}
2091 }
2092 
2093 /*
2094  * Check SQE restrictions (opcode and flags).
2095  *
2096  * Returns 'true' if SQE is allowed, 'false' otherwise.
2097  */
2098 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2099 					struct io_kiocb *req,
2100 					unsigned int sqe_flags)
2101 {
2102 	if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2103 		return false;
2104 
2105 	if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2106 	    ctx->restrictions.sqe_flags_required)
2107 		return false;
2108 
2109 	if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2110 			  ctx->restrictions.sqe_flags_required))
2111 		return false;
2112 
2113 	return true;
2114 }
2115 
2116 static void io_init_req_drain(struct io_kiocb *req)
2117 {
2118 	struct io_ring_ctx *ctx = req->ctx;
2119 	struct io_kiocb *head = ctx->submit_state.link.head;
2120 
2121 	ctx->drain_active = true;
2122 	if (head) {
2123 		/*
2124 		 * If we need to drain a request in the middle of a link, drain
2125 		 * the head request and the next request/link after the current
2126 		 * link. Considering sequential execution of links,
2127 		 * REQ_F_IO_DRAIN will be maintained for every request of our
2128 		 * link.
2129 		 */
2130 		head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2131 		ctx->drain_next = true;
2132 	}
2133 }
2134 
2135 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2136 {
2137 	/* ensure per-opcode data is cleared if we fail before prep */
2138 	memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2139 	return err;
2140 }
2141 
2142 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2143 		       const struct io_uring_sqe *sqe)
2144 	__must_hold(&ctx->uring_lock)
2145 {
2146 	const struct io_issue_def *def;
2147 	unsigned int sqe_flags;
2148 	int personality;
2149 	u8 opcode;
2150 
2151 	/* req is partially pre-initialised, see io_preinit_req() */
2152 	req->opcode = opcode = READ_ONCE(sqe->opcode);
2153 	/* same numerical values with corresponding REQ_F_*, safe to copy */
2154 	req->flags = sqe_flags = READ_ONCE(sqe->flags);
2155 	req->cqe.user_data = READ_ONCE(sqe->user_data);
2156 	req->file = NULL;
2157 	req->rsrc_node = NULL;
2158 	req->task = current;
2159 
2160 	if (unlikely(opcode >= IORING_OP_LAST)) {
2161 		req->opcode = 0;
2162 		return io_init_fail_req(req, -EINVAL);
2163 	}
2164 	def = &io_issue_defs[opcode];
2165 	if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2166 		/* enforce forwards compatibility on users */
2167 		if (sqe_flags & ~SQE_VALID_FLAGS)
2168 			return io_init_fail_req(req, -EINVAL);
2169 		if (sqe_flags & IOSQE_BUFFER_SELECT) {
2170 			if (!def->buffer_select)
2171 				return io_init_fail_req(req, -EOPNOTSUPP);
2172 			req->buf_index = READ_ONCE(sqe->buf_group);
2173 		}
2174 		if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2175 			ctx->drain_disabled = true;
2176 		if (sqe_flags & IOSQE_IO_DRAIN) {
2177 			if (ctx->drain_disabled)
2178 				return io_init_fail_req(req, -EOPNOTSUPP);
2179 			io_init_req_drain(req);
2180 		}
2181 	}
2182 	if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2183 		if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2184 			return io_init_fail_req(req, -EACCES);
2185 		/* knock it to the slow queue path, will be drained there */
2186 		if (ctx->drain_active)
2187 			req->flags |= REQ_F_FORCE_ASYNC;
2188 		/* if there is no link, we're at "next" request and need to drain */
2189 		if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2190 			ctx->drain_next = false;
2191 			ctx->drain_active = true;
2192 			req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2193 		}
2194 	}
2195 
2196 	if (!def->ioprio && sqe->ioprio)
2197 		return io_init_fail_req(req, -EINVAL);
2198 	if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2199 		return io_init_fail_req(req, -EINVAL);
2200 
2201 	if (def->needs_file) {
2202 		struct io_submit_state *state = &ctx->submit_state;
2203 
2204 		req->cqe.fd = READ_ONCE(sqe->fd);
2205 
2206 		/*
2207 		 * Plug now if we have more than 2 IO left after this, and the
2208 		 * target is potentially a read/write to block based storage.
2209 		 */
2210 		if (state->need_plug && def->plug) {
2211 			state->plug_started = true;
2212 			state->need_plug = false;
2213 			blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2214 		}
2215 	}
2216 
2217 	personality = READ_ONCE(sqe->personality);
2218 	if (personality) {
2219 		int ret;
2220 
2221 		req->creds = xa_load(&ctx->personalities, personality);
2222 		if (!req->creds)
2223 			return io_init_fail_req(req, -EINVAL);
2224 		get_cred(req->creds);
2225 		ret = security_uring_override_creds(req->creds);
2226 		if (ret) {
2227 			put_cred(req->creds);
2228 			return io_init_fail_req(req, ret);
2229 		}
2230 		req->flags |= REQ_F_CREDS;
2231 	}
2232 
2233 	return def->prep(req, sqe);
2234 }
2235 
2236 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2237 				      struct io_kiocb *req, int ret)
2238 {
2239 	struct io_ring_ctx *ctx = req->ctx;
2240 	struct io_submit_link *link = &ctx->submit_state.link;
2241 	struct io_kiocb *head = link->head;
2242 
2243 	trace_io_uring_req_failed(sqe, req, ret);
2244 
2245 	/*
2246 	 * Avoid breaking links in the middle as it renders links with SQPOLL
2247 	 * unusable. Instead of failing eagerly, continue assembling the link if
2248 	 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2249 	 * should find the flag and handle the rest.
2250 	 */
2251 	req_fail_link_node(req, ret);
2252 	if (head && !(head->flags & REQ_F_FAIL))
2253 		req_fail_link_node(head, -ECANCELED);
2254 
2255 	if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2256 		if (head) {
2257 			link->last->link = req;
2258 			link->head = NULL;
2259 			req = head;
2260 		}
2261 		io_queue_sqe_fallback(req);
2262 		return ret;
2263 	}
2264 
2265 	if (head)
2266 		link->last->link = req;
2267 	else
2268 		link->head = req;
2269 	link->last = req;
2270 	return 0;
2271 }
2272 
2273 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2274 			 const struct io_uring_sqe *sqe)
2275 	__must_hold(&ctx->uring_lock)
2276 {
2277 	struct io_submit_link *link = &ctx->submit_state.link;
2278 	int ret;
2279 
2280 	ret = io_init_req(ctx, req, sqe);
2281 	if (unlikely(ret))
2282 		return io_submit_fail_init(sqe, req, ret);
2283 
2284 	trace_io_uring_submit_req(req);
2285 
2286 	/*
2287 	 * If we already have a head request, queue this one for async
2288 	 * submittal once the head completes. If we don't have a head but
2289 	 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2290 	 * submitted sync once the chain is complete. If none of those
2291 	 * conditions are true (normal request), then just queue it.
2292 	 */
2293 	if (unlikely(link->head)) {
2294 		ret = io_req_prep_async(req);
2295 		if (unlikely(ret))
2296 			return io_submit_fail_init(sqe, req, ret);
2297 
2298 		trace_io_uring_link(req, link->head);
2299 		link->last->link = req;
2300 		link->last = req;
2301 
2302 		if (req->flags & IO_REQ_LINK_FLAGS)
2303 			return 0;
2304 		/* last request of the link, flush it */
2305 		req = link->head;
2306 		link->head = NULL;
2307 		if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2308 			goto fallback;
2309 
2310 	} else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2311 					  REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2312 		if (req->flags & IO_REQ_LINK_FLAGS) {
2313 			link->head = req;
2314 			link->last = req;
2315 		} else {
2316 fallback:
2317 			io_queue_sqe_fallback(req);
2318 		}
2319 		return 0;
2320 	}
2321 
2322 	io_queue_sqe(req);
2323 	return 0;
2324 }
2325 
2326 /*
2327  * Batched submission is done, ensure local IO is flushed out.
2328  */
2329 static void io_submit_state_end(struct io_ring_ctx *ctx)
2330 {
2331 	struct io_submit_state *state = &ctx->submit_state;
2332 
2333 	if (unlikely(state->link.head))
2334 		io_queue_sqe_fallback(state->link.head);
2335 	/* flush only after queuing links as they can generate completions */
2336 	io_submit_flush_completions(ctx);
2337 	if (state->plug_started)
2338 		blk_finish_plug(&state->plug);
2339 }
2340 
2341 /*
2342  * Start submission side cache.
2343  */
2344 static void io_submit_state_start(struct io_submit_state *state,
2345 				  unsigned int max_ios)
2346 {
2347 	state->plug_started = false;
2348 	state->need_plug = max_ios > 2;
2349 	state->submit_nr = max_ios;
2350 	/* set only head, no need to init link_last in advance */
2351 	state->link.head = NULL;
2352 }
2353 
2354 static void io_commit_sqring(struct io_ring_ctx *ctx)
2355 {
2356 	struct io_rings *rings = ctx->rings;
2357 
2358 	/*
2359 	 * Ensure any loads from the SQEs are done at this point,
2360 	 * since once we write the new head, the application could
2361 	 * write new data to them.
2362 	 */
2363 	smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2364 }
2365 
2366 /*
2367  * Fetch an sqe, if one is available. Note this returns a pointer to memory
2368  * that is mapped by userspace. This means that care needs to be taken to
2369  * ensure that reads are stable, as we cannot rely on userspace always
2370  * being a good citizen. If members of the sqe are validated and then later
2371  * used, it's important that those reads are done through READ_ONCE() to
2372  * prevent a re-load down the line.
2373  */
2374 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2375 {
2376 	unsigned mask = ctx->sq_entries - 1;
2377 	unsigned head = ctx->cached_sq_head++ & mask;
2378 
2379 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
2380 		head = READ_ONCE(ctx->sq_array[head]);
2381 		if (unlikely(head >= ctx->sq_entries)) {
2382 			/* drop invalid entries */
2383 			spin_lock(&ctx->completion_lock);
2384 			ctx->cq_extra--;
2385 			spin_unlock(&ctx->completion_lock);
2386 			WRITE_ONCE(ctx->rings->sq_dropped,
2387 				   READ_ONCE(ctx->rings->sq_dropped) + 1);
2388 			return false;
2389 		}
2390 	}
2391 
2392 	/*
2393 	 * The cached sq head (or cq tail) serves two purposes:
2394 	 *
2395 	 * 1) allows us to batch the cost of updating the user visible
2396 	 *    head updates.
2397 	 * 2) allows the kernel side to track the head on its own, even
2398 	 *    though the application is the one updating it.
2399 	 */
2400 
2401 	/* double index for 128-byte SQEs, twice as long */
2402 	if (ctx->flags & IORING_SETUP_SQE128)
2403 		head <<= 1;
2404 	*sqe = &ctx->sq_sqes[head];
2405 	return true;
2406 }
2407 
2408 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2409 	__must_hold(&ctx->uring_lock)
2410 {
2411 	unsigned int entries = io_sqring_entries(ctx);
2412 	unsigned int left;
2413 	int ret;
2414 
2415 	if (unlikely(!entries))
2416 		return 0;
2417 	/* make sure SQ entry isn't read before tail */
2418 	ret = left = min(nr, entries);
2419 	io_get_task_refs(left);
2420 	io_submit_state_start(&ctx->submit_state, left);
2421 
2422 	do {
2423 		const struct io_uring_sqe *sqe;
2424 		struct io_kiocb *req;
2425 
2426 		if (unlikely(!io_alloc_req(ctx, &req)))
2427 			break;
2428 		if (unlikely(!io_get_sqe(ctx, &sqe))) {
2429 			io_req_add_to_cache(req, ctx);
2430 			break;
2431 		}
2432 
2433 		/*
2434 		 * Continue submitting even for sqe failure if the
2435 		 * ring was setup with IORING_SETUP_SUBMIT_ALL
2436 		 */
2437 		if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2438 		    !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2439 			left--;
2440 			break;
2441 		}
2442 	} while (--left);
2443 
2444 	if (unlikely(left)) {
2445 		ret -= left;
2446 		/* try again if it submitted nothing and can't allocate a req */
2447 		if (!ret && io_req_cache_empty(ctx))
2448 			ret = -EAGAIN;
2449 		current->io_uring->cached_refs += left;
2450 	}
2451 
2452 	io_submit_state_end(ctx);
2453 	 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2454 	io_commit_sqring(ctx);
2455 	return ret;
2456 }
2457 
2458 struct io_wait_queue {
2459 	struct wait_queue_entry wq;
2460 	struct io_ring_ctx *ctx;
2461 	unsigned cq_tail;
2462 	unsigned nr_timeouts;
2463 	ktime_t timeout;
2464 };
2465 
2466 static inline bool io_has_work(struct io_ring_ctx *ctx)
2467 {
2468 	return test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq) ||
2469 	       !llist_empty(&ctx->work_llist);
2470 }
2471 
2472 static inline bool io_should_wake(struct io_wait_queue *iowq)
2473 {
2474 	struct io_ring_ctx *ctx = iowq->ctx;
2475 	int dist = READ_ONCE(ctx->rings->cq.tail) - (int) iowq->cq_tail;
2476 
2477 	/*
2478 	 * Wake up if we have enough events, or if a timeout occurred since we
2479 	 * started waiting. For timeouts, we always want to return to userspace,
2480 	 * regardless of event count.
2481 	 */
2482 	return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2483 }
2484 
2485 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2486 			    int wake_flags, void *key)
2487 {
2488 	struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2489 
2490 	/*
2491 	 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2492 	 * the task, and the next invocation will do it.
2493 	 */
2494 	if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2495 		return autoremove_wake_function(curr, mode, wake_flags, key);
2496 	return -1;
2497 }
2498 
2499 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2500 {
2501 	if (!llist_empty(&ctx->work_llist)) {
2502 		__set_current_state(TASK_RUNNING);
2503 		if (io_run_local_work(ctx, INT_MAX) > 0)
2504 			return 0;
2505 	}
2506 	if (io_run_task_work() > 0)
2507 		return 0;
2508 	if (task_sigpending(current))
2509 		return -EINTR;
2510 	return 0;
2511 }
2512 
2513 static bool current_pending_io(void)
2514 {
2515 	struct io_uring_task *tctx = current->io_uring;
2516 
2517 	if (!tctx)
2518 		return false;
2519 	return percpu_counter_read_positive(&tctx->inflight);
2520 }
2521 
2522 /* when returns >0, the caller should retry */
2523 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2524 					  struct io_wait_queue *iowq)
2525 {
2526 	int ret;
2527 
2528 	if (unlikely(READ_ONCE(ctx->check_cq)))
2529 		return 1;
2530 	if (unlikely(!llist_empty(&ctx->work_llist)))
2531 		return 1;
2532 	if (unlikely(task_work_pending(current)))
2533 		return 1;
2534 	if (unlikely(task_sigpending(current)))
2535 		return -EINTR;
2536 	if (unlikely(io_should_wake(iowq)))
2537 		return 0;
2538 
2539 	/*
2540 	 * Mark us as being in io_wait if we have pending requests, so cpufreq
2541 	 * can take into account that the task is waiting for IO - turns out
2542 	 * to be important for low QD IO.
2543 	 */
2544 	if (current_pending_io())
2545 		current->in_iowait = 1;
2546 	ret = 0;
2547 	if (iowq->timeout == KTIME_MAX)
2548 		schedule();
2549 	else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS))
2550 		ret = -ETIME;
2551 	current->in_iowait = 0;
2552 	return ret;
2553 }
2554 
2555 /*
2556  * Wait until events become available, if we don't already have some. The
2557  * application must reap them itself, as they reside on the shared cq ring.
2558  */
2559 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2560 			  const sigset_t __user *sig, size_t sigsz,
2561 			  struct __kernel_timespec __user *uts)
2562 {
2563 	struct io_wait_queue iowq;
2564 	struct io_rings *rings = ctx->rings;
2565 	int ret;
2566 
2567 	if (!io_allowed_run_tw(ctx))
2568 		return -EEXIST;
2569 	if (!llist_empty(&ctx->work_llist))
2570 		io_run_local_work(ctx, min_events);
2571 	io_run_task_work();
2572 	io_cqring_overflow_flush(ctx);
2573 	/* if user messes with these they will just get an early return */
2574 	if (__io_cqring_events_user(ctx) >= min_events)
2575 		return 0;
2576 
2577 	init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2578 	iowq.wq.private = current;
2579 	INIT_LIST_HEAD(&iowq.wq.entry);
2580 	iowq.ctx = ctx;
2581 	iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2582 	iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2583 	iowq.timeout = KTIME_MAX;
2584 
2585 	if (uts) {
2586 		struct timespec64 ts;
2587 
2588 		if (get_timespec64(&ts, uts))
2589 			return -EFAULT;
2590 		iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2591 	}
2592 
2593 	if (sig) {
2594 #ifdef CONFIG_COMPAT
2595 		if (in_compat_syscall())
2596 			ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2597 						      sigsz);
2598 		else
2599 #endif
2600 			ret = set_user_sigmask(sig, sigsz);
2601 
2602 		if (ret)
2603 			return ret;
2604 	}
2605 
2606 	trace_io_uring_cqring_wait(ctx, min_events);
2607 	do {
2608 		int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail);
2609 		unsigned long check_cq;
2610 
2611 		if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2612 			atomic_set(&ctx->cq_wait_nr, nr_wait);
2613 			set_current_state(TASK_INTERRUPTIBLE);
2614 		} else {
2615 			prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2616 							TASK_INTERRUPTIBLE);
2617 		}
2618 
2619 		ret = io_cqring_wait_schedule(ctx, &iowq);
2620 		__set_current_state(TASK_RUNNING);
2621 		atomic_set(&ctx->cq_wait_nr, 0);
2622 
2623 		/*
2624 		 * Run task_work after scheduling and before io_should_wake().
2625 		 * If we got woken because of task_work being processed, run it
2626 		 * now rather than let the caller do another wait loop.
2627 		 */
2628 		if (!llist_empty(&ctx->work_llist))
2629 			io_run_local_work(ctx, nr_wait);
2630 		io_run_task_work();
2631 
2632 		/*
2633 		 * Non-local task_work will be run on exit to userspace, but
2634 		 * if we're using DEFER_TASKRUN, then we could have waited
2635 		 * with a timeout for a number of requests. If the timeout
2636 		 * hits, we could have some requests ready to process. Ensure
2637 		 * this break is _after_ we have run task_work, to avoid
2638 		 * deferring running potentially pending requests until the
2639 		 * next time we wait for events.
2640 		 */
2641 		if (ret < 0)
2642 			break;
2643 
2644 		check_cq = READ_ONCE(ctx->check_cq);
2645 		if (unlikely(check_cq)) {
2646 			/* let the caller flush overflows, retry */
2647 			if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2648 				io_cqring_do_overflow_flush(ctx);
2649 			if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2650 				ret = -EBADR;
2651 				break;
2652 			}
2653 		}
2654 
2655 		if (io_should_wake(&iowq)) {
2656 			ret = 0;
2657 			break;
2658 		}
2659 		cond_resched();
2660 	} while (1);
2661 
2662 	if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2663 		finish_wait(&ctx->cq_wait, &iowq.wq);
2664 	restore_saved_sigmask_unless(ret == -EINTR);
2665 
2666 	return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2667 }
2668 
2669 void io_mem_free(void *ptr)
2670 {
2671 	if (!ptr)
2672 		return;
2673 
2674 	folio_put(virt_to_folio(ptr));
2675 }
2676 
2677 static void io_pages_free(struct page ***pages, int npages)
2678 {
2679 	struct page **page_array;
2680 	int i;
2681 
2682 	if (!pages)
2683 		return;
2684 
2685 	page_array = *pages;
2686 	if (!page_array)
2687 		return;
2688 
2689 	for (i = 0; i < npages; i++)
2690 		unpin_user_page(page_array[i]);
2691 	kvfree(page_array);
2692 	*pages = NULL;
2693 }
2694 
2695 static void *__io_uaddr_map(struct page ***pages, unsigned short *npages,
2696 			    unsigned long uaddr, size_t size)
2697 {
2698 	struct page **page_array;
2699 	unsigned int nr_pages;
2700 	void *page_addr;
2701 	int ret, i, pinned;
2702 
2703 	*npages = 0;
2704 
2705 	if (uaddr & (PAGE_SIZE - 1) || !size)
2706 		return ERR_PTR(-EINVAL);
2707 
2708 	nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2709 	if (nr_pages > USHRT_MAX)
2710 		return ERR_PTR(-EINVAL);
2711 	page_array = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
2712 	if (!page_array)
2713 		return ERR_PTR(-ENOMEM);
2714 
2715 
2716 	pinned = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
2717 				     page_array);
2718 	if (pinned != nr_pages) {
2719 		ret = (pinned < 0) ? pinned : -EFAULT;
2720 		goto free_pages;
2721 	}
2722 
2723 	page_addr = page_address(page_array[0]);
2724 	for (i = 0; i < nr_pages; i++) {
2725 		ret = -EINVAL;
2726 
2727 		/*
2728 		 * Can't support mapping user allocated ring memory on 32-bit
2729 		 * archs where it could potentially reside in highmem. Just
2730 		 * fail those with -EINVAL, just like we did on kernels that
2731 		 * didn't support this feature.
2732 		 */
2733 		if (PageHighMem(page_array[i]))
2734 			goto free_pages;
2735 
2736 		/*
2737 		 * No support for discontig pages for now, should either be a
2738 		 * single normal page, or a huge page. Later on we can add
2739 		 * support for remapping discontig pages, for now we will
2740 		 * just fail them with EINVAL.
2741 		 */
2742 		if (page_address(page_array[i]) != page_addr)
2743 			goto free_pages;
2744 		page_addr += PAGE_SIZE;
2745 	}
2746 
2747 	*pages = page_array;
2748 	*npages = nr_pages;
2749 	return page_to_virt(page_array[0]);
2750 
2751 free_pages:
2752 	io_pages_free(&page_array, pinned > 0 ? pinned : 0);
2753 	return ERR_PTR(ret);
2754 }
2755 
2756 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2757 			  size_t size)
2758 {
2759 	return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2760 				size);
2761 }
2762 
2763 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2764 			 size_t size)
2765 {
2766 	return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2767 				size);
2768 }
2769 
2770 static void io_rings_free(struct io_ring_ctx *ctx)
2771 {
2772 	if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2773 		io_mem_free(ctx->rings);
2774 		io_mem_free(ctx->sq_sqes);
2775 	} else {
2776 		io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
2777 		ctx->n_ring_pages = 0;
2778 		io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
2779 		ctx->n_sqe_pages = 0;
2780 	}
2781 
2782 	ctx->rings = NULL;
2783 	ctx->sq_sqes = NULL;
2784 }
2785 
2786 void *io_mem_alloc(size_t size)
2787 {
2788 	gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2789 	void *ret;
2790 
2791 	ret = (void *) __get_free_pages(gfp, get_order(size));
2792 	if (ret)
2793 		return ret;
2794 	return ERR_PTR(-ENOMEM);
2795 }
2796 
2797 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2798 				unsigned int cq_entries, size_t *sq_offset)
2799 {
2800 	struct io_rings *rings;
2801 	size_t off, sq_array_size;
2802 
2803 	off = struct_size(rings, cqes, cq_entries);
2804 	if (off == SIZE_MAX)
2805 		return SIZE_MAX;
2806 	if (ctx->flags & IORING_SETUP_CQE32) {
2807 		if (check_shl_overflow(off, 1, &off))
2808 			return SIZE_MAX;
2809 	}
2810 
2811 #ifdef CONFIG_SMP
2812 	off = ALIGN(off, SMP_CACHE_BYTES);
2813 	if (off == 0)
2814 		return SIZE_MAX;
2815 #endif
2816 
2817 	if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
2818 		if (sq_offset)
2819 			*sq_offset = SIZE_MAX;
2820 		return off;
2821 	}
2822 
2823 	if (sq_offset)
2824 		*sq_offset = off;
2825 
2826 	sq_array_size = array_size(sizeof(u32), sq_entries);
2827 	if (sq_array_size == SIZE_MAX)
2828 		return SIZE_MAX;
2829 
2830 	if (check_add_overflow(off, sq_array_size, &off))
2831 		return SIZE_MAX;
2832 
2833 	return off;
2834 }
2835 
2836 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
2837 			       unsigned int eventfd_async)
2838 {
2839 	struct io_ev_fd *ev_fd;
2840 	__s32 __user *fds = arg;
2841 	int fd;
2842 
2843 	ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2844 					lockdep_is_held(&ctx->uring_lock));
2845 	if (ev_fd)
2846 		return -EBUSY;
2847 
2848 	if (copy_from_user(&fd, fds, sizeof(*fds)))
2849 		return -EFAULT;
2850 
2851 	ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
2852 	if (!ev_fd)
2853 		return -ENOMEM;
2854 
2855 	ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
2856 	if (IS_ERR(ev_fd->cq_ev_fd)) {
2857 		int ret = PTR_ERR(ev_fd->cq_ev_fd);
2858 		kfree(ev_fd);
2859 		return ret;
2860 	}
2861 
2862 	spin_lock(&ctx->completion_lock);
2863 	ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
2864 	spin_unlock(&ctx->completion_lock);
2865 
2866 	ev_fd->eventfd_async = eventfd_async;
2867 	ctx->has_evfd = true;
2868 	rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
2869 	atomic_set(&ev_fd->refs, 1);
2870 	atomic_set(&ev_fd->ops, 0);
2871 	return 0;
2872 }
2873 
2874 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2875 {
2876 	struct io_ev_fd *ev_fd;
2877 
2878 	ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2879 					lockdep_is_held(&ctx->uring_lock));
2880 	if (ev_fd) {
2881 		ctx->has_evfd = false;
2882 		rcu_assign_pointer(ctx->io_ev_fd, NULL);
2883 		if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_FREE_BIT), &ev_fd->ops))
2884 			call_rcu(&ev_fd->rcu, io_eventfd_ops);
2885 		return 0;
2886 	}
2887 
2888 	return -ENXIO;
2889 }
2890 
2891 static void io_req_caches_free(struct io_ring_ctx *ctx)
2892 {
2893 	struct io_kiocb *req;
2894 	int nr = 0;
2895 
2896 	mutex_lock(&ctx->uring_lock);
2897 	io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2898 
2899 	while (!io_req_cache_empty(ctx)) {
2900 		req = io_extract_req(ctx);
2901 		kmem_cache_free(req_cachep, req);
2902 		nr++;
2903 	}
2904 	if (nr)
2905 		percpu_ref_put_many(&ctx->refs, nr);
2906 	mutex_unlock(&ctx->uring_lock);
2907 }
2908 
2909 static void io_rsrc_node_cache_free(struct io_cache_entry *entry)
2910 {
2911 	kfree(container_of(entry, struct io_rsrc_node, cache));
2912 }
2913 
2914 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2915 {
2916 	io_sq_thread_finish(ctx);
2917 	/* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
2918 	if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
2919 		return;
2920 
2921 	mutex_lock(&ctx->uring_lock);
2922 	if (ctx->buf_data)
2923 		__io_sqe_buffers_unregister(ctx);
2924 	if (ctx->file_data)
2925 		__io_sqe_files_unregister(ctx);
2926 	io_cqring_overflow_kill(ctx);
2927 	io_eventfd_unregister(ctx);
2928 	io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free);
2929 	io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
2930 	io_destroy_buffers(ctx);
2931 	mutex_unlock(&ctx->uring_lock);
2932 	if (ctx->sq_creds)
2933 		put_cred(ctx->sq_creds);
2934 	if (ctx->submitter_task)
2935 		put_task_struct(ctx->submitter_task);
2936 
2937 	/* there are no registered resources left, nobody uses it */
2938 	if (ctx->rsrc_node)
2939 		io_rsrc_node_destroy(ctx, ctx->rsrc_node);
2940 
2941 	WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
2942 	WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2943 
2944 	io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free);
2945 	if (ctx->mm_account) {
2946 		mmdrop(ctx->mm_account);
2947 		ctx->mm_account = NULL;
2948 	}
2949 	io_rings_free(ctx);
2950 	io_kbuf_mmap_list_free(ctx);
2951 
2952 	percpu_ref_exit(&ctx->refs);
2953 	free_uid(ctx->user);
2954 	io_req_caches_free(ctx);
2955 	if (ctx->hash_map)
2956 		io_wq_put_hash(ctx->hash_map);
2957 	kfree(ctx->cancel_table.hbs);
2958 	kfree(ctx->cancel_table_locked.hbs);
2959 	xa_destroy(&ctx->io_bl_xa);
2960 	kfree(ctx);
2961 }
2962 
2963 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2964 {
2965 	struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2966 					       poll_wq_task_work);
2967 
2968 	mutex_lock(&ctx->uring_lock);
2969 	ctx->poll_activated = true;
2970 	mutex_unlock(&ctx->uring_lock);
2971 
2972 	/*
2973 	 * Wake ups for some events between start of polling and activation
2974 	 * might've been lost due to loose synchronisation.
2975 	 */
2976 	wake_up_all(&ctx->poll_wq);
2977 	percpu_ref_put(&ctx->refs);
2978 }
2979 
2980 static __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2981 {
2982 	spin_lock(&ctx->completion_lock);
2983 	/* already activated or in progress */
2984 	if (ctx->poll_activated || ctx->poll_wq_task_work.func)
2985 		goto out;
2986 	if (WARN_ON_ONCE(!ctx->task_complete))
2987 		goto out;
2988 	if (!ctx->submitter_task)
2989 		goto out;
2990 	/*
2991 	 * with ->submitter_task only the submitter task completes requests, we
2992 	 * only need to sync with it, which is done by injecting a tw
2993 	 */
2994 	init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2995 	percpu_ref_get(&ctx->refs);
2996 	if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2997 		percpu_ref_put(&ctx->refs);
2998 out:
2999 	spin_unlock(&ctx->completion_lock);
3000 }
3001 
3002 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3003 {
3004 	struct io_ring_ctx *ctx = file->private_data;
3005 	__poll_t mask = 0;
3006 
3007 	if (unlikely(!ctx->poll_activated))
3008 		io_activate_pollwq(ctx);
3009 
3010 	poll_wait(file, &ctx->poll_wq, wait);
3011 	/*
3012 	 * synchronizes with barrier from wq_has_sleeper call in
3013 	 * io_commit_cqring
3014 	 */
3015 	smp_rmb();
3016 	if (!io_sqring_full(ctx))
3017 		mask |= EPOLLOUT | EPOLLWRNORM;
3018 
3019 	/*
3020 	 * Don't flush cqring overflow list here, just do a simple check.
3021 	 * Otherwise there could possible be ABBA deadlock:
3022 	 *      CPU0                    CPU1
3023 	 *      ----                    ----
3024 	 * lock(&ctx->uring_lock);
3025 	 *                              lock(&ep->mtx);
3026 	 *                              lock(&ctx->uring_lock);
3027 	 * lock(&ep->mtx);
3028 	 *
3029 	 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
3030 	 * pushes them to do the flush.
3031 	 */
3032 
3033 	if (__io_cqring_events_user(ctx) || io_has_work(ctx))
3034 		mask |= EPOLLIN | EPOLLRDNORM;
3035 
3036 	return mask;
3037 }
3038 
3039 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
3040 {
3041 	const struct cred *creds;
3042 
3043 	creds = xa_erase(&ctx->personalities, id);
3044 	if (creds) {
3045 		put_cred(creds);
3046 		return 0;
3047 	}
3048 
3049 	return -EINVAL;
3050 }
3051 
3052 struct io_tctx_exit {
3053 	struct callback_head		task_work;
3054 	struct completion		completion;
3055 	struct io_ring_ctx		*ctx;
3056 };
3057 
3058 static __cold void io_tctx_exit_cb(struct callback_head *cb)
3059 {
3060 	struct io_uring_task *tctx = current->io_uring;
3061 	struct io_tctx_exit *work;
3062 
3063 	work = container_of(cb, struct io_tctx_exit, task_work);
3064 	/*
3065 	 * When @in_cancel, we're in cancellation and it's racy to remove the
3066 	 * node. It'll be removed by the end of cancellation, just ignore it.
3067 	 * tctx can be NULL if the queueing of this task_work raced with
3068 	 * work cancelation off the exec path.
3069 	 */
3070 	if (tctx && !atomic_read(&tctx->in_cancel))
3071 		io_uring_del_tctx_node((unsigned long)work->ctx);
3072 	complete(&work->completion);
3073 }
3074 
3075 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
3076 {
3077 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3078 
3079 	return req->ctx == data;
3080 }
3081 
3082 static __cold void io_ring_exit_work(struct work_struct *work)
3083 {
3084 	struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
3085 	unsigned long timeout = jiffies + HZ * 60 * 5;
3086 	unsigned long interval = HZ / 20;
3087 	struct io_tctx_exit exit;
3088 	struct io_tctx_node *node;
3089 	int ret;
3090 
3091 	/*
3092 	 * If we're doing polled IO and end up having requests being
3093 	 * submitted async (out-of-line), then completions can come in while
3094 	 * we're waiting for refs to drop. We need to reap these manually,
3095 	 * as nobody else will be looking for them.
3096 	 */
3097 	do {
3098 		if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
3099 			mutex_lock(&ctx->uring_lock);
3100 			io_cqring_overflow_kill(ctx);
3101 			mutex_unlock(&ctx->uring_lock);
3102 		}
3103 
3104 		if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3105 			io_move_task_work_from_local(ctx);
3106 
3107 		while (io_uring_try_cancel_requests(ctx, NULL, true))
3108 			cond_resched();
3109 
3110 		if (ctx->sq_data) {
3111 			struct io_sq_data *sqd = ctx->sq_data;
3112 			struct task_struct *tsk;
3113 
3114 			io_sq_thread_park(sqd);
3115 			tsk = sqd->thread;
3116 			if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
3117 				io_wq_cancel_cb(tsk->io_uring->io_wq,
3118 						io_cancel_ctx_cb, ctx, true);
3119 			io_sq_thread_unpark(sqd);
3120 		}
3121 
3122 		io_req_caches_free(ctx);
3123 
3124 		if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
3125 			/* there is little hope left, don't run it too often */
3126 			interval = HZ * 60;
3127 		}
3128 		/*
3129 		 * This is really an uninterruptible wait, as it has to be
3130 		 * complete. But it's also run from a kworker, which doesn't
3131 		 * take signals, so it's fine to make it interruptible. This
3132 		 * avoids scenarios where we knowingly can wait much longer
3133 		 * on completions, for example if someone does a SIGSTOP on
3134 		 * a task that needs to finish task_work to make this loop
3135 		 * complete. That's a synthetic situation that should not
3136 		 * cause a stuck task backtrace, and hence a potential panic
3137 		 * on stuck tasks if that is enabled.
3138 		 */
3139 	} while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
3140 
3141 	init_completion(&exit.completion);
3142 	init_task_work(&exit.task_work, io_tctx_exit_cb);
3143 	exit.ctx = ctx;
3144 
3145 	mutex_lock(&ctx->uring_lock);
3146 	while (!list_empty(&ctx->tctx_list)) {
3147 		WARN_ON_ONCE(time_after(jiffies, timeout));
3148 
3149 		node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
3150 					ctx_node);
3151 		/* don't spin on a single task if cancellation failed */
3152 		list_rotate_left(&ctx->tctx_list);
3153 		ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
3154 		if (WARN_ON_ONCE(ret))
3155 			continue;
3156 
3157 		mutex_unlock(&ctx->uring_lock);
3158 		/*
3159 		 * See comment above for
3160 		 * wait_for_completion_interruptible_timeout() on why this
3161 		 * wait is marked as interruptible.
3162 		 */
3163 		wait_for_completion_interruptible(&exit.completion);
3164 		mutex_lock(&ctx->uring_lock);
3165 	}
3166 	mutex_unlock(&ctx->uring_lock);
3167 	spin_lock(&ctx->completion_lock);
3168 	spin_unlock(&ctx->completion_lock);
3169 
3170 	/* pairs with RCU read section in io_req_local_work_add() */
3171 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3172 		synchronize_rcu();
3173 
3174 	io_ring_ctx_free(ctx);
3175 }
3176 
3177 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3178 {
3179 	unsigned long index;
3180 	struct creds *creds;
3181 
3182 	mutex_lock(&ctx->uring_lock);
3183 	percpu_ref_kill(&ctx->refs);
3184 	xa_for_each(&ctx->personalities, index, creds)
3185 		io_unregister_personality(ctx, index);
3186 	if (ctx->rings)
3187 		io_poll_remove_all(ctx, NULL, true);
3188 	mutex_unlock(&ctx->uring_lock);
3189 
3190 	/*
3191 	 * If we failed setting up the ctx, we might not have any rings
3192 	 * and therefore did not submit any requests
3193 	 */
3194 	if (ctx->rings)
3195 		io_kill_timeouts(ctx, NULL, true);
3196 
3197 	flush_delayed_work(&ctx->fallback_work);
3198 
3199 	INIT_WORK(&ctx->exit_work, io_ring_exit_work);
3200 	/*
3201 	 * Use system_unbound_wq to avoid spawning tons of event kworkers
3202 	 * if we're exiting a ton of rings at the same time. It just adds
3203 	 * noise and overhead, there's no discernable change in runtime
3204 	 * over using system_wq.
3205 	 */
3206 	queue_work(iou_wq, &ctx->exit_work);
3207 }
3208 
3209 static int io_uring_release(struct inode *inode, struct file *file)
3210 {
3211 	struct io_ring_ctx *ctx = file->private_data;
3212 
3213 	file->private_data = NULL;
3214 	io_ring_ctx_wait_and_kill(ctx);
3215 	return 0;
3216 }
3217 
3218 struct io_task_cancel {
3219 	struct task_struct *task;
3220 	bool all;
3221 };
3222 
3223 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3224 {
3225 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3226 	struct io_task_cancel *cancel = data;
3227 
3228 	return io_match_task_safe(req, cancel->task, cancel->all);
3229 }
3230 
3231 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3232 					 struct task_struct *task,
3233 					 bool cancel_all)
3234 {
3235 	struct io_defer_entry *de;
3236 	LIST_HEAD(list);
3237 
3238 	spin_lock(&ctx->completion_lock);
3239 	list_for_each_entry_reverse(de, &ctx->defer_list, list) {
3240 		if (io_match_task_safe(de->req, task, cancel_all)) {
3241 			list_cut_position(&list, &ctx->defer_list, &de->list);
3242 			break;
3243 		}
3244 	}
3245 	spin_unlock(&ctx->completion_lock);
3246 	if (list_empty(&list))
3247 		return false;
3248 
3249 	while (!list_empty(&list)) {
3250 		de = list_first_entry(&list, struct io_defer_entry, list);
3251 		list_del_init(&de->list);
3252 		io_req_task_queue_fail(de->req, -ECANCELED);
3253 		kfree(de);
3254 	}
3255 	return true;
3256 }
3257 
3258 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3259 {
3260 	struct io_tctx_node *node;
3261 	enum io_wq_cancel cret;
3262 	bool ret = false;
3263 
3264 	mutex_lock(&ctx->uring_lock);
3265 	list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3266 		struct io_uring_task *tctx = node->task->io_uring;
3267 
3268 		/*
3269 		 * io_wq will stay alive while we hold uring_lock, because it's
3270 		 * killed after ctx nodes, which requires to take the lock.
3271 		 */
3272 		if (!tctx || !tctx->io_wq)
3273 			continue;
3274 		cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3275 		ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3276 	}
3277 	mutex_unlock(&ctx->uring_lock);
3278 
3279 	return ret;
3280 }
3281 
3282 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3283 						struct task_struct *task,
3284 						bool cancel_all)
3285 {
3286 	struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
3287 	struct io_uring_task *tctx = task ? task->io_uring : NULL;
3288 	enum io_wq_cancel cret;
3289 	bool ret = false;
3290 
3291 	/* set it so io_req_local_work_add() would wake us up */
3292 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3293 		atomic_set(&ctx->cq_wait_nr, 1);
3294 		smp_mb();
3295 	}
3296 
3297 	/* failed during ring init, it couldn't have issued any requests */
3298 	if (!ctx->rings)
3299 		return false;
3300 
3301 	if (!task) {
3302 		ret |= io_uring_try_cancel_iowq(ctx);
3303 	} else if (tctx && tctx->io_wq) {
3304 		/*
3305 		 * Cancels requests of all rings, not only @ctx, but
3306 		 * it's fine as the task is in exit/exec.
3307 		 */
3308 		cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3309 				       &cancel, true);
3310 		ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3311 	}
3312 
3313 	/* SQPOLL thread does its own polling */
3314 	if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3315 	    (ctx->sq_data && ctx->sq_data->thread == current)) {
3316 		while (!wq_list_empty(&ctx->iopoll_list)) {
3317 			io_iopoll_try_reap_events(ctx);
3318 			ret = true;
3319 			cond_resched();
3320 		}
3321 	}
3322 
3323 	if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3324 	    io_allowed_defer_tw_run(ctx))
3325 		ret |= io_run_local_work(ctx, INT_MAX) > 0;
3326 	ret |= io_cancel_defer_files(ctx, task, cancel_all);
3327 	mutex_lock(&ctx->uring_lock);
3328 	ret |= io_poll_remove_all(ctx, task, cancel_all);
3329 	mutex_unlock(&ctx->uring_lock);
3330 	ret |= io_kill_timeouts(ctx, task, cancel_all);
3331 	if (task)
3332 		ret |= io_run_task_work() > 0;
3333 	return ret;
3334 }
3335 
3336 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3337 {
3338 	if (tracked)
3339 		return atomic_read(&tctx->inflight_tracked);
3340 	return percpu_counter_sum(&tctx->inflight);
3341 }
3342 
3343 /*
3344  * Find any io_uring ctx that this task has registered or done IO on, and cancel
3345  * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3346  */
3347 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3348 {
3349 	struct io_uring_task *tctx = current->io_uring;
3350 	struct io_ring_ctx *ctx;
3351 	struct io_tctx_node *node;
3352 	unsigned long index;
3353 	s64 inflight;
3354 	DEFINE_WAIT(wait);
3355 
3356 	WARN_ON_ONCE(sqd && sqd->thread != current);
3357 
3358 	if (!current->io_uring)
3359 		return;
3360 	if (tctx->io_wq)
3361 		io_wq_exit_start(tctx->io_wq);
3362 
3363 	atomic_inc(&tctx->in_cancel);
3364 	do {
3365 		bool loop = false;
3366 
3367 		io_uring_drop_tctx_refs(current);
3368 		if (!tctx_inflight(tctx, !cancel_all))
3369 			break;
3370 
3371 		/* read completions before cancelations */
3372 		inflight = tctx_inflight(tctx, false);
3373 		if (!inflight)
3374 			break;
3375 
3376 		if (!sqd) {
3377 			xa_for_each(&tctx->xa, index, node) {
3378 				/* sqpoll task will cancel all its requests */
3379 				if (node->ctx->sq_data)
3380 					continue;
3381 				loop |= io_uring_try_cancel_requests(node->ctx,
3382 							current, cancel_all);
3383 			}
3384 		} else {
3385 			list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3386 				loop |= io_uring_try_cancel_requests(ctx,
3387 								     current,
3388 								     cancel_all);
3389 		}
3390 
3391 		if (loop) {
3392 			cond_resched();
3393 			continue;
3394 		}
3395 
3396 		prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3397 		io_run_task_work();
3398 		io_uring_drop_tctx_refs(current);
3399 		xa_for_each(&tctx->xa, index, node) {
3400 			if (!llist_empty(&node->ctx->work_llist)) {
3401 				WARN_ON_ONCE(node->ctx->submitter_task &&
3402 					     node->ctx->submitter_task != current);
3403 				goto end_wait;
3404 			}
3405 		}
3406 		/*
3407 		 * If we've seen completions, retry without waiting. This
3408 		 * avoids a race where a completion comes in before we did
3409 		 * prepare_to_wait().
3410 		 */
3411 		if (inflight == tctx_inflight(tctx, !cancel_all))
3412 			schedule();
3413 end_wait:
3414 		finish_wait(&tctx->wait, &wait);
3415 	} while (1);
3416 
3417 	io_uring_clean_tctx(tctx);
3418 	if (cancel_all) {
3419 		/*
3420 		 * We shouldn't run task_works after cancel, so just leave
3421 		 * ->in_cancel set for normal exit.
3422 		 */
3423 		atomic_dec(&tctx->in_cancel);
3424 		/* for exec all current's requests should be gone, kill tctx */
3425 		__io_uring_free(current);
3426 	}
3427 }
3428 
3429 void __io_uring_cancel(bool cancel_all)
3430 {
3431 	io_uring_cancel_generic(cancel_all, NULL);
3432 }
3433 
3434 static void *io_uring_validate_mmap_request(struct file *file,
3435 					    loff_t pgoff, size_t sz)
3436 {
3437 	struct io_ring_ctx *ctx = file->private_data;
3438 	loff_t offset = pgoff << PAGE_SHIFT;
3439 	struct page *page;
3440 	void *ptr;
3441 
3442 	switch (offset & IORING_OFF_MMAP_MASK) {
3443 	case IORING_OFF_SQ_RING:
3444 	case IORING_OFF_CQ_RING:
3445 		/* Don't allow mmap if the ring was setup without it */
3446 		if (ctx->flags & IORING_SETUP_NO_MMAP)
3447 			return ERR_PTR(-EINVAL);
3448 		ptr = ctx->rings;
3449 		break;
3450 	case IORING_OFF_SQES:
3451 		/* Don't allow mmap if the ring was setup without it */
3452 		if (ctx->flags & IORING_SETUP_NO_MMAP)
3453 			return ERR_PTR(-EINVAL);
3454 		ptr = ctx->sq_sqes;
3455 		break;
3456 	case IORING_OFF_PBUF_RING: {
3457 		struct io_buffer_list *bl;
3458 		unsigned int bgid;
3459 
3460 		bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT;
3461 		bl = io_pbuf_get_bl(ctx, bgid);
3462 		if (IS_ERR(bl))
3463 			return bl;
3464 		ptr = bl->buf_ring;
3465 		io_put_bl(ctx, bl);
3466 		break;
3467 		}
3468 	default:
3469 		return ERR_PTR(-EINVAL);
3470 	}
3471 
3472 	page = virt_to_head_page(ptr);
3473 	if (sz > page_size(page))
3474 		return ERR_PTR(-EINVAL);
3475 
3476 	return ptr;
3477 }
3478 
3479 #ifdef CONFIG_MMU
3480 
3481 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3482 {
3483 	size_t sz = vma->vm_end - vma->vm_start;
3484 	unsigned long pfn;
3485 	void *ptr;
3486 
3487 	ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
3488 	if (IS_ERR(ptr))
3489 		return PTR_ERR(ptr);
3490 
3491 	pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3492 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3493 }
3494 
3495 static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp,
3496 			unsigned long addr, unsigned long len,
3497 			unsigned long pgoff, unsigned long flags)
3498 {
3499 	void *ptr;
3500 
3501 	/*
3502 	 * Do not allow to map to user-provided address to avoid breaking the
3503 	 * aliasing rules. Userspace is not able to guess the offset address of
3504 	 * kernel kmalloc()ed memory area.
3505 	 */
3506 	if (addr)
3507 		return -EINVAL;
3508 
3509 	ptr = io_uring_validate_mmap_request(filp, pgoff, len);
3510 	if (IS_ERR(ptr))
3511 		return -ENOMEM;
3512 
3513 	/*
3514 	 * Some architectures have strong cache aliasing requirements.
3515 	 * For such architectures we need a coherent mapping which aliases
3516 	 * kernel memory *and* userspace memory. To achieve that:
3517 	 * - use a NULL file pointer to reference physical memory, and
3518 	 * - use the kernel virtual address of the shared io_uring context
3519 	 *   (instead of the userspace-provided address, which has to be 0UL
3520 	 *   anyway).
3521 	 * - use the same pgoff which the get_unmapped_area() uses to
3522 	 *   calculate the page colouring.
3523 	 * For architectures without such aliasing requirements, the
3524 	 * architecture will return any suitable mapping because addr is 0.
3525 	 */
3526 	filp = NULL;
3527 	flags |= MAP_SHARED;
3528 	pgoff = 0;	/* has been translated to ptr above */
3529 #ifdef SHM_COLOUR
3530 	addr = (uintptr_t) ptr;
3531 	pgoff = addr >> PAGE_SHIFT;
3532 #else
3533 	addr = 0UL;
3534 #endif
3535 	return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
3536 }
3537 
3538 #else /* !CONFIG_MMU */
3539 
3540 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3541 {
3542 	return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL;
3543 }
3544 
3545 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
3546 {
3547 	return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
3548 }
3549 
3550 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3551 	unsigned long addr, unsigned long len,
3552 	unsigned long pgoff, unsigned long flags)
3553 {
3554 	void *ptr;
3555 
3556 	ptr = io_uring_validate_mmap_request(file, pgoff, len);
3557 	if (IS_ERR(ptr))
3558 		return PTR_ERR(ptr);
3559 
3560 	return (unsigned long) ptr;
3561 }
3562 
3563 #endif /* !CONFIG_MMU */
3564 
3565 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3566 {
3567 	if (flags & IORING_ENTER_EXT_ARG) {
3568 		struct io_uring_getevents_arg arg;
3569 
3570 		if (argsz != sizeof(arg))
3571 			return -EINVAL;
3572 		if (copy_from_user(&arg, argp, sizeof(arg)))
3573 			return -EFAULT;
3574 	}
3575 	return 0;
3576 }
3577 
3578 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3579 			  struct __kernel_timespec __user **ts,
3580 			  const sigset_t __user **sig)
3581 {
3582 	struct io_uring_getevents_arg arg;
3583 
3584 	/*
3585 	 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3586 	 * is just a pointer to the sigset_t.
3587 	 */
3588 	if (!(flags & IORING_ENTER_EXT_ARG)) {
3589 		*sig = (const sigset_t __user *) argp;
3590 		*ts = NULL;
3591 		return 0;
3592 	}
3593 
3594 	/*
3595 	 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3596 	 * timespec and sigset_t pointers if good.
3597 	 */
3598 	if (*argsz != sizeof(arg))
3599 		return -EINVAL;
3600 	if (copy_from_user(&arg, argp, sizeof(arg)))
3601 		return -EFAULT;
3602 	if (arg.pad)
3603 		return -EINVAL;
3604 	*sig = u64_to_user_ptr(arg.sigmask);
3605 	*argsz = arg.sigmask_sz;
3606 	*ts = u64_to_user_ptr(arg.ts);
3607 	return 0;
3608 }
3609 
3610 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3611 		u32, min_complete, u32, flags, const void __user *, argp,
3612 		size_t, argsz)
3613 {
3614 	struct io_ring_ctx *ctx;
3615 	struct file *file;
3616 	long ret;
3617 
3618 	if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3619 			       IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3620 			       IORING_ENTER_REGISTERED_RING)))
3621 		return -EINVAL;
3622 
3623 	/*
3624 	 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3625 	 * need only dereference our task private array to find it.
3626 	 */
3627 	if (flags & IORING_ENTER_REGISTERED_RING) {
3628 		struct io_uring_task *tctx = current->io_uring;
3629 
3630 		if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3631 			return -EINVAL;
3632 		fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3633 		file = tctx->registered_rings[fd];
3634 		if (unlikely(!file))
3635 			return -EBADF;
3636 	} else {
3637 		file = fget(fd);
3638 		if (unlikely(!file))
3639 			return -EBADF;
3640 		ret = -EOPNOTSUPP;
3641 		if (unlikely(!io_is_uring_fops(file)))
3642 			goto out;
3643 	}
3644 
3645 	ctx = file->private_data;
3646 	ret = -EBADFD;
3647 	if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3648 		goto out;
3649 
3650 	/*
3651 	 * For SQ polling, the thread will do all submissions and completions.
3652 	 * Just return the requested submit count, and wake the thread if
3653 	 * we were asked to.
3654 	 */
3655 	ret = 0;
3656 	if (ctx->flags & IORING_SETUP_SQPOLL) {
3657 		io_cqring_overflow_flush(ctx);
3658 
3659 		if (unlikely(ctx->sq_data->thread == NULL)) {
3660 			ret = -EOWNERDEAD;
3661 			goto out;
3662 		}
3663 		if (flags & IORING_ENTER_SQ_WAKEUP)
3664 			wake_up(&ctx->sq_data->wait);
3665 		if (flags & IORING_ENTER_SQ_WAIT)
3666 			io_sqpoll_wait_sq(ctx);
3667 
3668 		ret = to_submit;
3669 	} else if (to_submit) {
3670 		ret = io_uring_add_tctx_node(ctx);
3671 		if (unlikely(ret))
3672 			goto out;
3673 
3674 		mutex_lock(&ctx->uring_lock);
3675 		ret = io_submit_sqes(ctx, to_submit);
3676 		if (ret != to_submit) {
3677 			mutex_unlock(&ctx->uring_lock);
3678 			goto out;
3679 		}
3680 		if (flags & IORING_ENTER_GETEVENTS) {
3681 			if (ctx->syscall_iopoll)
3682 				goto iopoll_locked;
3683 			/*
3684 			 * Ignore errors, we'll soon call io_cqring_wait() and
3685 			 * it should handle ownership problems if any.
3686 			 */
3687 			if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3688 				(void)io_run_local_work_locked(ctx, min_complete);
3689 		}
3690 		mutex_unlock(&ctx->uring_lock);
3691 	}
3692 
3693 	if (flags & IORING_ENTER_GETEVENTS) {
3694 		int ret2;
3695 
3696 		if (ctx->syscall_iopoll) {
3697 			/*
3698 			 * We disallow the app entering submit/complete with
3699 			 * polling, but we still need to lock the ring to
3700 			 * prevent racing with polled issue that got punted to
3701 			 * a workqueue.
3702 			 */
3703 			mutex_lock(&ctx->uring_lock);
3704 iopoll_locked:
3705 			ret2 = io_validate_ext_arg(flags, argp, argsz);
3706 			if (likely(!ret2)) {
3707 				min_complete = min(min_complete,
3708 						   ctx->cq_entries);
3709 				ret2 = io_iopoll_check(ctx, min_complete);
3710 			}
3711 			mutex_unlock(&ctx->uring_lock);
3712 		} else {
3713 			const sigset_t __user *sig;
3714 			struct __kernel_timespec __user *ts;
3715 
3716 			ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3717 			if (likely(!ret2)) {
3718 				min_complete = min(min_complete,
3719 						   ctx->cq_entries);
3720 				ret2 = io_cqring_wait(ctx, min_complete, sig,
3721 						      argsz, ts);
3722 			}
3723 		}
3724 
3725 		if (!ret) {
3726 			ret = ret2;
3727 
3728 			/*
3729 			 * EBADR indicates that one or more CQE were dropped.
3730 			 * Once the user has been informed we can clear the bit
3731 			 * as they are obviously ok with those drops.
3732 			 */
3733 			if (unlikely(ret2 == -EBADR))
3734 				clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3735 					  &ctx->check_cq);
3736 		}
3737 	}
3738 out:
3739 	if (!(flags & IORING_ENTER_REGISTERED_RING))
3740 		fput(file);
3741 	return ret;
3742 }
3743 
3744 static const struct file_operations io_uring_fops = {
3745 	.release	= io_uring_release,
3746 	.mmap		= io_uring_mmap,
3747 #ifndef CONFIG_MMU
3748 	.get_unmapped_area = io_uring_nommu_get_unmapped_area,
3749 	.mmap_capabilities = io_uring_nommu_mmap_capabilities,
3750 #else
3751 	.get_unmapped_area = io_uring_mmu_get_unmapped_area,
3752 #endif
3753 	.poll		= io_uring_poll,
3754 #ifdef CONFIG_PROC_FS
3755 	.show_fdinfo	= io_uring_show_fdinfo,
3756 #endif
3757 };
3758 
3759 bool io_is_uring_fops(struct file *file)
3760 {
3761 	return file->f_op == &io_uring_fops;
3762 }
3763 
3764 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3765 					 struct io_uring_params *p)
3766 {
3767 	struct io_rings *rings;
3768 	size_t size, sq_array_offset;
3769 	void *ptr;
3770 
3771 	/* make sure these are sane, as we already accounted them */
3772 	ctx->sq_entries = p->sq_entries;
3773 	ctx->cq_entries = p->cq_entries;
3774 
3775 	size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3776 	if (size == SIZE_MAX)
3777 		return -EOVERFLOW;
3778 
3779 	if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3780 		rings = io_mem_alloc(size);
3781 	else
3782 		rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3783 
3784 	if (IS_ERR(rings))
3785 		return PTR_ERR(rings);
3786 
3787 	ctx->rings = rings;
3788 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3789 		ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3790 	rings->sq_ring_mask = p->sq_entries - 1;
3791 	rings->cq_ring_mask = p->cq_entries - 1;
3792 	rings->sq_ring_entries = p->sq_entries;
3793 	rings->cq_ring_entries = p->cq_entries;
3794 
3795 	if (p->flags & IORING_SETUP_SQE128)
3796 		size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3797 	else
3798 		size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3799 	if (size == SIZE_MAX) {
3800 		io_rings_free(ctx);
3801 		return -EOVERFLOW;
3802 	}
3803 
3804 	if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3805 		ptr = io_mem_alloc(size);
3806 	else
3807 		ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3808 
3809 	if (IS_ERR(ptr)) {
3810 		io_rings_free(ctx);
3811 		return PTR_ERR(ptr);
3812 	}
3813 
3814 	ctx->sq_sqes = ptr;
3815 	return 0;
3816 }
3817 
3818 static int io_uring_install_fd(struct file *file)
3819 {
3820 	int fd;
3821 
3822 	fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3823 	if (fd < 0)
3824 		return fd;
3825 	fd_install(fd, file);
3826 	return fd;
3827 }
3828 
3829 /*
3830  * Allocate an anonymous fd, this is what constitutes the application
3831  * visible backing of an io_uring instance. The application mmaps this
3832  * fd to gain access to the SQ/CQ ring details.
3833  */
3834 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3835 {
3836 	return anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
3837 					 O_RDWR | O_CLOEXEC, NULL);
3838 }
3839 
3840 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3841 				  struct io_uring_params __user *params)
3842 {
3843 	struct io_ring_ctx *ctx;
3844 	struct io_uring_task *tctx;
3845 	struct file *file;
3846 	int ret;
3847 
3848 	if (!entries)
3849 		return -EINVAL;
3850 	if (entries > IORING_MAX_ENTRIES) {
3851 		if (!(p->flags & IORING_SETUP_CLAMP))
3852 			return -EINVAL;
3853 		entries = IORING_MAX_ENTRIES;
3854 	}
3855 
3856 	if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3857 	    && !(p->flags & IORING_SETUP_NO_MMAP))
3858 		return -EINVAL;
3859 
3860 	/*
3861 	 * Use twice as many entries for the CQ ring. It's possible for the
3862 	 * application to drive a higher depth than the size of the SQ ring,
3863 	 * since the sqes are only used at submission time. This allows for
3864 	 * some flexibility in overcommitting a bit. If the application has
3865 	 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3866 	 * of CQ ring entries manually.
3867 	 */
3868 	p->sq_entries = roundup_pow_of_two(entries);
3869 	if (p->flags & IORING_SETUP_CQSIZE) {
3870 		/*
3871 		 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3872 		 * to a power-of-two, if it isn't already. We do NOT impose
3873 		 * any cq vs sq ring sizing.
3874 		 */
3875 		if (!p->cq_entries)
3876 			return -EINVAL;
3877 		if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3878 			if (!(p->flags & IORING_SETUP_CLAMP))
3879 				return -EINVAL;
3880 			p->cq_entries = IORING_MAX_CQ_ENTRIES;
3881 		}
3882 		p->cq_entries = roundup_pow_of_two(p->cq_entries);
3883 		if (p->cq_entries < p->sq_entries)
3884 			return -EINVAL;
3885 	} else {
3886 		p->cq_entries = 2 * p->sq_entries;
3887 	}
3888 
3889 	ctx = io_ring_ctx_alloc(p);
3890 	if (!ctx)
3891 		return -ENOMEM;
3892 
3893 	if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3894 	    !(ctx->flags & IORING_SETUP_IOPOLL) &&
3895 	    !(ctx->flags & IORING_SETUP_SQPOLL))
3896 		ctx->task_complete = true;
3897 
3898 	if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
3899 		ctx->lockless_cq = true;
3900 
3901 	/*
3902 	 * lazy poll_wq activation relies on ->task_complete for synchronisation
3903 	 * purposes, see io_activate_pollwq()
3904 	 */
3905 	if (!ctx->task_complete)
3906 		ctx->poll_activated = true;
3907 
3908 	/*
3909 	 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3910 	 * space applications don't need to do io completion events
3911 	 * polling again, they can rely on io_sq_thread to do polling
3912 	 * work, which can reduce cpu usage and uring_lock contention.
3913 	 */
3914 	if (ctx->flags & IORING_SETUP_IOPOLL &&
3915 	    !(ctx->flags & IORING_SETUP_SQPOLL))
3916 		ctx->syscall_iopoll = 1;
3917 
3918 	ctx->compat = in_compat_syscall();
3919 	if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3920 		ctx->user = get_uid(current_user());
3921 
3922 	/*
3923 	 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3924 	 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3925 	 */
3926 	ret = -EINVAL;
3927 	if (ctx->flags & IORING_SETUP_SQPOLL) {
3928 		/* IPI related flags don't make sense with SQPOLL */
3929 		if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
3930 				  IORING_SETUP_TASKRUN_FLAG |
3931 				  IORING_SETUP_DEFER_TASKRUN))
3932 			goto err;
3933 		ctx->notify_method = TWA_SIGNAL_NO_IPI;
3934 	} else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
3935 		ctx->notify_method = TWA_SIGNAL_NO_IPI;
3936 	} else {
3937 		if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
3938 		    !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
3939 			goto err;
3940 		ctx->notify_method = TWA_SIGNAL;
3941 	}
3942 
3943 	/*
3944 	 * For DEFER_TASKRUN we require the completion task to be the same as the
3945 	 * submission task. This implies that there is only one submitter, so enforce
3946 	 * that.
3947 	 */
3948 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
3949 	    !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
3950 		goto err;
3951 	}
3952 
3953 	/*
3954 	 * This is just grabbed for accounting purposes. When a process exits,
3955 	 * the mm is exited and dropped before the files, hence we need to hang
3956 	 * on to this mm purely for the purposes of being able to unaccount
3957 	 * memory (locked/pinned vm). It's not used for anything else.
3958 	 */
3959 	mmgrab(current->mm);
3960 	ctx->mm_account = current->mm;
3961 
3962 	ret = io_allocate_scq_urings(ctx, p);
3963 	if (ret)
3964 		goto err;
3965 
3966 	ret = io_sq_offload_create(ctx, p);
3967 	if (ret)
3968 		goto err;
3969 
3970 	ret = io_rsrc_init(ctx);
3971 	if (ret)
3972 		goto err;
3973 
3974 	p->sq_off.head = offsetof(struct io_rings, sq.head);
3975 	p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3976 	p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3977 	p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3978 	p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3979 	p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3980 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3981 		p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3982 	p->sq_off.resv1 = 0;
3983 	if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3984 		p->sq_off.user_addr = 0;
3985 
3986 	p->cq_off.head = offsetof(struct io_rings, cq.head);
3987 	p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3988 	p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3989 	p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3990 	p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3991 	p->cq_off.cqes = offsetof(struct io_rings, cqes);
3992 	p->cq_off.flags = offsetof(struct io_rings, cq_flags);
3993 	p->cq_off.resv1 = 0;
3994 	if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3995 		p->cq_off.user_addr = 0;
3996 
3997 	p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
3998 			IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
3999 			IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
4000 			IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
4001 			IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
4002 			IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
4003 			IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING;
4004 
4005 	if (copy_to_user(params, p, sizeof(*p))) {
4006 		ret = -EFAULT;
4007 		goto err;
4008 	}
4009 
4010 	if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
4011 	    && !(ctx->flags & IORING_SETUP_R_DISABLED))
4012 		WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4013 
4014 	file = io_uring_get_file(ctx);
4015 	if (IS_ERR(file)) {
4016 		ret = PTR_ERR(file);
4017 		goto err;
4018 	}
4019 
4020 	ret = __io_uring_add_tctx_node(ctx);
4021 	if (ret)
4022 		goto err_fput;
4023 	tctx = current->io_uring;
4024 
4025 	/*
4026 	 * Install ring fd as the very last thing, so we don't risk someone
4027 	 * having closed it before we finish setup
4028 	 */
4029 	if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
4030 		ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
4031 	else
4032 		ret = io_uring_install_fd(file);
4033 	if (ret < 0)
4034 		goto err_fput;
4035 
4036 	trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4037 	return ret;
4038 err:
4039 	io_ring_ctx_wait_and_kill(ctx);
4040 	return ret;
4041 err_fput:
4042 	fput(file);
4043 	return ret;
4044 }
4045 
4046 /*
4047  * Sets up an aio uring context, and returns the fd. Applications asks for a
4048  * ring size, we return the actual sq/cq ring sizes (among other things) in the
4049  * params structure passed in.
4050  */
4051 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4052 {
4053 	struct io_uring_params p;
4054 	int i;
4055 
4056 	if (copy_from_user(&p, params, sizeof(p)))
4057 		return -EFAULT;
4058 	for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4059 		if (p.resv[i])
4060 			return -EINVAL;
4061 	}
4062 
4063 	if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4064 			IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
4065 			IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
4066 			IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
4067 			IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
4068 			IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
4069 			IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
4070 			IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
4071 			IORING_SETUP_NO_SQARRAY))
4072 		return -EINVAL;
4073 
4074 	return io_uring_create(entries, &p, params);
4075 }
4076 
4077 static inline bool io_uring_allowed(void)
4078 {
4079 	int disabled = READ_ONCE(sysctl_io_uring_disabled);
4080 	kgid_t io_uring_group;
4081 
4082 	if (disabled == 2)
4083 		return false;
4084 
4085 	if (disabled == 0 || capable(CAP_SYS_ADMIN))
4086 		return true;
4087 
4088 	io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
4089 	if (!gid_valid(io_uring_group))
4090 		return false;
4091 
4092 	return in_group_p(io_uring_group);
4093 }
4094 
4095 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4096 		struct io_uring_params __user *, params)
4097 {
4098 	if (!io_uring_allowed())
4099 		return -EPERM;
4100 
4101 	return io_uring_setup(entries, params);
4102 }
4103 
4104 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
4105 			   unsigned nr_args)
4106 {
4107 	struct io_uring_probe *p;
4108 	size_t size;
4109 	int i, ret;
4110 
4111 	size = struct_size(p, ops, nr_args);
4112 	if (size == SIZE_MAX)
4113 		return -EOVERFLOW;
4114 	p = kzalloc(size, GFP_KERNEL);
4115 	if (!p)
4116 		return -ENOMEM;
4117 
4118 	ret = -EFAULT;
4119 	if (copy_from_user(p, arg, size))
4120 		goto out;
4121 	ret = -EINVAL;
4122 	if (memchr_inv(p, 0, size))
4123 		goto out;
4124 
4125 	p->last_op = IORING_OP_LAST - 1;
4126 	if (nr_args > IORING_OP_LAST)
4127 		nr_args = IORING_OP_LAST;
4128 
4129 	for (i = 0; i < nr_args; i++) {
4130 		p->ops[i].op = i;
4131 		if (!io_issue_defs[i].not_supported)
4132 			p->ops[i].flags = IO_URING_OP_SUPPORTED;
4133 	}
4134 	p->ops_len = i;
4135 
4136 	ret = 0;
4137 	if (copy_to_user(arg, p, size))
4138 		ret = -EFAULT;
4139 out:
4140 	kfree(p);
4141 	return ret;
4142 }
4143 
4144 static int io_register_personality(struct io_ring_ctx *ctx)
4145 {
4146 	const struct cred *creds;
4147 	u32 id;
4148 	int ret;
4149 
4150 	creds = get_current_cred();
4151 
4152 	ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
4153 			XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
4154 	if (ret < 0) {
4155 		put_cred(creds);
4156 		return ret;
4157 	}
4158 	return id;
4159 }
4160 
4161 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
4162 					   void __user *arg, unsigned int nr_args)
4163 {
4164 	struct io_uring_restriction *res;
4165 	size_t size;
4166 	int i, ret;
4167 
4168 	/* Restrictions allowed only if rings started disabled */
4169 	if (!(ctx->flags & IORING_SETUP_R_DISABLED))
4170 		return -EBADFD;
4171 
4172 	/* We allow only a single restrictions registration */
4173 	if (ctx->restrictions.registered)
4174 		return -EBUSY;
4175 
4176 	if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
4177 		return -EINVAL;
4178 
4179 	size = array_size(nr_args, sizeof(*res));
4180 	if (size == SIZE_MAX)
4181 		return -EOVERFLOW;
4182 
4183 	res = memdup_user(arg, size);
4184 	if (IS_ERR(res))
4185 		return PTR_ERR(res);
4186 
4187 	ret = 0;
4188 
4189 	for (i = 0; i < nr_args; i++) {
4190 		switch (res[i].opcode) {
4191 		case IORING_RESTRICTION_REGISTER_OP:
4192 			if (res[i].register_op >= IORING_REGISTER_LAST) {
4193 				ret = -EINVAL;
4194 				goto out;
4195 			}
4196 
4197 			__set_bit(res[i].register_op,
4198 				  ctx->restrictions.register_op);
4199 			break;
4200 		case IORING_RESTRICTION_SQE_OP:
4201 			if (res[i].sqe_op >= IORING_OP_LAST) {
4202 				ret = -EINVAL;
4203 				goto out;
4204 			}
4205 
4206 			__set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
4207 			break;
4208 		case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
4209 			ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
4210 			break;
4211 		case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
4212 			ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
4213 			break;
4214 		default:
4215 			ret = -EINVAL;
4216 			goto out;
4217 		}
4218 	}
4219 
4220 out:
4221 	/* Reset all restrictions if an error happened */
4222 	if (ret != 0)
4223 		memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
4224 	else
4225 		ctx->restrictions.registered = true;
4226 
4227 	kfree(res);
4228 	return ret;
4229 }
4230 
4231 static int io_register_enable_rings(struct io_ring_ctx *ctx)
4232 {
4233 	if (!(ctx->flags & IORING_SETUP_R_DISABLED))
4234 		return -EBADFD;
4235 
4236 	if (ctx->flags & IORING_SETUP_SINGLE_ISSUER && !ctx->submitter_task) {
4237 		WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4238 		/*
4239 		 * Lazy activation attempts would fail if it was polled before
4240 		 * submitter_task is set.
4241 		 */
4242 		if (wq_has_sleeper(&ctx->poll_wq))
4243 			io_activate_pollwq(ctx);
4244 	}
4245 
4246 	if (ctx->restrictions.registered)
4247 		ctx->restricted = 1;
4248 
4249 	ctx->flags &= ~IORING_SETUP_R_DISABLED;
4250 	if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
4251 		wake_up(&ctx->sq_data->wait);
4252 	return 0;
4253 }
4254 
4255 static __cold int __io_register_iowq_aff(struct io_ring_ctx *ctx,
4256 					 cpumask_var_t new_mask)
4257 {
4258 	int ret;
4259 
4260 	if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
4261 		ret = io_wq_cpu_affinity(current->io_uring, new_mask);
4262 	} else {
4263 		mutex_unlock(&ctx->uring_lock);
4264 		ret = io_sqpoll_wq_cpu_affinity(ctx, new_mask);
4265 		mutex_lock(&ctx->uring_lock);
4266 	}
4267 
4268 	return ret;
4269 }
4270 
4271 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
4272 				       void __user *arg, unsigned len)
4273 {
4274 	cpumask_var_t new_mask;
4275 	int ret;
4276 
4277 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4278 		return -ENOMEM;
4279 
4280 	cpumask_clear(new_mask);
4281 	if (len > cpumask_size())
4282 		len = cpumask_size();
4283 
4284 	if (in_compat_syscall()) {
4285 		ret = compat_get_bitmap(cpumask_bits(new_mask),
4286 					(const compat_ulong_t __user *)arg,
4287 					len * 8 /* CHAR_BIT */);
4288 	} else {
4289 		ret = copy_from_user(new_mask, arg, len);
4290 	}
4291 
4292 	if (ret) {
4293 		free_cpumask_var(new_mask);
4294 		return -EFAULT;
4295 	}
4296 
4297 	ret = __io_register_iowq_aff(ctx, new_mask);
4298 	free_cpumask_var(new_mask);
4299 	return ret;
4300 }
4301 
4302 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
4303 {
4304 	return __io_register_iowq_aff(ctx, NULL);
4305 }
4306 
4307 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
4308 					       void __user *arg)
4309 	__must_hold(&ctx->uring_lock)
4310 {
4311 	struct io_tctx_node *node;
4312 	struct io_uring_task *tctx = NULL;
4313 	struct io_sq_data *sqd = NULL;
4314 	__u32 new_count[2];
4315 	int i, ret;
4316 
4317 	if (copy_from_user(new_count, arg, sizeof(new_count)))
4318 		return -EFAULT;
4319 	for (i = 0; i < ARRAY_SIZE(new_count); i++)
4320 		if (new_count[i] > INT_MAX)
4321 			return -EINVAL;
4322 
4323 	if (ctx->flags & IORING_SETUP_SQPOLL) {
4324 		sqd = ctx->sq_data;
4325 		if (sqd) {
4326 			/*
4327 			 * Observe the correct sqd->lock -> ctx->uring_lock
4328 			 * ordering. Fine to drop uring_lock here, we hold
4329 			 * a ref to the ctx.
4330 			 */
4331 			refcount_inc(&sqd->refs);
4332 			mutex_unlock(&ctx->uring_lock);
4333 			mutex_lock(&sqd->lock);
4334 			mutex_lock(&ctx->uring_lock);
4335 			if (sqd->thread)
4336 				tctx = sqd->thread->io_uring;
4337 		}
4338 	} else {
4339 		tctx = current->io_uring;
4340 	}
4341 
4342 	BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
4343 
4344 	for (i = 0; i < ARRAY_SIZE(new_count); i++)
4345 		if (new_count[i])
4346 			ctx->iowq_limits[i] = new_count[i];
4347 	ctx->iowq_limits_set = true;
4348 
4349 	if (tctx && tctx->io_wq) {
4350 		ret = io_wq_max_workers(tctx->io_wq, new_count);
4351 		if (ret)
4352 			goto err;
4353 	} else {
4354 		memset(new_count, 0, sizeof(new_count));
4355 	}
4356 
4357 	if (sqd) {
4358 		mutex_unlock(&sqd->lock);
4359 		io_put_sq_data(sqd);
4360 	}
4361 
4362 	if (copy_to_user(arg, new_count, sizeof(new_count)))
4363 		return -EFAULT;
4364 
4365 	/* that's it for SQPOLL, only the SQPOLL task creates requests */
4366 	if (sqd)
4367 		return 0;
4368 
4369 	/* now propagate the restriction to all registered users */
4370 	list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
4371 		struct io_uring_task *tctx = node->task->io_uring;
4372 
4373 		if (WARN_ON_ONCE(!tctx->io_wq))
4374 			continue;
4375 
4376 		for (i = 0; i < ARRAY_SIZE(new_count); i++)
4377 			new_count[i] = ctx->iowq_limits[i];
4378 		/* ignore errors, it always returns zero anyway */
4379 		(void)io_wq_max_workers(tctx->io_wq, new_count);
4380 	}
4381 	return 0;
4382 err:
4383 	if (sqd) {
4384 		mutex_unlock(&sqd->lock);
4385 		io_put_sq_data(sqd);
4386 	}
4387 	return ret;
4388 }
4389 
4390 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4391 			       void __user *arg, unsigned nr_args)
4392 	__releases(ctx->uring_lock)
4393 	__acquires(ctx->uring_lock)
4394 {
4395 	int ret;
4396 
4397 	/*
4398 	 * We don't quiesce the refs for register anymore and so it can't be
4399 	 * dying as we're holding a file ref here.
4400 	 */
4401 	if (WARN_ON_ONCE(percpu_ref_is_dying(&ctx->refs)))
4402 		return -ENXIO;
4403 
4404 	if (ctx->submitter_task && ctx->submitter_task != current)
4405 		return -EEXIST;
4406 
4407 	if (ctx->restricted) {
4408 		opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
4409 		if (!test_bit(opcode, ctx->restrictions.register_op))
4410 			return -EACCES;
4411 	}
4412 
4413 	switch (opcode) {
4414 	case IORING_REGISTER_BUFFERS:
4415 		ret = -EFAULT;
4416 		if (!arg)
4417 			break;
4418 		ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
4419 		break;
4420 	case IORING_UNREGISTER_BUFFERS:
4421 		ret = -EINVAL;
4422 		if (arg || nr_args)
4423 			break;
4424 		ret = io_sqe_buffers_unregister(ctx);
4425 		break;
4426 	case IORING_REGISTER_FILES:
4427 		ret = -EFAULT;
4428 		if (!arg)
4429 			break;
4430 		ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
4431 		break;
4432 	case IORING_UNREGISTER_FILES:
4433 		ret = -EINVAL;
4434 		if (arg || nr_args)
4435 			break;
4436 		ret = io_sqe_files_unregister(ctx);
4437 		break;
4438 	case IORING_REGISTER_FILES_UPDATE:
4439 		ret = io_register_files_update(ctx, arg, nr_args);
4440 		break;
4441 	case IORING_REGISTER_EVENTFD:
4442 		ret = -EINVAL;
4443 		if (nr_args != 1)
4444 			break;
4445 		ret = io_eventfd_register(ctx, arg, 0);
4446 		break;
4447 	case IORING_REGISTER_EVENTFD_ASYNC:
4448 		ret = -EINVAL;
4449 		if (nr_args != 1)
4450 			break;
4451 		ret = io_eventfd_register(ctx, arg, 1);
4452 		break;
4453 	case IORING_UNREGISTER_EVENTFD:
4454 		ret = -EINVAL;
4455 		if (arg || nr_args)
4456 			break;
4457 		ret = io_eventfd_unregister(ctx);
4458 		break;
4459 	case IORING_REGISTER_PROBE:
4460 		ret = -EINVAL;
4461 		if (!arg || nr_args > 256)
4462 			break;
4463 		ret = io_probe(ctx, arg, nr_args);
4464 		break;
4465 	case IORING_REGISTER_PERSONALITY:
4466 		ret = -EINVAL;
4467 		if (arg || nr_args)
4468 			break;
4469 		ret = io_register_personality(ctx);
4470 		break;
4471 	case IORING_UNREGISTER_PERSONALITY:
4472 		ret = -EINVAL;
4473 		if (arg)
4474 			break;
4475 		ret = io_unregister_personality(ctx, nr_args);
4476 		break;
4477 	case IORING_REGISTER_ENABLE_RINGS:
4478 		ret = -EINVAL;
4479 		if (arg || nr_args)
4480 			break;
4481 		ret = io_register_enable_rings(ctx);
4482 		break;
4483 	case IORING_REGISTER_RESTRICTIONS:
4484 		ret = io_register_restrictions(ctx, arg, nr_args);
4485 		break;
4486 	case IORING_REGISTER_FILES2:
4487 		ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
4488 		break;
4489 	case IORING_REGISTER_FILES_UPDATE2:
4490 		ret = io_register_rsrc_update(ctx, arg, nr_args,
4491 					      IORING_RSRC_FILE);
4492 		break;
4493 	case IORING_REGISTER_BUFFERS2:
4494 		ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
4495 		break;
4496 	case IORING_REGISTER_BUFFERS_UPDATE:
4497 		ret = io_register_rsrc_update(ctx, arg, nr_args,
4498 					      IORING_RSRC_BUFFER);
4499 		break;
4500 	case IORING_REGISTER_IOWQ_AFF:
4501 		ret = -EINVAL;
4502 		if (!arg || !nr_args)
4503 			break;
4504 		ret = io_register_iowq_aff(ctx, arg, nr_args);
4505 		break;
4506 	case IORING_UNREGISTER_IOWQ_AFF:
4507 		ret = -EINVAL;
4508 		if (arg || nr_args)
4509 			break;
4510 		ret = io_unregister_iowq_aff(ctx);
4511 		break;
4512 	case IORING_REGISTER_IOWQ_MAX_WORKERS:
4513 		ret = -EINVAL;
4514 		if (!arg || nr_args != 2)
4515 			break;
4516 		ret = io_register_iowq_max_workers(ctx, arg);
4517 		break;
4518 	case IORING_REGISTER_RING_FDS:
4519 		ret = io_ringfd_register(ctx, arg, nr_args);
4520 		break;
4521 	case IORING_UNREGISTER_RING_FDS:
4522 		ret = io_ringfd_unregister(ctx, arg, nr_args);
4523 		break;
4524 	case IORING_REGISTER_PBUF_RING:
4525 		ret = -EINVAL;
4526 		if (!arg || nr_args != 1)
4527 			break;
4528 		ret = io_register_pbuf_ring(ctx, arg);
4529 		break;
4530 	case IORING_UNREGISTER_PBUF_RING:
4531 		ret = -EINVAL;
4532 		if (!arg || nr_args != 1)
4533 			break;
4534 		ret = io_unregister_pbuf_ring(ctx, arg);
4535 		break;
4536 	case IORING_REGISTER_SYNC_CANCEL:
4537 		ret = -EINVAL;
4538 		if (!arg || nr_args != 1)
4539 			break;
4540 		ret = io_sync_cancel(ctx, arg);
4541 		break;
4542 	case IORING_REGISTER_FILE_ALLOC_RANGE:
4543 		ret = -EINVAL;
4544 		if (!arg || nr_args)
4545 			break;
4546 		ret = io_register_file_alloc_range(ctx, arg);
4547 		break;
4548 	default:
4549 		ret = -EINVAL;
4550 		break;
4551 	}
4552 
4553 	return ret;
4554 }
4555 
4556 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4557 		void __user *, arg, unsigned int, nr_args)
4558 {
4559 	struct io_ring_ctx *ctx;
4560 	long ret = -EBADF;
4561 	struct file *file;
4562 	bool use_registered_ring;
4563 
4564 	use_registered_ring = !!(opcode & IORING_REGISTER_USE_REGISTERED_RING);
4565 	opcode &= ~IORING_REGISTER_USE_REGISTERED_RING;
4566 
4567 	if (opcode >= IORING_REGISTER_LAST)
4568 		return -EINVAL;
4569 
4570 	if (use_registered_ring) {
4571 		/*
4572 		 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
4573 		 * need only dereference our task private array to find it.
4574 		 */
4575 		struct io_uring_task *tctx = current->io_uring;
4576 
4577 		if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
4578 			return -EINVAL;
4579 		fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
4580 		file = tctx->registered_rings[fd];
4581 		if (unlikely(!file))
4582 			return -EBADF;
4583 	} else {
4584 		file = fget(fd);
4585 		if (unlikely(!file))
4586 			return -EBADF;
4587 		ret = -EOPNOTSUPP;
4588 		if (!io_is_uring_fops(file))
4589 			goto out_fput;
4590 	}
4591 
4592 	ctx = file->private_data;
4593 
4594 	mutex_lock(&ctx->uring_lock);
4595 	ret = __io_uring_register(ctx, opcode, arg, nr_args);
4596 	mutex_unlock(&ctx->uring_lock);
4597 	trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
4598 out_fput:
4599 	if (!use_registered_ring)
4600 		fput(file);
4601 	return ret;
4602 }
4603 
4604 static int __init io_uring_init(void)
4605 {
4606 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
4607 	BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
4608 	BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
4609 } while (0)
4610 
4611 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
4612 	__BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
4613 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
4614 	__BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
4615 	BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
4616 	BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
4617 	BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
4618 	BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
4619 	BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
4620 	BUILD_BUG_SQE_ELEM(8,  __u64,  off);
4621 	BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
4622 	BUILD_BUG_SQE_ELEM(8,  __u32,  cmd_op);
4623 	BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
4624 	BUILD_BUG_SQE_ELEM(16, __u64,  addr);
4625 	BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
4626 	BUILD_BUG_SQE_ELEM(24, __u32,  len);
4627 	BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
4628 	BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
4629 	BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
4630 	BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
4631 	BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
4632 	BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
4633 	BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
4634 	BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
4635 	BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
4636 	BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
4637 	BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
4638 	BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
4639 	BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
4640 	BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
4641 	BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
4642 	BUILD_BUG_SQE_ELEM(28, __u32,  rename_flags);
4643 	BUILD_BUG_SQE_ELEM(28, __u32,  unlink_flags);
4644 	BUILD_BUG_SQE_ELEM(28, __u32,  hardlink_flags);
4645 	BUILD_BUG_SQE_ELEM(28, __u32,  xattr_flags);
4646 	BUILD_BUG_SQE_ELEM(28, __u32,  msg_ring_flags);
4647 	BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
4648 	BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
4649 	BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
4650 	BUILD_BUG_SQE_ELEM(42, __u16,  personality);
4651 	BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
4652 	BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
4653 	BUILD_BUG_SQE_ELEM(44, __u16,  addr_len);
4654 	BUILD_BUG_SQE_ELEM(46, __u16,  __pad3[0]);
4655 	BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
4656 	BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
4657 	BUILD_BUG_SQE_ELEM(56, __u64,  __pad2);
4658 
4659 	BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
4660 		     sizeof(struct io_uring_rsrc_update));
4661 	BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
4662 		     sizeof(struct io_uring_rsrc_update2));
4663 
4664 	/* ->buf_index is u16 */
4665 	BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
4666 	BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
4667 		     offsetof(struct io_uring_buf_ring, tail));
4668 
4669 	/* should fit into one byte */
4670 	BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
4671 	BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4672 	BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4673 
4674 	BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
4675 
4676 	BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4677 
4678 	io_uring_optable_init();
4679 
4680 	/*
4681 	 * Allow user copy in the per-command field, which starts after the
4682 	 * file in io_kiocb and until the opcode field. The openat2 handling
4683 	 * requires copying in user memory into the io_kiocb object in that
4684 	 * range, and HARDENED_USERCOPY will complain if we haven't
4685 	 * correctly annotated this range.
4686 	 */
4687 	req_cachep = kmem_cache_create_usercopy("io_kiocb",
4688 				sizeof(struct io_kiocb), 0,
4689 				SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4690 				SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU,
4691 				offsetof(struct io_kiocb, cmd.data),
4692 				sizeof_field(struct io_kiocb, cmd.data), NULL);
4693 
4694 	iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
4695 
4696 #ifdef CONFIG_SYSCTL
4697 	register_sysctl_init("kernel", kernel_io_uring_disabled_table);
4698 #endif
4699 
4700 	return 0;
4701 };
4702 __initcall(io_uring_init);
4703