xref: /linux/io_uring/io_uring.c (revision 2c142b63c8ee982cdfdba49a616027c266294838)
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.org/pub/scm/linux/kernel/git/axboe/liburing.git
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/errno.h>
44 #include <linux/syscalls.h>
45 #include <linux/refcount.h>
46 #include <linux/bits.h>
47 
48 #include <linux/sched/signal.h>
49 #include <linux/fs.h>
50 #include <linux/mm.h>
51 #include <linux/percpu.h>
52 #include <linux/slab.h>
53 #include <linux/anon_inodes.h>
54 #include <linux/uaccess.h>
55 #include <linux/nospec.h>
56 #include <linux/task_work.h>
57 #include <linux/io_uring.h>
58 #include <linux/io_uring/cmd.h>
59 #include <linux/audit.h>
60 #include <linux/security.h>
61 #include <linux/jump_label.h>
62 
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/io_uring.h>
65 
66 #include <uapi/linux/io_uring.h>
67 
68 #include "io-wq.h"
69 
70 #include "filetable.h"
71 #include "io_uring.h"
72 #include "opdef.h"
73 #include "refs.h"
74 #include "tctx.h"
75 #include "register.h"
76 #include "sqpoll.h"
77 #include "fdinfo.h"
78 #include "kbuf.h"
79 #include "rsrc.h"
80 #include "cancel.h"
81 #include "net.h"
82 #include "notif.h"
83 #include "waitid.h"
84 #include "futex.h"
85 #include "napi.h"
86 #include "uring_cmd.h"
87 #include "msg_ring.h"
88 #include "memmap.h"
89 #include "zcrx.h"
90 #include "bpf-ops.h"
91 
92 #include "timeout.h"
93 #include "poll.h"
94 #include "rw.h"
95 #include "alloc_cache.h"
96 #include "eventfd.h"
97 #include "wait.h"
98 #include "bpf_filter.h"
99 #include "loop.h"
100 
101 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
102 			  IOSQE_IO_HARDLINK | IOSQE_ASYNC)
103 
104 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
105 
106 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
107 				REQ_F_INFLIGHT | REQ_F_CREDS | REQ_F_ASYNC_DATA)
108 
109 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | IO_REQ_LINK_FLAGS | \
110 				 REQ_F_REISSUE | REQ_F_POLLED | \
111 				 IO_REQ_CLEAN_FLAGS)
112 
113 #define IO_TCTX_REFS_CACHE_NR	(1U << 10)
114 
115 #define IO_COMPL_BATCH			32
116 #define IO_REQ_ALLOC_BATCH		8
117 
118 /* requests with any of those set should undergo io_disarm_next() */
119 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
120 
121 static void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags);
122 static void __io_req_caches_free(struct io_ring_ctx *ctx);
123 
124 static __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(io_key_has_sqarray, HZ);
125 
126 struct kmem_cache *req_cachep;
127 static struct workqueue_struct *iou_wq __ro_after_init;
128 
129 static int __read_mostly sysctl_io_uring_disabled;
130 static int __read_mostly sysctl_io_uring_group = -1;
131 
132 #ifdef CONFIG_SYSCTL
133 static const struct ctl_table kernel_io_uring_disabled_table[] = {
134 	{
135 		.procname	= "io_uring_disabled",
136 		.data		= &sysctl_io_uring_disabled,
137 		.maxlen		= sizeof(sysctl_io_uring_disabled),
138 		.mode		= 0644,
139 		.proc_handler	= proc_dointvec_minmax,
140 		.extra1		= SYSCTL_ZERO,
141 		.extra2		= SYSCTL_TWO,
142 	},
143 	{
144 		.procname	= "io_uring_group",
145 		.data		= &sysctl_io_uring_group,
146 		.maxlen		= sizeof(gid_t),
147 		.mode		= 0644,
148 		.proc_handler	= proc_dointvec,
149 	},
150 };
151 #endif
152 
io_poison_cached_req(struct io_kiocb * req)153 static void io_poison_cached_req(struct io_kiocb *req)
154 {
155 	req->ctx = IO_URING_PTR_POISON;
156 	req->tctx = IO_URING_PTR_POISON;
157 	req->file = IO_URING_PTR_POISON;
158 	req->creds = IO_URING_PTR_POISON;
159 	req->io_task_work.func = IO_URING_PTR_POISON;
160 	req->apoll = IO_URING_PTR_POISON;
161 }
162 
io_poison_req(struct io_kiocb * req)163 static void io_poison_req(struct io_kiocb *req)
164 {
165 	io_poison_cached_req(req);
166 	req->async_data = IO_URING_PTR_POISON;
167 	req->kbuf = IO_URING_PTR_POISON;
168 	req->comp_list.next = IO_URING_PTR_POISON;
169 	req->file_node = IO_URING_PTR_POISON;
170 	req->link = IO_URING_PTR_POISON;
171 }
172 
req_fail_link_node(struct io_kiocb * req,int res)173 static inline void req_fail_link_node(struct io_kiocb *req, int res)
174 {
175 	req_set_fail(req);
176 	io_req_set_res(req, res, 0);
177 }
178 
io_req_add_to_cache(struct io_kiocb * req,struct io_ring_ctx * ctx)179 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
180 {
181 	if (IS_ENABLED(CONFIG_KASAN))
182 		io_poison_cached_req(req);
183 	wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
184 }
185 
io_ring_ctx_ref_free(struct percpu_ref * ref)186 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
187 {
188 	struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
189 
190 	complete(&ctx->ref_comp);
191 }
192 
io_alloc_hash_table(struct io_hash_table * table,unsigned bits)193 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
194 {
195 	unsigned int hash_buckets;
196 	int i;
197 
198 	do {
199 		hash_buckets = 1U << bits;
200 		table->hbs = kvmalloc_objs(table->hbs[0], hash_buckets,
201 					   GFP_KERNEL_ACCOUNT);
202 		if (table->hbs)
203 			break;
204 		if (bits == 1)
205 			return -ENOMEM;
206 		bits--;
207 	} while (1);
208 
209 	table->hash_bits = bits;
210 	for (i = 0; i < hash_buckets; i++)
211 		INIT_HLIST_HEAD(&table->hbs[i].list);
212 	return 0;
213 }
214 
io_free_alloc_caches(struct io_ring_ctx * ctx)215 static void io_free_alloc_caches(struct io_ring_ctx *ctx)
216 {
217 	io_alloc_cache_free(&ctx->apoll_cache, kfree);
218 	io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
219 	io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
220 	io_alloc_cache_free(&ctx->cmd_cache, io_cmd_cache_free);
221 	io_futex_cache_free(ctx);
222 	io_rsrc_cache_free(ctx);
223 }
224 
io_ring_ctx_alloc(struct io_uring_params * p)225 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
226 {
227 	struct io_ring_ctx *ctx;
228 	int hash_bits;
229 	bool ret;
230 
231 	ctx = kzalloc_obj(*ctx);
232 	if (!ctx)
233 		return NULL;
234 
235 	xa_init(&ctx->io_bl_xa);
236 
237 	/*
238 	 * Use 5 bits less than the max cq entries, that should give us around
239 	 * 32 entries per hash list if totally full and uniformly spread, but
240 	 * don't keep too many buckets to not overconsume memory.
241 	 */
242 	hash_bits = ilog2(p->cq_entries) - 5;
243 	hash_bits = clamp(hash_bits, 1, 8);
244 	if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
245 		goto err;
246 	if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
247 			    0, GFP_KERNEL))
248 		goto err;
249 
250 	ctx->flags = p->flags;
251 	ctx->hybrid_poll_time = LLONG_MAX;
252 	atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
253 	init_waitqueue_head(&ctx->sqo_sq_wait);
254 	INIT_LIST_HEAD(&ctx->sqd_list);
255 	INIT_LIST_HEAD(&ctx->cq_overflow_list);
256 	ret = io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX,
257 			    sizeof(struct async_poll), 0);
258 	ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
259 			    sizeof(struct io_async_msghdr),
260 			    offsetof(struct io_async_msghdr, clear));
261 	ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX,
262 			    sizeof(struct io_async_rw),
263 			    offsetof(struct io_async_rw, clear));
264 	ret |= io_alloc_cache_init(&ctx->cmd_cache, IO_ALLOC_CACHE_MAX,
265 			    sizeof(struct io_async_cmd),
266 			    sizeof(struct io_async_cmd));
267 	ret |= io_futex_cache_init(ctx);
268 	ret |= io_rsrc_cache_init(ctx);
269 	if (ret)
270 		goto free_ref;
271 	init_completion(&ctx->ref_comp);
272 	xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
273 	mutex_init(&ctx->uring_lock);
274 	init_waitqueue_head(&ctx->cq_wait);
275 	init_waitqueue_head(&ctx->poll_wq);
276 	spin_lock_init(&ctx->completion_lock);
277 	raw_spin_lock_init(&ctx->timeout_lock);
278 	INIT_LIST_HEAD(&ctx->iopoll_list);
279 	INIT_LIST_HEAD(&ctx->defer_list);
280 	INIT_LIST_HEAD(&ctx->timeout_list);
281 	INIT_LIST_HEAD(&ctx->ltimeout_list);
282 	init_llist_head(&ctx->work_llist);
283 	INIT_LIST_HEAD(&ctx->tctx_list);
284 	mutex_init(&ctx->tctx_lock);
285 	ctx->submit_state.free_list.next = NULL;
286 	INIT_HLIST_HEAD(&ctx->waitid_list);
287 	xa_init_flags(&ctx->zcrx_ctxs, XA_FLAGS_ALLOC);
288 #ifdef CONFIG_FUTEX
289 	INIT_HLIST_HEAD(&ctx->futex_list);
290 #endif
291 	INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
292 	INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
293 	INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
294 	io_napi_init(ctx);
295 	mutex_init(&ctx->mmap_lock);
296 
297 	return ctx;
298 
299 free_ref:
300 	percpu_ref_exit(&ctx->refs);
301 err:
302 	io_free_alloc_caches(ctx);
303 	kvfree(ctx->cancel_table.hbs);
304 	xa_destroy(&ctx->io_bl_xa);
305 	kfree(ctx);
306 	return NULL;
307 }
308 
io_clean_op(struct io_kiocb * req)309 static void io_clean_op(struct io_kiocb *req)
310 {
311 	if (unlikely(req->flags & REQ_F_BUFFER_SELECTED))
312 		io_kbuf_drop_legacy(req);
313 
314 	if (req->flags & REQ_F_NEED_CLEANUP) {
315 		const struct io_cold_def *def = &io_cold_defs[req->opcode];
316 
317 		if (def->cleanup)
318 			def->cleanup(req);
319 	}
320 	if (req->flags & REQ_F_INFLIGHT)
321 		atomic_dec(&req->tctx->inflight_tracked);
322 	if (req->flags & REQ_F_CREDS)
323 		put_cred(req->creds);
324 	if (req->flags & REQ_F_ASYNC_DATA) {
325 		kfree(req->async_data);
326 		req->async_data = NULL;
327 	}
328 	req->flags &= ~IO_REQ_CLEAN_FLAGS;
329 }
330 
331 /*
332  * Mark the request as inflight, so that file cancelation will find it.
333  * Can be used if the file is an io_uring instance, or if the request itself
334  * relies on ->mm being alive for the duration of the request.
335  */
io_req_track_inflight(struct io_kiocb * req)336 inline void io_req_track_inflight(struct io_kiocb *req)
337 {
338 	if (!(req->flags & REQ_F_INFLIGHT)) {
339 		req->flags |= REQ_F_INFLIGHT;
340 		atomic_inc(&req->tctx->inflight_tracked);
341 	}
342 }
343 
__io_prep_linked_timeout(struct io_kiocb * req)344 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
345 {
346 	if (WARN_ON_ONCE(!req->link))
347 		return NULL;
348 
349 	req->flags &= ~REQ_F_ARM_LTIMEOUT;
350 	req->flags |= REQ_F_LINK_TIMEOUT;
351 
352 	/* linked timeouts should have two refs once prep'ed */
353 	io_req_set_refcount(req);
354 	__io_req_set_refcount(req->link, 2);
355 	return req->link;
356 }
357 
io_prep_async_work(struct io_kiocb * req)358 static void io_prep_async_work(struct io_kiocb *req)
359 {
360 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
361 
362 	if (!(req->flags & REQ_F_CREDS)) {
363 		req->flags |= REQ_F_CREDS;
364 		req->creds = get_current_cred();
365 	}
366 
367 	req->work.list.next = NULL;
368 	atomic_set(&req->work.flags, 0);
369 	if (req->flags & REQ_F_FORCE_ASYNC)
370 		atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
371 
372 	if (req->file && !(req->flags & REQ_F_FIXED_FILE))
373 		req->flags |= io_file_get_flags(req->file);
374 
375 	if (req->file && (req->flags & REQ_F_ISREG)) {
376 		bool should_hash = def->hash_reg_file;
377 
378 		/* don't serialize this request if the fs doesn't need it */
379 		if (should_hash && (req->file->f_flags & O_DIRECT) &&
380 		    (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
381 			should_hash = false;
382 		if (should_hash || (req->flags & REQ_F_IOPOLL))
383 			io_wq_hash_work(&req->work, file_inode(req->file));
384 	} else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
385 		if (def->unbound_nonreg_file)
386 			atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
387 	}
388 }
389 
io_prep_async_link(struct io_kiocb * req)390 static void io_prep_async_link(struct io_kiocb *req)
391 {
392 	struct io_kiocb *cur;
393 
394 	if (req->flags & REQ_F_LINK_TIMEOUT) {
395 		struct io_ring_ctx *ctx = req->ctx;
396 
397 		raw_spin_lock_irq(&ctx->timeout_lock);
398 		io_for_each_link(cur, req)
399 			io_prep_async_work(cur);
400 		raw_spin_unlock_irq(&ctx->timeout_lock);
401 	} else {
402 		io_for_each_link(cur, req)
403 			io_prep_async_work(cur);
404 	}
405 }
406 
io_queue_iowq(struct io_kiocb * req)407 static void io_queue_iowq(struct io_kiocb *req)
408 {
409 	struct io_uring_task *tctx = req->tctx;
410 
411 	BUG_ON(!tctx);
412 
413 	if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
414 		io_req_task_queue_fail(req, -ECANCELED);
415 		return;
416 	}
417 
418 	/* init ->work of the whole link before punting */
419 	io_prep_async_link(req);
420 
421 	/*
422 	 * Not expected to happen, but if we do have a bug where this _can_
423 	 * happen, catch it here and ensure the request is marked as
424 	 * canceled. That will make io-wq go through the usual work cancel
425 	 * procedure rather than attempt to run this request (or create a new
426 	 * worker for it).
427 	 */
428 	if (WARN_ON_ONCE(!same_thread_group(tctx->task, current)))
429 		atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
430 
431 	trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
432 	io_wq_enqueue(tctx->io_wq, &req->work);
433 }
434 
io_req_queue_iowq_tw(struct io_tw_req tw_req,io_tw_token_t tw)435 static void io_req_queue_iowq_tw(struct io_tw_req tw_req, io_tw_token_t tw)
436 {
437 	io_queue_iowq(tw_req.req);
438 }
439 
io_req_queue_iowq(struct io_kiocb * req)440 void io_req_queue_iowq(struct io_kiocb *req)
441 {
442 	req->io_task_work.func = io_req_queue_iowq_tw;
443 	io_req_task_work_add(req);
444 }
445 
io_linked_nr(struct io_kiocb * req)446 unsigned io_linked_nr(struct io_kiocb *req)
447 {
448 	struct io_kiocb *tmp;
449 	unsigned nr = 0;
450 
451 	io_for_each_link(tmp, req)
452 		nr++;
453 	return nr;
454 }
455 
io_queue_deferred(struct io_ring_ctx * ctx)456 static __cold noinline void io_queue_deferred(struct io_ring_ctx *ctx)
457 {
458 	bool drain_seen = false, first = true;
459 
460 	lockdep_assert_held(&ctx->uring_lock);
461 	__io_req_caches_free(ctx);
462 
463 	while (!list_empty(&ctx->defer_list)) {
464 		struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
465 						struct io_defer_entry, list);
466 
467 		drain_seen |= de->req->flags & REQ_F_IO_DRAIN;
468 		if ((drain_seen || first) && ctx->nr_req_allocated != ctx->nr_drained)
469 			return;
470 
471 		list_del_init(&de->list);
472 		ctx->nr_drained -= io_linked_nr(de->req);
473 		io_req_task_queue(de->req);
474 		kfree(de);
475 		first = false;
476 	}
477 }
478 
__io_commit_cqring_flush(struct io_ring_ctx * ctx)479 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
480 {
481 	if (ctx->int_flags & IO_RING_F_POLL_ACTIVATED)
482 		io_poll_wq_wake(ctx);
483 	if (ctx->int_flags & IO_RING_F_OFF_TIMEOUT_USED)
484 		io_flush_timeouts(ctx);
485 	if (ctx->int_flags & IO_RING_F_HAS_EVFD)
486 		io_eventfd_signal(ctx, true);
487 }
488 
__io_cq_lock(struct io_ring_ctx * ctx)489 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
490 {
491 	if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ))
492 		spin_lock(&ctx->completion_lock);
493 }
494 
io_cq_lock(struct io_ring_ctx * ctx)495 static inline void io_cq_lock(struct io_ring_ctx *ctx)
496 	__acquires(ctx->completion_lock)
497 {
498 	spin_lock(&ctx->completion_lock);
499 }
500 
__io_cq_unlock_post(struct io_ring_ctx * ctx)501 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
502 {
503 	io_commit_cqring(ctx);
504 	if (!(ctx->int_flags & IO_RING_F_TASK_COMPLETE)) {
505 		if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ))
506 			spin_unlock(&ctx->completion_lock);
507 		/* IOPOLL rings only need to wake up if it's also SQPOLL */
508 		if (!(ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL))
509 			io_cqring_wake(ctx);
510 	}
511 	io_commit_cqring_flush(ctx);
512 }
513 
io_cq_unlock_post(struct io_ring_ctx * ctx)514 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
515 	__releases(ctx->completion_lock)
516 {
517 	io_commit_cqring(ctx);
518 	spin_unlock(&ctx->completion_lock);
519 	io_cqring_wake(ctx);
520 	io_commit_cqring_flush(ctx);
521 }
522 
__io_cqring_overflow_flush(struct io_ring_ctx * ctx,bool dying)523 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
524 {
525 	lockdep_assert_held(&ctx->uring_lock);
526 
527 	/* don't abort if we're dying, entries must get freed */
528 	if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
529 		return;
530 
531 	io_cq_lock(ctx);
532 	while (!list_empty(&ctx->cq_overflow_list)) {
533 		size_t cqe_size = sizeof(struct io_uring_cqe);
534 		struct io_uring_cqe *cqe;
535 		struct io_overflow_cqe *ocqe;
536 		bool is_cqe32 = false;
537 
538 		ocqe = list_first_entry(&ctx->cq_overflow_list,
539 					struct io_overflow_cqe, list);
540 		if (ocqe->cqe.flags & IORING_CQE_F_32 ||
541 		    ctx->flags & IORING_SETUP_CQE32) {
542 			is_cqe32 = true;
543 			cqe_size <<= 1;
544 		}
545 		if (ctx->flags & IORING_SETUP_CQE32)
546 			is_cqe32 = false;
547 
548 		if (!dying) {
549 			if (!io_get_cqe_overflow(ctx, &cqe, true, is_cqe32))
550 				break;
551 			memcpy(cqe, &ocqe->cqe, cqe_size);
552 		}
553 		list_del(&ocqe->list);
554 		kfree(ocqe);
555 
556 		/*
557 		 * For silly syzbot cases that deliberately overflow by huge
558 		 * amounts, check if we need to resched and drop and
559 		 * reacquire the locks if so. Nothing real would ever hit this.
560 		 * Ideally we'd have a non-posting unlock for this, but hard
561 		 * to care for a non-real case.
562 		 */
563 		if (need_resched()) {
564 			ctx->cqe_sentinel = ctx->cqe_cached;
565 			io_cq_unlock_post(ctx);
566 			mutex_unlock(&ctx->uring_lock);
567 			cond_resched();
568 			mutex_lock(&ctx->uring_lock);
569 			io_cq_lock(ctx);
570 		}
571 	}
572 
573 	if (list_empty(&ctx->cq_overflow_list)) {
574 		clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
575 		atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
576 	}
577 	io_cq_unlock_post(ctx);
578 }
579 
io_cqring_overflow_kill(struct io_ring_ctx * ctx)580 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
581 {
582 	if (ctx->rings)
583 		__io_cqring_overflow_flush(ctx, true);
584 }
585 
io_cqring_do_overflow_flush(struct io_ring_ctx * ctx)586 void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
587 {
588 	mutex_lock(&ctx->uring_lock);
589 	__io_cqring_overflow_flush(ctx, false);
590 	mutex_unlock(&ctx->uring_lock);
591 }
592 
io_cqring_overflow_flush_locked(struct io_ring_ctx * ctx)593 void io_cqring_overflow_flush_locked(struct io_ring_ctx *ctx)
594 {
595 	__io_cqring_overflow_flush(ctx, false);
596 }
597 
598 /* must to be called somewhat shortly after putting a request */
io_put_task(struct io_kiocb * req)599 static inline void io_put_task(struct io_kiocb *req)
600 {
601 	struct io_uring_task *tctx = req->tctx;
602 
603 	if (likely(tctx->task == current)) {
604 		tctx->cached_refs++;
605 	} else {
606 		percpu_counter_sub(&tctx->inflight, 1);
607 		if (unlikely(atomic_read(&tctx->in_cancel)))
608 			wake_up(&tctx->wait);
609 		put_task_struct(tctx->task);
610 	}
611 }
612 
io_task_refs_refill(struct io_uring_task * tctx)613 void io_task_refs_refill(struct io_uring_task *tctx)
614 {
615 	unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
616 
617 	percpu_counter_add(&tctx->inflight, refill);
618 	refcount_add(refill, &current->usage);
619 	tctx->cached_refs += refill;
620 }
621 
io_uring_drop_tctx_refs(struct task_struct * task)622 __cold void io_uring_drop_tctx_refs(struct task_struct *task)
623 {
624 	struct io_uring_task *tctx = task->io_uring;
625 	unsigned int refs = tctx->cached_refs;
626 
627 	if (refs) {
628 		tctx->cached_refs = 0;
629 		percpu_counter_sub(&tctx->inflight, refs);
630 		put_task_struct_many(task, refs);
631 	}
632 }
633 
io_cqring_add_overflow(struct io_ring_ctx * ctx,struct io_overflow_cqe * ocqe)634 static __cold bool io_cqring_add_overflow(struct io_ring_ctx *ctx,
635 					  struct io_overflow_cqe *ocqe)
636 {
637 	lockdep_assert_held(&ctx->completion_lock);
638 
639 	if (!ocqe) {
640 		struct io_rings *r = ctx->rings;
641 
642 		/*
643 		 * If we're in ring overflow flush mode, or in task cancel mode,
644 		 * or cannot allocate an overflow entry, then we need to drop it
645 		 * on the floor.
646 		 */
647 		WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
648 		set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
649 		return false;
650 	}
651 	if (list_empty(&ctx->cq_overflow_list)) {
652 		set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
653 		atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
654 
655 	}
656 	list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
657 	return true;
658 }
659 
io_alloc_ocqe(struct io_ring_ctx * ctx,struct io_cqe * cqe,struct io_big_cqe * big_cqe,gfp_t gfp)660 static struct io_overflow_cqe *io_alloc_ocqe(struct io_ring_ctx *ctx,
661 					     struct io_cqe *cqe,
662 					     struct io_big_cqe *big_cqe, gfp_t gfp)
663 {
664 	struct io_overflow_cqe *ocqe;
665 	size_t ocq_size = sizeof(struct io_overflow_cqe);
666 	bool is_cqe32 = false;
667 
668 	if (cqe->flags & IORING_CQE_F_32 || ctx->flags & IORING_SETUP_CQE32) {
669 		is_cqe32 = true;
670 		ocq_size += sizeof(struct io_uring_cqe);
671 	}
672 
673 	ocqe = kzalloc(ocq_size, gfp | __GFP_ACCOUNT);
674 	trace_io_uring_cqe_overflow(ctx, cqe->user_data, cqe->res, cqe->flags, ocqe);
675 	if (ocqe) {
676 		ocqe->cqe.user_data = cqe->user_data;
677 		ocqe->cqe.res = cqe->res;
678 		ocqe->cqe.flags = cqe->flags;
679 		if (is_cqe32 && big_cqe) {
680 			ocqe->cqe.big_cqe[0] = big_cqe->extra1;
681 			ocqe->cqe.big_cqe[1] = big_cqe->extra2;
682 		}
683 	}
684 	if (big_cqe)
685 		big_cqe->extra1 = big_cqe->extra2 = 0;
686 	return ocqe;
687 }
688 
689 /*
690  * Compute queued CQEs for free-space calculation, clamped to cq_entries.
691  */
io_cqring_queued(struct io_ring_ctx * ctx)692 static unsigned int io_cqring_queued(struct io_ring_ctx *ctx)
693 {
694 	struct io_rings *rings = io_get_rings(ctx);
695 	int diff;
696 
697 	diff = (int)(ctx->cached_cq_tail - READ_ONCE(rings->cq.head));
698 	if (diff >= 0)
699 		return min((unsigned int)diff, ctx->cq_entries);
700 	return 0;
701 }
702 
703 /*
704  * Fill an empty dummy CQE, in case alignment is off for posting a 32b CQE
705  * because the ring is a single 16b entry away from wrapping.
706  */
io_fill_nop_cqe(struct io_ring_ctx * ctx,unsigned int off)707 static bool io_fill_nop_cqe(struct io_ring_ctx *ctx, unsigned int off)
708 {
709 	if (io_cqring_queued(ctx) < ctx->cq_entries) {
710 		struct io_uring_cqe *cqe = &ctx->rings->cqes[off];
711 
712 		cqe->user_data = 0;
713 		cqe->res = 0;
714 		cqe->flags = IORING_CQE_F_SKIP;
715 		ctx->cached_cq_tail++;
716 		return true;
717 	}
718 	return false;
719 }
720 
721 /*
722  * writes to the cq entry need to come after reading head; the
723  * control dependency is enough as we're using WRITE_ONCE to
724  * fill the cq entry
725  */
io_cqe_cache_refill(struct io_ring_ctx * ctx,bool overflow,bool cqe32)726 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow, bool cqe32)
727 {
728 	struct io_rings *rings = ctx->rings;
729 	unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
730 	unsigned int free, len;
731 
732 	/*
733 	 * Posting into the CQ when there are pending overflowed CQEs may break
734 	 * ordering guarantees, which will affect links, F_MORE users and more.
735 	 * Force overflow the completion.
736 	 */
737 	if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
738 		return false;
739 
740 	/*
741 	 * Post dummy CQE if a 32b CQE is needed and there's only room for a
742 	 * 16b CQE before the ring wraps.
743 	 */
744 	if (cqe32 && off + 1 == ctx->cq_entries) {
745 		if (!io_fill_nop_cqe(ctx, off))
746 			return false;
747 		off = 0;
748 	}
749 
750 	free = ctx->cq_entries - io_cqring_queued(ctx);
751 	/* we need a contiguous range, limit based on the current array offset */
752 	len = min(free, ctx->cq_entries - off);
753 	if (len < (cqe32 + 1))
754 		return false;
755 
756 	if (ctx->flags & IORING_SETUP_CQE32) {
757 		off <<= 1;
758 		len <<= 1;
759 	}
760 
761 	ctx->cqe_cached = &rings->cqes[off];
762 	ctx->cqe_sentinel = ctx->cqe_cached + len;
763 	return true;
764 }
765 
io_fill_cqe_aux32(struct io_ring_ctx * ctx,struct io_uring_cqe src_cqe[2])766 static bool io_fill_cqe_aux32(struct io_ring_ctx *ctx,
767 			      struct io_uring_cqe src_cqe[2])
768 {
769 	struct io_uring_cqe *cqe;
770 
771 	if (WARN_ON_ONCE(!(ctx->flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED))))
772 		return false;
773 	if (unlikely(!io_get_cqe(ctx, &cqe, true)))
774 		return false;
775 
776 	memcpy(cqe, src_cqe, 2 * sizeof(*cqe));
777 	trace_io_uring_complete(ctx, NULL, cqe);
778 	return true;
779 }
780 
io_fill_cqe_aux(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)781 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
782 			      u32 cflags)
783 {
784 	bool cqe32 = cflags & IORING_CQE_F_32;
785 	struct io_uring_cqe *cqe;
786 
787 	if (likely(io_get_cqe(ctx, &cqe, cqe32))) {
788 		WRITE_ONCE(cqe->user_data, user_data);
789 		WRITE_ONCE(cqe->res, res);
790 		WRITE_ONCE(cqe->flags, cflags);
791 
792 		if (cqe32) {
793 			WRITE_ONCE(cqe->big_cqe[0], 0);
794 			WRITE_ONCE(cqe->big_cqe[1], 0);
795 		}
796 
797 		trace_io_uring_complete(ctx, NULL, cqe);
798 		return true;
799 	}
800 	return false;
801 }
802 
io_init_cqe(u64 user_data,s32 res,u32 cflags)803 static inline struct io_cqe io_init_cqe(u64 user_data, s32 res, u32 cflags)
804 {
805 	return (struct io_cqe) { .user_data = user_data, .res = res, .flags = cflags };
806 }
807 
io_cqe_overflow(struct io_ring_ctx * ctx,struct io_cqe * cqe,struct io_big_cqe * big_cqe)808 static __cold void io_cqe_overflow(struct io_ring_ctx *ctx, struct io_cqe *cqe,
809 				   struct io_big_cqe *big_cqe)
810 {
811 	struct io_overflow_cqe *ocqe;
812 
813 	ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_KERNEL);
814 	spin_lock(&ctx->completion_lock);
815 	io_cqring_add_overflow(ctx, ocqe);
816 	spin_unlock(&ctx->completion_lock);
817 }
818 
io_cqe_overflow_locked(struct io_ring_ctx * ctx,struct io_cqe * cqe,struct io_big_cqe * big_cqe)819 static __cold bool io_cqe_overflow_locked(struct io_ring_ctx *ctx,
820 					  struct io_cqe *cqe,
821 					  struct io_big_cqe *big_cqe)
822 {
823 	struct io_overflow_cqe *ocqe;
824 
825 	ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_NOWAIT);
826 	return io_cqring_add_overflow(ctx, ocqe);
827 }
828 
io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)829 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
830 {
831 	bool filled;
832 
833 	io_cq_lock(ctx);
834 	filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
835 	if (unlikely(!filled)) {
836 		struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
837 
838 		filled = io_cqe_overflow_locked(ctx, &cqe, NULL);
839 	}
840 	io_cq_unlock_post(ctx);
841 	return filled;
842 }
843 
844 /*
845  * Must be called from inline task_work so we know a flush will happen later,
846  * and obviously with ctx->uring_lock held (tw always has that).
847  */
io_add_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)848 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
849 {
850 	lockdep_assert_held(&ctx->uring_lock);
851 	lockdep_assert(ctx->int_flags & IO_RING_F_LOCKLESS_CQ);
852 
853 	if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
854 		struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
855 
856 		io_cqe_overflow(ctx, &cqe, NULL);
857 	}
858 	ctx->submit_state.cq_flush = true;
859 }
860 
861 /*
862  * A helper for multishot requests posting additional CQEs.
863  * Should only be used from a task_work including IO_URING_F_MULTISHOT.
864  */
io_req_post_cqe(struct io_kiocb * req,s32 res,u32 cflags)865 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
866 {
867 	struct io_ring_ctx *ctx = req->ctx;
868 	bool posted;
869 
870 	/*
871 	 * If multishot has already posted deferred completions, ensure that
872 	 * those are flushed first before posting this one. If not, CQEs
873 	 * could get reordered.
874 	 */
875 	if (!wq_list_empty(&ctx->submit_state.compl_reqs))
876 		__io_submit_flush_completions(ctx);
877 
878 	lockdep_assert(!io_wq_current_is_worker());
879 	lockdep_assert_held(&ctx->uring_lock);
880 
881 	if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) {
882 		spin_lock(&ctx->completion_lock);
883 		posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
884 		spin_unlock(&ctx->completion_lock);
885 	} else {
886 		posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
887 	}
888 
889 	ctx->submit_state.cq_flush = true;
890 	return posted;
891 }
892 
893 /*
894  * A helper for multishot requests posting additional CQEs.
895  * Should only be used from a task_work including IO_URING_F_MULTISHOT.
896  */
io_req_post_cqe32(struct io_kiocb * req,struct io_uring_cqe cqe[2])897 bool io_req_post_cqe32(struct io_kiocb *req, struct io_uring_cqe cqe[2])
898 {
899 	struct io_ring_ctx *ctx = req->ctx;
900 	bool posted;
901 
902 	lockdep_assert(!io_wq_current_is_worker());
903 	lockdep_assert_held(&ctx->uring_lock);
904 
905 	cqe[0].user_data = req->cqe.user_data;
906 	if (!(ctx->int_flags & IO_RING_F_LOCKLESS_CQ)) {
907 		spin_lock(&ctx->completion_lock);
908 		posted = io_fill_cqe_aux32(ctx, cqe);
909 		spin_unlock(&ctx->completion_lock);
910 	} else {
911 		posted = io_fill_cqe_aux32(ctx, cqe);
912 	}
913 
914 	ctx->submit_state.cq_flush = true;
915 	return posted;
916 }
917 
io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)918 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
919 {
920 	struct io_ring_ctx *ctx = req->ctx;
921 	bool completed = true;
922 
923 	/*
924 	 * All execution paths but io-wq use the deferred completions by
925 	 * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
926 	 */
927 	if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
928 		return;
929 
930 	/*
931 	 * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
932 	 * the submitter task context, IOPOLL protects with uring_lock.
933 	 */
934 	if ((ctx->int_flags & IO_RING_F_LOCKLESS_CQ) || (req->flags & REQ_F_REISSUE)) {
935 defer_complete:
936 		req->io_task_work.func = io_req_task_complete;
937 		io_req_task_work_add(req);
938 		return;
939 	}
940 
941 	io_cq_lock(ctx);
942 	if (!(req->flags & REQ_F_CQE_SKIP))
943 		completed = io_fill_cqe_req(ctx, req);
944 	io_cq_unlock_post(ctx);
945 
946 	if (!completed)
947 		goto defer_complete;
948 
949 	/*
950 	 * We don't free the request here because we know it's called from
951 	 * io-wq only, which holds a reference, so it cannot be the last put.
952 	 */
953 	req_ref_put(req);
954 }
955 
io_req_defer_failed(struct io_kiocb * req,s32 res)956 void io_req_defer_failed(struct io_kiocb *req, s32 res)
957 	__must_hold(&ctx->uring_lock)
958 {
959 	const struct io_cold_def *def = &io_cold_defs[req->opcode];
960 
961 	lockdep_assert_held(&req->ctx->uring_lock);
962 
963 	req_set_fail(req);
964 	io_req_set_res(req, res, io_put_kbuf(req, res, NULL));
965 	if (def->fail)
966 		def->fail(req);
967 	io_req_complete_defer(req);
968 }
969 
970 /*
971  * A request might get retired back into the request caches even before opcode
972  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
973  * Because of that, io_alloc_req() should be called only under ->uring_lock
974  * and with extra caution to not get a request that is still worked on.
975  */
__io_alloc_req_refill(struct io_ring_ctx * ctx)976 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
977 	__must_hold(&ctx->uring_lock)
978 {
979 	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO;
980 	void *reqs[IO_REQ_ALLOC_BATCH];
981 	int ret;
982 
983 	ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
984 
985 	/*
986 	 * Bulk alloc is all-or-nothing. If we fail to get a batch,
987 	 * retry single alloc to be on the safe side.
988 	 */
989 	if (unlikely(ret <= 0)) {
990 		reqs[0] = kmem_cache_alloc(req_cachep, gfp);
991 		if (!reqs[0])
992 			return false;
993 		ret = 1;
994 	}
995 
996 	percpu_ref_get_many(&ctx->refs, ret);
997 	ctx->nr_req_allocated += ret;
998 
999 	while (ret--) {
1000 		struct io_kiocb *req = reqs[ret];
1001 
1002 		io_req_add_to_cache(req, ctx);
1003 	}
1004 	return true;
1005 }
1006 
io_free_req(struct io_kiocb * req)1007 __cold void io_free_req(struct io_kiocb *req)
1008 {
1009 	/* refs were already put, restore them for io_req_task_complete() */
1010 	req->flags &= ~REQ_F_REFCOUNT;
1011 	/* we only want to free it, don't post CQEs */
1012 	req->flags |= REQ_F_CQE_SKIP;
1013 	req->io_task_work.func = io_req_task_complete;
1014 	io_req_task_work_add(req);
1015 }
1016 
__io_req_find_next_prep(struct io_kiocb * req)1017 static void __io_req_find_next_prep(struct io_kiocb *req)
1018 {
1019 	struct io_ring_ctx *ctx = req->ctx;
1020 
1021 	spin_lock(&ctx->completion_lock);
1022 	io_disarm_next(req);
1023 	spin_unlock(&ctx->completion_lock);
1024 }
1025 
io_req_find_next(struct io_kiocb * req)1026 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1027 {
1028 	struct io_kiocb *nxt;
1029 
1030 	/*
1031 	 * If LINK is set, we have dependent requests in this chain. If we
1032 	 * didn't fail this request, queue the first one up, moving any other
1033 	 * dependencies to the next request. In case of failure, fail the rest
1034 	 * of the chain.
1035 	 */
1036 	if (unlikely(req->flags & IO_DISARM_MASK))
1037 		__io_req_find_next_prep(req);
1038 	nxt = req->link;
1039 	req->link = NULL;
1040 	return nxt;
1041 }
1042 
io_req_task_cancel(struct io_tw_req tw_req,io_tw_token_t tw)1043 static void io_req_task_cancel(struct io_tw_req tw_req, io_tw_token_t tw)
1044 {
1045 	struct io_kiocb *req = tw_req.req;
1046 
1047 	io_tw_lock(req->ctx, tw);
1048 	io_req_defer_failed(req, req->cqe.res);
1049 }
1050 
io_req_task_submit(struct io_tw_req tw_req,io_tw_token_t tw)1051 void io_req_task_submit(struct io_tw_req tw_req, io_tw_token_t tw)
1052 {
1053 	struct io_kiocb *req = tw_req.req;
1054 	struct io_ring_ctx *ctx = req->ctx;
1055 
1056 	io_tw_lock(ctx, tw);
1057 	if (unlikely(tw.cancel))
1058 		io_req_defer_failed(req, -EFAULT);
1059 	else if (req->flags & REQ_F_FORCE_ASYNC)
1060 		io_queue_iowq(req);
1061 	else
1062 		io_queue_sqe(req, 0);
1063 }
1064 
io_req_task_queue_fail(struct io_kiocb * req,int ret)1065 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1066 {
1067 	io_req_set_res(req, ret, 0);
1068 	req->io_task_work.func = io_req_task_cancel;
1069 	io_req_task_work_add(req);
1070 }
1071 
io_req_task_queue(struct io_kiocb * req)1072 void io_req_task_queue(struct io_kiocb *req)
1073 {
1074 	req->io_task_work.func = io_req_task_submit;
1075 	io_req_task_work_add(req);
1076 }
1077 
io_queue_next(struct io_kiocb * req)1078 void io_queue_next(struct io_kiocb *req)
1079 {
1080 	struct io_kiocb *nxt = io_req_find_next(req);
1081 
1082 	if (nxt)
1083 		io_req_task_queue(nxt);
1084 }
1085 
io_req_put_rsrc_nodes(struct io_kiocb * req)1086 static inline void io_req_put_rsrc_nodes(struct io_kiocb *req)
1087 {
1088 	struct io_ring_ctx *ctx = req->ctx;
1089 
1090 	if (req->file_node) {
1091 		io_put_rsrc_node(ctx, req->file_node);
1092 		req->file_node = NULL;
1093 	}
1094 	if (req->flags & REQ_F_BUF_NODE)
1095 		io_put_rsrc_node(ctx, req->buf_node);
1096 }
1097 
io_free_batch_list(struct io_ring_ctx * ctx,struct io_wq_work_node * node)1098 static void io_free_batch_list(struct io_ring_ctx *ctx,
1099 			       struct io_wq_work_node *node)
1100 	__must_hold(&ctx->uring_lock)
1101 {
1102 	do {
1103 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1104 						    comp_list);
1105 
1106 		if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1107 			if (req->flags & REQ_F_REISSUE) {
1108 				node = req->comp_list.next;
1109 				req->flags &= ~REQ_F_REISSUE;
1110 				io_queue_iowq(req);
1111 				continue;
1112 			}
1113 			if (req->flags & REQ_F_REFCOUNT) {
1114 				node = req->comp_list.next;
1115 				if (!req_ref_put_and_test(req))
1116 					continue;
1117 			}
1118 			if ((req->flags & REQ_F_POLLED) && req->apoll) {
1119 				struct async_poll *apoll = req->apoll;
1120 
1121 				if (apoll->double_poll)
1122 					kfree(apoll->double_poll);
1123 				io_cache_free(&ctx->apoll_cache, apoll);
1124 				req->flags &= ~REQ_F_POLLED;
1125 			}
1126 			if (req->flags & IO_REQ_LINK_FLAGS)
1127 				io_queue_next(req);
1128 			if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1129 				io_clean_op(req);
1130 		}
1131 		io_put_file(req);
1132 		io_req_put_rsrc_nodes(req);
1133 		io_put_task(req);
1134 
1135 		node = req->comp_list.next;
1136 		io_req_add_to_cache(req, ctx);
1137 	} while (node);
1138 }
1139 
__io_submit_flush_completions(struct io_ring_ctx * ctx)1140 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1141 	__must_hold(&ctx->uring_lock)
1142 {
1143 	struct io_submit_state *state = &ctx->submit_state;
1144 	struct io_wq_work_node *node;
1145 
1146 	__io_cq_lock(ctx);
1147 	__wq_list_for_each(node, &state->compl_reqs) {
1148 		struct io_kiocb *req = container_of(node, struct io_kiocb,
1149 					    comp_list);
1150 
1151 		/*
1152 		 * Requests marked with REQUEUE should not post a CQE, they
1153 		 * will go through the io-wq retry machinery and post one
1154 		 * later.
1155 		 */
1156 		if (!(req->flags & (REQ_F_CQE_SKIP | REQ_F_REISSUE)) &&
1157 		    unlikely(!io_fill_cqe_req(ctx, req))) {
1158 			if (ctx->int_flags & IO_RING_F_LOCKLESS_CQ)
1159 				io_cqe_overflow(ctx, &req->cqe, &req->big_cqe);
1160 			else
1161 				io_cqe_overflow_locked(ctx, &req->cqe, &req->big_cqe);
1162 		}
1163 	}
1164 	__io_cq_unlock_post(ctx);
1165 
1166 	if (!wq_list_empty(&state->compl_reqs)) {
1167 		io_free_batch_list(ctx, state->compl_reqs.first);
1168 		INIT_WQ_LIST(&state->compl_reqs);
1169 	}
1170 
1171 	if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_ACTIVE))
1172 		io_queue_deferred(ctx);
1173 
1174 	ctx->submit_state.cq_flush = false;
1175 }
1176 
1177 /*
1178  * We can't just wait for polled events to come to us, we have to actively
1179  * find and complete them.
1180  */
io_iopoll_try_reap_events(struct io_ring_ctx * ctx)1181 __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1182 {
1183 	if (!(ctx->flags & IORING_SETUP_IOPOLL))
1184 		return;
1185 
1186 	mutex_lock(&ctx->uring_lock);
1187 	while (!list_empty(&ctx->iopoll_list)) {
1188 		/* let it sleep and repeat later if can't complete a request */
1189 		if (io_do_iopoll(ctx, true) == 0)
1190 			break;
1191 		/*
1192 		 * Ensure we allow local-to-the-cpu processing to take place,
1193 		 * in this case we need to ensure that we reap all events.
1194 		 * Also let task_work, etc. to progress by releasing the mutex
1195 		 */
1196 		if (need_resched()) {
1197 			mutex_unlock(&ctx->uring_lock);
1198 			cond_resched();
1199 			mutex_lock(&ctx->uring_lock);
1200 		}
1201 	}
1202 	mutex_unlock(&ctx->uring_lock);
1203 
1204 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
1205 		io_move_task_work_from_local(ctx);
1206 }
1207 
io_iopoll_check(struct io_ring_ctx * ctx,unsigned int min_events)1208 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned int min_events)
1209 {
1210 	unsigned long check_cq;
1211 
1212 	min_events = min(min_events, ctx->cq_entries);
1213 
1214 	lockdep_assert_held(&ctx->uring_lock);
1215 
1216 	if (!io_allowed_run_tw(ctx))
1217 		return -EEXIST;
1218 
1219 	check_cq = READ_ONCE(ctx->check_cq);
1220 	if (unlikely(check_cq)) {
1221 		if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1222 			__io_cqring_overflow_flush(ctx, false);
1223 		/*
1224 		 * Similarly do not spin if we have not informed the user of any
1225 		 * dropped CQE.
1226 		 */
1227 		if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1228 			return -EBADR;
1229 	}
1230 	/*
1231 	 * Don't enter poll loop if we already have events pending.
1232 	 * If we do, we can potentially be spinning for commands that
1233 	 * already triggered a CQE (eg in error).
1234 	 */
1235 	if (io_cqring_events(ctx))
1236 		return 0;
1237 
1238 	do {
1239 		int ret = 0;
1240 
1241 		/*
1242 		 * If a submit got punted to a workqueue, we can have the
1243 		 * application entering polling for a command before it gets
1244 		 * issued. That app will hold the uring_lock for the duration
1245 		 * of the poll right here, so we need to take a breather every
1246 		 * now and then to ensure that the issue has a chance to add
1247 		 * the poll to the issued list. Otherwise we can spin here
1248 		 * forever, while the workqueue is stuck trying to acquire the
1249 		 * very same mutex.
1250 		 */
1251 		if (list_empty(&ctx->iopoll_list) || io_task_work_pending(ctx)) {
1252 			(void) io_run_local_work_locked(ctx, min_events);
1253 
1254 			if (task_work_pending(current) || list_empty(&ctx->iopoll_list)) {
1255 				mutex_unlock(&ctx->uring_lock);
1256 				io_run_task_work();
1257 				mutex_lock(&ctx->uring_lock);
1258 			}
1259 			/* some requests don't go through iopoll_list */
1260 			if (list_empty(&ctx->iopoll_list))
1261 				break;
1262 		}
1263 		ret = io_do_iopoll(ctx, !min_events);
1264 		if (unlikely(ret < 0))
1265 			return ret;
1266 
1267 		if (task_sigpending(current))
1268 			return -EINTR;
1269 		if (need_resched())
1270 			break;
1271 	} while (io_cqring_events(ctx) < min_events);
1272 
1273 	return 0;
1274 }
1275 
io_req_task_complete(struct io_tw_req tw_req,io_tw_token_t tw)1276 void io_req_task_complete(struct io_tw_req tw_req, io_tw_token_t tw)
1277 {
1278 	io_req_complete_defer(tw_req.req);
1279 }
1280 
1281 /*
1282  * After the iocb has been issued, it's safe to be found on the poll list.
1283  * Adding the kiocb to the list AFTER submission ensures that we don't
1284  * find it from a io_do_iopoll() thread before the issuer is done
1285  * accessing the kiocb cookie.
1286  */
io_iopoll_req_issued(struct io_kiocb * req,unsigned int issue_flags)1287 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1288 {
1289 	struct io_ring_ctx *ctx = req->ctx;
1290 	const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1291 
1292 	/* workqueue context doesn't hold uring_lock, grab it now */
1293 	if (unlikely(needs_lock))
1294 		mutex_lock(&ctx->uring_lock);
1295 
1296 	/*
1297 	 * Track whether we have multiple files in our lists. This will impact
1298 	 * how we do polling eventually, not spinning if we're on potentially
1299 	 * different devices.
1300 	 */
1301 	if (list_empty(&ctx->iopoll_list)) {
1302 		ctx->poll_multi_queue = false;
1303 	} else if (!ctx->poll_multi_queue) {
1304 		struct io_kiocb *list_req;
1305 
1306 		list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb, iopoll_node);
1307 		if (list_req->file != req->file)
1308 			ctx->poll_multi_queue = true;
1309 	}
1310 
1311 	list_add_tail(&req->iopoll_node, &ctx->iopoll_list);
1312 
1313 	if (unlikely(needs_lock)) {
1314 		/*
1315 		 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1316 		 * in sq thread task context or in io worker task context. If
1317 		 * current task context is sq thread, we don't need to check
1318 		 * whether should wake up sq thread.
1319 		 */
1320 		if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1321 		    wq_has_sleeper(&ctx->sq_data->wait))
1322 			wake_up(&ctx->sq_data->wait);
1323 
1324 		mutex_unlock(&ctx->uring_lock);
1325 	}
1326 }
1327 
io_file_get_flags(struct file * file)1328 io_req_flags_t io_file_get_flags(struct file *file)
1329 {
1330 	io_req_flags_t res = 0;
1331 
1332 	BUILD_BUG_ON(REQ_F_ISREG_BIT != REQ_F_SUPPORT_NOWAIT_BIT + 1);
1333 
1334 	if (S_ISREG(file_inode(file)->i_mode))
1335 		res |= REQ_F_ISREG;
1336 	if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1337 		res |= REQ_F_SUPPORT_NOWAIT;
1338 	return res;
1339 }
1340 
io_drain_req(struct io_kiocb * req)1341 static __cold void io_drain_req(struct io_kiocb *req)
1342 	__must_hold(&ctx->uring_lock)
1343 {
1344 	struct io_ring_ctx *ctx = req->ctx;
1345 	bool drain = req->flags & IOSQE_IO_DRAIN;
1346 	struct io_defer_entry *de;
1347 
1348 	de = kmalloc_obj(*de, GFP_KERNEL_ACCOUNT);
1349 	if (!de) {
1350 		io_req_defer_failed(req, -ENOMEM);
1351 		return;
1352 	}
1353 
1354 	io_prep_async_link(req);
1355 	trace_io_uring_defer(req);
1356 	de->req = req;
1357 
1358 	ctx->nr_drained += io_linked_nr(req);
1359 	list_add_tail(&de->list, &ctx->defer_list);
1360 	io_queue_deferred(ctx);
1361 	if (!drain && list_empty(&ctx->defer_list))
1362 		ctx->int_flags &= ~IO_RING_F_DRAIN_ACTIVE;
1363 }
1364 
io_assign_file(struct io_kiocb * req,const struct io_issue_def * def,unsigned int issue_flags)1365 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1366 			   unsigned int issue_flags)
1367 {
1368 	if (req->file || !def->needs_file)
1369 		return true;
1370 
1371 	if (req->flags & REQ_F_FIXED_FILE)
1372 		req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1373 	else
1374 		req->file = io_file_get_normal(req, req->cqe.fd);
1375 
1376 	return !!req->file;
1377 }
1378 
1379 #define REQ_ISSUE_SLOW_FLAGS	(REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)
1380 
__io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags,const struct io_issue_def * def)1381 static inline int __io_issue_sqe(struct io_kiocb *req,
1382 				 unsigned int issue_flags,
1383 				 const struct io_issue_def *def)
1384 {
1385 	const struct cred *creds = NULL;
1386 	struct io_kiocb *link = NULL;
1387 	int ret;
1388 
1389 	if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) {
1390 		if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
1391 			creds = override_creds(req->creds);
1392 		if (req->flags & REQ_F_ARM_LTIMEOUT)
1393 			link = __io_prep_linked_timeout(req);
1394 	}
1395 
1396 	if (!def->audit_skip)
1397 		audit_uring_entry(req->opcode);
1398 
1399 	ret = def->issue(req, issue_flags);
1400 
1401 	if (!def->audit_skip)
1402 		audit_uring_exit(!ret, ret);
1403 
1404 	if (unlikely(creds || link)) {
1405 		if (creds)
1406 			revert_creds(creds);
1407 		if (link)
1408 			io_queue_linked_timeout(link);
1409 	}
1410 
1411 	return ret;
1412 }
1413 
io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags)1414 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1415 {
1416 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1417 	int ret;
1418 
1419 	if (unlikely(!io_assign_file(req, def, issue_flags)))
1420 		return -EBADF;
1421 
1422 	ret = __io_issue_sqe(req, issue_flags, def);
1423 
1424 	if (ret == IOU_COMPLETE) {
1425 		if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1426 			io_req_complete_defer(req);
1427 		else
1428 			io_req_complete_post(req, issue_flags);
1429 
1430 		return 0;
1431 	}
1432 
1433 	if (ret == IOU_ISSUE_SKIP_COMPLETE) {
1434 		ret = 0;
1435 
1436 		if (req->flags & REQ_F_IOPOLL)
1437 			io_iopoll_req_issued(req, issue_flags);
1438 	}
1439 	return ret;
1440 }
1441 
io_poll_issue(struct io_kiocb * req,io_tw_token_t tw)1442 int io_poll_issue(struct io_kiocb *req, io_tw_token_t tw)
1443 {
1444 	const unsigned int issue_flags = IO_URING_F_NONBLOCK |
1445 					 IO_URING_F_MULTISHOT |
1446 					 IO_URING_F_COMPLETE_DEFER;
1447 	int ret;
1448 
1449 	io_tw_lock(req->ctx, tw);
1450 
1451 	WARN_ON_ONCE(!req->file);
1452 	if (WARN_ON_ONCE(req->flags & REQ_F_IOPOLL))
1453 		return -EFAULT;
1454 
1455 	ret = __io_issue_sqe(req, issue_flags, &io_issue_defs[req->opcode]);
1456 
1457 	WARN_ON_ONCE(ret == IOU_ISSUE_SKIP_COMPLETE);
1458 	return ret;
1459 }
1460 
io_wq_free_work(struct io_wq_work * work)1461 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1462 {
1463 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1464 	struct io_kiocb *nxt = NULL;
1465 
1466 	if (req_ref_put_and_test_atomic(req)) {
1467 		if (req->flags & IO_REQ_LINK_FLAGS) {
1468 			struct io_ring_ctx *ctx = req->ctx;
1469 
1470 			mutex_lock(&ctx->uring_lock);
1471 			nxt = io_req_find_next(req);
1472 			mutex_unlock(&ctx->uring_lock);
1473 		}
1474 		io_free_req(req);
1475 	}
1476 	return nxt ? &nxt->work : NULL;
1477 }
1478 
io_wq_submit_work(struct io_wq_work * work)1479 void io_wq_submit_work(struct io_wq_work *work)
1480 {
1481 	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1482 	const struct io_issue_def *def = &io_issue_defs[req->opcode];
1483 	unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1484 	bool needs_poll = false;
1485 	int ret = 0, err = -ECANCELED;
1486 
1487 	/* one will be dropped by io_wq_free_work() after returning to io-wq */
1488 	if (!(req->flags & REQ_F_REFCOUNT))
1489 		__io_req_set_refcount(req, 2);
1490 	else
1491 		req_ref_get(req);
1492 
1493 	/* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1494 	if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
1495 fail:
1496 		io_req_task_queue_fail(req, err);
1497 		return;
1498 	}
1499 	if (!io_assign_file(req, def, issue_flags)) {
1500 		err = -EBADF;
1501 		atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1502 		goto fail;
1503 	}
1504 
1505 	/*
1506 	 * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
1507 	 * submitter task context. Final request completions are handed to the
1508 	 * right context, however this is not the case of auxiliary CQEs,
1509 	 * which is the main mean of operation for multishot requests.
1510 	 * Don't allow any multishot execution from io-wq. It's more restrictive
1511 	 * than necessary and also cleaner.
1512 	 */
1513 	if (req->flags & (REQ_F_MULTISHOT|REQ_F_APOLL_MULTISHOT)) {
1514 		err = -EBADFD;
1515 		if (!io_file_can_poll(req))
1516 			goto fail;
1517 		if (req->file->f_flags & O_NONBLOCK ||
1518 		    req->file->f_mode & FMODE_NOWAIT) {
1519 			err = -ECANCELED;
1520 			if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
1521 				goto fail;
1522 			return;
1523 		} else {
1524 			req->flags &= ~(REQ_F_APOLL_MULTISHOT|REQ_F_MULTISHOT);
1525 		}
1526 	}
1527 
1528 	if (req->flags & REQ_F_FORCE_ASYNC) {
1529 		bool opcode_poll = def->pollin || def->pollout;
1530 
1531 		if (opcode_poll && io_file_can_poll(req)) {
1532 			needs_poll = true;
1533 			issue_flags |= IO_URING_F_NONBLOCK;
1534 		}
1535 	}
1536 
1537 	do {
1538 		ret = io_issue_sqe(req, issue_flags);
1539 		if (ret != -EAGAIN)
1540 			break;
1541 
1542 		/*
1543 		 * If REQ_F_NOWAIT is set, then don't wait or retry with
1544 		 * poll. -EAGAIN is final for that case.
1545 		 */
1546 		if (req->flags & REQ_F_NOWAIT)
1547 			break;
1548 
1549 		/*
1550 		 * We can get EAGAIN for iopolled IO even though we're
1551 		 * forcing a sync submission from here, since we can't
1552 		 * wait for request slots on the block side.
1553 		 */
1554 		if (!needs_poll) {
1555 			if (!(req->flags & REQ_F_IOPOLL))
1556 				break;
1557 			if (io_wq_worker_stopped())
1558 				break;
1559 			cond_resched();
1560 			continue;
1561 		}
1562 
1563 		if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1564 			return;
1565 		/* aborted or ready, in either case retry blocking */
1566 		needs_poll = false;
1567 		issue_flags &= ~IO_URING_F_NONBLOCK;
1568 	} while (1);
1569 
1570 	/* avoid locking problems by failing it from a clean context */
1571 	if (ret)
1572 		io_req_task_queue_fail(req, ret);
1573 }
1574 
io_file_get_fixed(struct io_kiocb * req,int fd,unsigned int issue_flags)1575 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1576 				      unsigned int issue_flags)
1577 {
1578 	struct io_ring_ctx *ctx = req->ctx;
1579 	struct io_rsrc_node *node;
1580 	struct file *file = NULL;
1581 
1582 	io_ring_submit_lock(ctx, issue_flags);
1583 	node = io_rsrc_node_lookup(&ctx->file_table.data, fd);
1584 	if (node) {
1585 		node->refs++;
1586 		req->file_node = node;
1587 		req->flags |= io_slot_flags(node);
1588 		file = io_slot_file(node);
1589 	}
1590 	io_ring_submit_unlock(ctx, issue_flags);
1591 	return file;
1592 }
1593 
io_file_get_normal(struct io_kiocb * req,int fd)1594 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
1595 {
1596 	struct file *file = fget(fd);
1597 
1598 	trace_io_uring_file_get(req, fd);
1599 
1600 	/* we don't allow fixed io_uring files */
1601 	if (file && io_is_uring_fops(file))
1602 		io_req_track_inflight(req);
1603 	return file;
1604 }
1605 
io_req_sqe_copy(struct io_kiocb * req,unsigned int issue_flags)1606 static int io_req_sqe_copy(struct io_kiocb *req, unsigned int issue_flags)
1607 {
1608 	const struct io_cold_def *def = &io_cold_defs[req->opcode];
1609 
1610 	if (req->flags & REQ_F_SQE_COPIED)
1611 		return 0;
1612 	req->flags |= REQ_F_SQE_COPIED;
1613 	if (!def->sqe_copy)
1614 		return 0;
1615 	if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_INLINE)))
1616 		return -EFAULT;
1617 	def->sqe_copy(req);
1618 	return 0;
1619 }
1620 
io_queue_async(struct io_kiocb * req,unsigned int issue_flags,int ret)1621 static void io_queue_async(struct io_kiocb *req, unsigned int issue_flags, int ret)
1622 	__must_hold(&req->ctx->uring_lock)
1623 {
1624 	if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
1625 fail:
1626 		io_req_defer_failed(req, ret);
1627 		return;
1628 	}
1629 
1630 	ret = io_req_sqe_copy(req, issue_flags);
1631 	if (unlikely(ret))
1632 		goto fail;
1633 
1634 	switch (io_arm_poll_handler(req, 0)) {
1635 	case IO_APOLL_READY:
1636 		io_req_task_queue(req);
1637 		break;
1638 	case IO_APOLL_ABORTED:
1639 		io_queue_iowq(req);
1640 		break;
1641 	case IO_APOLL_OK:
1642 		break;
1643 	}
1644 }
1645 
io_queue_sqe(struct io_kiocb * req,unsigned int extra_flags)1646 static inline void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags)
1647 	__must_hold(&req->ctx->uring_lock)
1648 {
1649 	unsigned int issue_flags = IO_URING_F_NONBLOCK |
1650 				   IO_URING_F_COMPLETE_DEFER | extra_flags;
1651 	int ret;
1652 
1653 	ret = io_issue_sqe(req, issue_flags);
1654 
1655 	/*
1656 	 * We async punt it if the file wasn't marked NOWAIT, or if the file
1657 	 * doesn't support non-blocking read/write attempts
1658 	 */
1659 	if (unlikely(ret))
1660 		io_queue_async(req, issue_flags, ret);
1661 }
1662 
io_queue_sqe_fallback(struct io_kiocb * req)1663 static void io_queue_sqe_fallback(struct io_kiocb *req)
1664 	__must_hold(&req->ctx->uring_lock)
1665 {
1666 	if (unlikely(req->flags & REQ_F_FAIL)) {
1667 		/*
1668 		 * We don't submit, fail them all, for that replace hardlinks
1669 		 * with normal links. Extra REQ_F_LINK is tolerated.
1670 		 */
1671 		req->flags &= ~REQ_F_HARDLINK;
1672 		req->flags |= REQ_F_LINK;
1673 		io_req_defer_failed(req, req->cqe.res);
1674 	} else {
1675 		/* can't fail with IO_URING_F_INLINE */
1676 		io_req_sqe_copy(req, IO_URING_F_INLINE);
1677 		if (unlikely(req->ctx->int_flags & IO_RING_F_DRAIN_ACTIVE))
1678 			io_drain_req(req);
1679 		else
1680 			io_queue_iowq(req);
1681 	}
1682 }
1683 
1684 /*
1685  * Check SQE restrictions (opcode and flags).
1686  *
1687  * Returns 'true' if SQE is allowed, 'false' otherwise.
1688  */
io_check_restriction(struct io_ring_ctx * ctx,struct io_kiocb * req,unsigned int sqe_flags)1689 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
1690 					struct io_kiocb *req,
1691 					unsigned int sqe_flags)
1692 {
1693 	if (!(ctx->int_flags & IO_RING_F_OP_RESTRICTED))
1694 		return true;
1695 	if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
1696 		return false;
1697 
1698 	if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
1699 	    ctx->restrictions.sqe_flags_required)
1700 		return false;
1701 
1702 	if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
1703 			  ctx->restrictions.sqe_flags_required))
1704 		return false;
1705 
1706 	return true;
1707 }
1708 
io_init_drain(struct io_ring_ctx * ctx)1709 static void io_init_drain(struct io_ring_ctx *ctx)
1710 {
1711 	struct io_kiocb *head = ctx->submit_state.link.head;
1712 
1713 	ctx->int_flags |= IO_RING_F_DRAIN_ACTIVE;
1714 	if (head) {
1715 		/*
1716 		 * If we need to drain a request in the middle of a link, drain
1717 		 * the head request and the next request/link after the current
1718 		 * link. Considering sequential execution of links,
1719 		 * REQ_F_IO_DRAIN will be maintained for every request of our
1720 		 * link.
1721 		 */
1722 		head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1723 		ctx->int_flags |= IO_RING_F_DRAIN_NEXT;
1724 	}
1725 }
1726 
io_init_fail_req(struct io_kiocb * req,int err)1727 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
1728 {
1729 	/* ensure per-opcode data is cleared if we fail before prep */
1730 	memset(&req->cmd.data, 0, sizeof(req->cmd.data));
1731 	return err;
1732 }
1733 
io_init_req(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe,unsigned int * left)1734 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
1735 		       const struct io_uring_sqe *sqe, unsigned int *left)
1736 	__must_hold(&ctx->uring_lock)
1737 {
1738 	const struct io_issue_def *def;
1739 	unsigned int sqe_flags;
1740 	int personality;
1741 
1742 	req->ctx = ctx;
1743 	req->opcode = READ_ONCE(sqe->opcode);
1744 	/* same numerical values with corresponding REQ_F_*, safe to copy */
1745 	sqe_flags = READ_ONCE(sqe->flags);
1746 	req->flags = (__force io_req_flags_t) sqe_flags;
1747 	req->cqe.user_data = READ_ONCE(sqe->user_data);
1748 	req->file = NULL;
1749 	req->tctx = current->io_uring;
1750 	req->cancel_seq_set = false;
1751 	req->async_data = NULL;
1752 
1753 	if (unlikely(req->opcode >= IORING_OP_LAST)) {
1754 		req->opcode = 0;
1755 		return io_init_fail_req(req, -EINVAL);
1756 	}
1757 	req->opcode = array_index_nospec(req->opcode, IORING_OP_LAST);
1758 
1759 	def = &io_issue_defs[req->opcode];
1760 	if (def->is_128 && !(ctx->flags & IORING_SETUP_SQE128)) {
1761 		/*
1762 		 * A 128b op on a non-128b SQ requires mixed SQE support as
1763 		 * well as 2 contiguous entries.
1764 		 */
1765 		if (!(ctx->flags & IORING_SETUP_SQE_MIXED) || *left < 2 ||
1766 		    (unsigned)(sqe - ctx->sq_sqes) >= ctx->sq_entries - 1)
1767 			return io_init_fail_req(req, -EINVAL);
1768 		/*
1769 		 * A 128b operation on a mixed SQ uses two entries, so we have
1770 		 * to increment the head and cached refs, and decrement what's
1771 		 * left.
1772 		 */
1773 		current->io_uring->cached_refs++;
1774 		ctx->cached_sq_head++;
1775 		(*left)--;
1776 	}
1777 
1778 	if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
1779 		/* enforce forwards compatibility on users */
1780 		if (sqe_flags & ~SQE_VALID_FLAGS)
1781 			return io_init_fail_req(req, -EINVAL);
1782 		if (sqe_flags & IOSQE_BUFFER_SELECT) {
1783 			if (!def->buffer_select)
1784 				return io_init_fail_req(req, -EOPNOTSUPP);
1785 			req->buf_index = READ_ONCE(sqe->buf_group);
1786 		}
1787 		if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
1788 			ctx->int_flags |= IO_RING_F_DRAIN_DISABLED;
1789 		if (sqe_flags & IOSQE_IO_DRAIN) {
1790 			if (ctx->int_flags & IO_RING_F_DRAIN_DISABLED)
1791 				return io_init_fail_req(req, -EOPNOTSUPP);
1792 			io_init_drain(ctx);
1793 		}
1794 	}
1795 	if (unlikely(ctx->int_flags & (IO_RING_F_OP_RESTRICTED | IO_RING_F_DRAIN_ACTIVE | IO_RING_F_DRAIN_NEXT))) {
1796 		if (!io_check_restriction(ctx, req, sqe_flags))
1797 			return io_init_fail_req(req, -EACCES);
1798 		/* knock it to the slow queue path, will be drained there */
1799 		if (ctx->int_flags & IO_RING_F_DRAIN_ACTIVE)
1800 			req->flags |= REQ_F_FORCE_ASYNC;
1801 		/* if there is no link, we're at "next" request and need to drain */
1802 		if (unlikely(ctx->int_flags & IO_RING_F_DRAIN_NEXT) && !ctx->submit_state.link.head) {
1803 			ctx->int_flags &= ~IO_RING_F_DRAIN_NEXT;
1804 			ctx->int_flags |= IO_RING_F_DRAIN_ACTIVE;
1805 			req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
1806 		}
1807 	}
1808 
1809 	if (!def->ioprio && sqe->ioprio)
1810 		return io_init_fail_req(req, -EINVAL);
1811 	if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
1812 		return io_init_fail_req(req, -EINVAL);
1813 
1814 	if (def->needs_file) {
1815 		struct io_submit_state *state = &ctx->submit_state;
1816 
1817 		req->cqe.fd = READ_ONCE(sqe->fd);
1818 
1819 		/*
1820 		 * Plug now if we have more than 2 IO left after this, and the
1821 		 * target is potentially a read/write to block based storage.
1822 		 */
1823 		if (state->need_plug && def->plug) {
1824 			state->plug_started = true;
1825 			state->need_plug = false;
1826 			blk_start_plug_nr_ios(&state->plug, state->submit_nr);
1827 		}
1828 	}
1829 
1830 	personality = READ_ONCE(sqe->personality);
1831 	if (personality) {
1832 		int ret;
1833 
1834 		req->creds = xa_load(&ctx->personalities, personality);
1835 		if (!req->creds)
1836 			return io_init_fail_req(req, -EINVAL);
1837 		get_cred(req->creds);
1838 		ret = security_uring_override_creds(req->creds);
1839 		if (ret) {
1840 			put_cred(req->creds);
1841 			return io_init_fail_req(req, ret);
1842 		}
1843 		req->flags |= REQ_F_CREDS;
1844 	}
1845 
1846 	return def->prep(req, sqe);
1847 }
1848 
io_submit_fail_init(const struct io_uring_sqe * sqe,struct io_kiocb * req,int ret)1849 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
1850 				      struct io_kiocb *req, int ret)
1851 {
1852 	struct io_ring_ctx *ctx = req->ctx;
1853 	struct io_submit_link *link = &ctx->submit_state.link;
1854 	struct io_kiocb *head = link->head;
1855 
1856 	trace_io_uring_req_failed(sqe, req, ret);
1857 
1858 	/*
1859 	 * Avoid breaking links in the middle as it renders links with SQPOLL
1860 	 * unusable. Instead of failing eagerly, continue assembling the link if
1861 	 * applicable and mark the head with REQ_F_FAIL. The link flushing code
1862 	 * should find the flag and handle the rest.
1863 	 */
1864 	req_fail_link_node(req, ret);
1865 	if (head && !(head->flags & REQ_F_FAIL))
1866 		req_fail_link_node(head, -ECANCELED);
1867 
1868 	if (!(req->flags & IO_REQ_LINK_FLAGS)) {
1869 		if (head) {
1870 			link->last->link = req;
1871 			link->head = NULL;
1872 			req = head;
1873 		}
1874 		io_queue_sqe_fallback(req);
1875 		return ret;
1876 	}
1877 
1878 	if (head)
1879 		link->last->link = req;
1880 	else
1881 		link->head = req;
1882 	link->last = req;
1883 	return 0;
1884 }
1885 
io_submit_sqe(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe,unsigned int * left)1886 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
1887 			 const struct io_uring_sqe *sqe, unsigned int *left)
1888 	__must_hold(&ctx->uring_lock)
1889 {
1890 	struct io_submit_link *link = &ctx->submit_state.link;
1891 	int ret;
1892 
1893 	ret = io_init_req(ctx, req, sqe, left);
1894 	if (unlikely(ret))
1895 		return io_submit_fail_init(sqe, req, ret);
1896 
1897 	if (unlikely(ctx->bpf_filters)) {
1898 		ret = io_uring_run_bpf_filters(ctx->bpf_filters, req);
1899 		if (ret)
1900 			return io_submit_fail_init(sqe, req, ret);
1901 	}
1902 
1903 	trace_io_uring_submit_req(req);
1904 
1905 	/*
1906 	 * If we already have a head request, queue this one for async
1907 	 * submittal once the head completes. If we don't have a head but
1908 	 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
1909 	 * submitted sync once the chain is complete. If none of those
1910 	 * conditions are true (normal request), then just queue it.
1911 	 */
1912 	if (unlikely(link->head)) {
1913 		trace_io_uring_link(req, link->last);
1914 		io_req_sqe_copy(req, IO_URING_F_INLINE);
1915 		link->last->link = req;
1916 		link->last = req;
1917 
1918 		if (req->flags & IO_REQ_LINK_FLAGS)
1919 			return 0;
1920 		/* last request of the link, flush it */
1921 		req = link->head;
1922 		link->head = NULL;
1923 		if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
1924 			goto fallback;
1925 
1926 	} else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
1927 					  REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
1928 		if (req->flags & IO_REQ_LINK_FLAGS) {
1929 			link->head = req;
1930 			link->last = req;
1931 		} else {
1932 fallback:
1933 			io_queue_sqe_fallback(req);
1934 		}
1935 		return 0;
1936 	}
1937 
1938 	io_queue_sqe(req, IO_URING_F_INLINE);
1939 	return 0;
1940 }
1941 
1942 /*
1943  * Batched submission is done, ensure local IO is flushed out.
1944  */
io_submit_state_end(struct io_ring_ctx * ctx)1945 static void io_submit_state_end(struct io_ring_ctx *ctx)
1946 {
1947 	struct io_submit_state *state = &ctx->submit_state;
1948 
1949 	if (unlikely(state->link.head))
1950 		io_queue_sqe_fallback(state->link.head);
1951 	/* flush only after queuing links as they can generate completions */
1952 	io_submit_flush_completions(ctx);
1953 	if (state->plug_started)
1954 		blk_finish_plug(&state->plug);
1955 }
1956 
1957 /*
1958  * Start submission side cache.
1959  */
io_submit_state_start(struct io_submit_state * state,unsigned int max_ios)1960 static void io_submit_state_start(struct io_submit_state *state,
1961 				  unsigned int max_ios)
1962 {
1963 	state->plug_started = false;
1964 	state->need_plug = max_ios > 2;
1965 	state->submit_nr = max_ios;
1966 	/* set only head, no need to init link_last in advance */
1967 	state->link.head = NULL;
1968 }
1969 
io_commit_sqring(struct io_ring_ctx * ctx)1970 static void io_commit_sqring(struct io_ring_ctx *ctx)
1971 {
1972 	struct io_rings *rings = ctx->rings;
1973 
1974 	if (ctx->flags & IORING_SETUP_SQ_REWIND) {
1975 		ctx->cached_sq_head = 0;
1976 	} else {
1977 		/*
1978 		 * Ensure any loads from the SQEs are done at this point,
1979 		 * since once we write the new head, the application could
1980 		 * write new data to them.
1981 		 */
1982 		smp_store_release(&rings->sq.head, ctx->cached_sq_head);
1983 	}
1984 }
1985 
1986 /*
1987  * Fetch an sqe, if one is available. Note this returns a pointer to memory
1988  * that is mapped by userspace. This means that care needs to be taken to
1989  * ensure that reads are stable, as we cannot rely on userspace always
1990  * being a good citizen. If members of the sqe are validated and then later
1991  * used, it's important that those reads are done through READ_ONCE() to
1992  * prevent a re-load down the line.
1993  */
io_get_sqe(struct io_ring_ctx * ctx,const struct io_uring_sqe ** sqe)1994 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
1995 {
1996 	unsigned mask = ctx->sq_entries - 1;
1997 	unsigned head = ctx->cached_sq_head++ & mask;
1998 
1999 	if (static_branch_unlikely(&io_key_has_sqarray.key) &&
2000 	    (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) {
2001 		head = READ_ONCE(ctx->sq_array[head]);
2002 		if (unlikely(head >= ctx->sq_entries)) {
2003 			WRITE_ONCE(ctx->rings->sq_dropped,
2004 				   READ_ONCE(ctx->rings->sq_dropped) + 1);
2005 			return false;
2006 		}
2007 		head = array_index_nospec(head, ctx->sq_entries);
2008 	}
2009 
2010 	/*
2011 	 * The cached sq head (or cq tail) serves two purposes:
2012 	 *
2013 	 * 1) allows us to batch the cost of updating the user visible
2014 	 *    head updates.
2015 	 * 2) allows the kernel side to track the head on its own, even
2016 	 *    though the application is the one updating it.
2017 	 */
2018 
2019 	/* double index for 128-byte SQEs, twice as long */
2020 	if (ctx->flags & IORING_SETUP_SQE128)
2021 		head <<= 1;
2022 	*sqe = &ctx->sq_sqes[head];
2023 	return true;
2024 }
2025 
io_submit_sqes(struct io_ring_ctx * ctx,unsigned int nr)2026 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2027 	__must_hold(&ctx->uring_lock)
2028 {
2029 	unsigned int entries;
2030 	unsigned int left;
2031 	int ret;
2032 
2033 	if (ctx->flags & IORING_SETUP_SQ_REWIND)
2034 		entries = ctx->sq_entries;
2035 	else
2036 		entries = __io_sqring_entries(ctx);
2037 
2038 	entries = min(nr, entries);
2039 	if (unlikely(!entries))
2040 		return 0;
2041 
2042 	ret = left = entries;
2043 	io_get_task_refs(left);
2044 	io_submit_state_start(&ctx->submit_state, left);
2045 
2046 	do {
2047 		const struct io_uring_sqe *sqe;
2048 		struct io_kiocb *req;
2049 
2050 		if (unlikely(!io_alloc_req(ctx, &req)))
2051 			break;
2052 		if (unlikely(!io_get_sqe(ctx, &sqe))) {
2053 			io_req_add_to_cache(req, ctx);
2054 			break;
2055 		}
2056 
2057 		/*
2058 		 * Continue submitting even for sqe failure if the
2059 		 * ring was setup with IORING_SETUP_SUBMIT_ALL
2060 		 */
2061 		if (unlikely(io_submit_sqe(ctx, req, sqe, &left)) &&
2062 		    !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2063 			left--;
2064 			break;
2065 		}
2066 	} while (--left);
2067 
2068 	if (unlikely(left)) {
2069 		ret -= left;
2070 		/* try again if it submitted nothing and can't allocate a req */
2071 		if (!ret && io_req_cache_empty(ctx))
2072 			ret = -EAGAIN;
2073 		current->io_uring->cached_refs += left;
2074 	}
2075 
2076 	io_submit_state_end(ctx);
2077 	 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2078 	io_commit_sqring(ctx);
2079 	return ret;
2080 }
2081 
io_rings_free(struct io_ring_ctx * ctx)2082 static void io_rings_free(struct io_ring_ctx *ctx)
2083 {
2084 	io_free_region(ctx->user, &ctx->sq_region);
2085 	io_free_region(ctx->user, &ctx->ring_region);
2086 	ctx->rings = NULL;
2087 	RCU_INIT_POINTER(ctx->rings_rcu, NULL);
2088 	ctx->sq_sqes = NULL;
2089 }
2090 
rings_size(unsigned int flags,unsigned int sq_entries,unsigned int cq_entries,struct io_rings_layout * rl)2091 static int rings_size(unsigned int flags, unsigned int sq_entries,
2092 		      unsigned int cq_entries, struct io_rings_layout *rl)
2093 {
2094 	struct io_rings *rings;
2095 	size_t sqe_size;
2096 	size_t off;
2097 
2098 	if (flags & IORING_SETUP_CQE_MIXED) {
2099 		if (cq_entries < 2)
2100 			return -EOVERFLOW;
2101 	}
2102 	if (flags & IORING_SETUP_SQE_MIXED) {
2103 		if (sq_entries < 2)
2104 			return -EOVERFLOW;
2105 	}
2106 
2107 	rl->sq_array_offset = SIZE_MAX;
2108 
2109 	sqe_size = sizeof(struct io_uring_sqe);
2110 	if (flags & IORING_SETUP_SQE128)
2111 		sqe_size *= 2;
2112 
2113 	rl->sq_size = array_size(sqe_size, sq_entries);
2114 	if (rl->sq_size == SIZE_MAX)
2115 		return -EOVERFLOW;
2116 
2117 	off = struct_size(rings, cqes, cq_entries);
2118 	if (flags & IORING_SETUP_CQE32)
2119 		off = size_mul(off, 2);
2120 	if (off == SIZE_MAX)
2121 		return -EOVERFLOW;
2122 
2123 #ifdef CONFIG_SMP
2124 	off = ALIGN(off, SMP_CACHE_BYTES);
2125 	if (off == 0)
2126 		return -EOVERFLOW;
2127 #endif
2128 
2129 	if (!(flags & IORING_SETUP_NO_SQARRAY)) {
2130 		size_t sq_array_size;
2131 
2132 		rl->sq_array_offset = off;
2133 
2134 		sq_array_size = array_size(sizeof(u32), sq_entries);
2135 		off = size_add(off, sq_array_size);
2136 		if (off == SIZE_MAX)
2137 			return -EOVERFLOW;
2138 	}
2139 
2140 	rl->rings_size = off;
2141 	return 0;
2142 }
2143 
__io_req_caches_free(struct io_ring_ctx * ctx)2144 static __cold void __io_req_caches_free(struct io_ring_ctx *ctx)
2145 {
2146 	struct io_kiocb *req;
2147 	int nr = 0;
2148 
2149 	while (!io_req_cache_empty(ctx)) {
2150 		req = io_extract_req(ctx);
2151 		io_poison_req(req);
2152 		kmem_cache_free(req_cachep, req);
2153 		nr++;
2154 	}
2155 	if (nr) {
2156 		ctx->nr_req_allocated -= nr;
2157 		percpu_ref_put_many(&ctx->refs, nr);
2158 	}
2159 }
2160 
io_req_caches_free(struct io_ring_ctx * ctx)2161 static __cold void io_req_caches_free(struct io_ring_ctx *ctx)
2162 {
2163 	guard(mutex)(&ctx->uring_lock);
2164 	__io_req_caches_free(ctx);
2165 }
2166 
io_ring_ctx_free(struct io_ring_ctx * ctx)2167 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2168 {
2169 	io_unregister_bpf_ops(ctx);
2170 	io_sq_thread_finish(ctx);
2171 
2172 	mutex_lock(&ctx->uring_lock);
2173 	io_sqe_buffers_unregister(ctx);
2174 	io_sqe_files_unregister(ctx);
2175 	io_unregister_zcrx(ctx);
2176 	io_cqring_overflow_kill(ctx);
2177 	io_eventfd_unregister(ctx);
2178 	io_free_alloc_caches(ctx);
2179 	io_destroy_buffers(ctx);
2180 	io_free_region(ctx->user, &ctx->param_region);
2181 	mutex_unlock(&ctx->uring_lock);
2182 	if (ctx->sq_creds)
2183 		put_cred(ctx->sq_creds);
2184 	if (ctx->submitter_task)
2185 		put_task_struct(ctx->submitter_task);
2186 
2187 	WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2188 
2189 	if (ctx->mm_account) {
2190 		mmdrop(ctx->mm_account);
2191 		ctx->mm_account = NULL;
2192 	}
2193 	io_rings_free(ctx);
2194 
2195 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2196 		static_branch_slow_dec_deferred(&io_key_has_sqarray);
2197 
2198 	percpu_ref_exit(&ctx->refs);
2199 	free_uid(ctx->user);
2200 	io_req_caches_free(ctx);
2201 
2202 	if (ctx->restrictions.bpf_filters) {
2203 		WARN_ON_ONCE(ctx->bpf_filters !=
2204 			     ctx->restrictions.bpf_filters->filters);
2205 	} else {
2206 		WARN_ON_ONCE(ctx->bpf_filters);
2207 	}
2208 	io_put_bpf_filters(&ctx->restrictions);
2209 
2210 	WARN_ON_ONCE(ctx->nr_req_allocated);
2211 
2212 	if (ctx->hash_map)
2213 		io_wq_put_hash(ctx->hash_map);
2214 	io_napi_free(ctx);
2215 	kvfree(ctx->cancel_table.hbs);
2216 	xa_destroy(&ctx->io_bl_xa);
2217 	kfree(ctx);
2218 }
2219 
io_activate_pollwq_cb(struct callback_head * cb)2220 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
2221 {
2222 	struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
2223 					       poll_wq_task_work);
2224 
2225 	mutex_lock(&ctx->uring_lock);
2226 	ctx->int_flags |= IO_RING_F_POLL_ACTIVATED;
2227 	mutex_unlock(&ctx->uring_lock);
2228 
2229 	/*
2230 	 * Wake ups for some events between start of polling and activation
2231 	 * might've been lost due to loose synchronisation.
2232 	 */
2233 	wake_up_all(&ctx->poll_wq);
2234 	percpu_ref_put(&ctx->refs);
2235 }
2236 
io_activate_pollwq(struct io_ring_ctx * ctx)2237 __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
2238 {
2239 	spin_lock(&ctx->completion_lock);
2240 	/* already activated or in progress */
2241 	if ((ctx->int_flags & IO_RING_F_POLL_ACTIVATED) || ctx->poll_wq_task_work.func)
2242 		goto out;
2243 	if (WARN_ON_ONCE(!(ctx->int_flags & IO_RING_F_TASK_COMPLETE)))
2244 		goto out;
2245 	if (!ctx->submitter_task)
2246 		goto out;
2247 	/*
2248 	 * with ->submitter_task only the submitter task completes requests, we
2249 	 * only need to sync with it, which is done by injecting a tw
2250 	 */
2251 	init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
2252 	percpu_ref_get(&ctx->refs);
2253 	if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
2254 		percpu_ref_put(&ctx->refs);
2255 out:
2256 	spin_unlock(&ctx->completion_lock);
2257 }
2258 
io_uring_poll(struct file * file,poll_table * wait)2259 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
2260 {
2261 	struct io_ring_ctx *ctx = file->private_data;
2262 	__poll_t mask = 0;
2263 
2264 	if (unlikely(!(data_race(ctx->int_flags) & IO_RING_F_POLL_ACTIVATED)))
2265 		io_activate_pollwq(ctx);
2266 	/*
2267 	 * provides mb() which pairs with barrier from wq_has_sleeper
2268 	 * call in io_commit_cqring
2269 	 */
2270 	poll_wait(file, &ctx->poll_wq, wait);
2271 
2272 	rcu_read_lock();
2273 
2274 	if (!__io_sqring_full(ctx))
2275 		mask |= EPOLLOUT | EPOLLWRNORM;
2276 
2277 	/*
2278 	 * Don't flush cqring overflow list here, just do a simple check.
2279 	 * Otherwise there could possible be ABBA deadlock:
2280 	 *      CPU0                    CPU1
2281 	 *      ----                    ----
2282 	 * lock(&ctx->uring_lock);
2283 	 *                              lock(&ep->mtx);
2284 	 *                              lock(&ctx->uring_lock);
2285 	 * lock(&ep->mtx);
2286 	 *
2287 	 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
2288 	 * pushes them to do the flush.
2289 	 */
2290 
2291 	if (__io_cqring_events_user(ctx) || io_has_work(ctx))
2292 		mask |= EPOLLIN | EPOLLRDNORM;
2293 
2294 	rcu_read_unlock();
2295 	return mask;
2296 }
2297 
2298 struct io_tctx_exit {
2299 	struct callback_head		task_work;
2300 	struct completion		completion;
2301 	struct io_ring_ctx		*ctx;
2302 };
2303 
io_tctx_exit_cb(struct callback_head * cb)2304 static __cold void io_tctx_exit_cb(struct callback_head *cb)
2305 {
2306 	struct io_uring_task *tctx = current->io_uring;
2307 	struct io_tctx_exit *work;
2308 
2309 	work = container_of(cb, struct io_tctx_exit, task_work);
2310 	/*
2311 	 * When @in_cancel, we're in cancellation and it's racy to remove the
2312 	 * node. It'll be removed by the end of cancellation, just ignore it.
2313 	 * tctx can be NULL if the queueing of this task_work raced with
2314 	 * work cancelation off the exec path.
2315 	 */
2316 	if (tctx && !atomic_read(&tctx->in_cancel))
2317 		io_uring_del_tctx_node((unsigned long)work->ctx);
2318 	complete(&work->completion);
2319 }
2320 
io_ring_exit_work(struct work_struct * work)2321 static __cold void io_ring_exit_work(struct work_struct *work)
2322 {
2323 	struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
2324 	unsigned long timeout = jiffies + IO_URING_EXIT_WAIT_MAX;
2325 	unsigned long interval = HZ / 20;
2326 	struct io_tctx_exit exit;
2327 	struct io_tctx_node *node;
2328 	int ret;
2329 
2330 	mutex_lock(&ctx->uring_lock);
2331 	io_terminate_zcrx(ctx);
2332 	mutex_unlock(&ctx->uring_lock);
2333 
2334 	/*
2335 	 * If we're doing polled IO and end up having requests being
2336 	 * submitted async (out-of-line), then completions can come in while
2337 	 * we're waiting for refs to drop. We need to reap these manually,
2338 	 * as nobody else will be looking for them.
2339 	 */
2340 	do {
2341 		if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2342 			mutex_lock(&ctx->uring_lock);
2343 			io_cqring_overflow_kill(ctx);
2344 			mutex_unlock(&ctx->uring_lock);
2345 		}
2346 
2347 		/* The SQPOLL thread never reaches this path */
2348 		do {
2349 			if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2350 				io_move_task_work_from_local(ctx);
2351 			cond_resched();
2352 		} while (io_uring_try_cancel_requests(ctx, NULL, true, false));
2353 
2354 		if (ctx->sq_data) {
2355 			struct io_sq_data *sqd = ctx->sq_data;
2356 			struct task_struct *tsk;
2357 
2358 			io_sq_thread_park(sqd);
2359 			tsk = sqpoll_task_locked(sqd);
2360 			if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
2361 				io_wq_cancel_cb(tsk->io_uring->io_wq,
2362 						io_cancel_ctx_cb, ctx, true);
2363 			io_sq_thread_unpark(sqd);
2364 		}
2365 
2366 		io_req_caches_free(ctx);
2367 
2368 		if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
2369 			/* there is little hope left, don't run it too often */
2370 			interval = HZ * 60;
2371 		}
2372 		/*
2373 		 * This is really an uninterruptible wait, as it has to be
2374 		 * complete. But it's also run from a kworker, which doesn't
2375 		 * take signals, so it's fine to make it interruptible. This
2376 		 * avoids scenarios where we knowingly can wait much longer
2377 		 * on completions, for example if someone does a SIGSTOP on
2378 		 * a task that needs to finish task_work to make this loop
2379 		 * complete. That's a synthetic situation that should not
2380 		 * cause a stuck task backtrace, and hence a potential panic
2381 		 * on stuck tasks if that is enabled.
2382 		 */
2383 	} while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
2384 
2385 	init_completion(&exit.completion);
2386 	init_task_work(&exit.task_work, io_tctx_exit_cb);
2387 	exit.ctx = ctx;
2388 
2389 	mutex_lock(&ctx->uring_lock);
2390 	mutex_lock(&ctx->tctx_lock);
2391 	while (!list_empty(&ctx->tctx_list)) {
2392 		WARN_ON_ONCE(time_after(jiffies, timeout));
2393 
2394 		node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
2395 					ctx_node);
2396 		/* don't spin on a single task if cancellation failed */
2397 		list_rotate_left(&ctx->tctx_list);
2398 		ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
2399 		if (WARN_ON_ONCE(ret))
2400 			continue;
2401 
2402 		mutex_unlock(&ctx->tctx_lock);
2403 		mutex_unlock(&ctx->uring_lock);
2404 		/*
2405 		 * See comment above for
2406 		 * wait_for_completion_interruptible_timeout() on why this
2407 		 * wait is marked as interruptible.
2408 		 */
2409 		wait_for_completion_interruptible(&exit.completion);
2410 		mutex_lock(&ctx->uring_lock);
2411 		mutex_lock(&ctx->tctx_lock);
2412 	}
2413 	mutex_unlock(&ctx->tctx_lock);
2414 	mutex_unlock(&ctx->uring_lock);
2415 	spin_lock(&ctx->completion_lock);
2416 	spin_unlock(&ctx->completion_lock);
2417 
2418 	/* pairs with RCU read section in io_req_local_work_add() */
2419 	if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2420 		synchronize_rcu();
2421 
2422 	io_ring_ctx_free(ctx);
2423 }
2424 
io_ring_ctx_wait_and_kill(struct io_ring_ctx * ctx)2425 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2426 {
2427 	unsigned long index;
2428 	struct cred *creds;
2429 
2430 	mutex_lock(&ctx->uring_lock);
2431 	percpu_ref_kill(&ctx->refs);
2432 	xa_for_each(&ctx->personalities, index, creds)
2433 		io_unregister_personality(ctx, index);
2434 	mutex_unlock(&ctx->uring_lock);
2435 
2436 	flush_delayed_work(&ctx->fallback_work);
2437 
2438 	INIT_WORK(&ctx->exit_work, io_ring_exit_work);
2439 	/*
2440 	 * Use system_dfl_wq to avoid spawning tons of event kworkers
2441 	 * if we're exiting a ton of rings at the same time. It just adds
2442 	 * noise and overhead, there's no discernable change in runtime
2443 	 * over using system_percpu_wq.
2444 	 */
2445 	queue_work(iou_wq, &ctx->exit_work);
2446 }
2447 
io_uring_release(struct inode * inode,struct file * file)2448 static int io_uring_release(struct inode *inode, struct file *file)
2449 {
2450 	struct io_ring_ctx *ctx = file->private_data;
2451 
2452 	file->private_data = NULL;
2453 	io_ring_ctx_wait_and_kill(ctx);
2454 	return 0;
2455 }
2456 
io_get_ext_arg_reg(struct io_ring_ctx * ctx,const struct io_uring_getevents_arg __user * uarg)2457 static struct io_uring_reg_wait *io_get_ext_arg_reg(struct io_ring_ctx *ctx,
2458 			const struct io_uring_getevents_arg __user *uarg)
2459 {
2460 	unsigned long size = sizeof(struct io_uring_reg_wait);
2461 	unsigned long offset = (uintptr_t)uarg;
2462 	unsigned long end;
2463 
2464 	if (unlikely(offset % sizeof(long)))
2465 		return ERR_PTR(-EFAULT);
2466 
2467 	/* also protects from NULL ->cq_wait_arg as the size would be 0 */
2468 	if (unlikely(check_add_overflow(offset, size, &end) ||
2469 		     end > ctx->cq_wait_size))
2470 		return ERR_PTR(-EFAULT);
2471 
2472 	offset = array_index_nospec(offset, ctx->cq_wait_size - size);
2473 	return ctx->cq_wait_arg + offset;
2474 }
2475 
io_validate_ext_arg(struct io_ring_ctx * ctx,unsigned flags,const void __user * argp,size_t argsz)2476 static int io_validate_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
2477 			       const void __user *argp, size_t argsz)
2478 {
2479 	struct io_uring_getevents_arg arg;
2480 
2481 	if (!(flags & IORING_ENTER_EXT_ARG))
2482 		return 0;
2483 	if (flags & IORING_ENTER_EXT_ARG_REG)
2484 		return -EINVAL;
2485 	if (argsz != sizeof(arg))
2486 		return -EINVAL;
2487 	if (copy_from_user(&arg, argp, sizeof(arg)))
2488 		return -EFAULT;
2489 	return 0;
2490 }
2491 
io_get_ext_arg(struct io_ring_ctx * ctx,unsigned flags,const void __user * argp,struct ext_arg * ext_arg)2492 static int io_get_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
2493 			  const void __user *argp, struct ext_arg *ext_arg)
2494 {
2495 	const struct io_uring_getevents_arg __user *uarg = argp;
2496 	struct io_uring_getevents_arg arg;
2497 
2498 	ext_arg->iowait = !(flags & IORING_ENTER_NO_IOWAIT);
2499 
2500 	/*
2501 	 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
2502 	 * is just a pointer to the sigset_t.
2503 	 */
2504 	if (!(flags & IORING_ENTER_EXT_ARG)) {
2505 		ext_arg->sig = (const sigset_t __user *) argp;
2506 		return 0;
2507 	}
2508 
2509 	if (flags & IORING_ENTER_EXT_ARG_REG) {
2510 		struct io_uring_reg_wait *w;
2511 
2512 		if (ext_arg->argsz != sizeof(struct io_uring_reg_wait))
2513 			return -EINVAL;
2514 		w = io_get_ext_arg_reg(ctx, argp);
2515 		if (IS_ERR(w))
2516 			return PTR_ERR(w);
2517 
2518 		if (w->flags & ~IORING_REG_WAIT_TS)
2519 			return -EINVAL;
2520 		ext_arg->min_time = READ_ONCE(w->min_wait_usec) * NSEC_PER_USEC;
2521 		ext_arg->sig = u64_to_user_ptr(READ_ONCE(w->sigmask));
2522 		ext_arg->argsz = READ_ONCE(w->sigmask_sz);
2523 		if (w->flags & IORING_REG_WAIT_TS) {
2524 			ext_arg->ts.tv_sec = READ_ONCE(w->ts.tv_sec);
2525 			ext_arg->ts.tv_nsec = READ_ONCE(w->ts.tv_nsec);
2526 			ext_arg->ts_set = true;
2527 		}
2528 		return 0;
2529 	}
2530 
2531 	/*
2532 	 * EXT_ARG is set - ensure we agree on the size of it and copy in our
2533 	 * timespec and sigset_t pointers if good.
2534 	 */
2535 	if (ext_arg->argsz != sizeof(arg))
2536 		return -EINVAL;
2537 #ifdef CONFIG_64BIT
2538 	if (!user_access_begin(uarg, sizeof(*uarg)))
2539 		return -EFAULT;
2540 	unsafe_get_user(arg.sigmask, &uarg->sigmask, uaccess_end);
2541 	unsafe_get_user(arg.sigmask_sz, &uarg->sigmask_sz, uaccess_end);
2542 	unsafe_get_user(arg.min_wait_usec, &uarg->min_wait_usec, uaccess_end);
2543 	unsafe_get_user(arg.ts, &uarg->ts, uaccess_end);
2544 	user_access_end();
2545 #else
2546 	if (copy_from_user(&arg, uarg, sizeof(arg)))
2547 		return -EFAULT;
2548 #endif
2549 	ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC;
2550 	ext_arg->sig = u64_to_user_ptr(arg.sigmask);
2551 	ext_arg->argsz = arg.sigmask_sz;
2552 	if (arg.ts) {
2553 		if (get_timespec64(&ext_arg->ts, u64_to_user_ptr(arg.ts)))
2554 			return -EFAULT;
2555 		ext_arg->ts_set = true;
2556 	}
2557 	return 0;
2558 #ifdef CONFIG_64BIT
2559 uaccess_end:
2560 	user_access_end();
2561 	return -EFAULT;
2562 #endif
2563 }
2564 
2565 /*
2566  * Given an 'fd' value, return the ctx associated with if. If 'registered' is
2567  * true, then the registered index is used. Otherwise, the normal fd table.
2568  * Caller must call fput() on the returned file if it isn't a registered file,
2569  * unless it's an ERR_PTR.
2570  */
io_uring_ctx_get_file(unsigned int fd,bool registered)2571 struct file *io_uring_ctx_get_file(unsigned int fd, bool registered)
2572 {
2573 	struct file *file;
2574 
2575 	if (registered) {
2576 		/*
2577 		 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
2578 		 * need only dereference our task private array to find it.
2579 		 */
2580 		struct io_uring_task *tctx = current->io_uring;
2581 
2582 		if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
2583 			return ERR_PTR(-EINVAL);
2584 		fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
2585 		file = tctx->registered_rings[fd];
2586 	} else {
2587 		file = fget(fd);
2588 	}
2589 
2590 	if (unlikely(!file))
2591 		return ERR_PTR(-EBADF);
2592 	if (io_is_uring_fops(file))
2593 		return file;
2594 	if (!registered)
2595 		fput(file);
2596 	return ERR_PTR(-EOPNOTSUPP);
2597 }
2598 
2599 
SYSCALL_DEFINE6(io_uring_enter,unsigned int,fd,u32,to_submit,u32,min_complete,u32,flags,const void __user *,argp,size_t,argsz)2600 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
2601 		u32, min_complete, u32, flags, const void __user *, argp,
2602 		size_t, argsz)
2603 {
2604 	struct io_ring_ctx *ctx;
2605 	struct file *file;
2606 	long ret;
2607 
2608 	if (unlikely(flags & ~IORING_ENTER_FLAGS))
2609 		return -EINVAL;
2610 
2611 	file = io_uring_ctx_get_file(fd, flags & IORING_ENTER_REGISTERED_RING);
2612 	if (IS_ERR(file))
2613 		return PTR_ERR(file);
2614 	ctx = file->private_data;
2615 	ret = -EBADFD;
2616 	/*
2617 	 * Keep IORING_SETUP_R_DISABLED check before submitter_task load
2618 	 * in io_uring_add_tctx_node() -> __io_uring_add_tctx_node_from_submit()
2619 	 */
2620 	if (unlikely(smp_load_acquire(&ctx->flags) & IORING_SETUP_R_DISABLED))
2621 		goto out;
2622 
2623 	if (io_has_loop_ops(ctx)) {
2624 		ret = io_run_loop(ctx);
2625 		goto out;
2626 	}
2627 
2628 	/*
2629 	 * For SQ polling, the thread will do all submissions and completions.
2630 	 * Just return the requested submit count, and wake the thread if
2631 	 * we were asked to.
2632 	 */
2633 	ret = 0;
2634 	if (ctx->flags & IORING_SETUP_SQPOLL) {
2635 		if (unlikely(ctx->sq_data->thread == NULL)) {
2636 			ret = -EOWNERDEAD;
2637 			goto out;
2638 		}
2639 		if (flags & IORING_ENTER_SQ_WAKEUP)
2640 			wake_up(&ctx->sq_data->wait);
2641 		if (flags & IORING_ENTER_SQ_WAIT)
2642 			io_sqpoll_wait_sq(ctx);
2643 
2644 		ret = to_submit;
2645 	} else if (to_submit) {
2646 		ret = io_uring_add_tctx_node(ctx);
2647 		if (unlikely(ret))
2648 			goto out;
2649 
2650 		mutex_lock(&ctx->uring_lock);
2651 		ret = io_submit_sqes(ctx, to_submit);
2652 		if (ret != to_submit) {
2653 			mutex_unlock(&ctx->uring_lock);
2654 			goto out;
2655 		}
2656 		if (flags & IORING_ENTER_GETEVENTS) {
2657 			if (ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL)
2658 				goto iopoll_locked;
2659 			/*
2660 			 * Ignore errors, we'll soon call io_cqring_wait() and
2661 			 * it should handle ownership problems if any.
2662 			 */
2663 			if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
2664 				(void)io_run_local_work_locked(ctx, min_complete);
2665 		}
2666 		mutex_unlock(&ctx->uring_lock);
2667 	}
2668 
2669 	if (flags & IORING_ENTER_GETEVENTS) {
2670 		int ret2;
2671 
2672 		if (ctx->int_flags & IO_RING_F_SYSCALL_IOPOLL) {
2673 			/*
2674 			 * We disallow the app entering submit/complete with
2675 			 * polling, but we still need to lock the ring to
2676 			 * prevent racing with polled issue that got punted to
2677 			 * a workqueue.
2678 			 */
2679 			mutex_lock(&ctx->uring_lock);
2680 iopoll_locked:
2681 			ret2 = io_validate_ext_arg(ctx, flags, argp, argsz);
2682 			if (likely(!ret2))
2683 				ret2 = io_iopoll_check(ctx, min_complete);
2684 			mutex_unlock(&ctx->uring_lock);
2685 		} else {
2686 			struct ext_arg ext_arg = { .argsz = argsz };
2687 
2688 			ret2 = io_get_ext_arg(ctx, flags, argp, &ext_arg);
2689 			if (likely(!ret2))
2690 				ret2 = io_cqring_wait(ctx, min_complete, flags,
2691 						      &ext_arg);
2692 		}
2693 
2694 		if (!ret) {
2695 			ret = ret2;
2696 
2697 			/*
2698 			 * EBADR indicates that one or more CQE were dropped.
2699 			 * Once the user has been informed we can clear the bit
2700 			 * as they are obviously ok with those drops.
2701 			 */
2702 			if (unlikely(ret2 == -EBADR))
2703 				clear_bit(IO_CHECK_CQ_DROPPED_BIT,
2704 					  &ctx->check_cq);
2705 		}
2706 	}
2707 out:
2708 	if (!(flags & IORING_ENTER_REGISTERED_RING))
2709 		fput(file);
2710 	return ret;
2711 }
2712 
2713 static const struct file_operations io_uring_fops = {
2714 	.release	= io_uring_release,
2715 	.mmap		= io_uring_mmap,
2716 	.get_unmapped_area = io_uring_get_unmapped_area,
2717 #ifndef CONFIG_MMU
2718 	.mmap_capabilities = io_uring_nommu_mmap_capabilities,
2719 #endif
2720 	.poll		= io_uring_poll,
2721 #ifdef CONFIG_PROC_FS
2722 	.show_fdinfo	= io_uring_show_fdinfo,
2723 #endif
2724 };
2725 
io_is_uring_fops(struct file * file)2726 bool io_is_uring_fops(struct file *file)
2727 {
2728 	return file->f_op == &io_uring_fops;
2729 }
2730 
io_allocate_scq_urings(struct io_ring_ctx * ctx,struct io_ctx_config * config)2731 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2732 					 struct io_ctx_config *config)
2733 {
2734 	struct io_uring_params *p = &config->p;
2735 	struct io_rings_layout *rl = &config->layout;
2736 	struct io_uring_region_desc rd;
2737 	struct io_rings *rings;
2738 	int ret;
2739 
2740 	/* make sure these are sane, as we already accounted them */
2741 	ctx->sq_entries = p->sq_entries;
2742 	ctx->cq_entries = p->cq_entries;
2743 
2744 	memset(&rd, 0, sizeof(rd));
2745 	rd.size = PAGE_ALIGN(rl->rings_size);
2746 	if (ctx->flags & IORING_SETUP_NO_MMAP) {
2747 		rd.user_addr = p->cq_off.user_addr;
2748 		rd.flags |= IORING_MEM_REGION_TYPE_USER;
2749 	}
2750 	ret = io_create_region(ctx, &ctx->ring_region, &rd, IORING_OFF_CQ_RING);
2751 	if (ret)
2752 		return ret;
2753 	ctx->rings = rings = io_region_get_ptr(&ctx->ring_region);
2754 	rcu_assign_pointer(ctx->rings_rcu, rings);
2755 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2756 		ctx->sq_array = (u32 *)((char *)rings + rl->sq_array_offset);
2757 
2758 	memset(&rd, 0, sizeof(rd));
2759 	rd.size = PAGE_ALIGN(rl->sq_size);
2760 	if (ctx->flags & IORING_SETUP_NO_MMAP) {
2761 		rd.user_addr = p->sq_off.user_addr;
2762 		rd.flags |= IORING_MEM_REGION_TYPE_USER;
2763 	}
2764 	ret = io_create_region(ctx, &ctx->sq_region, &rd, IORING_OFF_SQES);
2765 	if (ret) {
2766 		io_rings_free(ctx);
2767 		return ret;
2768 	}
2769 	ctx->sq_sqes = io_region_get_ptr(&ctx->sq_region);
2770 
2771 	memset(rings, 0, sizeof(*rings));
2772 	WRITE_ONCE(rings->sq_ring_mask, ctx->sq_entries - 1);
2773 	WRITE_ONCE(rings->cq_ring_mask, ctx->cq_entries - 1);
2774 	WRITE_ONCE(rings->sq_ring_entries, ctx->sq_entries);
2775 	WRITE_ONCE(rings->cq_ring_entries, ctx->cq_entries);
2776 	return 0;
2777 }
2778 
io_uring_install_fd(struct file * file)2779 static int io_uring_install_fd(struct file *file)
2780 {
2781 	int fd;
2782 
2783 	fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2784 	if (fd < 0)
2785 		return fd;
2786 	fd_install(fd, file);
2787 	return fd;
2788 }
2789 
2790 /*
2791  * Allocate an anonymous fd, this is what constitutes the application
2792  * visible backing of an io_uring instance. The application mmaps this
2793  * fd to gain access to the SQ/CQ ring details.
2794  */
io_uring_get_file(struct io_ring_ctx * ctx)2795 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
2796 {
2797 	/* Create a new inode so that the LSM can block the creation.  */
2798 	return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
2799 					 O_RDWR | O_CLOEXEC, NULL);
2800 }
2801 
io_uring_sanitise_params(struct io_uring_params * p)2802 static int io_uring_sanitise_params(struct io_uring_params *p)
2803 {
2804 	unsigned flags = p->flags;
2805 
2806 	if (flags & ~IORING_SETUP_FLAGS)
2807 		return -EINVAL;
2808 
2809 	if (flags & IORING_SETUP_SQ_REWIND) {
2810 		if ((flags & IORING_SETUP_SQPOLL) ||
2811 		    !(flags & IORING_SETUP_NO_SQARRAY))
2812 			return -EINVAL;
2813 	}
2814 
2815 	/* There is no way to mmap rings without a real fd */
2816 	if ((flags & IORING_SETUP_REGISTERED_FD_ONLY) &&
2817 	    !(flags & IORING_SETUP_NO_MMAP))
2818 		return -EINVAL;
2819 
2820 	if (flags & IORING_SETUP_SQPOLL) {
2821 		/* IPI related flags don't make sense with SQPOLL */
2822 		if (flags & (IORING_SETUP_COOP_TASKRUN |
2823 			     IORING_SETUP_TASKRUN_FLAG |
2824 			     IORING_SETUP_DEFER_TASKRUN))
2825 			return -EINVAL;
2826 	}
2827 
2828 	if (flags & IORING_SETUP_TASKRUN_FLAG) {
2829 		if (!(flags & (IORING_SETUP_COOP_TASKRUN |
2830 			       IORING_SETUP_DEFER_TASKRUN)))
2831 			return -EINVAL;
2832 	}
2833 
2834 	/* HYBRID_IOPOLL only valid with IOPOLL */
2835 	if ((flags & IORING_SETUP_HYBRID_IOPOLL) && !(flags & IORING_SETUP_IOPOLL))
2836 		return -EINVAL;
2837 
2838 	/*
2839 	 * For DEFER_TASKRUN we require the completion task to be the same as
2840 	 * the submission task. This implies that there is only one submitter.
2841 	 */
2842 	if ((flags & IORING_SETUP_DEFER_TASKRUN) &&
2843 	    !(flags & IORING_SETUP_SINGLE_ISSUER))
2844 		return -EINVAL;
2845 
2846 	/*
2847 	 * Nonsensical to ask for CQE32 and mixed CQE support, it's not
2848 	 * supported to post 16b CQEs on a ring setup with CQE32.
2849 	 */
2850 	if ((flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)) ==
2851 	    (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED))
2852 		return -EINVAL;
2853 	/*
2854 	 * Nonsensical to ask for SQE128 and mixed SQE support, it's not
2855 	 * supported to post 64b SQEs on a ring setup with SQE128.
2856 	 */
2857 	if ((flags & (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED)) ==
2858 	    (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED))
2859 		return -EINVAL;
2860 
2861 	return 0;
2862 }
2863 
io_uring_fill_params(struct io_uring_params * p)2864 static int io_uring_fill_params(struct io_uring_params *p)
2865 {
2866 	unsigned entries = p->sq_entries;
2867 
2868 	if (!entries)
2869 		return -EINVAL;
2870 	if (entries > IORING_MAX_ENTRIES) {
2871 		if (!(p->flags & IORING_SETUP_CLAMP))
2872 			return -EINVAL;
2873 		entries = IORING_MAX_ENTRIES;
2874 	}
2875 
2876 	/*
2877 	 * Use twice as many entries for the CQ ring. It's possible for the
2878 	 * application to drive a higher depth than the size of the SQ ring,
2879 	 * since the sqes are only used at submission time. This allows for
2880 	 * some flexibility in overcommitting a bit. If the application has
2881 	 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
2882 	 * of CQ ring entries manually.
2883 	 */
2884 	p->sq_entries = roundup_pow_of_two(entries);
2885 	if (p->flags & IORING_SETUP_CQSIZE) {
2886 		/*
2887 		 * If IORING_SETUP_CQSIZE is set, we do the same roundup
2888 		 * to a power-of-two, if it isn't already. We do NOT impose
2889 		 * any cq vs sq ring sizing.
2890 		 */
2891 		if (!p->cq_entries)
2892 			return -EINVAL;
2893 		if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
2894 			if (!(p->flags & IORING_SETUP_CLAMP))
2895 				return -EINVAL;
2896 			p->cq_entries = IORING_MAX_CQ_ENTRIES;
2897 		}
2898 		p->cq_entries = roundup_pow_of_two(p->cq_entries);
2899 		if (p->cq_entries < p->sq_entries)
2900 			return -EINVAL;
2901 	} else {
2902 		p->cq_entries = 2 * p->sq_entries;
2903 	}
2904 
2905 	return 0;
2906 }
2907 
io_prepare_config(struct io_ctx_config * config)2908 int io_prepare_config(struct io_ctx_config *config)
2909 {
2910 	struct io_uring_params *p = &config->p;
2911 	int ret;
2912 
2913 	ret = io_uring_sanitise_params(p);
2914 	if (ret)
2915 		return ret;
2916 
2917 	ret = io_uring_fill_params(p);
2918 	if (ret)
2919 		return ret;
2920 
2921 	ret = rings_size(p->flags, p->sq_entries, p->cq_entries,
2922 			 &config->layout);
2923 	if (ret)
2924 		return ret;
2925 
2926 	p->sq_off.head = offsetof(struct io_rings, sq.head);
2927 	p->sq_off.tail = offsetof(struct io_rings, sq.tail);
2928 	p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
2929 	p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
2930 	p->sq_off.flags = offsetof(struct io_rings, sq_flags);
2931 	p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
2932 	p->sq_off.resv1 = 0;
2933 	if (!(p->flags & IORING_SETUP_NO_MMAP))
2934 		p->sq_off.user_addr = 0;
2935 
2936 	p->cq_off.head = offsetof(struct io_rings, cq.head);
2937 	p->cq_off.tail = offsetof(struct io_rings, cq.tail);
2938 	p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
2939 	p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
2940 	p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
2941 	p->cq_off.cqes = offsetof(struct io_rings, cqes);
2942 	p->cq_off.flags = offsetof(struct io_rings, cq_flags);
2943 	p->cq_off.resv1 = 0;
2944 	if (!(p->flags & IORING_SETUP_NO_MMAP))
2945 		p->cq_off.user_addr = 0;
2946 	if (!(p->flags & IORING_SETUP_NO_SQARRAY))
2947 		p->sq_off.array = config->layout.sq_array_offset;
2948 
2949 	return 0;
2950 }
2951 
io_restriction_clone(struct io_restriction * dst,struct io_restriction * src)2952 void io_restriction_clone(struct io_restriction *dst, struct io_restriction *src)
2953 {
2954 	memcpy(&dst->register_op, &src->register_op, sizeof(dst->register_op));
2955 	memcpy(&dst->sqe_op, &src->sqe_op, sizeof(dst->sqe_op));
2956 	dst->sqe_flags_allowed = src->sqe_flags_allowed;
2957 	dst->sqe_flags_required = src->sqe_flags_required;
2958 	dst->op_registered = src->op_registered;
2959 	dst->reg_registered = src->reg_registered;
2960 
2961 	io_bpf_filter_clone(dst, src);
2962 }
2963 
io_ctx_restriction_clone(struct io_ring_ctx * ctx,struct io_restriction * src)2964 static void io_ctx_restriction_clone(struct io_ring_ctx *ctx,
2965 				     struct io_restriction *src)
2966 {
2967 	struct io_restriction *dst = &ctx->restrictions;
2968 
2969 	io_restriction_clone(dst, src);
2970 	if (dst->bpf_filters)
2971 		WRITE_ONCE(ctx->bpf_filters, dst->bpf_filters->filters);
2972 	if (dst->op_registered)
2973 		ctx->int_flags |= IO_RING_F_OP_RESTRICTED;
2974 	if (dst->reg_registered)
2975 		ctx->int_flags |= IO_RING_F_REG_RESTRICTED;
2976 }
2977 
io_uring_create(struct io_ctx_config * config)2978 static __cold int io_uring_create(struct io_ctx_config *config)
2979 {
2980 	struct io_uring_params *p = &config->p;
2981 	struct io_ring_ctx *ctx;
2982 	struct io_uring_task *tctx;
2983 	struct file *file;
2984 	int ret;
2985 
2986 	ret = io_prepare_config(config);
2987 	if (ret)
2988 		return ret;
2989 
2990 	ctx = io_ring_ctx_alloc(p);
2991 	if (!ctx)
2992 		return -ENOMEM;
2993 
2994 	ctx->clockid = CLOCK_MONOTONIC;
2995 	ctx->clock_offset = 0;
2996 
2997 	if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
2998 		static_branch_deferred_inc(&io_key_has_sqarray);
2999 
3000 	if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3001 	    !(ctx->flags & IORING_SETUP_IOPOLL))
3002 		ctx->int_flags |= IO_RING_F_TASK_COMPLETE;
3003 
3004 	if ((ctx->int_flags & IO_RING_F_TASK_COMPLETE) ||
3005 	    (ctx->flags & IORING_SETUP_IOPOLL))
3006 		ctx->int_flags |= IO_RING_F_LOCKLESS_CQ;
3007 
3008 	/*
3009 	 * lazy poll_wq activation relies on ->task_complete for synchronisation
3010 	 * purposes, see io_activate_pollwq()
3011 	 */
3012 	if (!(ctx->int_flags & IO_RING_F_TASK_COMPLETE))
3013 		ctx->int_flags |= IO_RING_F_POLL_ACTIVATED;
3014 
3015 	/*
3016 	 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
3017 	 * space applications don't need to do io completion events
3018 	 * polling again, they can rely on io_sq_thread to do polling
3019 	 * work, which can reduce cpu usage and uring_lock contention.
3020 	 */
3021 	if (ctx->flags & IORING_SETUP_IOPOLL &&
3022 	    !(ctx->flags & IORING_SETUP_SQPOLL))
3023 		ctx->int_flags |= IO_RING_F_SYSCALL_IOPOLL;
3024 
3025 	if (in_compat_syscall())
3026 		ctx->int_flags |= IO_RING_F_COMPAT;
3027 	if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
3028 		ctx->user = get_uid(current_user());
3029 
3030 	/*
3031 	 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
3032 	 * COOP_TASKRUN is set, then IPIs are never needed by the app.
3033 	 */
3034 	if (ctx->flags & (IORING_SETUP_SQPOLL|IORING_SETUP_COOP_TASKRUN))
3035 		ctx->notify_method = TWA_SIGNAL_NO_IPI;
3036 	else
3037 		ctx->notify_method = TWA_SIGNAL;
3038 
3039 	/*
3040 	 * If the current task has restrictions enabled, then copy them to
3041 	 * our newly created ring and mark it as registered.
3042 	 */
3043 	if (current->io_uring_restrict)
3044 		io_ctx_restriction_clone(ctx, current->io_uring_restrict);
3045 
3046 	/*
3047 	 * This is just grabbed for accounting purposes. When a process exits,
3048 	 * the mm is exited and dropped before the files, hence we need to hang
3049 	 * on to this mm purely for the purposes of being able to unaccount
3050 	 * memory (locked/pinned vm). It's not used for anything else.
3051 	 */
3052 	mmgrab(current->mm);
3053 	ctx->mm_account = current->mm;
3054 
3055 	ret = io_allocate_scq_urings(ctx, config);
3056 	if (ret)
3057 		goto err;
3058 
3059 	ret = io_sq_offload_create(ctx, p);
3060 	if (ret)
3061 		goto err;
3062 
3063 	p->features = IORING_FEAT_FLAGS;
3064 
3065 	if (copy_to_user(config->uptr, p, sizeof(*p))) {
3066 		ret = -EFAULT;
3067 		goto err;
3068 	}
3069 
3070 	if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
3071 	    && !(ctx->flags & IORING_SETUP_R_DISABLED))
3072 		ctx->submitter_task = get_task_struct(current);
3073 
3074 	file = io_uring_get_file(ctx);
3075 	if (IS_ERR(file)) {
3076 		ret = PTR_ERR(file);
3077 		goto err;
3078 	}
3079 
3080 	ret = __io_uring_add_tctx_node(ctx);
3081 	if (ret)
3082 		goto err_fput;
3083 	tctx = current->io_uring;
3084 
3085 	/*
3086 	 * Install ring fd as the very last thing, so we don't risk someone
3087 	 * having closed it before we finish setup
3088 	 */
3089 	if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3090 		ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
3091 	else
3092 		ret = io_uring_install_fd(file);
3093 	if (ret < 0)
3094 		goto err_fput;
3095 
3096 	trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
3097 	return ret;
3098 err:
3099 	io_ring_ctx_wait_and_kill(ctx);
3100 	return ret;
3101 err_fput:
3102 	fput(file);
3103 	return ret;
3104 }
3105 
3106 /*
3107  * Sets up an aio uring context, and returns the fd. Applications asks for a
3108  * ring size, we return the actual sq/cq ring sizes (among other things) in the
3109  * params structure passed in.
3110  */
io_uring_setup(u32 entries,struct io_uring_params __user * params)3111 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3112 {
3113 	struct io_ctx_config config;
3114 
3115 	memset(&config, 0, sizeof(config));
3116 
3117 	if (copy_from_user(&config.p, params, sizeof(config.p)))
3118 		return -EFAULT;
3119 
3120 	if (!mem_is_zero(&config.p.resv, sizeof(config.p.resv)))
3121 		return -EINVAL;
3122 
3123 	config.p.sq_entries = entries;
3124 	config.uptr = params;
3125 	return io_uring_create(&config);
3126 }
3127 
io_uring_allowed(void)3128 static inline int io_uring_allowed(void)
3129 {
3130 	int disabled = READ_ONCE(sysctl_io_uring_disabled);
3131 	kgid_t io_uring_group;
3132 
3133 	if (disabled == 2)
3134 		return -EPERM;
3135 
3136 	if (disabled == 0 || capable(CAP_SYS_ADMIN))
3137 		goto allowed_lsm;
3138 
3139 	io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
3140 	if (!gid_valid(io_uring_group))
3141 		return -EPERM;
3142 
3143 	if (!in_group_p(io_uring_group))
3144 		return -EPERM;
3145 
3146 allowed_lsm:
3147 	return security_uring_allowed();
3148 }
3149 
SYSCALL_DEFINE2(io_uring_setup,u32,entries,struct io_uring_params __user *,params)3150 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3151 		struct io_uring_params __user *, params)
3152 {
3153 	int ret;
3154 
3155 	ret = io_uring_allowed();
3156 	if (ret)
3157 		return ret;
3158 
3159 	return io_uring_setup(entries, params);
3160 }
3161 
io_uring_init(void)3162 static int __init io_uring_init(void)
3163 {
3164 	struct kmem_cache_args kmem_args = {
3165 		.useroffset = offsetof(struct io_kiocb, cmd.data),
3166 		.usersize = sizeof_field(struct io_kiocb, cmd.data),
3167 		.freeptr_offset = offsetof(struct io_kiocb, work),
3168 		.use_freeptr_offset = true,
3169 	};
3170 
3171 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
3172 	BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
3173 	BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
3174 } while (0)
3175 
3176 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
3177 	__BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
3178 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
3179 	__BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
3180 	BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
3181 	BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
3182 	BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
3183 	BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
3184 	BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
3185 	BUILD_BUG_SQE_ELEM(8,  __u64,  off);
3186 	BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
3187 	BUILD_BUG_SQE_ELEM(8,  __u32,  cmd_op);
3188 	BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
3189 	BUILD_BUG_SQE_ELEM(16, __u64,  addr);
3190 	BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
3191 	BUILD_BUG_SQE_ELEM(24, __u32,  len);
3192 	BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
3193 	BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
3194 	BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
3195 	BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
3196 	BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
3197 	BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
3198 	BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
3199 	BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
3200 	BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
3201 	BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
3202 	BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
3203 	BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
3204 	BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
3205 	BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
3206 	BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
3207 	BUILD_BUG_SQE_ELEM(28, __u32,  rename_flags);
3208 	BUILD_BUG_SQE_ELEM(28, __u32,  unlink_flags);
3209 	BUILD_BUG_SQE_ELEM(28, __u32,  hardlink_flags);
3210 	BUILD_BUG_SQE_ELEM(28, __u32,  xattr_flags);
3211 	BUILD_BUG_SQE_ELEM(28, __u32,  msg_ring_flags);
3212 	BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
3213 	BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
3214 	BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
3215 	BUILD_BUG_SQE_ELEM(42, __u16,  personality);
3216 	BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
3217 	BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
3218 	BUILD_BUG_SQE_ELEM(44, __u16,  addr_len);
3219 	BUILD_BUG_SQE_ELEM(44, __u8,   write_stream);
3220 	BUILD_BUG_SQE_ELEM(45, __u8,   __pad4[0]);
3221 	BUILD_BUG_SQE_ELEM(46, __u16,  __pad3[0]);
3222 	BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
3223 	BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
3224 	BUILD_BUG_SQE_ELEM(48, __u64, attr_ptr);
3225 	BUILD_BUG_SQE_ELEM(56, __u64, attr_type_mask);
3226 	BUILD_BUG_SQE_ELEM(56, __u64,  __pad2);
3227 
3228 	BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
3229 		     sizeof(struct io_uring_rsrc_update));
3230 	BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
3231 		     sizeof(struct io_uring_rsrc_update2));
3232 
3233 	/* ->buf_index is u16 */
3234 	BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
3235 	BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
3236 		     offsetof(struct io_uring_buf_ring, tail));
3237 
3238 	/* should fit into one byte */
3239 	BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
3240 	BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
3241 	BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
3242 
3243 	BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
3244 
3245 	BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
3246 
3247 	/* top 8bits are for internal use */
3248 	BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
3249 
3250 	io_uring_optable_init();
3251 
3252 	/* imu->dir is u8 */
3253 	BUILD_BUG_ON((IO_IMU_DEST | IO_IMU_SOURCE) > U8_MAX);
3254 
3255 	/*
3256 	 * Allow user copy in the per-command field, which starts after the
3257 	 * file in io_kiocb and until the opcode field. The openat2 handling
3258 	 * requires copying in user memory into the io_kiocb object in that
3259 	 * range, and HARDENED_USERCOPY will complain if we haven't
3260 	 * correctly annotated this range.
3261 	 */
3262 	req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
3263 				SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
3264 				SLAB_TYPESAFE_BY_RCU);
3265 
3266 	iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
3267 	BUG_ON(!iou_wq);
3268 
3269 #ifdef CONFIG_SYSCTL
3270 	register_sysctl_init("kernel", kernel_io_uring_disabled_table);
3271 #endif
3272 
3273 	return 0;
3274 };
3275 __initcall(io_uring_init);
3276