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