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