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/fdtable.h>
55 #include <linux/mm.h>
56 #include <linux/mman.h>
57 #include <linux/percpu.h>
58 #include <linux/slab.h>
59 #include <linux/bvec.h>
60 #include <linux/net.h>
61 #include <net/sock.h>
62 #include <net/af_unix.h>
63 #include <linux/anon_inodes.h>
64 #include <linux/sched/mm.h>
65 #include <linux/uaccess.h>
66 #include <linux/nospec.h>
67 #include <linux/fsnotify.h>
68 #include <linux/fadvise.h>
69 #include <linux/task_work.h>
70 #include <linux/io_uring.h>
71 #include <linux/audit.h>
72 #include <linux/security.h>
73 #include <linux/vmalloc.h>
74 #include <asm/shmparam.h>
75
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/io_uring.h>
78
79 #include <uapi/linux/io_uring.h>
80
81 #include "io-wq.h"
82
83 #include "io_uring.h"
84 #include "opdef.h"
85 #include "refs.h"
86 #include "tctx.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
95 #include "timeout.h"
96 #include "poll.h"
97 #include "rw.h"
98 #include "alloc_cache.h"
99
100 #define IORING_MAX_ENTRIES 32768
101 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
102
103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
104 IORING_REGISTER_LAST + IORING_OP_LAST)
105
106 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
108
109 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
110 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
111
112 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
113 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
114 REQ_F_ASYNC_DATA)
115
116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
117 IO_REQ_CLEAN_FLAGS)
118
119 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
120
121 #define IO_COMPL_BATCH 32
122 #define IO_REQ_ALLOC_BATCH 8
123
124 enum {
125 IO_CHECK_CQ_OVERFLOW_BIT,
126 IO_CHECK_CQ_DROPPED_BIT,
127 };
128
129 enum {
130 IO_EVENTFD_OP_SIGNAL_BIT,
131 IO_EVENTFD_OP_FREE_BIT,
132 };
133
134 struct io_defer_entry {
135 struct list_head list;
136 struct io_kiocb *req;
137 u32 seq;
138 };
139
140 /* requests with any of those set should undergo io_disarm_next() */
141 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
142 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
143
144 static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
145 struct task_struct *task,
146 bool cancel_all);
147
148 static void io_queue_sqe(struct io_kiocb *req);
149
150 struct kmem_cache *req_cachep;
151 static struct workqueue_struct *iou_wq __ro_after_init;
152
153 static int __read_mostly sysctl_io_uring_disabled;
154 static int __read_mostly sysctl_io_uring_group = -1;
155
156 #ifdef CONFIG_SYSCTL
157 static struct ctl_table kernel_io_uring_disabled_table[] = {
158 {
159 .procname = "io_uring_disabled",
160 .data = &sysctl_io_uring_disabled,
161 .maxlen = sizeof(sysctl_io_uring_disabled),
162 .mode = 0644,
163 .proc_handler = proc_dointvec_minmax,
164 .extra1 = SYSCTL_ZERO,
165 .extra2 = SYSCTL_TWO,
166 },
167 {
168 .procname = "io_uring_group",
169 .data = &sysctl_io_uring_group,
170 .maxlen = sizeof(gid_t),
171 .mode = 0644,
172 .proc_handler = proc_dointvec,
173 },
174 {},
175 };
176 #endif
177
io_submit_flush_completions(struct io_ring_ctx * ctx)178 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
179 {
180 if (!wq_list_empty(&ctx->submit_state.compl_reqs) ||
181 ctx->submit_state.cqes_count)
182 __io_submit_flush_completions(ctx);
183 }
184
__io_cqring_events(struct io_ring_ctx * ctx)185 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
186 {
187 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
188 }
189
__io_cqring_events_user(struct io_ring_ctx * ctx)190 static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
191 {
192 return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
193 }
194
io_match_linked(struct io_kiocb * head)195 static bool io_match_linked(struct io_kiocb *head)
196 {
197 struct io_kiocb *req;
198
199 io_for_each_link(req, head) {
200 if (req->flags & REQ_F_INFLIGHT)
201 return true;
202 }
203 return false;
204 }
205
206 /*
207 * As io_match_task() but protected against racing with linked timeouts.
208 * User must not hold timeout_lock.
209 */
io_match_task_safe(struct io_kiocb * head,struct task_struct * task,bool cancel_all)210 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
211 bool cancel_all)
212 {
213 bool matched;
214
215 if (task && head->task != task)
216 return false;
217 if (cancel_all)
218 return true;
219
220 if (head->flags & REQ_F_LINK_TIMEOUT) {
221 struct io_ring_ctx *ctx = head->ctx;
222
223 /* protect against races with linked timeouts */
224 spin_lock_irq(&ctx->timeout_lock);
225 matched = io_match_linked(head);
226 spin_unlock_irq(&ctx->timeout_lock);
227 } else {
228 matched = io_match_linked(head);
229 }
230 return matched;
231 }
232
req_fail_link_node(struct io_kiocb * req,int res)233 static inline void req_fail_link_node(struct io_kiocb *req, int res)
234 {
235 req_set_fail(req);
236 io_req_set_res(req, res, 0);
237 }
238
io_req_add_to_cache(struct io_kiocb * req,struct io_ring_ctx * ctx)239 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
240 {
241 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
242 }
243
io_ring_ctx_ref_free(struct percpu_ref * ref)244 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
245 {
246 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
247
248 complete(&ctx->ref_comp);
249 }
250
io_fallback_req_func(struct work_struct * work)251 static __cold void io_fallback_req_func(struct work_struct *work)
252 {
253 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
254 fallback_work.work);
255 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
256 struct io_kiocb *req, *tmp;
257 struct io_tw_state ts = { .locked = true, };
258
259 percpu_ref_get(&ctx->refs);
260 mutex_lock(&ctx->uring_lock);
261 llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
262 req->io_task_work.func(req, &ts);
263 if (WARN_ON_ONCE(!ts.locked))
264 return;
265 io_submit_flush_completions(ctx);
266 mutex_unlock(&ctx->uring_lock);
267 percpu_ref_put(&ctx->refs);
268 }
269
io_alloc_hash_table(struct io_hash_table * table,unsigned bits)270 static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
271 {
272 unsigned hash_buckets = 1U << bits;
273 size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
274
275 table->hbs = kmalloc(hash_size, GFP_KERNEL);
276 if (!table->hbs)
277 return -ENOMEM;
278
279 table->hash_bits = bits;
280 init_hash_table(table, hash_buckets);
281 return 0;
282 }
283
io_ring_ctx_alloc(struct io_uring_params * p)284 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
285 {
286 struct io_ring_ctx *ctx;
287 int hash_bits;
288
289 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
290 if (!ctx)
291 return NULL;
292
293 xa_init(&ctx->io_bl_xa);
294
295 /*
296 * Use 5 bits less than the max cq entries, that should give us around
297 * 32 entries per hash list if totally full and uniformly spread, but
298 * don't keep too many buckets to not overconsume memory.
299 */
300 hash_bits = ilog2(p->cq_entries) - 5;
301 hash_bits = clamp(hash_bits, 1, 8);
302 if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
303 goto err;
304 if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
305 goto err;
306 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
307 0, GFP_KERNEL))
308 goto err;
309
310 ctx->flags = p->flags;
311 init_waitqueue_head(&ctx->sqo_sq_wait);
312 INIT_LIST_HEAD(&ctx->sqd_list);
313 INIT_LIST_HEAD(&ctx->cq_overflow_list);
314 INIT_LIST_HEAD(&ctx->io_buffers_cache);
315 io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
316 sizeof(struct io_rsrc_node));
317 io_alloc_cache_init(&ctx->apoll_cache, IO_ALLOC_CACHE_MAX,
318 sizeof(struct async_poll));
319 io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
320 sizeof(struct io_async_msghdr));
321 init_completion(&ctx->ref_comp);
322 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
323 mutex_init(&ctx->uring_lock);
324 init_waitqueue_head(&ctx->cq_wait);
325 init_waitqueue_head(&ctx->poll_wq);
326 init_waitqueue_head(&ctx->rsrc_quiesce_wq);
327 spin_lock_init(&ctx->completion_lock);
328 spin_lock_init(&ctx->timeout_lock);
329 INIT_WQ_LIST(&ctx->iopoll_list);
330 INIT_LIST_HEAD(&ctx->io_buffers_pages);
331 INIT_LIST_HEAD(&ctx->io_buffers_comp);
332 INIT_LIST_HEAD(&ctx->defer_list);
333 INIT_LIST_HEAD(&ctx->timeout_list);
334 INIT_LIST_HEAD(&ctx->ltimeout_list);
335 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
336 init_llist_head(&ctx->work_llist);
337 INIT_LIST_HEAD(&ctx->tctx_list);
338 ctx->submit_state.free_list.next = NULL;
339 INIT_WQ_LIST(&ctx->locked_free_list);
340 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
341 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
342 return ctx;
343 err:
344 kfree(ctx->cancel_table.hbs);
345 kfree(ctx->cancel_table_locked.hbs);
346 xa_destroy(&ctx->io_bl_xa);
347 kfree(ctx);
348 return NULL;
349 }
350
io_account_cq_overflow(struct io_ring_ctx * ctx)351 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
352 {
353 struct io_rings *r = ctx->rings;
354
355 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
356 ctx->cq_extra--;
357 }
358
req_need_defer(struct io_kiocb * req,u32 seq)359 static bool req_need_defer(struct io_kiocb *req, u32 seq)
360 {
361 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
362 struct io_ring_ctx *ctx = req->ctx;
363
364 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
365 }
366
367 return false;
368 }
369
io_clean_op(struct io_kiocb * req)370 static void io_clean_op(struct io_kiocb *req)
371 {
372 if (req->flags & REQ_F_BUFFER_SELECTED) {
373 spin_lock(&req->ctx->completion_lock);
374 io_put_kbuf_comp(req);
375 spin_unlock(&req->ctx->completion_lock);
376 }
377
378 if (req->flags & REQ_F_NEED_CLEANUP) {
379 const struct io_cold_def *def = &io_cold_defs[req->opcode];
380
381 if (def->cleanup)
382 def->cleanup(req);
383 }
384 if ((req->flags & REQ_F_POLLED) && req->apoll) {
385 kfree(req->apoll->double_poll);
386 kfree(req->apoll);
387 req->apoll = NULL;
388 }
389 if (req->flags & REQ_F_INFLIGHT) {
390 struct io_uring_task *tctx = req->task->io_uring;
391
392 atomic_dec(&tctx->inflight_tracked);
393 }
394 if (req->flags & REQ_F_CREDS)
395 put_cred(req->creds);
396 if (req->flags & REQ_F_ASYNC_DATA) {
397 kfree(req->async_data);
398 req->async_data = NULL;
399 }
400 req->flags &= ~IO_REQ_CLEAN_FLAGS;
401 }
402
io_req_track_inflight(struct io_kiocb * req)403 static inline void io_req_track_inflight(struct io_kiocb *req)
404 {
405 if (!(req->flags & REQ_F_INFLIGHT)) {
406 req->flags |= REQ_F_INFLIGHT;
407 atomic_inc(&req->task->io_uring->inflight_tracked);
408 }
409 }
410
__io_prep_linked_timeout(struct io_kiocb * req)411 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
412 {
413 if (WARN_ON_ONCE(!req->link))
414 return NULL;
415
416 req->flags &= ~REQ_F_ARM_LTIMEOUT;
417 req->flags |= REQ_F_LINK_TIMEOUT;
418
419 /* linked timeouts should have two refs once prep'ed */
420 io_req_set_refcount(req);
421 __io_req_set_refcount(req->link, 2);
422 return req->link;
423 }
424
io_prep_async_work(struct io_kiocb * req)425 static void io_prep_async_work(struct io_kiocb *req)
426 {
427 const struct io_issue_def *def = &io_issue_defs[req->opcode];
428 struct io_ring_ctx *ctx = req->ctx;
429
430 if (!(req->flags & REQ_F_CREDS)) {
431 req->flags |= REQ_F_CREDS;
432 req->creds = get_current_cred();
433 }
434
435 req->work.list.next = NULL;
436 req->work.flags = 0;
437 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
438 if (req->flags & REQ_F_FORCE_ASYNC)
439 req->work.flags |= IO_WQ_WORK_CONCURRENT;
440
441 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
442 req->flags |= io_file_get_flags(req->file);
443
444 if (req->file && (req->flags & REQ_F_ISREG)) {
445 bool should_hash = def->hash_reg_file;
446
447 /* don't serialize this request if the fs doesn't need it */
448 if (should_hash && (req->file->f_flags & O_DIRECT) &&
449 (req->file->f_mode & FMODE_DIO_PARALLEL_WRITE))
450 should_hash = false;
451 if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
452 io_wq_hash_work(&req->work, file_inode(req->file));
453 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
454 if (def->unbound_nonreg_file)
455 req->work.flags |= IO_WQ_WORK_UNBOUND;
456 }
457 }
458
io_prep_async_link(struct io_kiocb * req)459 static void io_prep_async_link(struct io_kiocb *req)
460 {
461 struct io_kiocb *cur;
462
463 if (req->flags & REQ_F_LINK_TIMEOUT) {
464 struct io_ring_ctx *ctx = req->ctx;
465
466 spin_lock_irq(&ctx->timeout_lock);
467 io_for_each_link(cur, req)
468 io_prep_async_work(cur);
469 spin_unlock_irq(&ctx->timeout_lock);
470 } else {
471 io_for_each_link(cur, req)
472 io_prep_async_work(cur);
473 }
474 }
475
io_queue_iowq(struct io_kiocb * req)476 static void io_queue_iowq(struct io_kiocb *req)
477 {
478 struct io_uring_task *tctx = req->task->io_uring;
479
480 BUG_ON(!tctx);
481
482 if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
483 io_req_task_queue_fail(req, -ECANCELED);
484 return;
485 }
486
487 /* init ->work of the whole link before punting */
488 io_prep_async_link(req);
489
490 /*
491 * Not expected to happen, but if we do have a bug where this _can_
492 * happen, catch it here and ensure the request is marked as
493 * canceled. That will make io-wq go through the usual work cancel
494 * procedure rather than attempt to run this request (or create a new
495 * worker for it).
496 */
497 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
498 req->work.flags |= IO_WQ_WORK_CANCEL;
499
500 trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
501 io_wq_enqueue(tctx->io_wq, &req->work);
502 }
503
io_queue_deferred(struct io_ring_ctx * ctx)504 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
505 {
506 while (!list_empty(&ctx->defer_list)) {
507 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
508 struct io_defer_entry, list);
509
510 if (req_need_defer(de->req, de->seq))
511 break;
512 list_del_init(&de->list);
513 io_req_task_queue(de->req);
514 kfree(de);
515 }
516 }
517
io_eventfd_free(struct rcu_head * rcu)518 static void io_eventfd_free(struct rcu_head *rcu)
519 {
520 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
521
522 eventfd_ctx_put(ev_fd->cq_ev_fd);
523 kfree(ev_fd);
524 }
525
io_eventfd_ops(struct rcu_head * rcu)526 static void io_eventfd_ops(struct rcu_head *rcu)
527 {
528 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
529 int ops = atomic_xchg(&ev_fd->ops, 0);
530
531 if (ops & BIT(IO_EVENTFD_OP_SIGNAL_BIT))
532 eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE);
533
534 /* IO_EVENTFD_OP_FREE_BIT may not be set here depending on callback
535 * ordering in a race but if references are 0 we know we have to free
536 * it regardless.
537 */
538 if (atomic_dec_and_test(&ev_fd->refs))
539 call_rcu(&ev_fd->rcu, io_eventfd_free);
540 }
541
io_eventfd_signal(struct io_ring_ctx * ctx)542 static void io_eventfd_signal(struct io_ring_ctx *ctx)
543 {
544 struct io_ev_fd *ev_fd = NULL;
545
546 rcu_read_lock();
547 /*
548 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
549 * and eventfd_signal
550 */
551 ev_fd = rcu_dereference(ctx->io_ev_fd);
552
553 /*
554 * Check again if ev_fd exists incase an io_eventfd_unregister call
555 * completed between the NULL check of ctx->io_ev_fd at the start of
556 * the function and rcu_read_lock.
557 */
558 if (unlikely(!ev_fd))
559 goto out;
560 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
561 goto out;
562 if (ev_fd->eventfd_async && !io_wq_current_is_worker())
563 goto out;
564
565 if (likely(eventfd_signal_allowed())) {
566 eventfd_signal_mask(ev_fd->cq_ev_fd, 1, EPOLL_URING_WAKE);
567 } else {
568 atomic_inc(&ev_fd->refs);
569 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_SIGNAL_BIT), &ev_fd->ops))
570 call_rcu_hurry(&ev_fd->rcu, io_eventfd_ops);
571 else
572 atomic_dec(&ev_fd->refs);
573 }
574
575 out:
576 rcu_read_unlock();
577 }
578
io_eventfd_flush_signal(struct io_ring_ctx * ctx)579 static void io_eventfd_flush_signal(struct io_ring_ctx *ctx)
580 {
581 bool skip;
582
583 spin_lock(&ctx->completion_lock);
584
585 /*
586 * Eventfd should only get triggered when at least one event has been
587 * posted. Some applications rely on the eventfd notification count
588 * only changing IFF a new CQE has been added to the CQ ring. There's
589 * no depedency on 1:1 relationship between how many times this
590 * function is called (and hence the eventfd count) and number of CQEs
591 * posted to the CQ ring.
592 */
593 skip = ctx->cached_cq_tail == ctx->evfd_last_cq_tail;
594 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
595 spin_unlock(&ctx->completion_lock);
596 if (skip)
597 return;
598
599 io_eventfd_signal(ctx);
600 }
601
__io_commit_cqring_flush(struct io_ring_ctx * ctx)602 void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
603 {
604 if (ctx->poll_activated)
605 io_poll_wq_wake(ctx);
606 if (ctx->off_timeout_used)
607 io_flush_timeouts(ctx);
608 if (ctx->drain_active) {
609 spin_lock(&ctx->completion_lock);
610 io_queue_deferred(ctx);
611 spin_unlock(&ctx->completion_lock);
612 }
613 if (ctx->has_evfd)
614 io_eventfd_flush_signal(ctx);
615 }
616
__io_cq_lock(struct io_ring_ctx * ctx)617 static inline void __io_cq_lock(struct io_ring_ctx *ctx)
618 {
619 if (!ctx->lockless_cq)
620 spin_lock(&ctx->completion_lock);
621 }
622
io_cq_lock(struct io_ring_ctx * ctx)623 static inline void io_cq_lock(struct io_ring_ctx *ctx)
624 __acquires(ctx->completion_lock)
625 {
626 spin_lock(&ctx->completion_lock);
627 }
628
__io_cq_unlock_post(struct io_ring_ctx * ctx)629 static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
630 {
631 io_commit_cqring(ctx);
632 if (!ctx->task_complete) {
633 if (!ctx->lockless_cq)
634 spin_unlock(&ctx->completion_lock);
635 /* IOPOLL rings only need to wake up if it's also SQPOLL */
636 if (!ctx->syscall_iopoll)
637 io_cqring_wake(ctx);
638 }
639 io_commit_cqring_flush(ctx);
640 }
641
io_cq_unlock_post(struct io_ring_ctx * ctx)642 static void io_cq_unlock_post(struct io_ring_ctx *ctx)
643 __releases(ctx->completion_lock)
644 {
645 io_commit_cqring(ctx);
646 spin_unlock(&ctx->completion_lock);
647 io_cqring_wake(ctx);
648 io_commit_cqring_flush(ctx);
649 }
650
651 /* Returns true if there are no backlogged entries after the flush */
io_cqring_overflow_kill(struct io_ring_ctx * ctx)652 static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
653 {
654 struct io_overflow_cqe *ocqe;
655 LIST_HEAD(list);
656
657 lockdep_assert_held(&ctx->uring_lock);
658
659 spin_lock(&ctx->completion_lock);
660 list_splice_init(&ctx->cq_overflow_list, &list);
661 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
662 spin_unlock(&ctx->completion_lock);
663
664 while (!list_empty(&list)) {
665 ocqe = list_first_entry(&list, struct io_overflow_cqe, list);
666 list_del(&ocqe->list);
667 kfree(ocqe);
668 }
669 }
670
__io_cqring_overflow_flush(struct io_ring_ctx * ctx)671 static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx)
672 {
673 size_t cqe_size = sizeof(struct io_uring_cqe);
674
675 lockdep_assert_held(&ctx->uring_lock);
676
677 if (__io_cqring_events(ctx) == ctx->cq_entries)
678 return;
679
680 if (ctx->flags & IORING_SETUP_CQE32)
681 cqe_size <<= 1;
682
683 io_cq_lock(ctx);
684 while (!list_empty(&ctx->cq_overflow_list)) {
685 struct io_uring_cqe *cqe;
686 struct io_overflow_cqe *ocqe;
687
688 if (!io_get_cqe_overflow(ctx, &cqe, true))
689 break;
690 ocqe = list_first_entry(&ctx->cq_overflow_list,
691 struct io_overflow_cqe, list);
692 memcpy(cqe, &ocqe->cqe, cqe_size);
693 list_del(&ocqe->list);
694 kfree(ocqe);
695
696 /*
697 * For silly syzbot cases that deliberately overflow by huge
698 * amounts, check if we need to resched and drop and
699 * reacquire the locks if so. Nothing real would ever hit this.
700 * Ideally we'd have a non-posting unlock for this, but hard
701 * to care for a non-real case.
702 */
703 if (need_resched()) {
704 ctx->cqe_sentinel = ctx->cqe_cached;
705 io_cq_unlock_post(ctx);
706 mutex_unlock(&ctx->uring_lock);
707 cond_resched();
708 mutex_lock(&ctx->uring_lock);
709 io_cq_lock(ctx);
710 }
711 }
712
713 if (list_empty(&ctx->cq_overflow_list)) {
714 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
715 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
716 }
717 io_cq_unlock_post(ctx);
718 }
719
io_cqring_do_overflow_flush(struct io_ring_ctx * ctx)720 static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
721 {
722 mutex_lock(&ctx->uring_lock);
723 __io_cqring_overflow_flush(ctx);
724 mutex_unlock(&ctx->uring_lock);
725 }
726
io_cqring_overflow_flush(struct io_ring_ctx * ctx)727 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx)
728 {
729 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
730 io_cqring_do_overflow_flush(ctx);
731 }
732
733 /* can be called by any task */
io_put_task_remote(struct task_struct * task)734 static void io_put_task_remote(struct task_struct *task)
735 {
736 struct io_uring_task *tctx = task->io_uring;
737
738 percpu_counter_sub(&tctx->inflight, 1);
739 if (unlikely(atomic_read(&tctx->in_cancel)))
740 wake_up(&tctx->wait);
741 put_task_struct(task);
742 }
743
744 /* used by a task to put its own references */
io_put_task_local(struct task_struct * task)745 static void io_put_task_local(struct task_struct *task)
746 {
747 task->io_uring->cached_refs++;
748 }
749
750 /* must to be called somewhat shortly after putting a request */
io_put_task(struct task_struct * task)751 static inline void io_put_task(struct task_struct *task)
752 {
753 if (likely(task == current))
754 io_put_task_local(task);
755 else
756 io_put_task_remote(task);
757 }
758
io_task_refs_refill(struct io_uring_task * tctx)759 void io_task_refs_refill(struct io_uring_task *tctx)
760 {
761 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
762
763 percpu_counter_add(&tctx->inflight, refill);
764 refcount_add(refill, ¤t->usage);
765 tctx->cached_refs += refill;
766 }
767
io_uring_drop_tctx_refs(struct task_struct * task)768 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
769 {
770 struct io_uring_task *tctx = task->io_uring;
771 unsigned int refs = tctx->cached_refs;
772
773 if (refs) {
774 tctx->cached_refs = 0;
775 percpu_counter_sub(&tctx->inflight, refs);
776 put_task_struct_many(task, refs);
777 }
778 }
779
io_cqring_event_overflow(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,u64 extra1,u64 extra2)780 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
781 s32 res, u32 cflags, u64 extra1, u64 extra2)
782 {
783 struct io_overflow_cqe *ocqe;
784 size_t ocq_size = sizeof(struct io_overflow_cqe);
785 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
786
787 lockdep_assert_held(&ctx->completion_lock);
788
789 if (is_cqe32)
790 ocq_size += sizeof(struct io_uring_cqe);
791
792 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
793 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
794 if (!ocqe) {
795 /*
796 * If we're in ring overflow flush mode, or in task cancel mode,
797 * or cannot allocate an overflow entry, then we need to drop it
798 * on the floor.
799 */
800 io_account_cq_overflow(ctx);
801 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
802 return false;
803 }
804 if (list_empty(&ctx->cq_overflow_list)) {
805 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
806 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
807
808 }
809 ocqe->cqe.user_data = user_data;
810 ocqe->cqe.res = res;
811 ocqe->cqe.flags = cflags;
812 if (is_cqe32) {
813 ocqe->cqe.big_cqe[0] = extra1;
814 ocqe->cqe.big_cqe[1] = extra2;
815 }
816 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
817 return true;
818 }
819
io_req_cqe_overflow(struct io_kiocb * req)820 void io_req_cqe_overflow(struct io_kiocb *req)
821 {
822 io_cqring_event_overflow(req->ctx, req->cqe.user_data,
823 req->cqe.res, req->cqe.flags,
824 req->big_cqe.extra1, req->big_cqe.extra2);
825 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
826 }
827
828 /*
829 * writes to the cq entry need to come after reading head; the
830 * control dependency is enough as we're using WRITE_ONCE to
831 * fill the cq entry
832 */
io_cqe_cache_refill(struct io_ring_ctx * ctx,bool overflow)833 bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
834 {
835 struct io_rings *rings = ctx->rings;
836 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
837 unsigned int free, queued, len;
838
839 /*
840 * Posting into the CQ when there are pending overflowed CQEs may break
841 * ordering guarantees, which will affect links, F_MORE users and more.
842 * Force overflow the completion.
843 */
844 if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
845 return false;
846
847 /* userspace may cheat modifying the tail, be safe and do min */
848 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
849 free = ctx->cq_entries - queued;
850 /* we need a contiguous range, limit based on the current array offset */
851 len = min(free, ctx->cq_entries - off);
852 if (!len)
853 return false;
854
855 if (ctx->flags & IORING_SETUP_CQE32) {
856 off <<= 1;
857 len <<= 1;
858 }
859
860 ctx->cqe_cached = &rings->cqes[off];
861 ctx->cqe_sentinel = ctx->cqe_cached + len;
862 return true;
863 }
864
io_fill_cqe_aux(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)865 static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
866 u32 cflags)
867 {
868 struct io_uring_cqe *cqe;
869
870 ctx->cq_extra++;
871
872 /*
873 * If we can't get a cq entry, userspace overflowed the
874 * submission (by quite a lot). Increment the overflow count in
875 * the ring.
876 */
877 if (likely(io_get_cqe(ctx, &cqe))) {
878 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
879
880 WRITE_ONCE(cqe->user_data, user_data);
881 WRITE_ONCE(cqe->res, res);
882 WRITE_ONCE(cqe->flags, cflags);
883
884 if (ctx->flags & IORING_SETUP_CQE32) {
885 WRITE_ONCE(cqe->big_cqe[0], 0);
886 WRITE_ONCE(cqe->big_cqe[1], 0);
887 }
888 return true;
889 }
890 return false;
891 }
892
__io_flush_post_cqes(struct io_ring_ctx * ctx)893 static void __io_flush_post_cqes(struct io_ring_ctx *ctx)
894 __must_hold(&ctx->uring_lock)
895 {
896 struct io_submit_state *state = &ctx->submit_state;
897 unsigned int i;
898
899 lockdep_assert_held(&ctx->uring_lock);
900 for (i = 0; i < state->cqes_count; i++) {
901 struct io_uring_cqe *cqe = &ctx->completion_cqes[i];
902
903 if (!io_fill_cqe_aux(ctx, cqe->user_data, cqe->res, cqe->flags)) {
904 if (ctx->lockless_cq) {
905 spin_lock(&ctx->completion_lock);
906 io_cqring_event_overflow(ctx, cqe->user_data,
907 cqe->res, cqe->flags, 0, 0);
908 spin_unlock(&ctx->completion_lock);
909 } else {
910 io_cqring_event_overflow(ctx, cqe->user_data,
911 cqe->res, cqe->flags, 0, 0);
912 }
913 }
914 }
915 state->cqes_count = 0;
916 }
917
__io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,bool allow_overflow)918 static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags,
919 bool allow_overflow)
920 {
921 bool filled;
922
923 io_cq_lock(ctx);
924 filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
925 if (!filled && allow_overflow)
926 filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
927
928 io_cq_unlock_post(ctx);
929 return filled;
930 }
931
io_post_aux_cqe(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)932 bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
933 {
934 return __io_post_aux_cqe(ctx, user_data, res, cflags, true);
935 }
936
937 /*
938 * A helper for multishot requests posting additional CQEs.
939 * Should only be used from a task_work including IO_URING_F_MULTISHOT.
940 */
io_fill_cqe_req_aux(struct io_kiocb * req,bool defer,s32 res,u32 cflags)941 bool io_fill_cqe_req_aux(struct io_kiocb *req, bool defer, s32 res, u32 cflags)
942 {
943 struct io_ring_ctx *ctx = req->ctx;
944 u64 user_data = req->cqe.user_data;
945 struct io_uring_cqe *cqe;
946
947 if (!defer)
948 return __io_post_aux_cqe(ctx, user_data, res, cflags, false);
949
950 lockdep_assert_held(&ctx->uring_lock);
951
952 if (ctx->submit_state.cqes_count == ARRAY_SIZE(ctx->completion_cqes)) {
953 __io_cq_lock(ctx);
954 __io_flush_post_cqes(ctx);
955 /* no need to flush - flush is deferred */
956 __io_cq_unlock_post(ctx);
957 }
958
959 /* For defered completions this is not as strict as it is otherwise,
960 * however it's main job is to prevent unbounded posted completions,
961 * and in that it works just as well.
962 */
963 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
964 return false;
965
966 cqe = &ctx->completion_cqes[ctx->submit_state.cqes_count++];
967 cqe->user_data = user_data;
968 cqe->res = res;
969 cqe->flags = cflags;
970 return true;
971 }
972
__io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)973 static void __io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
974 {
975 struct io_ring_ctx *ctx = req->ctx;
976 struct io_rsrc_node *rsrc_node = NULL;
977
978 io_cq_lock(ctx);
979 if (!(req->flags & REQ_F_CQE_SKIP)) {
980 if (!io_fill_cqe_req(ctx, req))
981 io_req_cqe_overflow(req);
982 }
983
984 /*
985 * If we're the last reference to this request, add to our locked
986 * free_list cache.
987 */
988 if (req_ref_put_and_test(req)) {
989 if (req->flags & IO_REQ_LINK_FLAGS) {
990 if (req->flags & IO_DISARM_MASK)
991 io_disarm_next(req);
992 if (req->link) {
993 io_req_task_queue(req->link);
994 req->link = NULL;
995 }
996 }
997 io_put_kbuf_comp(req);
998 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
999 io_clean_op(req);
1000 io_put_file(req);
1001
1002 rsrc_node = req->rsrc_node;
1003 /*
1004 * Selected buffer deallocation in io_clean_op() assumes that
1005 * we don't hold ->completion_lock. Clean them here to avoid
1006 * deadlocks.
1007 */
1008 io_put_task_remote(req->task);
1009 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1010 ctx->locked_free_nr++;
1011 }
1012 io_cq_unlock_post(ctx);
1013
1014 if (rsrc_node) {
1015 io_ring_submit_lock(ctx, issue_flags);
1016 io_put_rsrc_node(ctx, rsrc_node);
1017 io_ring_submit_unlock(ctx, issue_flags);
1018 }
1019 }
1020
io_req_complete_post(struct io_kiocb * req,unsigned issue_flags)1021 void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
1022 {
1023 if (req->ctx->task_complete && req->ctx->submitter_task != current) {
1024 req->io_task_work.func = io_req_task_complete;
1025 io_req_task_work_add(req);
1026 } else if (!(issue_flags & IO_URING_F_UNLOCKED) ||
1027 !(req->ctx->flags & IORING_SETUP_IOPOLL)) {
1028 __io_req_complete_post(req, issue_flags);
1029 } else {
1030 struct io_ring_ctx *ctx = req->ctx;
1031
1032 mutex_lock(&ctx->uring_lock);
1033 __io_req_complete_post(req, issue_flags & ~IO_URING_F_UNLOCKED);
1034 mutex_unlock(&ctx->uring_lock);
1035 }
1036 }
1037
io_req_defer_failed(struct io_kiocb * req,s32 res)1038 void io_req_defer_failed(struct io_kiocb *req, s32 res)
1039 __must_hold(&ctx->uring_lock)
1040 {
1041 const struct io_cold_def *def = &io_cold_defs[req->opcode];
1042
1043 lockdep_assert_held(&req->ctx->uring_lock);
1044
1045 req_set_fail(req);
1046 io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1047 if (def->fail)
1048 def->fail(req);
1049 io_req_complete_defer(req);
1050 }
1051
1052 /*
1053 * Don't initialise the fields below on every allocation, but do that in
1054 * advance and keep them valid across allocations.
1055 */
io_preinit_req(struct io_kiocb * req,struct io_ring_ctx * ctx)1056 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1057 {
1058 req->ctx = ctx;
1059 req->link = NULL;
1060 req->async_data = NULL;
1061 /* not necessary, but safer to zero */
1062 memset(&req->cqe, 0, sizeof(req->cqe));
1063 memset(&req->big_cqe, 0, sizeof(req->big_cqe));
1064 }
1065
io_flush_cached_locked_reqs(struct io_ring_ctx * ctx,struct io_submit_state * state)1066 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1067 struct io_submit_state *state)
1068 {
1069 spin_lock(&ctx->completion_lock);
1070 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1071 ctx->locked_free_nr = 0;
1072 spin_unlock(&ctx->completion_lock);
1073 }
1074
1075 /*
1076 * A request might get retired back into the request caches even before opcode
1077 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1078 * Because of that, io_alloc_req() should be called only under ->uring_lock
1079 * and with extra caution to not get a request that is still worked on.
1080 */
__io_alloc_req_refill(struct io_ring_ctx * ctx)1081 __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1082 __must_hold(&ctx->uring_lock)
1083 {
1084 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1085 void *reqs[IO_REQ_ALLOC_BATCH];
1086 int ret, i;
1087
1088 /*
1089 * If we have more than a batch's worth of requests in our IRQ side
1090 * locked cache, grab the lock and move them over to our submission
1091 * side cache.
1092 */
1093 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1094 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1095 if (!io_req_cache_empty(ctx))
1096 return true;
1097 }
1098
1099 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1100
1101 /*
1102 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1103 * retry single alloc to be on the safe side.
1104 */
1105 if (unlikely(ret <= 0)) {
1106 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1107 if (!reqs[0])
1108 return false;
1109 ret = 1;
1110 }
1111
1112 percpu_ref_get_many(&ctx->refs, ret);
1113 for (i = 0; i < ret; i++) {
1114 struct io_kiocb *req = reqs[i];
1115
1116 io_preinit_req(req, ctx);
1117 io_req_add_to_cache(req, ctx);
1118 }
1119 return true;
1120 }
1121
io_free_req(struct io_kiocb * req)1122 __cold void io_free_req(struct io_kiocb *req)
1123 {
1124 /* refs were already put, restore them for io_req_task_complete() */
1125 req->flags &= ~REQ_F_REFCOUNT;
1126 /* we only want to free it, don't post CQEs */
1127 req->flags |= REQ_F_CQE_SKIP;
1128 req->io_task_work.func = io_req_task_complete;
1129 io_req_task_work_add(req);
1130 }
1131
__io_req_find_next_prep(struct io_kiocb * req)1132 static void __io_req_find_next_prep(struct io_kiocb *req)
1133 {
1134 struct io_ring_ctx *ctx = req->ctx;
1135
1136 spin_lock(&ctx->completion_lock);
1137 io_disarm_next(req);
1138 spin_unlock(&ctx->completion_lock);
1139 }
1140
io_req_find_next(struct io_kiocb * req)1141 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1142 {
1143 struct io_kiocb *nxt;
1144
1145 /*
1146 * If LINK is set, we have dependent requests in this chain. If we
1147 * didn't fail this request, queue the first one up, moving any other
1148 * dependencies to the next request. In case of failure, fail the rest
1149 * of the chain.
1150 */
1151 if (unlikely(req->flags & IO_DISARM_MASK))
1152 __io_req_find_next_prep(req);
1153 nxt = req->link;
1154 req->link = NULL;
1155 return nxt;
1156 }
1157
ctx_flush_and_put(struct io_ring_ctx * ctx,struct io_tw_state * ts)1158 static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
1159 {
1160 if (!ctx)
1161 return;
1162 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1163 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1164 if (ts->locked) {
1165 io_submit_flush_completions(ctx);
1166 mutex_unlock(&ctx->uring_lock);
1167 ts->locked = false;
1168 }
1169 percpu_ref_put(&ctx->refs);
1170 }
1171
handle_tw_list(struct llist_node * node,struct io_ring_ctx ** ctx,struct io_tw_state * ts)1172 static unsigned int handle_tw_list(struct llist_node *node,
1173 struct io_ring_ctx **ctx,
1174 struct io_tw_state *ts)
1175 {
1176 unsigned int count = 0;
1177
1178 do {
1179 struct llist_node *next = node->next;
1180 struct io_kiocb *req = container_of(node, struct io_kiocb,
1181 io_task_work.node);
1182
1183 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1184
1185 if (req->ctx != *ctx) {
1186 ctx_flush_and_put(*ctx, ts);
1187 *ctx = req->ctx;
1188 /* if not contended, grab and improve batching */
1189 ts->locked = mutex_trylock(&(*ctx)->uring_lock);
1190 percpu_ref_get(&(*ctx)->refs);
1191 }
1192 INDIRECT_CALL_2(req->io_task_work.func,
1193 io_poll_task_func, io_req_rw_complete,
1194 req, ts);
1195 node = next;
1196 count++;
1197 if (unlikely(need_resched())) {
1198 ctx_flush_and_put(*ctx, ts);
1199 *ctx = NULL;
1200 cond_resched();
1201 }
1202 } while (node);
1203
1204 return count;
1205 }
1206
1207 /**
1208 * io_llist_xchg - swap all entries in a lock-less list
1209 * @head: the head of lock-less list to delete all entries
1210 * @new: new entry as the head of the list
1211 *
1212 * If list is empty, return NULL, otherwise, return the pointer to the first entry.
1213 * The order of entries returned is from the newest to the oldest added one.
1214 */
io_llist_xchg(struct llist_head * head,struct llist_node * new)1215 static inline struct llist_node *io_llist_xchg(struct llist_head *head,
1216 struct llist_node *new)
1217 {
1218 return xchg(&head->first, new);
1219 }
1220
io_fallback_tw(struct io_uring_task * tctx,bool sync)1221 static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
1222 {
1223 struct llist_node *node = llist_del_all(&tctx->task_list);
1224 struct io_ring_ctx *last_ctx = NULL;
1225 struct io_kiocb *req;
1226
1227 while (node) {
1228 req = container_of(node, struct io_kiocb, io_task_work.node);
1229 node = node->next;
1230 if (last_ctx != req->ctx) {
1231 if (last_ctx) {
1232 if (sync)
1233 flush_delayed_work(&last_ctx->fallback_work);
1234 percpu_ref_put(&last_ctx->refs);
1235 }
1236 last_ctx = req->ctx;
1237 percpu_ref_get(&last_ctx->refs);
1238 }
1239 if (llist_add(&req->io_task_work.node, &last_ctx->fallback_llist))
1240 schedule_delayed_work(&last_ctx->fallback_work, 1);
1241 }
1242
1243 if (last_ctx) {
1244 if (sync)
1245 flush_delayed_work(&last_ctx->fallback_work);
1246 percpu_ref_put(&last_ctx->refs);
1247 }
1248 }
1249
tctx_task_work(struct callback_head * cb)1250 void tctx_task_work(struct callback_head *cb)
1251 {
1252 struct io_tw_state ts = {};
1253 struct io_ring_ctx *ctx = NULL;
1254 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1255 task_work);
1256 struct llist_node *node;
1257 unsigned int count = 0;
1258
1259 if (unlikely(current->flags & PF_EXITING)) {
1260 io_fallback_tw(tctx, true);
1261 return;
1262 }
1263
1264 node = llist_del_all(&tctx->task_list);
1265 if (node)
1266 count = handle_tw_list(node, &ctx, &ts);
1267
1268 ctx_flush_and_put(ctx, &ts);
1269
1270 /* relaxed read is enough as only the task itself sets ->in_cancel */
1271 if (unlikely(atomic_read(&tctx->in_cancel)))
1272 io_uring_drop_tctx_refs(current);
1273
1274 trace_io_uring_task_work_run(tctx, count, 1);
1275 }
1276
io_req_local_work_add(struct io_kiocb * req,unsigned flags)1277 static inline void io_req_local_work_add(struct io_kiocb *req, unsigned flags)
1278 {
1279 struct io_ring_ctx *ctx = req->ctx;
1280 unsigned nr_wait, nr_tw, nr_tw_prev;
1281 struct llist_node *first;
1282
1283 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
1284 flags &= ~IOU_F_TWQ_LAZY_WAKE;
1285
1286 first = READ_ONCE(ctx->work_llist.first);
1287 do {
1288 nr_tw_prev = 0;
1289 if (first) {
1290 struct io_kiocb *first_req = container_of(first,
1291 struct io_kiocb,
1292 io_task_work.node);
1293 /*
1294 * Might be executed at any moment, rely on
1295 * SLAB_TYPESAFE_BY_RCU to keep it alive.
1296 */
1297 nr_tw_prev = READ_ONCE(first_req->nr_tw);
1298 }
1299 nr_tw = nr_tw_prev + 1;
1300 /* Large enough to fail the nr_wait comparison below */
1301 if (!(flags & IOU_F_TWQ_LAZY_WAKE))
1302 nr_tw = INT_MAX;
1303
1304 req->nr_tw = nr_tw;
1305 req->io_task_work.node.next = first;
1306 } while (!try_cmpxchg(&ctx->work_llist.first, &first,
1307 &req->io_task_work.node));
1308
1309 if (!first) {
1310 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1311 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1312 if (ctx->has_evfd)
1313 io_eventfd_signal(ctx);
1314 }
1315
1316 nr_wait = atomic_read(&ctx->cq_wait_nr);
1317 /* no one is waiting */
1318 if (!nr_wait)
1319 return;
1320 /* either not enough or the previous add has already woken it up */
1321 if (nr_wait > nr_tw || nr_tw_prev >= nr_wait)
1322 return;
1323 /* pairs with set_current_state() in io_cqring_wait() */
1324 smp_mb__after_atomic();
1325 wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
1326 }
1327
io_req_normal_work_add(struct io_kiocb * req)1328 static void io_req_normal_work_add(struct io_kiocb *req)
1329 {
1330 struct io_uring_task *tctx = req->task->io_uring;
1331 struct io_ring_ctx *ctx = req->ctx;
1332
1333 /* task_work already pending, we're done */
1334 if (!llist_add(&req->io_task_work.node, &tctx->task_list))
1335 return;
1336
1337 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1338 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1339
1340 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1341 return;
1342
1343 io_fallback_tw(tctx, false);
1344 }
1345
__io_req_task_work_add(struct io_kiocb * req,unsigned flags)1346 void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
1347 {
1348 if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
1349 rcu_read_lock();
1350 io_req_local_work_add(req, flags);
1351 rcu_read_unlock();
1352 } else {
1353 io_req_normal_work_add(req);
1354 }
1355 }
1356
io_move_task_work_from_local(struct io_ring_ctx * ctx)1357 static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
1358 {
1359 struct llist_node *node;
1360
1361 node = llist_del_all(&ctx->work_llist);
1362 while (node) {
1363 struct io_kiocb *req = container_of(node, struct io_kiocb,
1364 io_task_work.node);
1365
1366 node = node->next;
1367 io_req_normal_work_add(req);
1368 }
1369 }
1370
io_run_local_work_continue(struct io_ring_ctx * ctx,int events,int min_events)1371 static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
1372 int min_events)
1373 {
1374 if (llist_empty(&ctx->work_llist))
1375 return false;
1376 if (events < min_events)
1377 return true;
1378 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1379 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1380 return false;
1381 }
1382
__io_run_local_work(struct io_ring_ctx * ctx,struct io_tw_state * ts,int min_events)1383 static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
1384 int min_events)
1385 {
1386 struct llist_node *node;
1387 unsigned int loops = 0;
1388 int ret = 0;
1389
1390 if (WARN_ON_ONCE(ctx->submitter_task != current))
1391 return -EEXIST;
1392 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1393 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1394 again:
1395 /*
1396 * llists are in reverse order, flip it back the right way before
1397 * running the pending items.
1398 */
1399 node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
1400 while (node) {
1401 struct llist_node *next = node->next;
1402 struct io_kiocb *req = container_of(node, struct io_kiocb,
1403 io_task_work.node);
1404 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1405 INDIRECT_CALL_2(req->io_task_work.func,
1406 io_poll_task_func, io_req_rw_complete,
1407 req, ts);
1408 ret++;
1409 node = next;
1410 }
1411 loops++;
1412
1413 if (io_run_local_work_continue(ctx, ret, min_events))
1414 goto again;
1415 if (ts->locked) {
1416 io_submit_flush_completions(ctx);
1417 if (io_run_local_work_continue(ctx, ret, min_events))
1418 goto again;
1419 }
1420
1421 trace_io_uring_local_work_run(ctx, ret, loops);
1422 return ret;
1423 }
1424
io_run_local_work_locked(struct io_ring_ctx * ctx,int min_events)1425 static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
1426 int min_events)
1427 {
1428 struct io_tw_state ts = { .locked = true, };
1429 int ret;
1430
1431 if (llist_empty(&ctx->work_llist))
1432 return 0;
1433
1434 ret = __io_run_local_work(ctx, &ts, min_events);
1435 /* shouldn't happen! */
1436 if (WARN_ON_ONCE(!ts.locked))
1437 mutex_lock(&ctx->uring_lock);
1438 return ret;
1439 }
1440
io_run_local_work(struct io_ring_ctx * ctx,int min_events)1441 static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
1442 {
1443 struct io_tw_state ts = {};
1444 int ret;
1445
1446 ts.locked = mutex_trylock(&ctx->uring_lock);
1447 ret = __io_run_local_work(ctx, &ts, min_events);
1448 if (ts.locked)
1449 mutex_unlock(&ctx->uring_lock);
1450
1451 return ret;
1452 }
1453
io_req_task_cancel(struct io_kiocb * req,struct io_tw_state * ts)1454 static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
1455 {
1456 io_tw_lock(req->ctx, ts);
1457 io_req_defer_failed(req, req->cqe.res);
1458 }
1459
io_req_task_submit(struct io_kiocb * req,struct io_tw_state * ts)1460 void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
1461 {
1462 io_tw_lock(req->ctx, ts);
1463 /* req->task == current here, checking PF_EXITING is safe */
1464 if (unlikely(req->task->flags & PF_EXITING))
1465 io_req_defer_failed(req, -EFAULT);
1466 else if (req->flags & REQ_F_FORCE_ASYNC)
1467 io_queue_iowq(req);
1468 else
1469 io_queue_sqe(req);
1470 }
1471
io_req_task_queue_fail(struct io_kiocb * req,int ret)1472 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1473 {
1474 io_req_set_res(req, ret, 0);
1475 req->io_task_work.func = io_req_task_cancel;
1476 io_req_task_work_add(req);
1477 }
1478
io_req_task_queue(struct io_kiocb * req)1479 void io_req_task_queue(struct io_kiocb *req)
1480 {
1481 req->io_task_work.func = io_req_task_submit;
1482 io_req_task_work_add(req);
1483 }
1484
io_queue_next(struct io_kiocb * req)1485 void io_queue_next(struct io_kiocb *req)
1486 {
1487 struct io_kiocb *nxt = io_req_find_next(req);
1488
1489 if (nxt)
1490 io_req_task_queue(nxt);
1491 }
1492
io_free_batch_list(struct io_ring_ctx * ctx,struct io_wq_work_node * node)1493 static void io_free_batch_list(struct io_ring_ctx *ctx,
1494 struct io_wq_work_node *node)
1495 __must_hold(&ctx->uring_lock)
1496 {
1497 do {
1498 struct io_kiocb *req = container_of(node, struct io_kiocb,
1499 comp_list);
1500
1501 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1502 if (req->flags & REQ_F_REFCOUNT) {
1503 node = req->comp_list.next;
1504 if (!req_ref_put_and_test(req))
1505 continue;
1506 }
1507 if ((req->flags & REQ_F_POLLED) && req->apoll) {
1508 struct async_poll *apoll = req->apoll;
1509
1510 if (apoll->double_poll)
1511 kfree(apoll->double_poll);
1512 if (!io_alloc_cache_put(&ctx->apoll_cache, &apoll->cache))
1513 kfree(apoll);
1514 req->flags &= ~REQ_F_POLLED;
1515 }
1516 if (req->flags & IO_REQ_LINK_FLAGS)
1517 io_queue_next(req);
1518 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1519 io_clean_op(req);
1520 }
1521 io_put_file(req);
1522
1523 io_req_put_rsrc_locked(req, ctx);
1524
1525 io_put_task(req->task);
1526 node = req->comp_list.next;
1527 io_req_add_to_cache(req, ctx);
1528 } while (node);
1529 }
1530
__io_submit_flush_completions(struct io_ring_ctx * ctx)1531 void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1532 __must_hold(&ctx->uring_lock)
1533 {
1534 struct io_submit_state *state = &ctx->submit_state;
1535 struct io_wq_work_node *node;
1536
1537 __io_cq_lock(ctx);
1538 /* must come first to preserve CQE ordering in failure cases */
1539 if (state->cqes_count)
1540 __io_flush_post_cqes(ctx);
1541 __wq_list_for_each(node, &state->compl_reqs) {
1542 struct io_kiocb *req = container_of(node, struct io_kiocb,
1543 comp_list);
1544
1545 if (!(req->flags & REQ_F_CQE_SKIP) &&
1546 unlikely(!io_fill_cqe_req(ctx, req))) {
1547 if (ctx->lockless_cq) {
1548 spin_lock(&ctx->completion_lock);
1549 io_req_cqe_overflow(req);
1550 spin_unlock(&ctx->completion_lock);
1551 } else {
1552 io_req_cqe_overflow(req);
1553 }
1554 }
1555 }
1556 __io_cq_unlock_post(ctx);
1557
1558 if (!wq_list_empty(&ctx->submit_state.compl_reqs)) {
1559 io_free_batch_list(ctx, state->compl_reqs.first);
1560 INIT_WQ_LIST(&state->compl_reqs);
1561 }
1562 }
1563
io_cqring_events(struct io_ring_ctx * ctx)1564 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1565 {
1566 /* See comment at the top of this file */
1567 smp_rmb();
1568 return __io_cqring_events(ctx);
1569 }
1570
1571 /*
1572 * We can't just wait for polled events to come to us, we have to actively
1573 * find and complete them.
1574 */
io_iopoll_try_reap_events(struct io_ring_ctx * ctx)1575 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1576 {
1577 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1578 return;
1579
1580 mutex_lock(&ctx->uring_lock);
1581 while (!wq_list_empty(&ctx->iopoll_list)) {
1582 /* let it sleep and repeat later if can't complete a request */
1583 if (io_do_iopoll(ctx, true) == 0)
1584 break;
1585 /*
1586 * Ensure we allow local-to-the-cpu processing to take place,
1587 * in this case we need to ensure that we reap all events.
1588 * Also let task_work, etc. to progress by releasing the mutex
1589 */
1590 if (need_resched()) {
1591 mutex_unlock(&ctx->uring_lock);
1592 cond_resched();
1593 mutex_lock(&ctx->uring_lock);
1594 }
1595 }
1596 mutex_unlock(&ctx->uring_lock);
1597 }
1598
io_iopoll_check(struct io_ring_ctx * ctx,long min)1599 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1600 {
1601 unsigned int nr_events = 0;
1602 unsigned long check_cq;
1603
1604 lockdep_assert_held(&ctx->uring_lock);
1605
1606 if (!io_allowed_run_tw(ctx))
1607 return -EEXIST;
1608
1609 check_cq = READ_ONCE(ctx->check_cq);
1610 if (unlikely(check_cq)) {
1611 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1612 __io_cqring_overflow_flush(ctx);
1613 /*
1614 * Similarly do not spin if we have not informed the user of any
1615 * dropped CQE.
1616 */
1617 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
1618 return -EBADR;
1619 }
1620 /*
1621 * Don't enter poll loop if we already have events pending.
1622 * If we do, we can potentially be spinning for commands that
1623 * already triggered a CQE (eg in error).
1624 */
1625 if (io_cqring_events(ctx))
1626 return 0;
1627
1628 do {
1629 int ret = 0;
1630
1631 /*
1632 * If a submit got punted to a workqueue, we can have the
1633 * application entering polling for a command before it gets
1634 * issued. That app will hold the uring_lock for the duration
1635 * of the poll right here, so we need to take a breather every
1636 * now and then to ensure that the issue has a chance to add
1637 * the poll to the issued list. Otherwise we can spin here
1638 * forever, while the workqueue is stuck trying to acquire the
1639 * very same mutex.
1640 */
1641 if (wq_list_empty(&ctx->iopoll_list) ||
1642 io_task_work_pending(ctx)) {
1643 u32 tail = ctx->cached_cq_tail;
1644
1645 (void) io_run_local_work_locked(ctx, min);
1646
1647 if (task_work_pending(current) ||
1648 wq_list_empty(&ctx->iopoll_list)) {
1649 mutex_unlock(&ctx->uring_lock);
1650 io_run_task_work();
1651 mutex_lock(&ctx->uring_lock);
1652 }
1653 /* some requests don't go through iopoll_list */
1654 if (tail != ctx->cached_cq_tail ||
1655 wq_list_empty(&ctx->iopoll_list))
1656 break;
1657 }
1658 ret = io_do_iopoll(ctx, !min);
1659 if (unlikely(ret < 0))
1660 return ret;
1661
1662 if (task_sigpending(current))
1663 return -EINTR;
1664 if (need_resched())
1665 break;
1666
1667 nr_events += ret;
1668 } while (nr_events < min);
1669
1670 return 0;
1671 }
1672
io_req_task_complete(struct io_kiocb * req,struct io_tw_state * ts)1673 void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
1674 {
1675 if (ts->locked)
1676 io_req_complete_defer(req);
1677 else
1678 io_req_complete_post(req, IO_URING_F_UNLOCKED);
1679 }
1680
1681 /*
1682 * After the iocb has been issued, it's safe to be found on the poll list.
1683 * Adding the kiocb to the list AFTER submission ensures that we don't
1684 * find it from a io_do_iopoll() thread before the issuer is done
1685 * accessing the kiocb cookie.
1686 */
io_iopoll_req_issued(struct io_kiocb * req,unsigned int issue_flags)1687 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
1688 {
1689 struct io_ring_ctx *ctx = req->ctx;
1690 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
1691
1692 /* workqueue context doesn't hold uring_lock, grab it now */
1693 if (unlikely(needs_lock))
1694 mutex_lock(&ctx->uring_lock);
1695
1696 /*
1697 * Track whether we have multiple files in our lists. This will impact
1698 * how we do polling eventually, not spinning if we're on potentially
1699 * different devices.
1700 */
1701 if (wq_list_empty(&ctx->iopoll_list)) {
1702 ctx->poll_multi_queue = false;
1703 } else if (!ctx->poll_multi_queue) {
1704 struct io_kiocb *list_req;
1705
1706 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
1707 comp_list);
1708 if (list_req->file != req->file)
1709 ctx->poll_multi_queue = true;
1710 }
1711
1712 /*
1713 * For fast devices, IO may have already completed. If it has, add
1714 * it to the front so we find it first.
1715 */
1716 if (READ_ONCE(req->iopoll_completed))
1717 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
1718 else
1719 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
1720
1721 if (unlikely(needs_lock)) {
1722 /*
1723 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
1724 * in sq thread task context or in io worker task context. If
1725 * current task context is sq thread, we don't need to check
1726 * whether should wake up sq thread.
1727 */
1728 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
1729 wq_has_sleeper(&ctx->sq_data->wait))
1730 wake_up(&ctx->sq_data->wait);
1731
1732 mutex_unlock(&ctx->uring_lock);
1733 }
1734 }
1735
io_file_get_flags(struct file * file)1736 unsigned int io_file_get_flags(struct file *file)
1737 {
1738 unsigned int res = 0;
1739
1740 if (S_ISREG(file_inode(file)->i_mode))
1741 res |= REQ_F_ISREG;
1742 if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
1743 res |= REQ_F_SUPPORT_NOWAIT;
1744 return res;
1745 }
1746
io_alloc_async_data(struct io_kiocb * req)1747 bool io_alloc_async_data(struct io_kiocb *req)
1748 {
1749 WARN_ON_ONCE(!io_cold_defs[req->opcode].async_size);
1750 req->async_data = kmalloc(io_cold_defs[req->opcode].async_size, GFP_KERNEL);
1751 if (req->async_data) {
1752 req->flags |= REQ_F_ASYNC_DATA;
1753 return false;
1754 }
1755 return true;
1756 }
1757
io_req_prep_async(struct io_kiocb * req)1758 int io_req_prep_async(struct io_kiocb *req)
1759 {
1760 const struct io_cold_def *cdef = &io_cold_defs[req->opcode];
1761 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1762 int ret;
1763
1764 /* assign early for deferred execution for non-fixed file */
1765 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE) && !req->file)
1766 req->file = io_file_get_normal(req, req->cqe.fd);
1767 if (!cdef->prep_async)
1768 return 0;
1769 if (WARN_ON_ONCE(req_has_async_data(req)))
1770 return -EFAULT;
1771 if (!def->manual_alloc) {
1772 if (io_alloc_async_data(req))
1773 return -EAGAIN;
1774 }
1775 ret = cdef->prep_async(req);
1776 io_kbuf_recycle(req, 0);
1777 return ret;
1778 }
1779
io_get_sequence(struct io_kiocb * req)1780 static u32 io_get_sequence(struct io_kiocb *req)
1781 {
1782 u32 seq = req->ctx->cached_sq_head;
1783 struct io_kiocb *cur;
1784
1785 /* need original cached_sq_head, but it was increased for each req */
1786 io_for_each_link(cur, req)
1787 seq--;
1788 return seq;
1789 }
1790
io_drain_req(struct io_kiocb * req)1791 static __cold void io_drain_req(struct io_kiocb *req)
1792 __must_hold(&ctx->uring_lock)
1793 {
1794 struct io_ring_ctx *ctx = req->ctx;
1795 struct io_defer_entry *de;
1796 int ret;
1797 u32 seq = io_get_sequence(req);
1798
1799 /* Still need defer if there is pending req in defer list. */
1800 spin_lock(&ctx->completion_lock);
1801 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
1802 spin_unlock(&ctx->completion_lock);
1803 queue:
1804 ctx->drain_active = false;
1805 io_req_task_queue(req);
1806 return;
1807 }
1808 spin_unlock(&ctx->completion_lock);
1809
1810 io_prep_async_link(req);
1811 de = kmalloc(sizeof(*de), GFP_KERNEL);
1812 if (!de) {
1813 ret = -ENOMEM;
1814 io_req_defer_failed(req, ret);
1815 return;
1816 }
1817
1818 spin_lock(&ctx->completion_lock);
1819 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
1820 spin_unlock(&ctx->completion_lock);
1821 kfree(de);
1822 goto queue;
1823 }
1824
1825 trace_io_uring_defer(req);
1826 de->req = req;
1827 de->seq = seq;
1828 list_add_tail(&de->list, &ctx->defer_list);
1829 spin_unlock(&ctx->completion_lock);
1830 }
1831
io_assign_file(struct io_kiocb * req,const struct io_issue_def * def,unsigned int issue_flags)1832 static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
1833 unsigned int issue_flags)
1834 {
1835 if (req->file || !def->needs_file)
1836 return true;
1837
1838 if (req->flags & REQ_F_FIXED_FILE)
1839 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
1840 else
1841 req->file = io_file_get_normal(req, req->cqe.fd);
1842
1843 return !!req->file;
1844 }
1845
1846 #define REQ_ISSUE_SLOW_FLAGS (REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)
1847
io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags)1848 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
1849 {
1850 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1851 const struct cred *creds = NULL;
1852 struct io_kiocb *link = NULL;
1853 int ret;
1854
1855 if (unlikely(!io_assign_file(req, def, issue_flags)))
1856 return -EBADF;
1857
1858 if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) {
1859 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
1860 creds = override_creds(req->creds);
1861 if (req->flags & REQ_F_ARM_LTIMEOUT)
1862 link = __io_prep_linked_timeout(req);
1863 }
1864
1865 if (!def->audit_skip)
1866 audit_uring_entry(req->opcode);
1867
1868 ret = def->issue(req, issue_flags);
1869
1870 if (!def->audit_skip)
1871 audit_uring_exit(!ret, ret);
1872
1873 if (unlikely(creds || link)) {
1874 if (creds)
1875 revert_creds(creds);
1876 if (link)
1877 io_queue_linked_timeout(link);
1878 }
1879
1880 if (ret == IOU_OK) {
1881 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1882 io_req_complete_defer(req);
1883 else
1884 io_req_complete_post(req, issue_flags);
1885
1886 return 0;
1887 }
1888
1889 if (ret != IOU_ISSUE_SKIP_COMPLETE)
1890 return ret;
1891
1892 /* If the op doesn't have a file, we're not polling for it */
1893 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
1894 io_iopoll_req_issued(req, issue_flags);
1895
1896 return 0;
1897 }
1898
io_poll_issue(struct io_kiocb * req,struct io_tw_state * ts)1899 int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
1900 {
1901 io_tw_lock(req->ctx, ts);
1902 return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
1903 IO_URING_F_COMPLETE_DEFER);
1904 }
1905
io_wq_free_work(struct io_wq_work * work)1906 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
1907 {
1908 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1909 struct io_kiocb *nxt = NULL;
1910
1911 if (req_ref_put_and_test_atomic(req)) {
1912 if (req->flags & IO_REQ_LINK_FLAGS)
1913 nxt = io_req_find_next(req);
1914 io_free_req(req);
1915 }
1916 return nxt ? &nxt->work : NULL;
1917 }
1918
io_wq_submit_work(struct io_wq_work * work)1919 void io_wq_submit_work(struct io_wq_work *work)
1920 {
1921 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1922 const struct io_issue_def *def = &io_issue_defs[req->opcode];
1923 unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
1924 bool needs_poll = false;
1925 int ret = 0, err = -ECANCELED;
1926
1927 /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
1928 if (!(req->flags & REQ_F_REFCOUNT))
1929 __io_req_set_refcount(req, 2);
1930 else
1931 req_ref_get(req);
1932
1933 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
1934 if (work->flags & IO_WQ_WORK_CANCEL) {
1935 fail:
1936 io_req_task_queue_fail(req, err);
1937 return;
1938 }
1939 if (!io_assign_file(req, def, issue_flags)) {
1940 err = -EBADF;
1941 work->flags |= IO_WQ_WORK_CANCEL;
1942 goto fail;
1943 }
1944
1945 if (req->flags & REQ_F_FORCE_ASYNC) {
1946 bool opcode_poll = def->pollin || def->pollout;
1947
1948 if (opcode_poll && io_file_can_poll(req)) {
1949 needs_poll = true;
1950 issue_flags |= IO_URING_F_NONBLOCK;
1951 }
1952 }
1953
1954 do {
1955 ret = io_issue_sqe(req, issue_flags);
1956 if (ret != -EAGAIN)
1957 break;
1958
1959 /*
1960 * If REQ_F_NOWAIT is set, then don't wait or retry with
1961 * poll. -EAGAIN is final for that case.
1962 */
1963 if (req->flags & REQ_F_NOWAIT)
1964 break;
1965
1966 /*
1967 * We can get EAGAIN for iopolled IO even though we're
1968 * forcing a sync submission from here, since we can't
1969 * wait for request slots on the block side.
1970 */
1971 if (!needs_poll) {
1972 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
1973 break;
1974 if (io_wq_worker_stopped())
1975 break;
1976 cond_resched();
1977 continue;
1978 }
1979
1980 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
1981 return;
1982 /* aborted or ready, in either case retry blocking */
1983 needs_poll = false;
1984 issue_flags &= ~IO_URING_F_NONBLOCK;
1985 } while (1);
1986
1987 /* avoid locking problems by failing it from a clean context */
1988 if (ret < 0)
1989 io_req_task_queue_fail(req, ret);
1990 }
1991
io_file_get_fixed(struct io_kiocb * req,int fd,unsigned int issue_flags)1992 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1993 unsigned int issue_flags)
1994 {
1995 struct io_ring_ctx *ctx = req->ctx;
1996 struct io_fixed_file *slot;
1997 struct file *file = NULL;
1998
1999 io_ring_submit_lock(ctx, issue_flags);
2000
2001 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
2002 goto out;
2003 fd = array_index_nospec(fd, ctx->nr_user_files);
2004 slot = io_fixed_file_slot(&ctx->file_table, fd);
2005 file = io_slot_file(slot);
2006 req->flags |= io_slot_flags(slot);
2007 io_req_set_rsrc_node(req, ctx, 0);
2008 out:
2009 io_ring_submit_unlock(ctx, issue_flags);
2010 return file;
2011 }
2012
io_file_get_normal(struct io_kiocb * req,int fd)2013 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
2014 {
2015 struct file *file = fget(fd);
2016
2017 trace_io_uring_file_get(req, fd);
2018
2019 /* we don't allow fixed io_uring files */
2020 if (file && io_is_uring_fops(file))
2021 io_req_track_inflight(req);
2022 return file;
2023 }
2024
io_queue_async(struct io_kiocb * req,int ret)2025 static void io_queue_async(struct io_kiocb *req, int ret)
2026 __must_hold(&req->ctx->uring_lock)
2027 {
2028 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
2029 io_req_defer_failed(req, ret);
2030 return;
2031 }
2032
2033 switch (io_arm_poll_handler(req, 0)) {
2034 case IO_APOLL_READY:
2035 io_kbuf_recycle(req, 0);
2036 io_req_task_queue(req);
2037 break;
2038 case IO_APOLL_ABORTED:
2039 io_kbuf_recycle(req, 0);
2040 io_queue_iowq(req);
2041 break;
2042 case IO_APOLL_OK:
2043 break;
2044 }
2045 }
2046
io_queue_sqe(struct io_kiocb * req)2047 static inline void io_queue_sqe(struct io_kiocb *req)
2048 __must_hold(&req->ctx->uring_lock)
2049 {
2050 int ret;
2051
2052 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
2053
2054 /*
2055 * We async punt it if the file wasn't marked NOWAIT, or if the file
2056 * doesn't support non-blocking read/write attempts
2057 */
2058 if (unlikely(ret))
2059 io_queue_async(req, ret);
2060 }
2061
io_queue_sqe_fallback(struct io_kiocb * req)2062 static void io_queue_sqe_fallback(struct io_kiocb *req)
2063 __must_hold(&req->ctx->uring_lock)
2064 {
2065 if (unlikely(req->flags & REQ_F_FAIL)) {
2066 /*
2067 * We don't submit, fail them all, for that replace hardlinks
2068 * with normal links. Extra REQ_F_LINK is tolerated.
2069 */
2070 req->flags &= ~REQ_F_HARDLINK;
2071 req->flags |= REQ_F_LINK;
2072 io_req_defer_failed(req, req->cqe.res);
2073 } else {
2074 int ret = io_req_prep_async(req);
2075
2076 if (unlikely(ret)) {
2077 io_req_defer_failed(req, ret);
2078 return;
2079 }
2080
2081 if (unlikely(req->ctx->drain_active))
2082 io_drain_req(req);
2083 else
2084 io_queue_iowq(req);
2085 }
2086 }
2087
2088 /*
2089 * Check SQE restrictions (opcode and flags).
2090 *
2091 * Returns 'true' if SQE is allowed, 'false' otherwise.
2092 */
io_check_restriction(struct io_ring_ctx * ctx,struct io_kiocb * req,unsigned int sqe_flags)2093 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
2094 struct io_kiocb *req,
2095 unsigned int sqe_flags)
2096 {
2097 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
2098 return false;
2099
2100 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
2101 ctx->restrictions.sqe_flags_required)
2102 return false;
2103
2104 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
2105 ctx->restrictions.sqe_flags_required))
2106 return false;
2107
2108 return true;
2109 }
2110
io_init_req_drain(struct io_kiocb * req)2111 static void io_init_req_drain(struct io_kiocb *req)
2112 {
2113 struct io_ring_ctx *ctx = req->ctx;
2114 struct io_kiocb *head = ctx->submit_state.link.head;
2115
2116 ctx->drain_active = true;
2117 if (head) {
2118 /*
2119 * If we need to drain a request in the middle of a link, drain
2120 * the head request and the next request/link after the current
2121 * link. Considering sequential execution of links,
2122 * REQ_F_IO_DRAIN will be maintained for every request of our
2123 * link.
2124 */
2125 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2126 ctx->drain_next = true;
2127 }
2128 }
2129
io_init_fail_req(struct io_kiocb * req,int err)2130 static __cold int io_init_fail_req(struct io_kiocb *req, int err)
2131 {
2132 /* ensure per-opcode data is cleared if we fail before prep */
2133 memset(&req->cmd.data, 0, sizeof(req->cmd.data));
2134 return err;
2135 }
2136
io_init_req(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2137 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
2138 const struct io_uring_sqe *sqe)
2139 __must_hold(&ctx->uring_lock)
2140 {
2141 const struct io_issue_def *def;
2142 unsigned int sqe_flags;
2143 int personality;
2144 u8 opcode;
2145
2146 /* req is partially pre-initialised, see io_preinit_req() */
2147 req->opcode = opcode = READ_ONCE(sqe->opcode);
2148 /* same numerical values with corresponding REQ_F_*, safe to copy */
2149 req->flags = sqe_flags = READ_ONCE(sqe->flags);
2150 req->cqe.user_data = READ_ONCE(sqe->user_data);
2151 req->file = NULL;
2152 req->rsrc_node = NULL;
2153 req->task = current;
2154
2155 if (unlikely(opcode >= IORING_OP_LAST)) {
2156 req->opcode = 0;
2157 return io_init_fail_req(req, -EINVAL);
2158 }
2159 opcode = array_index_nospec(opcode, IORING_OP_LAST);
2160
2161 def = &io_issue_defs[opcode];
2162 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
2163 /* enforce forwards compatibility on users */
2164 if (sqe_flags & ~SQE_VALID_FLAGS)
2165 return io_init_fail_req(req, -EINVAL);
2166 if (sqe_flags & IOSQE_BUFFER_SELECT) {
2167 if (!def->buffer_select)
2168 return io_init_fail_req(req, -EOPNOTSUPP);
2169 req->buf_index = READ_ONCE(sqe->buf_group);
2170 }
2171 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
2172 ctx->drain_disabled = true;
2173 if (sqe_flags & IOSQE_IO_DRAIN) {
2174 if (ctx->drain_disabled)
2175 return io_init_fail_req(req, -EOPNOTSUPP);
2176 io_init_req_drain(req);
2177 }
2178 }
2179 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
2180 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
2181 return io_init_fail_req(req, -EACCES);
2182 /* knock it to the slow queue path, will be drained there */
2183 if (ctx->drain_active)
2184 req->flags |= REQ_F_FORCE_ASYNC;
2185 /* if there is no link, we're at "next" request and need to drain */
2186 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
2187 ctx->drain_next = false;
2188 ctx->drain_active = true;
2189 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2190 }
2191 }
2192
2193 if (!def->ioprio && sqe->ioprio)
2194 return io_init_fail_req(req, -EINVAL);
2195 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
2196 return io_init_fail_req(req, -EINVAL);
2197
2198 if (def->needs_file) {
2199 struct io_submit_state *state = &ctx->submit_state;
2200
2201 req->cqe.fd = READ_ONCE(sqe->fd);
2202
2203 /*
2204 * Plug now if we have more than 2 IO left after this, and the
2205 * target is potentially a read/write to block based storage.
2206 */
2207 if (state->need_plug && def->plug) {
2208 state->plug_started = true;
2209 state->need_plug = false;
2210 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
2211 }
2212 }
2213
2214 personality = READ_ONCE(sqe->personality);
2215 if (personality) {
2216 int ret;
2217
2218 req->creds = xa_load(&ctx->personalities, personality);
2219 if (!req->creds)
2220 return io_init_fail_req(req, -EINVAL);
2221 get_cred(req->creds);
2222 ret = security_uring_override_creds(req->creds);
2223 if (ret) {
2224 put_cred(req->creds);
2225 return io_init_fail_req(req, ret);
2226 }
2227 req->flags |= REQ_F_CREDS;
2228 }
2229
2230 return def->prep(req, sqe);
2231 }
2232
io_submit_fail_init(const struct io_uring_sqe * sqe,struct io_kiocb * req,int ret)2233 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
2234 struct io_kiocb *req, int ret)
2235 {
2236 struct io_ring_ctx *ctx = req->ctx;
2237 struct io_submit_link *link = &ctx->submit_state.link;
2238 struct io_kiocb *head = link->head;
2239
2240 trace_io_uring_req_failed(sqe, req, ret);
2241
2242 /*
2243 * Avoid breaking links in the middle as it renders links with SQPOLL
2244 * unusable. Instead of failing eagerly, continue assembling the link if
2245 * applicable and mark the head with REQ_F_FAIL. The link flushing code
2246 * should find the flag and handle the rest.
2247 */
2248 req_fail_link_node(req, ret);
2249 if (head && !(head->flags & REQ_F_FAIL))
2250 req_fail_link_node(head, -ECANCELED);
2251
2252 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
2253 if (head) {
2254 link->last->link = req;
2255 link->head = NULL;
2256 req = head;
2257 }
2258 io_queue_sqe_fallback(req);
2259 return ret;
2260 }
2261
2262 if (head)
2263 link->last->link = req;
2264 else
2265 link->head = req;
2266 link->last = req;
2267 return 0;
2268 }
2269
io_submit_sqe(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)2270 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2271 const struct io_uring_sqe *sqe)
2272 __must_hold(&ctx->uring_lock)
2273 {
2274 struct io_submit_link *link = &ctx->submit_state.link;
2275 int ret;
2276
2277 ret = io_init_req(ctx, req, sqe);
2278 if (unlikely(ret))
2279 return io_submit_fail_init(sqe, req, ret);
2280
2281 trace_io_uring_submit_req(req);
2282
2283 /*
2284 * If we already have a head request, queue this one for async
2285 * submittal once the head completes. If we don't have a head but
2286 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2287 * submitted sync once the chain is complete. If none of those
2288 * conditions are true (normal request), then just queue it.
2289 */
2290 if (unlikely(link->head)) {
2291 ret = io_req_prep_async(req);
2292 if (unlikely(ret))
2293 return io_submit_fail_init(sqe, req, ret);
2294
2295 trace_io_uring_link(req, link->head);
2296 link->last->link = req;
2297 link->last = req;
2298
2299 if (req->flags & IO_REQ_LINK_FLAGS)
2300 return 0;
2301 /* last request of the link, flush it */
2302 req = link->head;
2303 link->head = NULL;
2304 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
2305 goto fallback;
2306
2307 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
2308 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
2309 if (req->flags & IO_REQ_LINK_FLAGS) {
2310 link->head = req;
2311 link->last = req;
2312 } else {
2313 fallback:
2314 io_queue_sqe_fallback(req);
2315 }
2316 return 0;
2317 }
2318
2319 io_queue_sqe(req);
2320 return 0;
2321 }
2322
2323 /*
2324 * Batched submission is done, ensure local IO is flushed out.
2325 */
io_submit_state_end(struct io_ring_ctx * ctx)2326 static void io_submit_state_end(struct io_ring_ctx *ctx)
2327 {
2328 struct io_submit_state *state = &ctx->submit_state;
2329
2330 if (unlikely(state->link.head))
2331 io_queue_sqe_fallback(state->link.head);
2332 /* flush only after queuing links as they can generate completions */
2333 io_submit_flush_completions(ctx);
2334 if (state->plug_started)
2335 blk_finish_plug(&state->plug);
2336 }
2337
2338 /*
2339 * Start submission side cache.
2340 */
io_submit_state_start(struct io_submit_state * state,unsigned int max_ios)2341 static void io_submit_state_start(struct io_submit_state *state,
2342 unsigned int max_ios)
2343 {
2344 state->plug_started = false;
2345 state->need_plug = max_ios > 2;
2346 state->submit_nr = max_ios;
2347 /* set only head, no need to init link_last in advance */
2348 state->link.head = NULL;
2349 }
2350
io_commit_sqring(struct io_ring_ctx * ctx)2351 static void io_commit_sqring(struct io_ring_ctx *ctx)
2352 {
2353 struct io_rings *rings = ctx->rings;
2354
2355 /*
2356 * Ensure any loads from the SQEs are done at this point,
2357 * since once we write the new head, the application could
2358 * write new data to them.
2359 */
2360 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2361 }
2362
2363 /*
2364 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2365 * that is mapped by userspace. This means that care needs to be taken to
2366 * ensure that reads are stable, as we cannot rely on userspace always
2367 * being a good citizen. If members of the sqe are validated and then later
2368 * used, it's important that those reads are done through READ_ONCE() to
2369 * prevent a re-load down the line.
2370 */
io_get_sqe(struct io_ring_ctx * ctx,const struct io_uring_sqe ** sqe)2371 static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
2372 {
2373 unsigned mask = ctx->sq_entries - 1;
2374 unsigned head = ctx->cached_sq_head++ & mask;
2375
2376 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
2377 head = READ_ONCE(ctx->sq_array[head]);
2378 if (unlikely(head >= ctx->sq_entries)) {
2379 /* drop invalid entries */
2380 spin_lock(&ctx->completion_lock);
2381 ctx->cq_extra--;
2382 spin_unlock(&ctx->completion_lock);
2383 WRITE_ONCE(ctx->rings->sq_dropped,
2384 READ_ONCE(ctx->rings->sq_dropped) + 1);
2385 return false;
2386 }
2387 }
2388
2389 /*
2390 * The cached sq head (or cq tail) serves two purposes:
2391 *
2392 * 1) allows us to batch the cost of updating the user visible
2393 * head updates.
2394 * 2) allows the kernel side to track the head on its own, even
2395 * though the application is the one updating it.
2396 */
2397
2398 /* double index for 128-byte SQEs, twice as long */
2399 if (ctx->flags & IORING_SETUP_SQE128)
2400 head <<= 1;
2401 *sqe = &ctx->sq_sqes[head];
2402 return true;
2403 }
2404
io_submit_sqes(struct io_ring_ctx * ctx,unsigned int nr)2405 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2406 __must_hold(&ctx->uring_lock)
2407 {
2408 unsigned int entries = io_sqring_entries(ctx);
2409 unsigned int left;
2410 int ret;
2411
2412 if (unlikely(!entries))
2413 return 0;
2414 /* make sure SQ entry isn't read before tail */
2415 ret = left = min(nr, entries);
2416 io_get_task_refs(left);
2417 io_submit_state_start(&ctx->submit_state, left);
2418
2419 do {
2420 const struct io_uring_sqe *sqe;
2421 struct io_kiocb *req;
2422
2423 if (unlikely(!io_alloc_req(ctx, &req)))
2424 break;
2425 if (unlikely(!io_get_sqe(ctx, &sqe))) {
2426 io_req_add_to_cache(req, ctx);
2427 break;
2428 }
2429
2430 /*
2431 * Continue submitting even for sqe failure if the
2432 * ring was setup with IORING_SETUP_SUBMIT_ALL
2433 */
2434 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
2435 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
2436 left--;
2437 break;
2438 }
2439 } while (--left);
2440
2441 if (unlikely(left)) {
2442 ret -= left;
2443 /* try again if it submitted nothing and can't allocate a req */
2444 if (!ret && io_req_cache_empty(ctx))
2445 ret = -EAGAIN;
2446 current->io_uring->cached_refs += left;
2447 }
2448
2449 io_submit_state_end(ctx);
2450 /* Commit SQ ring head once we've consumed and submitted all SQEs */
2451 io_commit_sqring(ctx);
2452 return ret;
2453 }
2454
2455 struct io_wait_queue {
2456 struct wait_queue_entry wq;
2457 struct io_ring_ctx *ctx;
2458 unsigned cq_tail;
2459 unsigned nr_timeouts;
2460 ktime_t timeout;
2461 };
2462
io_has_work(struct io_ring_ctx * ctx)2463 static inline bool io_has_work(struct io_ring_ctx *ctx)
2464 {
2465 return test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq) ||
2466 !llist_empty(&ctx->work_llist);
2467 }
2468
io_should_wake(struct io_wait_queue * iowq)2469 static inline bool io_should_wake(struct io_wait_queue *iowq)
2470 {
2471 struct io_ring_ctx *ctx = iowq->ctx;
2472 int dist = READ_ONCE(ctx->rings->cq.tail) - (int) iowq->cq_tail;
2473
2474 /*
2475 * Wake up if we have enough events, or if a timeout occurred since we
2476 * started waiting. For timeouts, we always want to return to userspace,
2477 * regardless of event count.
2478 */
2479 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2480 }
2481
io_wake_function(struct wait_queue_entry * curr,unsigned int mode,int wake_flags,void * key)2482 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2483 int wake_flags, void *key)
2484 {
2485 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
2486
2487 /*
2488 * Cannot safely flush overflowed CQEs from here, ensure we wake up
2489 * the task, and the next invocation will do it.
2490 */
2491 if (io_should_wake(iowq) || io_has_work(iowq->ctx))
2492 return autoremove_wake_function(curr, mode, wake_flags, key);
2493 return -1;
2494 }
2495
io_run_task_work_sig(struct io_ring_ctx * ctx)2496 int io_run_task_work_sig(struct io_ring_ctx *ctx)
2497 {
2498 if (!llist_empty(&ctx->work_llist)) {
2499 __set_current_state(TASK_RUNNING);
2500 if (io_run_local_work(ctx, INT_MAX) > 0)
2501 return 0;
2502 }
2503 if (io_run_task_work() > 0)
2504 return 0;
2505 if (task_sigpending(current))
2506 return -EINTR;
2507 return 0;
2508 }
2509
current_pending_io(void)2510 static bool current_pending_io(void)
2511 {
2512 struct io_uring_task *tctx = current->io_uring;
2513
2514 if (!tctx)
2515 return false;
2516 return percpu_counter_read_positive(&tctx->inflight);
2517 }
2518
2519 /* when returns >0, the caller should retry */
io_cqring_wait_schedule(struct io_ring_ctx * ctx,struct io_wait_queue * iowq)2520 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
2521 struct io_wait_queue *iowq)
2522 {
2523 int ret;
2524
2525 if (unlikely(READ_ONCE(ctx->check_cq)))
2526 return 1;
2527 if (unlikely(!llist_empty(&ctx->work_llist)))
2528 return 1;
2529 if (unlikely(task_work_pending(current)))
2530 return 1;
2531 if (unlikely(task_sigpending(current)))
2532 return -EINTR;
2533 if (unlikely(io_should_wake(iowq)))
2534 return 0;
2535
2536 /*
2537 * Mark us as being in io_wait if we have pending requests, so cpufreq
2538 * can take into account that the task is waiting for IO - turns out
2539 * to be important for low QD IO.
2540 */
2541 if (current_pending_io())
2542 current->in_iowait = 1;
2543 ret = 0;
2544 if (iowq->timeout == KTIME_MAX)
2545 schedule();
2546 else if (!schedule_hrtimeout(&iowq->timeout, HRTIMER_MODE_ABS))
2547 ret = -ETIME;
2548 current->in_iowait = 0;
2549 return ret;
2550 }
2551
2552 /*
2553 * Wait until events become available, if we don't already have some. The
2554 * application must reap them itself, as they reside on the shared cq ring.
2555 */
io_cqring_wait(struct io_ring_ctx * ctx,int min_events,const sigset_t __user * sig,size_t sigsz,struct __kernel_timespec __user * uts)2556 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
2557 const sigset_t __user *sig, size_t sigsz,
2558 struct __kernel_timespec __user *uts)
2559 {
2560 struct io_wait_queue iowq;
2561 struct io_rings *rings = ctx->rings;
2562 int ret;
2563
2564 if (!io_allowed_run_tw(ctx))
2565 return -EEXIST;
2566 if (!llist_empty(&ctx->work_llist))
2567 io_run_local_work(ctx, min_events);
2568 io_run_task_work();
2569 io_cqring_overflow_flush(ctx);
2570 /* if user messes with these they will just get an early return */
2571 if (__io_cqring_events_user(ctx) >= min_events)
2572 return 0;
2573
2574 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
2575 iowq.wq.private = current;
2576 INIT_LIST_HEAD(&iowq.wq.entry);
2577 iowq.ctx = ctx;
2578 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
2579 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
2580 iowq.timeout = KTIME_MAX;
2581
2582 if (uts) {
2583 struct timespec64 ts;
2584
2585 if (get_timespec64(&ts, uts))
2586 return -EFAULT;
2587 iowq.timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
2588 }
2589
2590 if (sig) {
2591 #ifdef CONFIG_COMPAT
2592 if (in_compat_syscall())
2593 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
2594 sigsz);
2595 else
2596 #endif
2597 ret = set_user_sigmask(sig, sigsz);
2598
2599 if (ret)
2600 return ret;
2601 }
2602
2603 trace_io_uring_cqring_wait(ctx, min_events);
2604 do {
2605 int nr_wait = (int) iowq.cq_tail - READ_ONCE(ctx->rings->cq.tail);
2606 unsigned long check_cq;
2607
2608 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
2609 atomic_set(&ctx->cq_wait_nr, nr_wait);
2610 set_current_state(TASK_INTERRUPTIBLE);
2611 } else {
2612 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
2613 TASK_INTERRUPTIBLE);
2614 }
2615
2616 ret = io_cqring_wait_schedule(ctx, &iowq);
2617 __set_current_state(TASK_RUNNING);
2618 atomic_set(&ctx->cq_wait_nr, 0);
2619
2620 /*
2621 * Run task_work after scheduling and before io_should_wake().
2622 * If we got woken because of task_work being processed, run it
2623 * now rather than let the caller do another wait loop.
2624 */
2625 if (!llist_empty(&ctx->work_llist))
2626 io_run_local_work(ctx, nr_wait);
2627 io_run_task_work();
2628
2629 /*
2630 * Non-local task_work will be run on exit to userspace, but
2631 * if we're using DEFER_TASKRUN, then we could have waited
2632 * with a timeout for a number of requests. If the timeout
2633 * hits, we could have some requests ready to process. Ensure
2634 * this break is _after_ we have run task_work, to avoid
2635 * deferring running potentially pending requests until the
2636 * next time we wait for events.
2637 */
2638 if (ret < 0)
2639 break;
2640
2641 check_cq = READ_ONCE(ctx->check_cq);
2642 if (unlikely(check_cq)) {
2643 /* let the caller flush overflows, retry */
2644 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2645 io_cqring_do_overflow_flush(ctx);
2646 if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
2647 ret = -EBADR;
2648 break;
2649 }
2650 }
2651
2652 if (io_should_wake(&iowq)) {
2653 ret = 0;
2654 break;
2655 }
2656 cond_resched();
2657 } while (1);
2658
2659 if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
2660 finish_wait(&ctx->cq_wait, &iowq.wq);
2661 restore_saved_sigmask_unless(ret == -EINTR);
2662
2663 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2664 }
2665
io_pages_unmap(void * ptr,struct page *** pages,unsigned short * npages,bool put_pages)2666 void io_pages_unmap(void *ptr, struct page ***pages, unsigned short *npages,
2667 bool put_pages)
2668 {
2669 bool do_vunmap = false;
2670
2671 if (!ptr)
2672 return;
2673
2674 if (put_pages && *npages) {
2675 struct page **to_free = *pages;
2676 int i;
2677
2678 /*
2679 * Only did vmap for the non-compound multiple page case.
2680 * For the compound page, we just need to put the head.
2681 */
2682 if (PageCompound(to_free[0]))
2683 *npages = 1;
2684 else if (*npages > 1)
2685 do_vunmap = true;
2686 for (i = 0; i < *npages; i++)
2687 put_page(to_free[i]);
2688 }
2689 if (do_vunmap)
2690 vunmap(ptr);
2691 kvfree(*pages);
2692 *pages = NULL;
2693 *npages = 0;
2694 }
2695
io_pages_free(struct page *** pages,int npages)2696 static void io_pages_free(struct page ***pages, int npages)
2697 {
2698 struct page **page_array;
2699 int i;
2700
2701 if (!pages)
2702 return;
2703
2704 page_array = *pages;
2705 if (!page_array)
2706 return;
2707
2708 for (i = 0; i < npages; i++)
2709 unpin_user_page(page_array[i]);
2710 kvfree(page_array);
2711 *pages = NULL;
2712 }
2713
io_pin_pages(unsigned long uaddr,unsigned long len,int * npages)2714 struct page **io_pin_pages(unsigned long uaddr, unsigned long len, int *npages)
2715 {
2716 unsigned long start, end, nr_pages;
2717 struct page **pages;
2718 int ret;
2719
2720 end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
2721 start = uaddr >> PAGE_SHIFT;
2722 nr_pages = end - start;
2723 if (WARN_ON_ONCE(!nr_pages))
2724 return ERR_PTR(-EINVAL);
2725
2726 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
2727 if (!pages)
2728 return ERR_PTR(-ENOMEM);
2729
2730 ret = pin_user_pages_fast(uaddr, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
2731 pages);
2732 /* success, mapped all pages */
2733 if (ret == nr_pages) {
2734 *npages = nr_pages;
2735 return pages;
2736 }
2737
2738 /* partial map, or didn't map anything */
2739 if (ret >= 0) {
2740 /* if we did partial map, release any pages we did get */
2741 if (ret)
2742 unpin_user_pages(pages, ret);
2743 ret = -EFAULT;
2744 }
2745 kvfree(pages);
2746 return ERR_PTR(ret);
2747 }
2748
__io_uaddr_map(struct page *** pages,unsigned short * npages,unsigned long uaddr,size_t size)2749 static void *__io_uaddr_map(struct page ***pages, unsigned short *npages,
2750 unsigned long uaddr, size_t size)
2751 {
2752 struct page **page_array;
2753 unsigned int nr_pages;
2754 void *page_addr;
2755
2756 *npages = 0;
2757
2758 if (uaddr & (PAGE_SIZE - 1) || !size)
2759 return ERR_PTR(-EINVAL);
2760
2761 nr_pages = 0;
2762 page_array = io_pin_pages(uaddr, size, &nr_pages);
2763 if (IS_ERR(page_array))
2764 return page_array;
2765
2766 page_addr = vmap(page_array, nr_pages, VM_MAP, PAGE_KERNEL);
2767 if (page_addr) {
2768 *pages = page_array;
2769 *npages = nr_pages;
2770 return page_addr;
2771 }
2772
2773 io_pages_free(&page_array, nr_pages);
2774 return ERR_PTR(-ENOMEM);
2775 }
2776
io_rings_map(struct io_ring_ctx * ctx,unsigned long uaddr,size_t size)2777 static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2778 size_t size)
2779 {
2780 return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
2781 size);
2782 }
2783
io_sqes_map(struct io_ring_ctx * ctx,unsigned long uaddr,size_t size)2784 static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
2785 size_t size)
2786 {
2787 return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
2788 size);
2789 }
2790
io_rings_free(struct io_ring_ctx * ctx)2791 static void io_rings_free(struct io_ring_ctx *ctx)
2792 {
2793 if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
2794 io_pages_unmap(ctx->rings, &ctx->ring_pages, &ctx->n_ring_pages,
2795 true);
2796 io_pages_unmap(ctx->sq_sqes, &ctx->sqe_pages, &ctx->n_sqe_pages,
2797 true);
2798 } else {
2799 io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
2800 ctx->n_ring_pages = 0;
2801 io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
2802 ctx->n_sqe_pages = 0;
2803 vunmap(ctx->rings);
2804 vunmap(ctx->sq_sqes);
2805 }
2806
2807 ctx->rings = NULL;
2808 ctx->sq_sqes = NULL;
2809 }
2810
io_mem_alloc_compound(struct page ** pages,int nr_pages,size_t size,gfp_t gfp)2811 static void *io_mem_alloc_compound(struct page **pages, int nr_pages,
2812 size_t size, gfp_t gfp)
2813 {
2814 struct page *page;
2815 int i, order;
2816
2817 order = get_order(size);
2818 if (order > 10)
2819 return ERR_PTR(-ENOMEM);
2820 else if (order)
2821 gfp |= __GFP_COMP;
2822
2823 page = alloc_pages(gfp, order);
2824 if (!page)
2825 return ERR_PTR(-ENOMEM);
2826
2827 for (i = 0; i < nr_pages; i++)
2828 pages[i] = page + i;
2829
2830 return page_address(page);
2831 }
2832
io_mem_alloc_single(struct page ** pages,int nr_pages,size_t size,gfp_t gfp)2833 static void *io_mem_alloc_single(struct page **pages, int nr_pages, size_t size,
2834 gfp_t gfp)
2835 {
2836 void *ret;
2837 int i;
2838
2839 for (i = 0; i < nr_pages; i++) {
2840 pages[i] = alloc_page(gfp);
2841 if (!pages[i])
2842 goto err;
2843 }
2844
2845 ret = vmap(pages, nr_pages, VM_MAP, PAGE_KERNEL);
2846 if (ret)
2847 return ret;
2848 err:
2849 while (i--)
2850 put_page(pages[i]);
2851 return ERR_PTR(-ENOMEM);
2852 }
2853
io_pages_map(struct page *** out_pages,unsigned short * npages,size_t size)2854 void *io_pages_map(struct page ***out_pages, unsigned short *npages,
2855 size_t size)
2856 {
2857 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN;
2858 struct page **pages;
2859 int nr_pages;
2860 void *ret;
2861
2862 nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2863 pages = kvmalloc_array(nr_pages, sizeof(struct page *), gfp);
2864 if (!pages)
2865 return ERR_PTR(-ENOMEM);
2866
2867 ret = io_mem_alloc_compound(pages, nr_pages, size, gfp);
2868 if (!IS_ERR(ret))
2869 goto done;
2870 if (nr_pages == 1)
2871 goto fail;
2872
2873 ret = io_mem_alloc_single(pages, nr_pages, size, gfp);
2874 if (!IS_ERR(ret)) {
2875 done:
2876 *out_pages = pages;
2877 *npages = nr_pages;
2878 return ret;
2879 }
2880 fail:
2881 kvfree(pages);
2882 *out_pages = NULL;
2883 *npages = 0;
2884 return ret;
2885 }
2886
rings_size(struct io_ring_ctx * ctx,unsigned int sq_entries,unsigned int cq_entries,size_t * sq_offset)2887 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
2888 unsigned int cq_entries, size_t *sq_offset)
2889 {
2890 struct io_rings *rings;
2891 size_t off, sq_array_size;
2892
2893 off = struct_size(rings, cqes, cq_entries);
2894 if (off == SIZE_MAX)
2895 return SIZE_MAX;
2896 if (ctx->flags & IORING_SETUP_CQE32) {
2897 if (check_shl_overflow(off, 1, &off))
2898 return SIZE_MAX;
2899 }
2900
2901 #ifdef CONFIG_SMP
2902 off = ALIGN(off, SMP_CACHE_BYTES);
2903 if (off == 0)
2904 return SIZE_MAX;
2905 #endif
2906
2907 if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
2908 if (sq_offset)
2909 *sq_offset = SIZE_MAX;
2910 return off;
2911 }
2912
2913 if (sq_offset)
2914 *sq_offset = off;
2915
2916 sq_array_size = array_size(sizeof(u32), sq_entries);
2917 if (sq_array_size == SIZE_MAX)
2918 return SIZE_MAX;
2919
2920 if (check_add_overflow(off, sq_array_size, &off))
2921 return SIZE_MAX;
2922
2923 return off;
2924 }
2925
io_eventfd_register(struct io_ring_ctx * ctx,void __user * arg,unsigned int eventfd_async)2926 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
2927 unsigned int eventfd_async)
2928 {
2929 struct io_ev_fd *ev_fd;
2930 __s32 __user *fds = arg;
2931 int fd;
2932
2933 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2934 lockdep_is_held(&ctx->uring_lock));
2935 if (ev_fd)
2936 return -EBUSY;
2937
2938 if (copy_from_user(&fd, fds, sizeof(*fds)))
2939 return -EFAULT;
2940
2941 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
2942 if (!ev_fd)
2943 return -ENOMEM;
2944
2945 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
2946 if (IS_ERR(ev_fd->cq_ev_fd)) {
2947 int ret = PTR_ERR(ev_fd->cq_ev_fd);
2948 kfree(ev_fd);
2949 return ret;
2950 }
2951
2952 spin_lock(&ctx->completion_lock);
2953 ctx->evfd_last_cq_tail = ctx->cached_cq_tail;
2954 spin_unlock(&ctx->completion_lock);
2955
2956 ev_fd->eventfd_async = eventfd_async;
2957 ctx->has_evfd = true;
2958 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
2959 atomic_set(&ev_fd->refs, 1);
2960 atomic_set(&ev_fd->ops, 0);
2961 return 0;
2962 }
2963
io_eventfd_unregister(struct io_ring_ctx * ctx)2964 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
2965 {
2966 struct io_ev_fd *ev_fd;
2967
2968 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
2969 lockdep_is_held(&ctx->uring_lock));
2970 if (ev_fd) {
2971 ctx->has_evfd = false;
2972 rcu_assign_pointer(ctx->io_ev_fd, NULL);
2973 if (!atomic_fetch_or(BIT(IO_EVENTFD_OP_FREE_BIT), &ev_fd->ops))
2974 call_rcu(&ev_fd->rcu, io_eventfd_ops);
2975 return 0;
2976 }
2977
2978 return -ENXIO;
2979 }
2980
io_req_caches_free(struct io_ring_ctx * ctx)2981 static void io_req_caches_free(struct io_ring_ctx *ctx)
2982 {
2983 struct io_kiocb *req;
2984 int nr = 0;
2985
2986 mutex_lock(&ctx->uring_lock);
2987 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2988
2989 while (!io_req_cache_empty(ctx)) {
2990 req = io_extract_req(ctx);
2991 kmem_cache_free(req_cachep, req);
2992 nr++;
2993 }
2994 if (nr)
2995 percpu_ref_put_many(&ctx->refs, nr);
2996 mutex_unlock(&ctx->uring_lock);
2997 }
2998
io_rsrc_node_cache_free(struct io_cache_entry * entry)2999 static void io_rsrc_node_cache_free(struct io_cache_entry *entry)
3000 {
3001 kfree(container_of(entry, struct io_rsrc_node, cache));
3002 }
3003
io_ring_ctx_free(struct io_ring_ctx * ctx)3004 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
3005 {
3006 io_sq_thread_finish(ctx);
3007 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
3008 if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
3009 return;
3010
3011 mutex_lock(&ctx->uring_lock);
3012 if (ctx->buf_data)
3013 __io_sqe_buffers_unregister(ctx);
3014 if (ctx->file_data)
3015 __io_sqe_files_unregister(ctx);
3016 io_cqring_overflow_kill(ctx);
3017 io_eventfd_unregister(ctx);
3018 io_alloc_cache_free(&ctx->apoll_cache, io_apoll_cache_free);
3019 io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
3020 io_destroy_buffers(ctx);
3021 mutex_unlock(&ctx->uring_lock);
3022 if (ctx->sq_creds)
3023 put_cred(ctx->sq_creds);
3024 if (ctx->submitter_task)
3025 put_task_struct(ctx->submitter_task);
3026
3027 /* there are no registered resources left, nobody uses it */
3028 if (ctx->rsrc_node)
3029 io_rsrc_node_destroy(ctx, ctx->rsrc_node);
3030
3031 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
3032 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
3033
3034 io_alloc_cache_free(&ctx->rsrc_node_cache, io_rsrc_node_cache_free);
3035 if (ctx->mm_account) {
3036 mmdrop(ctx->mm_account);
3037 ctx->mm_account = NULL;
3038 }
3039 io_rings_free(ctx);
3040
3041 percpu_ref_exit(&ctx->refs);
3042 free_uid(ctx->user);
3043 io_req_caches_free(ctx);
3044 if (ctx->hash_map)
3045 io_wq_put_hash(ctx->hash_map);
3046 kfree(ctx->cancel_table.hbs);
3047 kfree(ctx->cancel_table_locked.hbs);
3048 xa_destroy(&ctx->io_bl_xa);
3049 kfree(ctx);
3050 }
3051
io_activate_pollwq_cb(struct callback_head * cb)3052 static __cold void io_activate_pollwq_cb(struct callback_head *cb)
3053 {
3054 struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
3055 poll_wq_task_work);
3056
3057 mutex_lock(&ctx->uring_lock);
3058 ctx->poll_activated = true;
3059 mutex_unlock(&ctx->uring_lock);
3060
3061 /*
3062 * Wake ups for some events between start of polling and activation
3063 * might've been lost due to loose synchronisation.
3064 */
3065 wake_up_all(&ctx->poll_wq);
3066 percpu_ref_put(&ctx->refs);
3067 }
3068
io_activate_pollwq(struct io_ring_ctx * ctx)3069 static __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
3070 {
3071 spin_lock(&ctx->completion_lock);
3072 /* already activated or in progress */
3073 if (ctx->poll_activated || ctx->poll_wq_task_work.func)
3074 goto out;
3075 if (WARN_ON_ONCE(!ctx->task_complete))
3076 goto out;
3077 if (!ctx->submitter_task)
3078 goto out;
3079 /*
3080 * with ->submitter_task only the submitter task completes requests, we
3081 * only need to sync with it, which is done by injecting a tw
3082 */
3083 init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
3084 percpu_ref_get(&ctx->refs);
3085 if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
3086 percpu_ref_put(&ctx->refs);
3087 out:
3088 spin_unlock(&ctx->completion_lock);
3089 }
3090
io_uring_poll(struct file * file,poll_table * wait)3091 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3092 {
3093 struct io_ring_ctx *ctx = file->private_data;
3094 __poll_t mask = 0;
3095
3096 if (unlikely(!ctx->poll_activated))
3097 io_activate_pollwq(ctx);
3098
3099 poll_wait(file, &ctx->poll_wq, wait);
3100 /*
3101 * synchronizes with barrier from wq_has_sleeper call in
3102 * io_commit_cqring
3103 */
3104 smp_rmb();
3105 if (!io_sqring_full(ctx))
3106 mask |= EPOLLOUT | EPOLLWRNORM;
3107
3108 /*
3109 * Don't flush cqring overflow list here, just do a simple check.
3110 * Otherwise there could possible be ABBA deadlock:
3111 * CPU0 CPU1
3112 * ---- ----
3113 * lock(&ctx->uring_lock);
3114 * lock(&ep->mtx);
3115 * lock(&ctx->uring_lock);
3116 * lock(&ep->mtx);
3117 *
3118 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
3119 * pushes them to do the flush.
3120 */
3121
3122 if (__io_cqring_events_user(ctx) || io_has_work(ctx))
3123 mask |= EPOLLIN | EPOLLRDNORM;
3124
3125 return mask;
3126 }
3127
io_unregister_personality(struct io_ring_ctx * ctx,unsigned id)3128 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
3129 {
3130 const struct cred *creds;
3131
3132 creds = xa_erase(&ctx->personalities, id);
3133 if (creds) {
3134 put_cred(creds);
3135 return 0;
3136 }
3137
3138 return -EINVAL;
3139 }
3140
3141 struct io_tctx_exit {
3142 struct callback_head task_work;
3143 struct completion completion;
3144 struct io_ring_ctx *ctx;
3145 };
3146
io_tctx_exit_cb(struct callback_head * cb)3147 static __cold void io_tctx_exit_cb(struct callback_head *cb)
3148 {
3149 struct io_uring_task *tctx = current->io_uring;
3150 struct io_tctx_exit *work;
3151
3152 work = container_of(cb, struct io_tctx_exit, task_work);
3153 /*
3154 * When @in_cancel, we're in cancellation and it's racy to remove the
3155 * node. It'll be removed by the end of cancellation, just ignore it.
3156 * tctx can be NULL if the queueing of this task_work raced with
3157 * work cancelation off the exec path.
3158 */
3159 if (tctx && !atomic_read(&tctx->in_cancel))
3160 io_uring_del_tctx_node((unsigned long)work->ctx);
3161 complete(&work->completion);
3162 }
3163
io_cancel_ctx_cb(struct io_wq_work * work,void * data)3164 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
3165 {
3166 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3167
3168 return req->ctx == data;
3169 }
3170
io_ring_exit_work(struct work_struct * work)3171 static __cold void io_ring_exit_work(struct work_struct *work)
3172 {
3173 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
3174 unsigned long timeout = jiffies + HZ * 60 * 5;
3175 unsigned long interval = HZ / 20;
3176 struct io_tctx_exit exit;
3177 struct io_tctx_node *node;
3178 int ret;
3179
3180 /*
3181 * If we're doing polled IO and end up having requests being
3182 * submitted async (out-of-line), then completions can come in while
3183 * we're waiting for refs to drop. We need to reap these manually,
3184 * as nobody else will be looking for them.
3185 */
3186 do {
3187 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
3188 mutex_lock(&ctx->uring_lock);
3189 io_cqring_overflow_kill(ctx);
3190 mutex_unlock(&ctx->uring_lock);
3191 }
3192
3193 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3194 io_move_task_work_from_local(ctx);
3195
3196 while (io_uring_try_cancel_requests(ctx, NULL, true))
3197 cond_resched();
3198
3199 if (ctx->sq_data) {
3200 struct io_sq_data *sqd = ctx->sq_data;
3201 struct task_struct *tsk;
3202
3203 io_sq_thread_park(sqd);
3204 tsk = sqd->thread;
3205 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
3206 io_wq_cancel_cb(tsk->io_uring->io_wq,
3207 io_cancel_ctx_cb, ctx, true);
3208 io_sq_thread_unpark(sqd);
3209 }
3210
3211 io_req_caches_free(ctx);
3212
3213 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
3214 /* there is little hope left, don't run it too often */
3215 interval = HZ * 60;
3216 }
3217 /*
3218 * This is really an uninterruptible wait, as it has to be
3219 * complete. But it's also run from a kworker, which doesn't
3220 * take signals, so it's fine to make it interruptible. This
3221 * avoids scenarios where we knowingly can wait much longer
3222 * on completions, for example if someone does a SIGSTOP on
3223 * a task that needs to finish task_work to make this loop
3224 * complete. That's a synthetic situation that should not
3225 * cause a stuck task backtrace, and hence a potential panic
3226 * on stuck tasks if that is enabled.
3227 */
3228 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
3229
3230 init_completion(&exit.completion);
3231 init_task_work(&exit.task_work, io_tctx_exit_cb);
3232 exit.ctx = ctx;
3233
3234 mutex_lock(&ctx->uring_lock);
3235 while (!list_empty(&ctx->tctx_list)) {
3236 WARN_ON_ONCE(time_after(jiffies, timeout));
3237
3238 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
3239 ctx_node);
3240 /* don't spin on a single task if cancellation failed */
3241 list_rotate_left(&ctx->tctx_list);
3242 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
3243 if (WARN_ON_ONCE(ret))
3244 continue;
3245
3246 mutex_unlock(&ctx->uring_lock);
3247 /*
3248 * See comment above for
3249 * wait_for_completion_interruptible_timeout() on why this
3250 * wait is marked as interruptible.
3251 */
3252 wait_for_completion_interruptible(&exit.completion);
3253 mutex_lock(&ctx->uring_lock);
3254 }
3255 mutex_unlock(&ctx->uring_lock);
3256 spin_lock(&ctx->completion_lock);
3257 spin_unlock(&ctx->completion_lock);
3258
3259 /* pairs with RCU read section in io_req_local_work_add() */
3260 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3261 synchronize_rcu();
3262
3263 io_ring_ctx_free(ctx);
3264 }
3265
io_ring_ctx_wait_and_kill(struct io_ring_ctx * ctx)3266 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3267 {
3268 unsigned long index;
3269 struct creds *creds;
3270
3271 mutex_lock(&ctx->uring_lock);
3272 percpu_ref_kill(&ctx->refs);
3273 xa_for_each(&ctx->personalities, index, creds)
3274 io_unregister_personality(ctx, index);
3275 if (ctx->rings)
3276 io_poll_remove_all(ctx, NULL, true);
3277 mutex_unlock(&ctx->uring_lock);
3278
3279 /*
3280 * If we failed setting up the ctx, we might not have any rings
3281 * and therefore did not submit any requests
3282 */
3283 if (ctx->rings)
3284 io_kill_timeouts(ctx, NULL, true);
3285
3286 flush_delayed_work(&ctx->fallback_work);
3287
3288 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
3289 /*
3290 * Use system_unbound_wq to avoid spawning tons of event kworkers
3291 * if we're exiting a ton of rings at the same time. It just adds
3292 * noise and overhead, there's no discernable change in runtime
3293 * over using system_wq.
3294 */
3295 queue_work(iou_wq, &ctx->exit_work);
3296 }
3297
io_uring_release(struct inode * inode,struct file * file)3298 static int io_uring_release(struct inode *inode, struct file *file)
3299 {
3300 struct io_ring_ctx *ctx = file->private_data;
3301
3302 file->private_data = NULL;
3303 io_ring_ctx_wait_and_kill(ctx);
3304 return 0;
3305 }
3306
3307 struct io_task_cancel {
3308 struct task_struct *task;
3309 bool all;
3310 };
3311
io_cancel_task_cb(struct io_wq_work * work,void * data)3312 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
3313 {
3314 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3315 struct io_task_cancel *cancel = data;
3316
3317 return io_match_task_safe(req, cancel->task, cancel->all);
3318 }
3319
io_cancel_defer_files(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)3320 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
3321 struct task_struct *task,
3322 bool cancel_all)
3323 {
3324 struct io_defer_entry *de;
3325 LIST_HEAD(list);
3326
3327 spin_lock(&ctx->completion_lock);
3328 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
3329 if (io_match_task_safe(de->req, task, cancel_all)) {
3330 list_cut_position(&list, &ctx->defer_list, &de->list);
3331 break;
3332 }
3333 }
3334 spin_unlock(&ctx->completion_lock);
3335 if (list_empty(&list))
3336 return false;
3337
3338 while (!list_empty(&list)) {
3339 de = list_first_entry(&list, struct io_defer_entry, list);
3340 list_del_init(&de->list);
3341 io_req_task_queue_fail(de->req, -ECANCELED);
3342 kfree(de);
3343 }
3344 return true;
3345 }
3346
io_uring_try_cancel_iowq(struct io_ring_ctx * ctx)3347 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
3348 {
3349 struct io_tctx_node *node;
3350 enum io_wq_cancel cret;
3351 bool ret = false;
3352
3353 mutex_lock(&ctx->uring_lock);
3354 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3355 struct io_uring_task *tctx = node->task->io_uring;
3356
3357 /*
3358 * io_wq will stay alive while we hold uring_lock, because it's
3359 * killed after ctx nodes, which requires to take the lock.
3360 */
3361 if (!tctx || !tctx->io_wq)
3362 continue;
3363 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
3364 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3365 }
3366 mutex_unlock(&ctx->uring_lock);
3367
3368 return ret;
3369 }
3370
io_uring_try_cancel_requests(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)3371 static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
3372 struct task_struct *task,
3373 bool cancel_all)
3374 {
3375 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
3376 struct io_uring_task *tctx = task ? task->io_uring : NULL;
3377 enum io_wq_cancel cret;
3378 bool ret = false;
3379
3380 /* set it so io_req_local_work_add() would wake us up */
3381 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
3382 atomic_set(&ctx->cq_wait_nr, 1);
3383 smp_mb();
3384 }
3385
3386 /* failed during ring init, it couldn't have issued any requests */
3387 if (!ctx->rings)
3388 return false;
3389
3390 if (!task) {
3391 ret |= io_uring_try_cancel_iowq(ctx);
3392 } else if (tctx && tctx->io_wq) {
3393 /*
3394 * Cancels requests of all rings, not only @ctx, but
3395 * it's fine as the task is in exit/exec.
3396 */
3397 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
3398 &cancel, true);
3399 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
3400 }
3401
3402 /* SQPOLL thread does its own polling */
3403 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
3404 (ctx->sq_data && ctx->sq_data->thread == current)) {
3405 while (!wq_list_empty(&ctx->iopoll_list)) {
3406 io_iopoll_try_reap_events(ctx);
3407 ret = true;
3408 cond_resched();
3409 }
3410 }
3411
3412 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3413 io_allowed_defer_tw_run(ctx))
3414 ret |= io_run_local_work(ctx, INT_MAX) > 0;
3415 ret |= io_cancel_defer_files(ctx, task, cancel_all);
3416 mutex_lock(&ctx->uring_lock);
3417 ret |= io_poll_remove_all(ctx, task, cancel_all);
3418 mutex_unlock(&ctx->uring_lock);
3419 ret |= io_kill_timeouts(ctx, task, cancel_all);
3420 if (task)
3421 ret |= io_run_task_work() > 0;
3422 return ret;
3423 }
3424
tctx_inflight(struct io_uring_task * tctx,bool tracked)3425 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
3426 {
3427 if (tracked)
3428 return atomic_read(&tctx->inflight_tracked);
3429 return percpu_counter_sum(&tctx->inflight);
3430 }
3431
3432 /*
3433 * Find any io_uring ctx that this task has registered or done IO on, and cancel
3434 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
3435 */
io_uring_cancel_generic(bool cancel_all,struct io_sq_data * sqd)3436 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
3437 {
3438 struct io_uring_task *tctx = current->io_uring;
3439 struct io_ring_ctx *ctx;
3440 struct io_tctx_node *node;
3441 unsigned long index;
3442 s64 inflight;
3443 DEFINE_WAIT(wait);
3444
3445 WARN_ON_ONCE(sqd && sqd->thread != current);
3446
3447 if (!current->io_uring)
3448 return;
3449 if (tctx->io_wq)
3450 io_wq_exit_start(tctx->io_wq);
3451
3452 atomic_inc(&tctx->in_cancel);
3453 do {
3454 bool loop = false;
3455
3456 io_uring_drop_tctx_refs(current);
3457 if (!tctx_inflight(tctx, !cancel_all))
3458 break;
3459
3460 /* read completions before cancelations */
3461 inflight = tctx_inflight(tctx, false);
3462 if (!inflight)
3463 break;
3464
3465 if (!sqd) {
3466 xa_for_each(&tctx->xa, index, node) {
3467 /* sqpoll task will cancel all its requests */
3468 if (node->ctx->sq_data)
3469 continue;
3470 loop |= io_uring_try_cancel_requests(node->ctx,
3471 current, cancel_all);
3472 }
3473 } else {
3474 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
3475 loop |= io_uring_try_cancel_requests(ctx,
3476 current,
3477 cancel_all);
3478 }
3479
3480 if (loop) {
3481 cond_resched();
3482 continue;
3483 }
3484
3485 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
3486 io_run_task_work();
3487 io_uring_drop_tctx_refs(current);
3488 xa_for_each(&tctx->xa, index, node) {
3489 if (!llist_empty(&node->ctx->work_llist)) {
3490 WARN_ON_ONCE(node->ctx->submitter_task &&
3491 node->ctx->submitter_task != current);
3492 goto end_wait;
3493 }
3494 }
3495 /*
3496 * If we've seen completions, retry without waiting. This
3497 * avoids a race where a completion comes in before we did
3498 * prepare_to_wait().
3499 */
3500 if (inflight == tctx_inflight(tctx, !cancel_all))
3501 schedule();
3502 end_wait:
3503 finish_wait(&tctx->wait, &wait);
3504 } while (1);
3505
3506 io_uring_clean_tctx(tctx);
3507 if (cancel_all) {
3508 /*
3509 * We shouldn't run task_works after cancel, so just leave
3510 * ->in_cancel set for normal exit.
3511 */
3512 atomic_dec(&tctx->in_cancel);
3513 /* for exec all current's requests should be gone, kill tctx */
3514 __io_uring_free(current);
3515 }
3516 }
3517
__io_uring_cancel(bool cancel_all)3518 void __io_uring_cancel(bool cancel_all)
3519 {
3520 io_uring_unreg_ringfd();
3521 io_uring_cancel_generic(cancel_all, NULL);
3522 }
3523
io_uring_validate_mmap_request(struct file * file,loff_t pgoff,size_t sz)3524 static void *io_uring_validate_mmap_request(struct file *file,
3525 loff_t pgoff, size_t sz)
3526 {
3527 struct io_ring_ctx *ctx = file->private_data;
3528 loff_t offset = pgoff << PAGE_SHIFT;
3529
3530 switch ((pgoff << PAGE_SHIFT) & IORING_OFF_MMAP_MASK) {
3531 case IORING_OFF_SQ_RING:
3532 case IORING_OFF_CQ_RING:
3533 /* Don't allow mmap if the ring was setup without it */
3534 if (ctx->flags & IORING_SETUP_NO_MMAP)
3535 return ERR_PTR(-EINVAL);
3536 return ctx->rings;
3537 case IORING_OFF_SQES:
3538 /* Don't allow mmap if the ring was setup without it */
3539 if (ctx->flags & IORING_SETUP_NO_MMAP)
3540 return ERR_PTR(-EINVAL);
3541 return ctx->sq_sqes;
3542 case IORING_OFF_PBUF_RING: {
3543 struct io_buffer_list *bl;
3544 unsigned int bgid;
3545 void *ptr;
3546
3547 bgid = (offset & ~IORING_OFF_MMAP_MASK) >> IORING_OFF_PBUF_SHIFT;
3548 bl = io_pbuf_get_bl(ctx, bgid);
3549 if (IS_ERR(bl))
3550 return bl;
3551 ptr = bl->buf_ring;
3552 io_put_bl(ctx, bl);
3553 return ptr;
3554 }
3555 }
3556
3557 return ERR_PTR(-EINVAL);
3558 }
3559
io_uring_mmap_pages(struct io_ring_ctx * ctx,struct vm_area_struct * vma,struct page ** pages,int npages)3560 int io_uring_mmap_pages(struct io_ring_ctx *ctx, struct vm_area_struct *vma,
3561 struct page **pages, int npages)
3562 {
3563 unsigned long nr_pages = npages;
3564
3565 vm_flags_set(vma, VM_DONTEXPAND);
3566 return vm_insert_pages(vma, vma->vm_start, pages, &nr_pages);
3567 }
3568
3569 #ifdef CONFIG_MMU
3570
io_uring_mmap(struct file * file,struct vm_area_struct * vma)3571 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3572 {
3573 struct io_ring_ctx *ctx = file->private_data;
3574 size_t sz = vma->vm_end - vma->vm_start;
3575 long offset = vma->vm_pgoff << PAGE_SHIFT;
3576 unsigned int npages;
3577 void *ptr;
3578
3579 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
3580 if (IS_ERR(ptr))
3581 return PTR_ERR(ptr);
3582
3583 switch (offset & IORING_OFF_MMAP_MASK) {
3584 case IORING_OFF_SQ_RING:
3585 case IORING_OFF_CQ_RING:
3586 npages = min(ctx->n_ring_pages, (sz + PAGE_SIZE - 1) >> PAGE_SHIFT);
3587 return io_uring_mmap_pages(ctx, vma, ctx->ring_pages, npages);
3588 case IORING_OFF_SQES:
3589 return io_uring_mmap_pages(ctx, vma, ctx->sqe_pages,
3590 ctx->n_sqe_pages);
3591 case IORING_OFF_PBUF_RING:
3592 return io_pbuf_mmap(file, vma);
3593 }
3594
3595 return -EINVAL;
3596 }
3597
io_uring_mmu_get_unmapped_area(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)3598 static unsigned long io_uring_mmu_get_unmapped_area(struct file *filp,
3599 unsigned long addr, unsigned long len,
3600 unsigned long pgoff, unsigned long flags)
3601 {
3602 void *ptr;
3603
3604 /*
3605 * Do not allow to map to user-provided address to avoid breaking the
3606 * aliasing rules. Userspace is not able to guess the offset address of
3607 * kernel kmalloc()ed memory area.
3608 */
3609 if (addr)
3610 return -EINVAL;
3611
3612 ptr = io_uring_validate_mmap_request(filp, pgoff, len);
3613 if (IS_ERR(ptr))
3614 return -ENOMEM;
3615
3616 /*
3617 * Some architectures have strong cache aliasing requirements.
3618 * For such architectures we need a coherent mapping which aliases
3619 * kernel memory *and* userspace memory. To achieve that:
3620 * - use a NULL file pointer to reference physical memory, and
3621 * - use the kernel virtual address of the shared io_uring context
3622 * (instead of the userspace-provided address, which has to be 0UL
3623 * anyway).
3624 * - use the same pgoff which the get_unmapped_area() uses to
3625 * calculate the page colouring.
3626 * For architectures without such aliasing requirements, the
3627 * architecture will return any suitable mapping because addr is 0.
3628 */
3629 filp = NULL;
3630 flags |= MAP_SHARED;
3631 pgoff = 0; /* has been translated to ptr above */
3632 #ifdef SHM_COLOUR
3633 addr = (uintptr_t) ptr;
3634 pgoff = addr >> PAGE_SHIFT;
3635 #else
3636 addr = 0UL;
3637 #endif
3638 return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
3639 }
3640
3641 #else /* !CONFIG_MMU */
3642
io_uring_mmap(struct file * file,struct vm_area_struct * vma)3643 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3644 {
3645 return is_nommu_shared_mapping(vma->vm_flags) ? 0 : -EINVAL;
3646 }
3647
io_uring_nommu_mmap_capabilities(struct file * file)3648 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
3649 {
3650 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
3651 }
3652
io_uring_nommu_get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)3653 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
3654 unsigned long addr, unsigned long len,
3655 unsigned long pgoff, unsigned long flags)
3656 {
3657 void *ptr;
3658
3659 ptr = io_uring_validate_mmap_request(file, pgoff, len);
3660 if (IS_ERR(ptr))
3661 return PTR_ERR(ptr);
3662
3663 return (unsigned long) ptr;
3664 }
3665
3666 #endif /* !CONFIG_MMU */
3667
io_validate_ext_arg(unsigned flags,const void __user * argp,size_t argsz)3668 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
3669 {
3670 if (flags & IORING_ENTER_EXT_ARG) {
3671 struct io_uring_getevents_arg arg;
3672
3673 if (argsz != sizeof(arg))
3674 return -EINVAL;
3675 if (copy_from_user(&arg, argp, sizeof(arg)))
3676 return -EFAULT;
3677 }
3678 return 0;
3679 }
3680
io_get_ext_arg(unsigned flags,const void __user * argp,size_t * argsz,struct __kernel_timespec __user ** ts,const sigset_t __user ** sig)3681 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
3682 struct __kernel_timespec __user **ts,
3683 const sigset_t __user **sig)
3684 {
3685 struct io_uring_getevents_arg arg;
3686
3687 /*
3688 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
3689 * is just a pointer to the sigset_t.
3690 */
3691 if (!(flags & IORING_ENTER_EXT_ARG)) {
3692 *sig = (const sigset_t __user *) argp;
3693 *ts = NULL;
3694 return 0;
3695 }
3696
3697 /*
3698 * EXT_ARG is set - ensure we agree on the size of it and copy in our
3699 * timespec and sigset_t pointers if good.
3700 */
3701 if (*argsz != sizeof(arg))
3702 return -EINVAL;
3703 if (copy_from_user(&arg, argp, sizeof(arg)))
3704 return -EFAULT;
3705 if (arg.pad)
3706 return -EINVAL;
3707 *sig = u64_to_user_ptr(arg.sigmask);
3708 *argsz = arg.sigmask_sz;
3709 *ts = u64_to_user_ptr(arg.ts);
3710 return 0;
3711 }
3712
SYSCALL_DEFINE6(io_uring_enter,unsigned int,fd,u32,to_submit,u32,min_complete,u32,flags,const void __user *,argp,size_t,argsz)3713 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3714 u32, min_complete, u32, flags, const void __user *, argp,
3715 size_t, argsz)
3716 {
3717 struct io_ring_ctx *ctx;
3718 struct file *file;
3719 long ret;
3720
3721 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
3722 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
3723 IORING_ENTER_REGISTERED_RING)))
3724 return -EINVAL;
3725
3726 /*
3727 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
3728 * need only dereference our task private array to find it.
3729 */
3730 if (flags & IORING_ENTER_REGISTERED_RING) {
3731 struct io_uring_task *tctx = current->io_uring;
3732
3733 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
3734 return -EINVAL;
3735 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
3736 file = tctx->registered_rings[fd];
3737 if (unlikely(!file))
3738 return -EBADF;
3739 } else {
3740 file = fget(fd);
3741 if (unlikely(!file))
3742 return -EBADF;
3743 ret = -EOPNOTSUPP;
3744 if (unlikely(!io_is_uring_fops(file)))
3745 goto out;
3746 }
3747
3748 ctx = file->private_data;
3749 ret = -EBADFD;
3750 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
3751 goto out;
3752
3753 /*
3754 * For SQ polling, the thread will do all submissions and completions.
3755 * Just return the requested submit count, and wake the thread if
3756 * we were asked to.
3757 */
3758 ret = 0;
3759 if (ctx->flags & IORING_SETUP_SQPOLL) {
3760 io_cqring_overflow_flush(ctx);
3761
3762 if (unlikely(ctx->sq_data->thread == NULL)) {
3763 ret = -EOWNERDEAD;
3764 goto out;
3765 }
3766 if (flags & IORING_ENTER_SQ_WAKEUP)
3767 wake_up(&ctx->sq_data->wait);
3768 if (flags & IORING_ENTER_SQ_WAIT)
3769 io_sqpoll_wait_sq(ctx);
3770
3771 ret = to_submit;
3772 } else if (to_submit) {
3773 ret = io_uring_add_tctx_node(ctx);
3774 if (unlikely(ret))
3775 goto out;
3776
3777 mutex_lock(&ctx->uring_lock);
3778 ret = io_submit_sqes(ctx, to_submit);
3779 if (ret != to_submit) {
3780 mutex_unlock(&ctx->uring_lock);
3781 goto out;
3782 }
3783 if (flags & IORING_ENTER_GETEVENTS) {
3784 if (ctx->syscall_iopoll)
3785 goto iopoll_locked;
3786 /*
3787 * Ignore errors, we'll soon call io_cqring_wait() and
3788 * it should handle ownership problems if any.
3789 */
3790 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
3791 (void)io_run_local_work_locked(ctx, min_complete);
3792 }
3793 mutex_unlock(&ctx->uring_lock);
3794 }
3795
3796 if (flags & IORING_ENTER_GETEVENTS) {
3797 int ret2;
3798
3799 if (ctx->syscall_iopoll) {
3800 /*
3801 * We disallow the app entering submit/complete with
3802 * polling, but we still need to lock the ring to
3803 * prevent racing with polled issue that got punted to
3804 * a workqueue.
3805 */
3806 mutex_lock(&ctx->uring_lock);
3807 iopoll_locked:
3808 ret2 = io_validate_ext_arg(flags, argp, argsz);
3809 if (likely(!ret2)) {
3810 min_complete = min(min_complete,
3811 ctx->cq_entries);
3812 ret2 = io_iopoll_check(ctx, min_complete);
3813 }
3814 mutex_unlock(&ctx->uring_lock);
3815 } else {
3816 const sigset_t __user *sig;
3817 struct __kernel_timespec __user *ts;
3818
3819 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
3820 if (likely(!ret2)) {
3821 min_complete = min(min_complete,
3822 ctx->cq_entries);
3823 ret2 = io_cqring_wait(ctx, min_complete, sig,
3824 argsz, ts);
3825 }
3826 }
3827
3828 if (!ret) {
3829 ret = ret2;
3830
3831 /*
3832 * EBADR indicates that one or more CQE were dropped.
3833 * Once the user has been informed we can clear the bit
3834 * as they are obviously ok with those drops.
3835 */
3836 if (unlikely(ret2 == -EBADR))
3837 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
3838 &ctx->check_cq);
3839 }
3840 }
3841 out:
3842 if (!(flags & IORING_ENTER_REGISTERED_RING))
3843 fput(file);
3844 return ret;
3845 }
3846
3847 static const struct file_operations io_uring_fops = {
3848 .release = io_uring_release,
3849 .mmap = io_uring_mmap,
3850 #ifndef CONFIG_MMU
3851 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
3852 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
3853 #else
3854 .get_unmapped_area = io_uring_mmu_get_unmapped_area,
3855 #endif
3856 .poll = io_uring_poll,
3857 #ifdef CONFIG_PROC_FS
3858 .show_fdinfo = io_uring_show_fdinfo,
3859 #endif
3860 };
3861
io_is_uring_fops(struct file * file)3862 bool io_is_uring_fops(struct file *file)
3863 {
3864 return file->f_op == &io_uring_fops;
3865 }
3866
io_allocate_scq_urings(struct io_ring_ctx * ctx,struct io_uring_params * p)3867 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3868 struct io_uring_params *p)
3869 {
3870 struct io_rings *rings;
3871 size_t size, sq_array_offset;
3872 void *ptr;
3873
3874 /* make sure these are sane, as we already accounted them */
3875 ctx->sq_entries = p->sq_entries;
3876 ctx->cq_entries = p->cq_entries;
3877
3878 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
3879 if (size == SIZE_MAX)
3880 return -EOVERFLOW;
3881
3882 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3883 rings = io_pages_map(&ctx->ring_pages, &ctx->n_ring_pages, size);
3884 else
3885 rings = io_rings_map(ctx, p->cq_off.user_addr, size);
3886
3887 if (IS_ERR(rings))
3888 return PTR_ERR(rings);
3889
3890 ctx->rings = rings;
3891 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
3892 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3893 rings->sq_ring_mask = p->sq_entries - 1;
3894 rings->cq_ring_mask = p->cq_entries - 1;
3895 rings->sq_ring_entries = p->sq_entries;
3896 rings->cq_ring_entries = p->cq_entries;
3897
3898 if (p->flags & IORING_SETUP_SQE128)
3899 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
3900 else
3901 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3902 if (size == SIZE_MAX) {
3903 io_rings_free(ctx);
3904 return -EOVERFLOW;
3905 }
3906
3907 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
3908 ptr = io_pages_map(&ctx->sqe_pages, &ctx->n_sqe_pages, size);
3909 else
3910 ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
3911
3912 if (IS_ERR(ptr)) {
3913 io_rings_free(ctx);
3914 return PTR_ERR(ptr);
3915 }
3916
3917 ctx->sq_sqes = ptr;
3918 return 0;
3919 }
3920
io_uring_install_fd(struct file * file)3921 static int io_uring_install_fd(struct file *file)
3922 {
3923 int fd;
3924
3925 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3926 if (fd < 0)
3927 return fd;
3928 fd_install(fd, file);
3929 return fd;
3930 }
3931
3932 /*
3933 * Allocate an anonymous fd, this is what constitutes the application
3934 * visible backing of an io_uring instance. The application mmaps this
3935 * fd to gain access to the SQ/CQ ring details.
3936 */
io_uring_get_file(struct io_ring_ctx * ctx)3937 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
3938 {
3939 return anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
3940 O_RDWR | O_CLOEXEC, NULL);
3941 }
3942
io_uring_create(unsigned entries,struct io_uring_params * p,struct io_uring_params __user * params)3943 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
3944 struct io_uring_params __user *params)
3945 {
3946 struct io_ring_ctx *ctx;
3947 struct io_uring_task *tctx;
3948 struct file *file;
3949 int ret;
3950
3951 if (!entries)
3952 return -EINVAL;
3953 if (entries > IORING_MAX_ENTRIES) {
3954 if (!(p->flags & IORING_SETUP_CLAMP))
3955 return -EINVAL;
3956 entries = IORING_MAX_ENTRIES;
3957 }
3958
3959 if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
3960 && !(p->flags & IORING_SETUP_NO_MMAP))
3961 return -EINVAL;
3962
3963 /*
3964 * Use twice as many entries for the CQ ring. It's possible for the
3965 * application to drive a higher depth than the size of the SQ ring,
3966 * since the sqes are only used at submission time. This allows for
3967 * some flexibility in overcommitting a bit. If the application has
3968 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
3969 * of CQ ring entries manually.
3970 */
3971 p->sq_entries = roundup_pow_of_two(entries);
3972 if (p->flags & IORING_SETUP_CQSIZE) {
3973 /*
3974 * If IORING_SETUP_CQSIZE is set, we do the same roundup
3975 * to a power-of-two, if it isn't already. We do NOT impose
3976 * any cq vs sq ring sizing.
3977 */
3978 if (!p->cq_entries)
3979 return -EINVAL;
3980 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
3981 if (!(p->flags & IORING_SETUP_CLAMP))
3982 return -EINVAL;
3983 p->cq_entries = IORING_MAX_CQ_ENTRIES;
3984 }
3985 p->cq_entries = roundup_pow_of_two(p->cq_entries);
3986 if (p->cq_entries < p->sq_entries)
3987 return -EINVAL;
3988 } else {
3989 p->cq_entries = 2 * p->sq_entries;
3990 }
3991
3992 ctx = io_ring_ctx_alloc(p);
3993 if (!ctx)
3994 return -ENOMEM;
3995
3996 if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
3997 !(ctx->flags & IORING_SETUP_IOPOLL) &&
3998 !(ctx->flags & IORING_SETUP_SQPOLL))
3999 ctx->task_complete = true;
4000
4001 if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
4002 ctx->lockless_cq = true;
4003
4004 /*
4005 * lazy poll_wq activation relies on ->task_complete for synchronisation
4006 * purposes, see io_activate_pollwq()
4007 */
4008 if (!ctx->task_complete)
4009 ctx->poll_activated = true;
4010
4011 /*
4012 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
4013 * space applications don't need to do io completion events
4014 * polling again, they can rely on io_sq_thread to do polling
4015 * work, which can reduce cpu usage and uring_lock contention.
4016 */
4017 if (ctx->flags & IORING_SETUP_IOPOLL &&
4018 !(ctx->flags & IORING_SETUP_SQPOLL))
4019 ctx->syscall_iopoll = 1;
4020
4021 ctx->compat = in_compat_syscall();
4022 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
4023 ctx->user = get_uid(current_user());
4024
4025 /*
4026 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
4027 * COOP_TASKRUN is set, then IPIs are never needed by the app.
4028 */
4029 ret = -EINVAL;
4030 if (ctx->flags & IORING_SETUP_SQPOLL) {
4031 /* IPI related flags don't make sense with SQPOLL */
4032 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
4033 IORING_SETUP_TASKRUN_FLAG |
4034 IORING_SETUP_DEFER_TASKRUN))
4035 goto err;
4036 ctx->notify_method = TWA_SIGNAL_NO_IPI;
4037 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
4038 ctx->notify_method = TWA_SIGNAL_NO_IPI;
4039 } else {
4040 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
4041 !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
4042 goto err;
4043 ctx->notify_method = TWA_SIGNAL;
4044 }
4045
4046 /*
4047 * For DEFER_TASKRUN we require the completion task to be the same as the
4048 * submission task. This implies that there is only one submitter, so enforce
4049 * that.
4050 */
4051 if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
4052 !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
4053 goto err;
4054 }
4055
4056 /*
4057 * This is just grabbed for accounting purposes. When a process exits,
4058 * the mm is exited and dropped before the files, hence we need to hang
4059 * on to this mm purely for the purposes of being able to unaccount
4060 * memory (locked/pinned vm). It's not used for anything else.
4061 */
4062 mmgrab(current->mm);
4063 ctx->mm_account = current->mm;
4064
4065 ret = io_allocate_scq_urings(ctx, p);
4066 if (ret)
4067 goto err;
4068
4069 ret = io_sq_offload_create(ctx, p);
4070 if (ret)
4071 goto err;
4072
4073 ret = io_rsrc_init(ctx);
4074 if (ret)
4075 goto err;
4076
4077 p->sq_off.head = offsetof(struct io_rings, sq.head);
4078 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
4079 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
4080 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
4081 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
4082 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
4083 if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
4084 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
4085 p->sq_off.resv1 = 0;
4086 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
4087 p->sq_off.user_addr = 0;
4088
4089 p->cq_off.head = offsetof(struct io_rings, cq.head);
4090 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
4091 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
4092 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
4093 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
4094 p->cq_off.cqes = offsetof(struct io_rings, cqes);
4095 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
4096 p->cq_off.resv1 = 0;
4097 if (!(ctx->flags & IORING_SETUP_NO_MMAP))
4098 p->cq_off.user_addr = 0;
4099
4100 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
4101 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
4102 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
4103 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
4104 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
4105 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
4106 IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING;
4107
4108 if (copy_to_user(params, p, sizeof(*p))) {
4109 ret = -EFAULT;
4110 goto err;
4111 }
4112
4113 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
4114 && !(ctx->flags & IORING_SETUP_R_DISABLED))
4115 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4116
4117 file = io_uring_get_file(ctx);
4118 if (IS_ERR(file)) {
4119 ret = PTR_ERR(file);
4120 goto err;
4121 }
4122
4123 ret = __io_uring_add_tctx_node(ctx);
4124 if (ret)
4125 goto err_fput;
4126 tctx = current->io_uring;
4127
4128 /*
4129 * Install ring fd as the very last thing, so we don't risk someone
4130 * having closed it before we finish setup
4131 */
4132 if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
4133 ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
4134 else
4135 ret = io_uring_install_fd(file);
4136 if (ret < 0)
4137 goto err_fput;
4138
4139 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
4140 return ret;
4141 err:
4142 io_ring_ctx_wait_and_kill(ctx);
4143 return ret;
4144 err_fput:
4145 fput(file);
4146 return ret;
4147 }
4148
4149 /*
4150 * Sets up an aio uring context, and returns the fd. Applications asks for a
4151 * ring size, we return the actual sq/cq ring sizes (among other things) in the
4152 * params structure passed in.
4153 */
io_uring_setup(u32 entries,struct io_uring_params __user * params)4154 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
4155 {
4156 struct io_uring_params p;
4157 int i;
4158
4159 if (copy_from_user(&p, params, sizeof(p)))
4160 return -EFAULT;
4161 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
4162 if (p.resv[i])
4163 return -EINVAL;
4164 }
4165
4166 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
4167 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
4168 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
4169 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
4170 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
4171 IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
4172 IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
4173 IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
4174 IORING_SETUP_NO_SQARRAY))
4175 return -EINVAL;
4176
4177 return io_uring_create(entries, &p, params);
4178 }
4179
io_uring_allowed(void)4180 static inline bool io_uring_allowed(void)
4181 {
4182 int disabled = READ_ONCE(sysctl_io_uring_disabled);
4183 kgid_t io_uring_group;
4184
4185 if (disabled == 2)
4186 return false;
4187
4188 if (disabled == 0 || capable(CAP_SYS_ADMIN))
4189 return true;
4190
4191 io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
4192 if (!gid_valid(io_uring_group))
4193 return false;
4194
4195 return in_group_p(io_uring_group);
4196 }
4197
SYSCALL_DEFINE2(io_uring_setup,u32,entries,struct io_uring_params __user *,params)4198 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
4199 struct io_uring_params __user *, params)
4200 {
4201 if (!io_uring_allowed())
4202 return -EPERM;
4203
4204 return io_uring_setup(entries, params);
4205 }
4206
io_probe(struct io_ring_ctx * ctx,void __user * arg,unsigned nr_args)4207 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
4208 unsigned nr_args)
4209 {
4210 struct io_uring_probe *p;
4211 size_t size;
4212 int i, ret;
4213
4214 size = struct_size(p, ops, nr_args);
4215 if (size == SIZE_MAX)
4216 return -EOVERFLOW;
4217 p = kzalloc(size, GFP_KERNEL);
4218 if (!p)
4219 return -ENOMEM;
4220
4221 ret = -EFAULT;
4222 if (copy_from_user(p, arg, size))
4223 goto out;
4224 ret = -EINVAL;
4225 if (memchr_inv(p, 0, size))
4226 goto out;
4227
4228 p->last_op = IORING_OP_LAST - 1;
4229 if (nr_args > IORING_OP_LAST)
4230 nr_args = IORING_OP_LAST;
4231
4232 for (i = 0; i < nr_args; i++) {
4233 p->ops[i].op = i;
4234 if (!io_issue_defs[i].not_supported)
4235 p->ops[i].flags = IO_URING_OP_SUPPORTED;
4236 }
4237 p->ops_len = i;
4238
4239 ret = 0;
4240 if (copy_to_user(arg, p, size))
4241 ret = -EFAULT;
4242 out:
4243 kfree(p);
4244 return ret;
4245 }
4246
io_register_personality(struct io_ring_ctx * ctx)4247 static int io_register_personality(struct io_ring_ctx *ctx)
4248 {
4249 const struct cred *creds;
4250 u32 id;
4251 int ret;
4252
4253 creds = get_current_cred();
4254
4255 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
4256 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
4257 if (ret < 0) {
4258 put_cred(creds);
4259 return ret;
4260 }
4261 return id;
4262 }
4263
io_register_restrictions(struct io_ring_ctx * ctx,void __user * arg,unsigned int nr_args)4264 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
4265 void __user *arg, unsigned int nr_args)
4266 {
4267 struct io_uring_restriction *res;
4268 size_t size;
4269 int i, ret;
4270
4271 /* Restrictions allowed only if rings started disabled */
4272 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
4273 return -EBADFD;
4274
4275 /* We allow only a single restrictions registration */
4276 if (ctx->restrictions.registered)
4277 return -EBUSY;
4278
4279 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
4280 return -EINVAL;
4281
4282 size = array_size(nr_args, sizeof(*res));
4283 if (size == SIZE_MAX)
4284 return -EOVERFLOW;
4285
4286 res = memdup_user(arg, size);
4287 if (IS_ERR(res))
4288 return PTR_ERR(res);
4289
4290 ret = 0;
4291
4292 for (i = 0; i < nr_args; i++) {
4293 switch (res[i].opcode) {
4294 case IORING_RESTRICTION_REGISTER_OP:
4295 if (res[i].register_op >= IORING_REGISTER_LAST) {
4296 ret = -EINVAL;
4297 goto out;
4298 }
4299
4300 __set_bit(res[i].register_op,
4301 ctx->restrictions.register_op);
4302 break;
4303 case IORING_RESTRICTION_SQE_OP:
4304 if (res[i].sqe_op >= IORING_OP_LAST) {
4305 ret = -EINVAL;
4306 goto out;
4307 }
4308
4309 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
4310 break;
4311 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
4312 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
4313 break;
4314 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
4315 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
4316 break;
4317 default:
4318 ret = -EINVAL;
4319 goto out;
4320 }
4321 }
4322
4323 out:
4324 /* Reset all restrictions if an error happened */
4325 if (ret != 0)
4326 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
4327 else
4328 ctx->restrictions.registered = true;
4329
4330 kfree(res);
4331 return ret;
4332 }
4333
io_register_enable_rings(struct io_ring_ctx * ctx)4334 static int io_register_enable_rings(struct io_ring_ctx *ctx)
4335 {
4336 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
4337 return -EBADFD;
4338
4339 if (ctx->flags & IORING_SETUP_SINGLE_ISSUER && !ctx->submitter_task) {
4340 WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
4341 /*
4342 * Lazy activation attempts would fail if it was polled before
4343 * submitter_task is set.
4344 */
4345 if (wq_has_sleeper(&ctx->poll_wq))
4346 io_activate_pollwq(ctx);
4347 }
4348
4349 if (ctx->restrictions.registered)
4350 ctx->restricted = 1;
4351
4352 ctx->flags &= ~IORING_SETUP_R_DISABLED;
4353 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
4354 wake_up(&ctx->sq_data->wait);
4355 return 0;
4356 }
4357
__io_register_iowq_aff(struct io_ring_ctx * ctx,cpumask_var_t new_mask)4358 static __cold int __io_register_iowq_aff(struct io_ring_ctx *ctx,
4359 cpumask_var_t new_mask)
4360 {
4361 int ret;
4362
4363 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
4364 ret = io_wq_cpu_affinity(current->io_uring, new_mask);
4365 } else {
4366 mutex_unlock(&ctx->uring_lock);
4367 ret = io_sqpoll_wq_cpu_affinity(ctx, new_mask);
4368 mutex_lock(&ctx->uring_lock);
4369 }
4370
4371 return ret;
4372 }
4373
io_register_iowq_aff(struct io_ring_ctx * ctx,void __user * arg,unsigned len)4374 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
4375 void __user *arg, unsigned len)
4376 {
4377 cpumask_var_t new_mask;
4378 int ret;
4379
4380 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4381 return -ENOMEM;
4382
4383 cpumask_clear(new_mask);
4384 if (len > cpumask_size())
4385 len = cpumask_size();
4386
4387 if (in_compat_syscall()) {
4388 ret = compat_get_bitmap(cpumask_bits(new_mask),
4389 (const compat_ulong_t __user *)arg,
4390 len * 8 /* CHAR_BIT */);
4391 } else {
4392 ret = copy_from_user(new_mask, arg, len);
4393 }
4394
4395 if (ret) {
4396 free_cpumask_var(new_mask);
4397 return -EFAULT;
4398 }
4399
4400 ret = __io_register_iowq_aff(ctx, new_mask);
4401 free_cpumask_var(new_mask);
4402 return ret;
4403 }
4404
io_unregister_iowq_aff(struct io_ring_ctx * ctx)4405 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
4406 {
4407 return __io_register_iowq_aff(ctx, NULL);
4408 }
4409
io_register_iowq_max_workers(struct io_ring_ctx * ctx,void __user * arg)4410 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
4411 void __user *arg)
4412 __must_hold(&ctx->uring_lock)
4413 {
4414 struct io_tctx_node *node;
4415 struct io_uring_task *tctx = NULL;
4416 struct io_sq_data *sqd = NULL;
4417 __u32 new_count[2];
4418 int i, ret;
4419
4420 if (copy_from_user(new_count, arg, sizeof(new_count)))
4421 return -EFAULT;
4422 for (i = 0; i < ARRAY_SIZE(new_count); i++)
4423 if (new_count[i] > INT_MAX)
4424 return -EINVAL;
4425
4426 if (ctx->flags & IORING_SETUP_SQPOLL) {
4427 sqd = ctx->sq_data;
4428 if (sqd) {
4429 /*
4430 * Observe the correct sqd->lock -> ctx->uring_lock
4431 * ordering. Fine to drop uring_lock here, we hold
4432 * a ref to the ctx.
4433 */
4434 refcount_inc(&sqd->refs);
4435 mutex_unlock(&ctx->uring_lock);
4436 mutex_lock(&sqd->lock);
4437 mutex_lock(&ctx->uring_lock);
4438 if (sqd->thread)
4439 tctx = sqd->thread->io_uring;
4440 }
4441 } else {
4442 tctx = current->io_uring;
4443 }
4444
4445 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
4446
4447 for (i = 0; i < ARRAY_SIZE(new_count); i++)
4448 if (new_count[i])
4449 ctx->iowq_limits[i] = new_count[i];
4450 ctx->iowq_limits_set = true;
4451
4452 if (tctx && tctx->io_wq) {
4453 ret = io_wq_max_workers(tctx->io_wq, new_count);
4454 if (ret)
4455 goto err;
4456 } else {
4457 memset(new_count, 0, sizeof(new_count));
4458 }
4459
4460 if (sqd) {
4461 mutex_unlock(&ctx->uring_lock);
4462 mutex_unlock(&sqd->lock);
4463 io_put_sq_data(sqd);
4464 mutex_lock(&ctx->uring_lock);
4465 }
4466
4467 if (copy_to_user(arg, new_count, sizeof(new_count)))
4468 return -EFAULT;
4469
4470 /* that's it for SQPOLL, only the SQPOLL task creates requests */
4471 if (sqd)
4472 return 0;
4473
4474 /* now propagate the restriction to all registered users */
4475 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
4476 struct io_uring_task *tctx = node->task->io_uring;
4477
4478 if (WARN_ON_ONCE(!tctx->io_wq))
4479 continue;
4480
4481 for (i = 0; i < ARRAY_SIZE(new_count); i++)
4482 new_count[i] = ctx->iowq_limits[i];
4483 /* ignore errors, it always returns zero anyway */
4484 (void)io_wq_max_workers(tctx->io_wq, new_count);
4485 }
4486 return 0;
4487 err:
4488 if (sqd) {
4489 mutex_unlock(&ctx->uring_lock);
4490 mutex_unlock(&sqd->lock);
4491 io_put_sq_data(sqd);
4492 mutex_lock(&ctx->uring_lock);
4493
4494 }
4495 return ret;
4496 }
4497
__io_uring_register(struct io_ring_ctx * ctx,unsigned opcode,void __user * arg,unsigned nr_args)4498 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
4499 void __user *arg, unsigned nr_args)
4500 __releases(ctx->uring_lock)
4501 __acquires(ctx->uring_lock)
4502 {
4503 int ret;
4504
4505 /*
4506 * We don't quiesce the refs for register anymore and so it can't be
4507 * dying as we're holding a file ref here.
4508 */
4509 if (WARN_ON_ONCE(percpu_ref_is_dying(&ctx->refs)))
4510 return -ENXIO;
4511
4512 if (ctx->submitter_task && ctx->submitter_task != current)
4513 return -EEXIST;
4514
4515 if (ctx->restricted) {
4516 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
4517 if (!test_bit(opcode, ctx->restrictions.register_op))
4518 return -EACCES;
4519 }
4520
4521 switch (opcode) {
4522 case IORING_REGISTER_BUFFERS:
4523 ret = -EFAULT;
4524 if (!arg)
4525 break;
4526 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
4527 break;
4528 case IORING_UNREGISTER_BUFFERS:
4529 ret = -EINVAL;
4530 if (arg || nr_args)
4531 break;
4532 ret = io_sqe_buffers_unregister(ctx);
4533 break;
4534 case IORING_REGISTER_FILES:
4535 ret = -EFAULT;
4536 if (!arg)
4537 break;
4538 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
4539 break;
4540 case IORING_UNREGISTER_FILES:
4541 ret = -EINVAL;
4542 if (arg || nr_args)
4543 break;
4544 ret = io_sqe_files_unregister(ctx);
4545 break;
4546 case IORING_REGISTER_FILES_UPDATE:
4547 ret = io_register_files_update(ctx, arg, nr_args);
4548 break;
4549 case IORING_REGISTER_EVENTFD:
4550 ret = -EINVAL;
4551 if (nr_args != 1)
4552 break;
4553 ret = io_eventfd_register(ctx, arg, 0);
4554 break;
4555 case IORING_REGISTER_EVENTFD_ASYNC:
4556 ret = -EINVAL;
4557 if (nr_args != 1)
4558 break;
4559 ret = io_eventfd_register(ctx, arg, 1);
4560 break;
4561 case IORING_UNREGISTER_EVENTFD:
4562 ret = -EINVAL;
4563 if (arg || nr_args)
4564 break;
4565 ret = io_eventfd_unregister(ctx);
4566 break;
4567 case IORING_REGISTER_PROBE:
4568 ret = -EINVAL;
4569 if (!arg || nr_args > 256)
4570 break;
4571 ret = io_probe(ctx, arg, nr_args);
4572 break;
4573 case IORING_REGISTER_PERSONALITY:
4574 ret = -EINVAL;
4575 if (arg || nr_args)
4576 break;
4577 ret = io_register_personality(ctx);
4578 break;
4579 case IORING_UNREGISTER_PERSONALITY:
4580 ret = -EINVAL;
4581 if (arg)
4582 break;
4583 ret = io_unregister_personality(ctx, nr_args);
4584 break;
4585 case IORING_REGISTER_ENABLE_RINGS:
4586 ret = -EINVAL;
4587 if (arg || nr_args)
4588 break;
4589 ret = io_register_enable_rings(ctx);
4590 break;
4591 case IORING_REGISTER_RESTRICTIONS:
4592 ret = io_register_restrictions(ctx, arg, nr_args);
4593 break;
4594 case IORING_REGISTER_FILES2:
4595 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
4596 break;
4597 case IORING_REGISTER_FILES_UPDATE2:
4598 ret = io_register_rsrc_update(ctx, arg, nr_args,
4599 IORING_RSRC_FILE);
4600 break;
4601 case IORING_REGISTER_BUFFERS2:
4602 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
4603 break;
4604 case IORING_REGISTER_BUFFERS_UPDATE:
4605 ret = io_register_rsrc_update(ctx, arg, nr_args,
4606 IORING_RSRC_BUFFER);
4607 break;
4608 case IORING_REGISTER_IOWQ_AFF:
4609 ret = -EINVAL;
4610 if (!arg || !nr_args)
4611 break;
4612 ret = io_register_iowq_aff(ctx, arg, nr_args);
4613 break;
4614 case IORING_UNREGISTER_IOWQ_AFF:
4615 ret = -EINVAL;
4616 if (arg || nr_args)
4617 break;
4618 ret = io_unregister_iowq_aff(ctx);
4619 break;
4620 case IORING_REGISTER_IOWQ_MAX_WORKERS:
4621 ret = -EINVAL;
4622 if (!arg || nr_args != 2)
4623 break;
4624 ret = io_register_iowq_max_workers(ctx, arg);
4625 break;
4626 case IORING_REGISTER_RING_FDS:
4627 ret = io_ringfd_register(ctx, arg, nr_args);
4628 break;
4629 case IORING_UNREGISTER_RING_FDS:
4630 ret = io_ringfd_unregister(ctx, arg, nr_args);
4631 break;
4632 case IORING_REGISTER_PBUF_RING:
4633 ret = -EINVAL;
4634 if (!arg || nr_args != 1)
4635 break;
4636 ret = io_register_pbuf_ring(ctx, arg);
4637 break;
4638 case IORING_UNREGISTER_PBUF_RING:
4639 ret = -EINVAL;
4640 if (!arg || nr_args != 1)
4641 break;
4642 ret = io_unregister_pbuf_ring(ctx, arg);
4643 break;
4644 case IORING_REGISTER_SYNC_CANCEL:
4645 ret = -EINVAL;
4646 if (!arg || nr_args != 1)
4647 break;
4648 ret = io_sync_cancel(ctx, arg);
4649 break;
4650 case IORING_REGISTER_FILE_ALLOC_RANGE:
4651 ret = -EINVAL;
4652 if (!arg || nr_args)
4653 break;
4654 ret = io_register_file_alloc_range(ctx, arg);
4655 break;
4656 default:
4657 ret = -EINVAL;
4658 break;
4659 }
4660
4661 return ret;
4662 }
4663
SYSCALL_DEFINE4(io_uring_register,unsigned int,fd,unsigned int,opcode,void __user *,arg,unsigned int,nr_args)4664 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4665 void __user *, arg, unsigned int, nr_args)
4666 {
4667 struct io_ring_ctx *ctx;
4668 long ret = -EBADF;
4669 struct file *file;
4670 bool use_registered_ring;
4671
4672 use_registered_ring = !!(opcode & IORING_REGISTER_USE_REGISTERED_RING);
4673 opcode &= ~IORING_REGISTER_USE_REGISTERED_RING;
4674
4675 if (opcode >= IORING_REGISTER_LAST)
4676 return -EINVAL;
4677
4678 if (use_registered_ring) {
4679 /*
4680 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
4681 * need only dereference our task private array to find it.
4682 */
4683 struct io_uring_task *tctx = current->io_uring;
4684
4685 if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
4686 return -EINVAL;
4687 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
4688 file = tctx->registered_rings[fd];
4689 if (unlikely(!file))
4690 return -EBADF;
4691 } else {
4692 file = fget(fd);
4693 if (unlikely(!file))
4694 return -EBADF;
4695 ret = -EOPNOTSUPP;
4696 if (!io_is_uring_fops(file))
4697 goto out_fput;
4698 }
4699
4700 ctx = file->private_data;
4701
4702 mutex_lock(&ctx->uring_lock);
4703 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4704 mutex_unlock(&ctx->uring_lock);
4705 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
4706 out_fput:
4707 if (!use_registered_ring)
4708 fput(file);
4709 return ret;
4710 }
4711
io_uring_init(void)4712 static int __init io_uring_init(void)
4713 {
4714 #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
4715 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
4716 BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
4717 } while (0)
4718
4719 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
4720 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
4721 #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
4722 __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
4723 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
4724 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
4725 BUILD_BUG_SQE_ELEM(1, __u8, flags);
4726 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
4727 BUILD_BUG_SQE_ELEM(4, __s32, fd);
4728 BUILD_BUG_SQE_ELEM(8, __u64, off);
4729 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
4730 BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
4731 BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
4732 BUILD_BUG_SQE_ELEM(16, __u64, addr);
4733 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
4734 BUILD_BUG_SQE_ELEM(24, __u32, len);
4735 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
4736 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
4737 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
4738 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
4739 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
4740 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
4741 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
4742 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
4743 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
4744 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
4745 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
4746 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
4747 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
4748 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
4749 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
4750 BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
4751 BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
4752 BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
4753 BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
4754 BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
4755 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
4756 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
4757 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
4758 BUILD_BUG_SQE_ELEM(42, __u16, personality);
4759 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
4760 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
4761 BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
4762 BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
4763 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
4764 BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
4765 BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
4766
4767 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
4768 sizeof(struct io_uring_rsrc_update));
4769 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
4770 sizeof(struct io_uring_rsrc_update2));
4771
4772 /* ->buf_index is u16 */
4773 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
4774 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
4775 offsetof(struct io_uring_buf_ring, tail));
4776
4777 /* should fit into one byte */
4778 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
4779 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
4780 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
4781
4782 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
4783
4784 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
4785
4786 io_uring_optable_init();
4787
4788 /*
4789 * Allow user copy in the per-command field, which starts after the
4790 * file in io_kiocb and until the opcode field. The openat2 handling
4791 * requires copying in user memory into the io_kiocb object in that
4792 * range, and HARDENED_USERCOPY will complain if we haven't
4793 * correctly annotated this range.
4794 */
4795 req_cachep = kmem_cache_create_usercopy("io_kiocb",
4796 sizeof(struct io_kiocb), 0,
4797 SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4798 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU,
4799 offsetof(struct io_kiocb, cmd.data),
4800 sizeof_field(struct io_kiocb, cmd.data), NULL);
4801
4802 iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
4803
4804 #ifdef CONFIG_SYSCTL
4805 register_sysctl_init("kernel", kernel_io_uring_disabled_table);
4806 #endif
4807
4808 return 0;
4809 };
4810 __initcall(io_uring_init);
4811