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