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