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