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