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