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