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