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