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