io_uring: move poll handling into its own file
[linux-block.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 <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
51
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
63 #include <net/sock.h>
64 #include <net/af_unix.h>
65 #include <net/scm.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/fsnotify.h>
74 #include <linux/fadvise.h>
75 #include <linux/eventpoll.h>
76 #include <linux/task_work.h>
77 #include <linux/pagemap.h>
78 #include <linux/io_uring.h>
79 #include <linux/audit.h>
80 #include <linux/security.h>
81
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
84
85 #include <uapi/linux/io_uring.h>
86
87 #include "io-wq.h"
88
89 #include "io_uring_types.h"
90 #include "io_uring.h"
91 #include "opdef.h"
92 #include "refs.h"
93 #include "tctx.h"
94 #include "sqpoll.h"
95 #include "fdinfo.h"
96
97 #include "xattr.h"
98 #include "nop.h"
99 #include "fs.h"
100 #include "splice.h"
101 #include "sync.h"
102 #include "advise.h"
103 #include "openclose.h"
104 #include "uring_cmd.h"
105 #include "epoll.h"
106 #include "statx.h"
107 #include "net.h"
108 #include "msg_ring.h"
109 #include "timeout.h"
110 #include "poll.h"
111
112 #define IORING_MAX_ENTRIES      32768
113 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
114
115 /* only define max */
116 #define IORING_MAX_FIXED_FILES  (1U << 20)
117 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
118                                  IORING_REGISTER_LAST + IORING_OP_LAST)
119
120 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
121 #define IO_RSRC_TAG_TABLE_MAX   (1U << IO_RSRC_TAG_TABLE_SHIFT)
122 #define IO_RSRC_TAG_TABLE_MASK  (IO_RSRC_TAG_TABLE_MAX - 1)
123
124 #define IORING_MAX_REG_BUFFERS  (1U << 14)
125
126 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
127                           IOSQE_IO_HARDLINK | IOSQE_ASYNC)
128
129 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
130                         IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
131
132 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
133                                 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
134                                 REQ_F_ASYNC_DATA)
135
136 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
137                                  IO_REQ_CLEAN_FLAGS)
138
139 #define IO_TCTX_REFS_CACHE_NR   (1U << 10)
140
141 struct io_rsrc_put {
142         struct list_head list;
143         u64 tag;
144         union {
145                 void *rsrc;
146                 struct file *file;
147                 struct io_mapped_ubuf *buf;
148         };
149 };
150
151 struct io_rsrc_node {
152         struct percpu_ref               refs;
153         struct list_head                node;
154         struct list_head                rsrc_list;
155         struct io_rsrc_data             *rsrc_data;
156         struct llist_node               llist;
157         bool                            done;
158 };
159
160 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
161
162 struct io_rsrc_data {
163         struct io_ring_ctx              *ctx;
164
165         u64                             **tags;
166         unsigned int                    nr;
167         rsrc_put_fn                     *do_put;
168         atomic_t                        refs;
169         struct completion               done;
170         bool                            quiesce;
171 };
172
173 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
174 struct io_buffer_list {
175         /*
176          * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
177          * then these are classic provided buffers and ->buf_list is used.
178          */
179         union {
180                 struct list_head buf_list;
181                 struct {
182                         struct page **buf_pages;
183                         struct io_uring_buf_ring *buf_ring;
184                 };
185         };
186         __u16 bgid;
187
188         /* below is for ring provided buffers */
189         __u16 buf_nr_pages;
190         __u16 nr_entries;
191         __u16 head;
192         __u16 mask;
193 };
194
195 struct io_buffer {
196         struct list_head list;
197         __u64 addr;
198         __u32 len;
199         __u16 bid;
200         __u16 bgid;
201 };
202
203 #define IO_COMPL_BATCH                  32
204 #define IO_REQ_CACHE_SIZE               32
205 #define IO_REQ_ALLOC_BATCH              8
206
207 #define BGID_ARRAY                      64
208
209 /*
210  * First field must be the file pointer in all the
211  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
212  */
213 struct io_cancel {
214         struct file                     *file;
215         u64                             addr;
216         u32                             flags;
217         s32                             fd;
218 };
219
220 struct io_rw {
221         /* NOTE: kiocb has the file as the first member, so don't do it here */
222         struct kiocb                    kiocb;
223         u64                             addr;
224         u32                             len;
225         rwf_t                           flags;
226 };
227
228 struct io_rsrc_update {
229         struct file                     *file;
230         u64                             arg;
231         u32                             nr_args;
232         u32                             offset;
233 };
234
235 struct io_provide_buf {
236         struct file                     *file;
237         __u64                           addr;
238         __u32                           len;
239         __u32                           bgid;
240         __u16                           nbufs;
241         __u16                           bid;
242 };
243
244 struct io_rw_state {
245         struct iov_iter                 iter;
246         struct iov_iter_state           iter_state;
247         struct iovec                    fast_iov[UIO_FASTIOV];
248 };
249
250 struct io_async_rw {
251         struct io_rw_state              s;
252         const struct iovec              *free_iovec;
253         size_t                          bytes_done;
254         struct wait_page_queue          wpq;
255 };
256
257 enum {
258         IORING_RSRC_FILE                = 0,
259         IORING_RSRC_BUFFER              = 1,
260 };
261
262 enum {
263         IO_CHECK_CQ_OVERFLOW_BIT,
264         IO_CHECK_CQ_DROPPED_BIT,
265 };
266
267 struct io_defer_entry {
268         struct list_head        list;
269         struct io_kiocb         *req;
270         u32                     seq;
271 };
272
273 /* requests with any of those set should undergo io_disarm_next() */
274 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
275 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
276
277 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
278                                          struct task_struct *task,
279                                          bool cancel_all);
280
281 static void io_dismantle_req(struct io_kiocb *req);
282 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
283                                      struct io_uring_rsrc_update2 *up,
284                                      unsigned nr_args);
285 static void io_clean_op(struct io_kiocb *req);
286 static void io_queue_sqe(struct io_kiocb *req);
287 static void io_rsrc_put_work(struct work_struct *work);
288
289 static void io_req_task_queue(struct io_kiocb *req);
290 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
291 static int io_req_prep_async(struct io_kiocb *req);
292
293 static void io_eventfd_signal(struct io_ring_ctx *ctx);
294
295 static struct kmem_cache *req_cachep;
296
297 const char *io_uring_get_opcode(u8 opcode)
298 {
299         if (opcode < IORING_OP_LAST)
300                 return io_op_defs[opcode].name;
301         return "INVALID";
302 }
303
304 struct sock *io_uring_get_socket(struct file *file)
305 {
306 #if defined(CONFIG_UNIX)
307         if (io_is_uring_fops(file)) {
308                 struct io_ring_ctx *ctx = file->private_data;
309
310                 return ctx->ring_sock->sk;
311         }
312 #endif
313         return NULL;
314 }
315 EXPORT_SYMBOL(io_uring_get_socket);
316
317 #if defined(CONFIG_UNIX)
318 static inline bool io_file_need_scm(struct file *filp)
319 {
320 #if defined(IO_URING_SCM_ALL)
321         return true;
322 #else
323         return !!unix_get_socket(filp);
324 #endif
325 }
326 #else
327 static inline bool io_file_need_scm(struct file *filp)
328 {
329         return false;
330 }
331 #endif
332
333 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
334 {
335         if (!*locked) {
336                 mutex_lock(&ctx->uring_lock);
337                 *locked = true;
338         }
339 }
340
341 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
342 {
343         if (!wq_list_empty(&ctx->submit_state.compl_reqs))
344                 __io_submit_flush_completions(ctx);
345 }
346
347 #define IO_RSRC_REF_BATCH       100
348
349 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
350 {
351         percpu_ref_put_many(&node->refs, nr);
352 }
353
354 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
355                                           struct io_ring_ctx *ctx)
356         __must_hold(&ctx->uring_lock)
357 {
358         struct io_rsrc_node *node = req->rsrc_node;
359
360         if (node) {
361                 if (node == ctx->rsrc_node)
362                         ctx->rsrc_cached_refs++;
363                 else
364                         io_rsrc_put_node(node, 1);
365         }
366 }
367
368 static inline void io_req_put_rsrc(struct io_kiocb *req)
369 {
370         if (req->rsrc_node)
371                 io_rsrc_put_node(req->rsrc_node, 1);
372 }
373
374 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
375         __must_hold(&ctx->uring_lock)
376 {
377         if (ctx->rsrc_cached_refs) {
378                 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
379                 ctx->rsrc_cached_refs = 0;
380         }
381 }
382
383 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
384         __must_hold(&ctx->uring_lock)
385 {
386         ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
387         percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
388 }
389
390 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
391                                         struct io_ring_ctx *ctx,
392                                         unsigned int issue_flags)
393 {
394         if (!req->rsrc_node) {
395                 req->rsrc_node = ctx->rsrc_node;
396
397                 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
398                         lockdep_assert_held(&ctx->uring_lock);
399                         ctx->rsrc_cached_refs--;
400                         if (unlikely(ctx->rsrc_cached_refs < 0))
401                                 io_rsrc_refs_refill(ctx);
402                 } else {
403                         percpu_ref_get(&req->rsrc_node->refs);
404                 }
405         }
406 }
407
408 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
409 {
410         if (req->flags & REQ_F_BUFFER_RING) {
411                 if (req->buf_list)
412                         req->buf_list->head++;
413                 req->flags &= ~REQ_F_BUFFER_RING;
414         } else {
415                 list_add(&req->kbuf->list, list);
416                 req->flags &= ~REQ_F_BUFFER_SELECTED;
417         }
418
419         return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
420 }
421
422 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
423 {
424         lockdep_assert_held(&req->ctx->completion_lock);
425
426         if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
427                 return 0;
428         return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
429 }
430
431 inline unsigned int io_put_kbuf(struct io_kiocb *req, unsigned issue_flags)
432 {
433         unsigned int cflags;
434
435         if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
436                 return 0;
437
438         /*
439          * We can add this buffer back to two lists:
440          *
441          * 1) The io_buffers_cache list. This one is protected by the
442          *    ctx->uring_lock. If we already hold this lock, add back to this
443          *    list as we can grab it from issue as well.
444          * 2) The io_buffers_comp list. This one is protected by the
445          *    ctx->completion_lock.
446          *
447          * We migrate buffers from the comp_list to the issue cache list
448          * when we need one.
449          */
450         if (req->flags & REQ_F_BUFFER_RING) {
451                 /* no buffers to recycle for this case */
452                 cflags = __io_put_kbuf(req, NULL);
453         } else if (issue_flags & IO_URING_F_UNLOCKED) {
454                 struct io_ring_ctx *ctx = req->ctx;
455
456                 spin_lock(&ctx->completion_lock);
457                 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
458                 spin_unlock(&ctx->completion_lock);
459         } else {
460                 lockdep_assert_held(&req->ctx->uring_lock);
461
462                 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
463         }
464
465         return cflags;
466 }
467
468 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
469                                                  unsigned int bgid)
470 {
471         if (ctx->io_bl && bgid < BGID_ARRAY)
472                 return &ctx->io_bl[bgid];
473
474         return xa_load(&ctx->io_bl_xa, bgid);
475 }
476
477 void __io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
478 {
479         struct io_ring_ctx *ctx = req->ctx;
480         struct io_buffer_list *bl;
481         struct io_buffer *buf;
482
483         /*
484          * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
485          * the flag and hence ensure that bl->head doesn't get incremented.
486          * If the tail has already been incremented, hang on to it.
487          */
488         if (req->flags & REQ_F_BUFFER_RING) {
489                 if (req->buf_list) {
490                         if (req->flags & REQ_F_PARTIAL_IO) {
491                                 req->buf_list->head++;
492                                 req->buf_list = NULL;
493                         } else {
494                                 req->buf_index = req->buf_list->bgid;
495                                 req->flags &= ~REQ_F_BUFFER_RING;
496                         }
497                 }
498                 return;
499         }
500
501         io_ring_submit_lock(ctx, issue_flags);
502
503         buf = req->kbuf;
504         bl = io_buffer_get_list(ctx, buf->bgid);
505         list_add(&buf->list, &bl->buf_list);
506         req->flags &= ~REQ_F_BUFFER_SELECTED;
507         req->buf_index = buf->bgid;
508
509         io_ring_submit_unlock(ctx, issue_flags);
510 }
511
512 static bool io_match_linked(struct io_kiocb *head)
513 {
514         struct io_kiocb *req;
515
516         io_for_each_link(req, head) {
517                 if (req->flags & REQ_F_INFLIGHT)
518                         return true;
519         }
520         return false;
521 }
522
523 /*
524  * As io_match_task() but protected against racing with linked timeouts.
525  * User must not hold timeout_lock.
526  */
527 bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
528                         bool cancel_all)
529 {
530         bool matched;
531
532         if (task && head->task != task)
533                 return false;
534         if (cancel_all)
535                 return true;
536
537         if (head->flags & REQ_F_LINK_TIMEOUT) {
538                 struct io_ring_ctx *ctx = head->ctx;
539
540                 /* protect against races with linked timeouts */
541                 spin_lock_irq(&ctx->timeout_lock);
542                 matched = io_match_linked(head);
543                 spin_unlock_irq(&ctx->timeout_lock);
544         } else {
545                 matched = io_match_linked(head);
546         }
547         return matched;
548 }
549
550 static inline void req_fail_link_node(struct io_kiocb *req, int res)
551 {
552         req_set_fail(req);
553         io_req_set_res(req, res, 0);
554 }
555
556 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
557 {
558         wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
559 }
560
561 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
562 {
563         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
564
565         complete(&ctx->ref_comp);
566 }
567
568 static __cold void io_fallback_req_func(struct work_struct *work)
569 {
570         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
571                                                 fallback_work.work);
572         struct llist_node *node = llist_del_all(&ctx->fallback_llist);
573         struct io_kiocb *req, *tmp;
574         bool locked = false;
575
576         percpu_ref_get(&ctx->refs);
577         llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
578                 req->io_task_work.func(req, &locked);
579
580         if (locked) {
581                 io_submit_flush_completions(ctx);
582                 mutex_unlock(&ctx->uring_lock);
583         }
584         percpu_ref_put(&ctx->refs);
585 }
586
587 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
588 {
589         struct io_ring_ctx *ctx;
590         int hash_bits;
591
592         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
593         if (!ctx)
594                 return NULL;
595
596         xa_init(&ctx->io_bl_xa);
597
598         /*
599          * Use 5 bits less than the max cq entries, that should give us around
600          * 32 entries per hash list if totally full and uniformly spread.
601          */
602         hash_bits = ilog2(p->cq_entries);
603         hash_bits -= 5;
604         if (hash_bits <= 0)
605                 hash_bits = 1;
606         ctx->cancel_hash_bits = hash_bits;
607         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
608                                         GFP_KERNEL);
609         if (!ctx->cancel_hash)
610                 goto err;
611         __hash_init(ctx->cancel_hash, 1U << hash_bits);
612
613         ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
614         if (!ctx->dummy_ubuf)
615                 goto err;
616         /* set invalid range, so io_import_fixed() fails meeting it */
617         ctx->dummy_ubuf->ubuf = -1UL;
618
619         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
620                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
621                 goto err;
622
623         ctx->flags = p->flags;
624         init_waitqueue_head(&ctx->sqo_sq_wait);
625         INIT_LIST_HEAD(&ctx->sqd_list);
626         INIT_LIST_HEAD(&ctx->cq_overflow_list);
627         INIT_LIST_HEAD(&ctx->io_buffers_cache);
628         INIT_LIST_HEAD(&ctx->apoll_cache);
629         init_completion(&ctx->ref_comp);
630         xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
631         mutex_init(&ctx->uring_lock);
632         init_waitqueue_head(&ctx->cq_wait);
633         spin_lock_init(&ctx->completion_lock);
634         spin_lock_init(&ctx->timeout_lock);
635         INIT_WQ_LIST(&ctx->iopoll_list);
636         INIT_LIST_HEAD(&ctx->io_buffers_pages);
637         INIT_LIST_HEAD(&ctx->io_buffers_comp);
638         INIT_LIST_HEAD(&ctx->defer_list);
639         INIT_LIST_HEAD(&ctx->timeout_list);
640         INIT_LIST_HEAD(&ctx->ltimeout_list);
641         spin_lock_init(&ctx->rsrc_ref_lock);
642         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
643         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
644         init_llist_head(&ctx->rsrc_put_llist);
645         INIT_LIST_HEAD(&ctx->tctx_list);
646         ctx->submit_state.free_list.next = NULL;
647         INIT_WQ_LIST(&ctx->locked_free_list);
648         INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
649         INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
650         return ctx;
651 err:
652         kfree(ctx->dummy_ubuf);
653         kfree(ctx->cancel_hash);
654         kfree(ctx->io_bl);
655         xa_destroy(&ctx->io_bl_xa);
656         kfree(ctx);
657         return NULL;
658 }
659
660 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
661 {
662         struct io_rings *r = ctx->rings;
663
664         WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
665         ctx->cq_extra--;
666 }
667
668 static bool req_need_defer(struct io_kiocb *req, u32 seq)
669 {
670         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
671                 struct io_ring_ctx *ctx = req->ctx;
672
673                 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
674         }
675
676         return false;
677 }
678
679 static inline bool io_req_ffs_set(struct io_kiocb *req)
680 {
681         return req->flags & REQ_F_FIXED_FILE;
682 }
683
684 static inline void io_req_track_inflight(struct io_kiocb *req)
685 {
686         if (!(req->flags & REQ_F_INFLIGHT)) {
687                 req->flags |= REQ_F_INFLIGHT;
688                 atomic_inc(&req->task->io_uring->inflight_tracked);
689         }
690 }
691
692 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
693 {
694         if (WARN_ON_ONCE(!req->link))
695                 return NULL;
696
697         req->flags &= ~REQ_F_ARM_LTIMEOUT;
698         req->flags |= REQ_F_LINK_TIMEOUT;
699
700         /* linked timeouts should have two refs once prep'ed */
701         io_req_set_refcount(req);
702         __io_req_set_refcount(req->link, 2);
703         return req->link;
704 }
705
706 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
707 {
708         if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
709                 return NULL;
710         return __io_prep_linked_timeout(req);
711 }
712
713 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
714 {
715         io_queue_linked_timeout(__io_prep_linked_timeout(req));
716 }
717
718 static inline void io_arm_ltimeout(struct io_kiocb *req)
719 {
720         if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
721                 __io_arm_ltimeout(req);
722 }
723
724 static void io_prep_async_work(struct io_kiocb *req)
725 {
726         const struct io_op_def *def = &io_op_defs[req->opcode];
727         struct io_ring_ctx *ctx = req->ctx;
728
729         if (!(req->flags & REQ_F_CREDS)) {
730                 req->flags |= REQ_F_CREDS;
731                 req->creds = get_current_cred();
732         }
733
734         req->work.list.next = NULL;
735         req->work.flags = 0;
736         req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
737         if (req->flags & REQ_F_FORCE_ASYNC)
738                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
739
740         if (req->flags & REQ_F_ISREG) {
741                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
742                         io_wq_hash_work(&req->work, file_inode(req->file));
743         } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
744                 if (def->unbound_nonreg_file)
745                         req->work.flags |= IO_WQ_WORK_UNBOUND;
746         }
747 }
748
749 static void io_prep_async_link(struct io_kiocb *req)
750 {
751         struct io_kiocb *cur;
752
753         if (req->flags & REQ_F_LINK_TIMEOUT) {
754                 struct io_ring_ctx *ctx = req->ctx;
755
756                 spin_lock_irq(&ctx->timeout_lock);
757                 io_for_each_link(cur, req)
758                         io_prep_async_work(cur);
759                 spin_unlock_irq(&ctx->timeout_lock);
760         } else {
761                 io_for_each_link(cur, req)
762                         io_prep_async_work(cur);
763         }
764 }
765
766 static inline void io_req_add_compl_list(struct io_kiocb *req)
767 {
768         struct io_submit_state *state = &req->ctx->submit_state;
769
770         if (!(req->flags & REQ_F_CQE_SKIP))
771                 state->flush_cqes = true;
772         wq_list_add_tail(&req->comp_list, &state->compl_reqs);
773 }
774
775 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
776 {
777         struct io_kiocb *link = io_prep_linked_timeout(req);
778         struct io_uring_task *tctx = req->task->io_uring;
779
780         BUG_ON(!tctx);
781         BUG_ON(!tctx->io_wq);
782
783         /* init ->work of the whole link before punting */
784         io_prep_async_link(req);
785
786         /*
787          * Not expected to happen, but if we do have a bug where this _can_
788          * happen, catch it here and ensure the request is marked as
789          * canceled. That will make io-wq go through the usual work cancel
790          * procedure rather than attempt to run this request (or create a new
791          * worker for it).
792          */
793         if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
794                 req->work.flags |= IO_WQ_WORK_CANCEL;
795
796         trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
797                                         req->opcode, req->flags, &req->work,
798                                         io_wq_is_hashed(&req->work));
799         io_wq_enqueue(tctx->io_wq, &req->work);
800         if (link)
801                 io_queue_linked_timeout(link);
802 }
803
804 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
805 {
806         while (!list_empty(&ctx->defer_list)) {
807                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
808                                                 struct io_defer_entry, list);
809
810                 if (req_need_defer(de->req, de->seq))
811                         break;
812                 list_del_init(&de->list);
813                 io_req_task_queue(de->req);
814                 kfree(de);
815         }
816 }
817
818 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
819 {
820         if (ctx->off_timeout_used || ctx->drain_active) {
821                 spin_lock(&ctx->completion_lock);
822                 if (ctx->off_timeout_used)
823                         io_flush_timeouts(ctx);
824                 if (ctx->drain_active)
825                         io_queue_deferred(ctx);
826                 io_commit_cqring(ctx);
827                 spin_unlock(&ctx->completion_lock);
828         }
829         if (ctx->has_evfd)
830                 io_eventfd_signal(ctx);
831 }
832
833 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
834 {
835         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
836 }
837
838 /*
839  * writes to the cq entry need to come after reading head; the
840  * control dependency is enough as we're using WRITE_ONCE to
841  * fill the cq entry
842  */
843 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
844 {
845         struct io_rings *rings = ctx->rings;
846         unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
847         unsigned int shift = 0;
848         unsigned int free, queued, len;
849
850         if (ctx->flags & IORING_SETUP_CQE32)
851                 shift = 1;
852
853         /* userspace may cheat modifying the tail, be safe and do min */
854         queued = min(__io_cqring_events(ctx), ctx->cq_entries);
855         free = ctx->cq_entries - queued;
856         /* we need a contiguous range, limit based on the current array offset */
857         len = min(free, ctx->cq_entries - off);
858         if (!len)
859                 return NULL;
860
861         ctx->cached_cq_tail++;
862         ctx->cqe_cached = &rings->cqes[off];
863         ctx->cqe_sentinel = ctx->cqe_cached + len;
864         ctx->cqe_cached++;
865         return &rings->cqes[off << shift];
866 }
867
868 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
869 {
870         if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
871                 struct io_uring_cqe *cqe = ctx->cqe_cached;
872
873                 if (ctx->flags & IORING_SETUP_CQE32) {
874                         unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
875
876                         cqe += off;
877                 }
878
879                 ctx->cached_cq_tail++;
880                 ctx->cqe_cached++;
881                 return cqe;
882         }
883
884         return __io_get_cqe(ctx);
885 }
886
887 static void io_eventfd_signal(struct io_ring_ctx *ctx)
888 {
889         struct io_ev_fd *ev_fd;
890
891         rcu_read_lock();
892         /*
893          * rcu_dereference ctx->io_ev_fd once and use it for both for checking
894          * and eventfd_signal
895          */
896         ev_fd = rcu_dereference(ctx->io_ev_fd);
897
898         /*
899          * Check again if ev_fd exists incase an io_eventfd_unregister call
900          * completed between the NULL check of ctx->io_ev_fd at the start of
901          * the function and rcu_read_lock.
902          */
903         if (unlikely(!ev_fd))
904                 goto out;
905         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
906                 goto out;
907
908         if (!ev_fd->eventfd_async || io_wq_current_is_worker())
909                 eventfd_signal(ev_fd->cq_ev_fd, 1);
910 out:
911         rcu_read_unlock();
912 }
913
914 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
915 {
916         /*
917          * wake_up_all() may seem excessive, but io_wake_function() and
918          * io_should_wake() handle the termination of the loop and only
919          * wake as many waiters as we need to.
920          */
921         if (wq_has_sleeper(&ctx->cq_wait))
922                 wake_up_all(&ctx->cq_wait);
923 }
924
925 /*
926  * This should only get called when at least one event has been posted.
927  * Some applications rely on the eventfd notification count only changing
928  * IFF a new CQE has been added to the CQ ring. There's no depedency on
929  * 1:1 relationship between how many times this function is called (and
930  * hence the eventfd count) and number of CQEs posted to the CQ ring.
931  */
932 void io_cqring_ev_posted(struct io_ring_ctx *ctx)
933 {
934         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
935                      ctx->has_evfd))
936                 __io_commit_cqring_flush(ctx);
937
938         io_cqring_wake(ctx);
939 }
940
941 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
942 {
943         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
944                      ctx->has_evfd))
945                 __io_commit_cqring_flush(ctx);
946
947         if (ctx->flags & IORING_SETUP_SQPOLL)
948                 io_cqring_wake(ctx);
949 }
950
951 /* Returns true if there are no backlogged entries after the flush */
952 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
953 {
954         bool all_flushed, posted;
955         size_t cqe_size = sizeof(struct io_uring_cqe);
956
957         if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
958                 return false;
959
960         if (ctx->flags & IORING_SETUP_CQE32)
961                 cqe_size <<= 1;
962
963         posted = false;
964         spin_lock(&ctx->completion_lock);
965         while (!list_empty(&ctx->cq_overflow_list)) {
966                 struct io_uring_cqe *cqe = io_get_cqe(ctx);
967                 struct io_overflow_cqe *ocqe;
968
969                 if (!cqe && !force)
970                         break;
971                 ocqe = list_first_entry(&ctx->cq_overflow_list,
972                                         struct io_overflow_cqe, list);
973                 if (cqe)
974                         memcpy(cqe, &ocqe->cqe, cqe_size);
975                 else
976                         io_account_cq_overflow(ctx);
977
978                 posted = true;
979                 list_del(&ocqe->list);
980                 kfree(ocqe);
981         }
982
983         all_flushed = list_empty(&ctx->cq_overflow_list);
984         if (all_flushed) {
985                 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
986                 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
987         }
988
989         io_commit_cqring(ctx);
990         spin_unlock(&ctx->completion_lock);
991         if (posted)
992                 io_cqring_ev_posted(ctx);
993         return all_flushed;
994 }
995
996 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
997 {
998         bool ret = true;
999
1000         if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
1001                 /* iopoll syncs against uring_lock, not completion_lock */
1002                 if (ctx->flags & IORING_SETUP_IOPOLL)
1003                         mutex_lock(&ctx->uring_lock);
1004                 ret = __io_cqring_overflow_flush(ctx, false);
1005                 if (ctx->flags & IORING_SETUP_IOPOLL)
1006                         mutex_unlock(&ctx->uring_lock);
1007         }
1008
1009         return ret;
1010 }
1011
1012 static void __io_put_task(struct task_struct *task, int nr)
1013 {
1014         struct io_uring_task *tctx = task->io_uring;
1015
1016         percpu_counter_sub(&tctx->inflight, nr);
1017         if (unlikely(atomic_read(&tctx->in_idle)))
1018                 wake_up(&tctx->wait);
1019         put_task_struct_many(task, nr);
1020 }
1021
1022 /* must to be called somewhat shortly after putting a request */
1023 static inline void io_put_task(struct task_struct *task, int nr)
1024 {
1025         if (likely(task == current))
1026                 task->io_uring->cached_refs += nr;
1027         else
1028                 __io_put_task(task, nr);
1029 }
1030
1031 static void io_task_refs_refill(struct io_uring_task *tctx)
1032 {
1033         unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1034
1035         percpu_counter_add(&tctx->inflight, refill);
1036         refcount_add(refill, &current->usage);
1037         tctx->cached_refs += refill;
1038 }
1039
1040 static inline void io_get_task_refs(int nr)
1041 {
1042         struct io_uring_task *tctx = current->io_uring;
1043
1044         tctx->cached_refs -= nr;
1045         if (unlikely(tctx->cached_refs < 0))
1046                 io_task_refs_refill(tctx);
1047 }
1048
1049 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1050 {
1051         struct io_uring_task *tctx = task->io_uring;
1052         unsigned int refs = tctx->cached_refs;
1053
1054         if (refs) {
1055                 tctx->cached_refs = 0;
1056                 percpu_counter_sub(&tctx->inflight, refs);
1057                 put_task_struct_many(task, refs);
1058         }
1059 }
1060
1061 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1062                                      s32 res, u32 cflags, u64 extra1,
1063                                      u64 extra2)
1064 {
1065         struct io_overflow_cqe *ocqe;
1066         size_t ocq_size = sizeof(struct io_overflow_cqe);
1067         bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
1068
1069         if (is_cqe32)
1070                 ocq_size += sizeof(struct io_uring_cqe);
1071
1072         ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
1073         trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
1074         if (!ocqe) {
1075                 /*
1076                  * If we're in ring overflow flush mode, or in task cancel mode,
1077                  * or cannot allocate an overflow entry, then we need to drop it
1078                  * on the floor.
1079                  */
1080                 io_account_cq_overflow(ctx);
1081                 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
1082                 return false;
1083         }
1084         if (list_empty(&ctx->cq_overflow_list)) {
1085                 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1086                 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1087
1088         }
1089         ocqe->cqe.user_data = user_data;
1090         ocqe->cqe.res = res;
1091         ocqe->cqe.flags = cflags;
1092         if (is_cqe32) {
1093                 ocqe->cqe.big_cqe[0] = extra1;
1094                 ocqe->cqe.big_cqe[1] = extra2;
1095         }
1096         list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1097         return true;
1098 }
1099
1100 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
1101                                      struct io_kiocb *req)
1102 {
1103         struct io_uring_cqe *cqe;
1104
1105         if (!(ctx->flags & IORING_SETUP_CQE32)) {
1106                 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1107                                         req->cqe.res, req->cqe.flags, 0, 0);
1108
1109                 /*
1110                  * If we can't get a cq entry, userspace overflowed the
1111                  * submission (by quite a lot). Increment the overflow count in
1112                  * the ring.
1113                  */
1114                 cqe = io_get_cqe(ctx);
1115                 if (likely(cqe)) {
1116                         memcpy(cqe, &req->cqe, sizeof(*cqe));
1117                         return true;
1118                 }
1119
1120                 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1121                                                 req->cqe.res, req->cqe.flags,
1122                                                 0, 0);
1123         } else {
1124                 u64 extra1 = 0, extra2 = 0;
1125
1126                 if (req->flags & REQ_F_CQE32_INIT) {
1127                         extra1 = req->extra1;
1128                         extra2 = req->extra2;
1129                 }
1130
1131                 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1132                                         req->cqe.res, req->cqe.flags, extra1, extra2);
1133
1134                 /*
1135                  * If we can't get a cq entry, userspace overflowed the
1136                  * submission (by quite a lot). Increment the overflow count in
1137                  * the ring.
1138                  */
1139                 cqe = io_get_cqe(ctx);
1140                 if (likely(cqe)) {
1141                         memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
1142                         WRITE_ONCE(cqe->big_cqe[0], extra1);
1143                         WRITE_ONCE(cqe->big_cqe[1], extra2);
1144                         return true;
1145                 }
1146
1147                 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1148                                 req->cqe.res, req->cqe.flags,
1149                                 extra1, extra2);
1150         }
1151 }
1152
1153 bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
1154                      u32 cflags)
1155 {
1156         struct io_uring_cqe *cqe;
1157
1158         ctx->cq_extra++;
1159         trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1160
1161         /*
1162          * If we can't get a cq entry, userspace overflowed the
1163          * submission (by quite a lot). Increment the overflow count in
1164          * the ring.
1165          */
1166         cqe = io_get_cqe(ctx);
1167         if (likely(cqe)) {
1168                 WRITE_ONCE(cqe->user_data, user_data);
1169                 WRITE_ONCE(cqe->res, res);
1170                 WRITE_ONCE(cqe->flags, cflags);
1171
1172                 if (ctx->flags & IORING_SETUP_CQE32) {
1173                         WRITE_ONCE(cqe->big_cqe[0], 0);
1174                         WRITE_ONCE(cqe->big_cqe[1], 0);
1175                 }
1176                 return true;
1177         }
1178         return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1179 }
1180
1181 static void __io_req_complete_put(struct io_kiocb *req)
1182 {
1183         /*
1184          * If we're the last reference to this request, add to our locked
1185          * free_list cache.
1186          */
1187         if (req_ref_put_and_test(req)) {
1188                 struct io_ring_ctx *ctx = req->ctx;
1189
1190                 if (req->flags & IO_REQ_LINK_FLAGS) {
1191                         if (req->flags & IO_DISARM_MASK)
1192                                 io_disarm_next(req);
1193                         if (req->link) {
1194                                 io_req_task_queue(req->link);
1195                                 req->link = NULL;
1196                         }
1197                 }
1198                 io_req_put_rsrc(req);
1199                 /*
1200                  * Selected buffer deallocation in io_clean_op() assumes that
1201                  * we don't hold ->completion_lock. Clean them here to avoid
1202                  * deadlocks.
1203                  */
1204                 io_put_kbuf_comp(req);
1205                 io_dismantle_req(req);
1206                 io_put_task(req->task, 1);
1207                 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1208                 ctx->locked_free_nr++;
1209         }
1210 }
1211
1212 void __io_req_complete_post(struct io_kiocb *req)
1213 {
1214         if (!(req->flags & REQ_F_CQE_SKIP))
1215                 __io_fill_cqe_req(req->ctx, req);
1216         __io_req_complete_put(req);
1217 }
1218
1219 void io_req_complete_post(struct io_kiocb *req)
1220 {
1221         struct io_ring_ctx *ctx = req->ctx;
1222
1223         spin_lock(&ctx->completion_lock);
1224         __io_req_complete_post(req);
1225         io_commit_cqring(ctx);
1226         spin_unlock(&ctx->completion_lock);
1227         io_cqring_ev_posted(ctx);
1228 }
1229
1230 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1231 {
1232         if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1233                 req->flags |= REQ_F_COMPLETE_INLINE;
1234         else
1235                 io_req_complete_post(req);
1236 }
1237
1238 void io_req_complete_failed(struct io_kiocb *req, s32 res)
1239 {
1240         req_set_fail(req);
1241         io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1242         io_req_complete_post(req);
1243 }
1244
1245 /*
1246  * Don't initialise the fields below on every allocation, but do that in
1247  * advance and keep them valid across allocations.
1248  */
1249 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1250 {
1251         req->ctx = ctx;
1252         req->link = NULL;
1253         req->async_data = NULL;
1254         /* not necessary, but safer to zero */
1255         req->cqe.res = 0;
1256 }
1257
1258 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1259                                         struct io_submit_state *state)
1260 {
1261         spin_lock(&ctx->completion_lock);
1262         wq_list_splice(&ctx->locked_free_list, &state->free_list);
1263         ctx->locked_free_nr = 0;
1264         spin_unlock(&ctx->completion_lock);
1265 }
1266
1267 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1268 {
1269         return !ctx->submit_state.free_list.next;
1270 }
1271
1272 /*
1273  * A request might get retired back into the request caches even before opcode
1274  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1275  * Because of that, io_alloc_req() should be called only under ->uring_lock
1276  * and with extra caution to not get a request that is still worked on.
1277  */
1278 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1279         __must_hold(&ctx->uring_lock)
1280 {
1281         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1282         void *reqs[IO_REQ_ALLOC_BATCH];
1283         int ret, i;
1284
1285         /*
1286          * If we have more than a batch's worth of requests in our IRQ side
1287          * locked cache, grab the lock and move them over to our submission
1288          * side cache.
1289          */
1290         if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1291                 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1292                 if (!io_req_cache_empty(ctx))
1293                         return true;
1294         }
1295
1296         ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1297
1298         /*
1299          * Bulk alloc is all-or-nothing. If we fail to get a batch,
1300          * retry single alloc to be on the safe side.
1301          */
1302         if (unlikely(ret <= 0)) {
1303                 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1304                 if (!reqs[0])
1305                         return false;
1306                 ret = 1;
1307         }
1308
1309         percpu_ref_get_many(&ctx->refs, ret);
1310         for (i = 0; i < ret; i++) {
1311                 struct io_kiocb *req = reqs[i];
1312
1313                 io_preinit_req(req, ctx);
1314                 io_req_add_to_cache(req, ctx);
1315         }
1316         return true;
1317 }
1318
1319 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1320 {
1321         if (unlikely(io_req_cache_empty(ctx)))
1322                 return __io_alloc_req_refill(ctx);
1323         return true;
1324 }
1325
1326 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1327 {
1328         struct io_wq_work_node *node;
1329
1330         node = wq_stack_extract(&ctx->submit_state.free_list);
1331         return container_of(node, struct io_kiocb, comp_list);
1332 }
1333
1334 static inline void io_dismantle_req(struct io_kiocb *req)
1335 {
1336         unsigned int flags = req->flags;
1337
1338         if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1339                 io_clean_op(req);
1340         if (!(flags & REQ_F_FIXED_FILE))
1341                 io_put_file(req->file);
1342 }
1343
1344 __cold void io_free_req(struct io_kiocb *req)
1345 {
1346         struct io_ring_ctx *ctx = req->ctx;
1347
1348         io_req_put_rsrc(req);
1349         io_dismantle_req(req);
1350         io_put_task(req->task, 1);
1351
1352         spin_lock(&ctx->completion_lock);
1353         wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1354         ctx->locked_free_nr++;
1355         spin_unlock(&ctx->completion_lock);
1356 }
1357
1358 static void __io_req_find_next_prep(struct io_kiocb *req)
1359 {
1360         struct io_ring_ctx *ctx = req->ctx;
1361         bool posted;
1362
1363         spin_lock(&ctx->completion_lock);
1364         posted = io_disarm_next(req);
1365         io_commit_cqring(ctx);
1366         spin_unlock(&ctx->completion_lock);
1367         if (posted)
1368                 io_cqring_ev_posted(ctx);
1369 }
1370
1371 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1372 {
1373         struct io_kiocb *nxt;
1374
1375         /*
1376          * If LINK is set, we have dependent requests in this chain. If we
1377          * didn't fail this request, queue the first one up, moving any other
1378          * dependencies to the next request. In case of failure, fail the rest
1379          * of the chain.
1380          */
1381         if (unlikely(req->flags & IO_DISARM_MASK))
1382                 __io_req_find_next_prep(req);
1383         nxt = req->link;
1384         req->link = NULL;
1385         return nxt;
1386 }
1387
1388 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
1389 {
1390         if (!ctx)
1391                 return;
1392         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1393                 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1394         if (*locked) {
1395                 io_submit_flush_completions(ctx);
1396                 mutex_unlock(&ctx->uring_lock);
1397                 *locked = false;
1398         }
1399         percpu_ref_put(&ctx->refs);
1400 }
1401
1402 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
1403 {
1404         io_commit_cqring(ctx);
1405         spin_unlock(&ctx->completion_lock);
1406         io_cqring_ev_posted(ctx);
1407 }
1408
1409 static void handle_prev_tw_list(struct io_wq_work_node *node,
1410                                 struct io_ring_ctx **ctx, bool *uring_locked)
1411 {
1412         if (*ctx && !*uring_locked)
1413                 spin_lock(&(*ctx)->completion_lock);
1414
1415         do {
1416                 struct io_wq_work_node *next = node->next;
1417                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1418                                                     io_task_work.node);
1419
1420                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1421
1422                 if (req->ctx != *ctx) {
1423                         if (unlikely(!*uring_locked && *ctx))
1424                                 ctx_commit_and_unlock(*ctx);
1425
1426                         ctx_flush_and_put(*ctx, uring_locked);
1427                         *ctx = req->ctx;
1428                         /* if not contended, grab and improve batching */
1429                         *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
1430                         percpu_ref_get(&(*ctx)->refs);
1431                         if (unlikely(!*uring_locked))
1432                                 spin_lock(&(*ctx)->completion_lock);
1433                 }
1434                 if (likely(*uring_locked)) {
1435                         req->io_task_work.func(req, uring_locked);
1436                 } else {
1437                         req->cqe.flags = io_put_kbuf_comp(req);
1438                         __io_req_complete_post(req);
1439                 }
1440                 node = next;
1441         } while (node);
1442
1443         if (unlikely(!*uring_locked))
1444                 ctx_commit_and_unlock(*ctx);
1445 }
1446
1447 static void handle_tw_list(struct io_wq_work_node *node,
1448                            struct io_ring_ctx **ctx, bool *locked)
1449 {
1450         do {
1451                 struct io_wq_work_node *next = node->next;
1452                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1453                                                     io_task_work.node);
1454
1455                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
1456
1457                 if (req->ctx != *ctx) {
1458                         ctx_flush_and_put(*ctx, locked);
1459                         *ctx = req->ctx;
1460                         /* if not contended, grab and improve batching */
1461                         *locked = mutex_trylock(&(*ctx)->uring_lock);
1462                         percpu_ref_get(&(*ctx)->refs);
1463                 }
1464                 req->io_task_work.func(req, locked);
1465                 node = next;
1466         } while (node);
1467 }
1468
1469 void tctx_task_work(struct callback_head *cb)
1470 {
1471         bool uring_locked = false;
1472         struct io_ring_ctx *ctx = NULL;
1473         struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1474                                                   task_work);
1475
1476         while (1) {
1477                 struct io_wq_work_node *node1, *node2;
1478
1479                 spin_lock_irq(&tctx->task_lock);
1480                 node1 = tctx->prio_task_list.first;
1481                 node2 = tctx->task_list.first;
1482                 INIT_WQ_LIST(&tctx->task_list);
1483                 INIT_WQ_LIST(&tctx->prio_task_list);
1484                 if (!node2 && !node1)
1485                         tctx->task_running = false;
1486                 spin_unlock_irq(&tctx->task_lock);
1487                 if (!node2 && !node1)
1488                         break;
1489
1490                 if (node1)
1491                         handle_prev_tw_list(node1, &ctx, &uring_locked);
1492                 if (node2)
1493                         handle_tw_list(node2, &ctx, &uring_locked);
1494                 cond_resched();
1495
1496                 if (data_race(!tctx->task_list.first) &&
1497                     data_race(!tctx->prio_task_list.first) && uring_locked)
1498                         io_submit_flush_completions(ctx);
1499         }
1500
1501         ctx_flush_and_put(ctx, &uring_locked);
1502
1503         /* relaxed read is enough as only the task itself sets ->in_idle */
1504         if (unlikely(atomic_read(&tctx->in_idle)))
1505                 io_uring_drop_tctx_refs(current);
1506 }
1507
1508 static void __io_req_task_work_add(struct io_kiocb *req,
1509                                    struct io_uring_task *tctx,
1510                                    struct io_wq_work_list *list)
1511 {
1512         struct io_ring_ctx *ctx = req->ctx;
1513         struct io_wq_work_node *node;
1514         unsigned long flags;
1515         bool running;
1516
1517         spin_lock_irqsave(&tctx->task_lock, flags);
1518         wq_list_add_tail(&req->io_task_work.node, list);
1519         running = tctx->task_running;
1520         if (!running)
1521                 tctx->task_running = true;
1522         spin_unlock_irqrestore(&tctx->task_lock, flags);
1523
1524         /* task_work already pending, we're done */
1525         if (running)
1526                 return;
1527
1528         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1529                 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1530
1531         if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
1532                 return;
1533
1534         spin_lock_irqsave(&tctx->task_lock, flags);
1535         tctx->task_running = false;
1536         node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
1537         spin_unlock_irqrestore(&tctx->task_lock, flags);
1538
1539         while (node) {
1540                 req = container_of(node, struct io_kiocb, io_task_work.node);
1541                 node = node->next;
1542                 if (llist_add(&req->io_task_work.fallback_node,
1543                               &req->ctx->fallback_llist))
1544                         schedule_delayed_work(&req->ctx->fallback_work, 1);
1545         }
1546 }
1547
1548 void io_req_task_work_add(struct io_kiocb *req)
1549 {
1550         struct io_uring_task *tctx = req->task->io_uring;
1551
1552         __io_req_task_work_add(req, tctx, &tctx->task_list);
1553 }
1554
1555 static void io_req_task_prio_work_add(struct io_kiocb *req)
1556 {
1557         struct io_uring_task *tctx = req->task->io_uring;
1558
1559         if (req->ctx->flags & IORING_SETUP_SQPOLL)
1560                 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
1561         else
1562                 __io_req_task_work_add(req, tctx, &tctx->task_list);
1563 }
1564
1565 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
1566 {
1567         io_req_complete_post(req);
1568 }
1569
1570 void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
1571 {
1572         io_req_set_res(req, res, cflags);
1573         req->io_task_work.func = io_req_tw_post;
1574         io_req_task_work_add(req);
1575 }
1576
1577 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
1578 {
1579         /* not needed for normal modes, but SQPOLL depends on it */
1580         io_tw_lock(req->ctx, locked);
1581         io_req_complete_failed(req, req->cqe.res);
1582 }
1583
1584 void io_req_task_submit(struct io_kiocb *req, bool *locked)
1585 {
1586         io_tw_lock(req->ctx, locked);
1587         /* req->task == current here, checking PF_EXITING is safe */
1588         if (likely(!(req->task->flags & PF_EXITING)))
1589                 io_queue_sqe(req);
1590         else
1591                 io_req_complete_failed(req, -EFAULT);
1592 }
1593
1594 void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1595 {
1596         io_req_set_res(req, ret, 0);
1597         req->io_task_work.func = io_req_task_cancel;
1598         io_req_task_work_add(req);
1599 }
1600
1601 static void io_req_task_queue(struct io_kiocb *req)
1602 {
1603         req->io_task_work.func = io_req_task_submit;
1604         io_req_task_work_add(req);
1605 }
1606
1607 static void io_req_task_queue_reissue(struct io_kiocb *req)
1608 {
1609         req->io_task_work.func = io_queue_iowq;
1610         io_req_task_work_add(req);
1611 }
1612
1613 void io_queue_next(struct io_kiocb *req)
1614 {
1615         struct io_kiocb *nxt = io_req_find_next(req);
1616
1617         if (nxt)
1618                 io_req_task_queue(nxt);
1619 }
1620
1621 static void io_free_batch_list(struct io_ring_ctx *ctx,
1622                                 struct io_wq_work_node *node)
1623         __must_hold(&ctx->uring_lock)
1624 {
1625         struct task_struct *task = NULL;
1626         int task_refs = 0;
1627
1628         do {
1629                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1630                                                     comp_list);
1631
1632                 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
1633                         if (req->flags & REQ_F_REFCOUNT) {
1634                                 node = req->comp_list.next;
1635                                 if (!req_ref_put_and_test(req))
1636                                         continue;
1637                         }
1638                         if ((req->flags & REQ_F_POLLED) && req->apoll) {
1639                                 struct async_poll *apoll = req->apoll;
1640
1641                                 if (apoll->double_poll)
1642                                         kfree(apoll->double_poll);
1643                                 list_add(&apoll->poll.wait.entry,
1644                                                 &ctx->apoll_cache);
1645                                 req->flags &= ~REQ_F_POLLED;
1646                         }
1647                         if (req->flags & IO_REQ_LINK_FLAGS)
1648                                 io_queue_next(req);
1649                         if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
1650                                 io_clean_op(req);
1651                 }
1652                 if (!(req->flags & REQ_F_FIXED_FILE))
1653                         io_put_file(req->file);
1654
1655                 io_req_put_rsrc_locked(req, ctx);
1656
1657                 if (req->task != task) {
1658                         if (task)
1659                                 io_put_task(task, task_refs);
1660                         task = req->task;
1661                         task_refs = 0;
1662                 }
1663                 task_refs++;
1664                 node = req->comp_list.next;
1665                 io_req_add_to_cache(req, ctx);
1666         } while (node);
1667
1668         if (task)
1669                 io_put_task(task, task_refs);
1670 }
1671
1672 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
1673         __must_hold(&ctx->uring_lock)
1674 {
1675         struct io_wq_work_node *node, *prev;
1676         struct io_submit_state *state = &ctx->submit_state;
1677
1678         if (state->flush_cqes) {
1679                 spin_lock(&ctx->completion_lock);
1680                 wq_list_for_each(node, prev, &state->compl_reqs) {
1681                         struct io_kiocb *req = container_of(node, struct io_kiocb,
1682                                                     comp_list);
1683
1684                         if (!(req->flags & REQ_F_CQE_SKIP))
1685                                 __io_fill_cqe_req(ctx, req);
1686                 }
1687
1688                 io_commit_cqring(ctx);
1689                 spin_unlock(&ctx->completion_lock);
1690                 io_cqring_ev_posted(ctx);
1691                 state->flush_cqes = false;
1692         }
1693
1694         io_free_batch_list(ctx, state->compl_reqs.first);
1695         INIT_WQ_LIST(&state->compl_reqs);
1696 }
1697
1698 /*
1699  * Drop reference to request, return next in chain (if there is one) if this
1700  * was the last reference to this request.
1701  */
1702 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
1703 {
1704         struct io_kiocb *nxt = NULL;
1705
1706         if (req_ref_put_and_test(req)) {
1707                 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
1708                         nxt = io_req_find_next(req);
1709                 io_free_req(req);
1710         }
1711         return nxt;
1712 }
1713
1714 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
1715 {
1716         /* See comment at the top of this file */
1717         smp_rmb();
1718         return __io_cqring_events(ctx);
1719 }
1720
1721 int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
1722 {
1723         struct io_wq_work_node *pos, *start, *prev;
1724         unsigned int poll_flags = BLK_POLL_NOSLEEP;
1725         DEFINE_IO_COMP_BATCH(iob);
1726         int nr_events = 0;
1727
1728         /*
1729          * Only spin for completions if we don't have multiple devices hanging
1730          * off our complete list.
1731          */
1732         if (ctx->poll_multi_queue || force_nonspin)
1733                 poll_flags |= BLK_POLL_ONESHOT;
1734
1735         wq_list_for_each(pos, start, &ctx->iopoll_list) {
1736                 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1737                 struct io_rw *rw = io_kiocb_to_cmd(req);
1738                 int ret;
1739
1740                 /*
1741                  * Move completed and retryable entries to our local lists.
1742                  * If we find a request that requires polling, break out
1743                  * and complete those lists first, if we have entries there.
1744                  */
1745                 if (READ_ONCE(req->iopoll_completed))
1746                         break;
1747
1748                 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
1749                 if (unlikely(ret < 0))
1750                         return ret;
1751                 else if (ret)
1752                         poll_flags |= BLK_POLL_ONESHOT;
1753
1754                 /* iopoll may have completed current req */
1755                 if (!rq_list_empty(iob.req_list) ||
1756                     READ_ONCE(req->iopoll_completed))
1757                         break;
1758         }
1759
1760         if (!rq_list_empty(iob.req_list))
1761                 iob.complete(&iob);
1762         else if (!pos)
1763                 return 0;
1764
1765         prev = start;
1766         wq_list_for_each_resume(pos, prev) {
1767                 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
1768
1769                 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
1770                 if (!smp_load_acquire(&req->iopoll_completed))
1771                         break;
1772                 nr_events++;
1773                 if (unlikely(req->flags & REQ_F_CQE_SKIP))
1774                         continue;
1775
1776                 req->cqe.flags = io_put_kbuf(req, 0);
1777                 __io_fill_cqe_req(req->ctx, req);
1778         }
1779
1780         if (unlikely(!nr_events))
1781                 return 0;
1782
1783         io_commit_cqring(ctx);
1784         io_cqring_ev_posted_iopoll(ctx);
1785         pos = start ? start->next : ctx->iopoll_list.first;
1786         wq_list_cut(&ctx->iopoll_list, prev, start);
1787         io_free_batch_list(ctx, pos);
1788         return nr_events;
1789 }
1790
1791 /*
1792  * We can't just wait for polled events to come to us, we have to actively
1793  * find and complete them.
1794  */
1795 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
1796 {
1797         if (!(ctx->flags & IORING_SETUP_IOPOLL))
1798                 return;
1799
1800         mutex_lock(&ctx->uring_lock);
1801         while (!wq_list_empty(&ctx->iopoll_list)) {
1802                 /* let it sleep and repeat later if can't complete a request */
1803                 if (io_do_iopoll(ctx, true) == 0)
1804                         break;
1805                 /*
1806                  * Ensure we allow local-to-the-cpu processing to take place,
1807                  * in this case we need to ensure that we reap all events.
1808                  * Also let task_work, etc. to progress by releasing the mutex
1809                  */
1810                 if (need_resched()) {
1811                         mutex_unlock(&ctx->uring_lock);
1812                         cond_resched();
1813                         mutex_lock(&ctx->uring_lock);
1814                 }
1815         }
1816         mutex_unlock(&ctx->uring_lock);
1817 }
1818
1819 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
1820 {
1821         unsigned int nr_events = 0;
1822         int ret = 0;
1823         unsigned long check_cq;
1824
1825         /*
1826          * Don't enter poll loop if we already have events pending.
1827          * If we do, we can potentially be spinning for commands that
1828          * already triggered a CQE (eg in error).
1829          */
1830         check_cq = READ_ONCE(ctx->check_cq);
1831         if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
1832                 __io_cqring_overflow_flush(ctx, false);
1833         if (io_cqring_events(ctx))
1834                 return 0;
1835
1836         /*
1837          * Similarly do not spin if we have not informed the user of any
1838          * dropped CQE.
1839          */
1840         if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
1841                 return -EBADR;
1842
1843         do {
1844                 /*
1845                  * If a submit got punted to a workqueue, we can have the
1846                  * application entering polling for a command before it gets
1847                  * issued. That app will hold the uring_lock for the duration
1848                  * of the poll right here, so we need to take a breather every
1849                  * now and then to ensure that the issue has a chance to add
1850                  * the poll to the issued list. Otherwise we can spin here
1851                  * forever, while the workqueue is stuck trying to acquire the
1852                  * very same mutex.
1853                  */
1854                 if (wq_list_empty(&ctx->iopoll_list)) {
1855                         u32 tail = ctx->cached_cq_tail;
1856
1857                         mutex_unlock(&ctx->uring_lock);
1858                         io_run_task_work();
1859                         mutex_lock(&ctx->uring_lock);
1860
1861                         /* some requests don't go through iopoll_list */
1862                         if (tail != ctx->cached_cq_tail ||
1863                             wq_list_empty(&ctx->iopoll_list))
1864                                 break;
1865                 }
1866                 ret = io_do_iopoll(ctx, !min);
1867                 if (ret < 0)
1868                         break;
1869                 nr_events += ret;
1870                 ret = 0;
1871         } while (nr_events < min && !need_resched());
1872
1873         return ret;
1874 }
1875
1876 static void kiocb_end_write(struct io_kiocb *req)
1877 {
1878         /*
1879          * Tell lockdep we inherited freeze protection from submission
1880          * thread.
1881          */
1882         if (req->flags & REQ_F_ISREG) {
1883                 struct super_block *sb = file_inode(req->file)->i_sb;
1884
1885                 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
1886                 sb_end_write(sb);
1887         }
1888 }
1889
1890 #ifdef CONFIG_BLOCK
1891 static bool io_resubmit_prep(struct io_kiocb *req)
1892 {
1893         struct io_async_rw *io = req->async_data;
1894
1895         if (!req_has_async_data(req))
1896                 return !io_req_prep_async(req);
1897         iov_iter_restore(&io->s.iter, &io->s.iter_state);
1898         return true;
1899 }
1900
1901 static bool io_rw_should_reissue(struct io_kiocb *req)
1902 {
1903         umode_t mode = file_inode(req->file)->i_mode;
1904         struct io_ring_ctx *ctx = req->ctx;
1905
1906         if (!S_ISBLK(mode) && !S_ISREG(mode))
1907                 return false;
1908         if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
1909             !(ctx->flags & IORING_SETUP_IOPOLL)))
1910                 return false;
1911         /*
1912          * If ref is dying, we might be running poll reap from the exit work.
1913          * Don't attempt to reissue from that path, just let it fail with
1914          * -EAGAIN.
1915          */
1916         if (percpu_ref_is_dying(&ctx->refs))
1917                 return false;
1918         /*
1919          * Play it safe and assume not safe to re-import and reissue if we're
1920          * not in the original thread group (or in task context).
1921          */
1922         if (!same_thread_group(req->task, current) || !in_task())
1923                 return false;
1924         return true;
1925 }
1926 #else
1927 static bool io_resubmit_prep(struct io_kiocb *req)
1928 {
1929         return false;
1930 }
1931 static bool io_rw_should_reissue(struct io_kiocb *req)
1932 {
1933         return false;
1934 }
1935 #endif
1936
1937 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
1938 {
1939         struct io_rw *rw = io_kiocb_to_cmd(req);
1940
1941         if (rw->kiocb.ki_flags & IOCB_WRITE) {
1942                 kiocb_end_write(req);
1943                 fsnotify_modify(req->file);
1944         } else {
1945                 fsnotify_access(req->file);
1946         }
1947         if (unlikely(res != req->cqe.res)) {
1948                 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
1949                     io_rw_should_reissue(req)) {
1950                         req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
1951                         return true;
1952                 }
1953                 req_set_fail(req);
1954                 req->cqe.res = res;
1955         }
1956         return false;
1957 }
1958
1959 inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
1960 {
1961         if (*locked) {
1962                 req->cqe.flags |= io_put_kbuf(req, 0);
1963                 req->flags |= REQ_F_COMPLETE_INLINE;
1964                 io_req_add_compl_list(req);
1965         } else {
1966                 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
1967                 io_req_complete_post(req);
1968         }
1969 }
1970
1971 static void __io_complete_rw(struct io_kiocb *req, long res,
1972                              unsigned int issue_flags)
1973 {
1974         if (__io_complete_rw_common(req, res))
1975                 return;
1976         io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
1977         __io_req_complete(req, issue_flags);
1978 }
1979
1980 static void io_complete_rw(struct kiocb *kiocb, long res)
1981 {
1982         struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1983         struct io_kiocb *req = cmd_to_io_kiocb(rw);
1984
1985         if (__io_complete_rw_common(req, res))
1986                 return;
1987         io_req_set_res(req, res, 0);
1988         req->io_task_work.func = io_req_task_complete;
1989         io_req_task_prio_work_add(req);
1990 }
1991
1992 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
1993 {
1994         struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
1995         struct io_kiocb *req = cmd_to_io_kiocb(rw);
1996
1997         if (kiocb->ki_flags & IOCB_WRITE)
1998                 kiocb_end_write(req);
1999         if (unlikely(res != req->cqe.res)) {
2000                 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2001                         req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2002                         return;
2003                 }
2004                 req->cqe.res = res;
2005         }
2006
2007         /* order with io_iopoll_complete() checking ->iopoll_completed */
2008         smp_store_release(&req->iopoll_completed, 1);
2009 }
2010
2011 /*
2012  * After the iocb has been issued, it's safe to be found on the poll list.
2013  * Adding the kiocb to the list AFTER submission ensures that we don't
2014  * find it from a io_do_iopoll() thread before the issuer is done
2015  * accessing the kiocb cookie.
2016  */
2017 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2018 {
2019         struct io_ring_ctx *ctx = req->ctx;
2020         const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2021
2022         /* workqueue context doesn't hold uring_lock, grab it now */
2023         if (unlikely(needs_lock))
2024                 mutex_lock(&ctx->uring_lock);
2025
2026         /*
2027          * Track whether we have multiple files in our lists. This will impact
2028          * how we do polling eventually, not spinning if we're on potentially
2029          * different devices.
2030          */
2031         if (wq_list_empty(&ctx->iopoll_list)) {
2032                 ctx->poll_multi_queue = false;
2033         } else if (!ctx->poll_multi_queue) {
2034                 struct io_kiocb *list_req;
2035
2036                 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2037                                         comp_list);
2038                 if (list_req->file != req->file)
2039                         ctx->poll_multi_queue = true;
2040         }
2041
2042         /*
2043          * For fast devices, IO may have already completed. If it has, add
2044          * it to the front so we find it first.
2045          */
2046         if (READ_ONCE(req->iopoll_completed))
2047                 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2048         else
2049                 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2050
2051         if (unlikely(needs_lock)) {
2052                 /*
2053                  * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2054                  * in sq thread task context or in io worker task context. If
2055                  * current task context is sq thread, we don't need to check
2056                  * whether should wake up sq thread.
2057                  */
2058                 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2059                     wq_has_sleeper(&ctx->sq_data->wait))
2060                         wake_up(&ctx->sq_data->wait);
2061
2062                 mutex_unlock(&ctx->uring_lock);
2063         }
2064 }
2065
2066 static bool io_bdev_nowait(struct block_device *bdev)
2067 {
2068         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2069 }
2070
2071 /*
2072  * If we tracked the file through the SCM inflight mechanism, we could support
2073  * any file. For now, just ensure that anything potentially problematic is done
2074  * inline.
2075  */
2076 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2077 {
2078         if (S_ISBLK(mode)) {
2079                 if (IS_ENABLED(CONFIG_BLOCK) &&
2080                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2081                         return true;
2082                 return false;
2083         }
2084         if (S_ISSOCK(mode))
2085                 return true;
2086         if (S_ISREG(mode)) {
2087                 if (IS_ENABLED(CONFIG_BLOCK) &&
2088                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2089                     !io_is_uring_fops(file))
2090                         return true;
2091                 return false;
2092         }
2093
2094         /* any ->read/write should understand O_NONBLOCK */
2095         if (file->f_flags & O_NONBLOCK)
2096                 return true;
2097         return file->f_mode & FMODE_NOWAIT;
2098 }
2099
2100 /*
2101  * If we tracked the file through the SCM inflight mechanism, we could support
2102  * any file. For now, just ensure that anything potentially problematic is done
2103  * inline.
2104  */
2105 unsigned int io_file_get_flags(struct file *file)
2106 {
2107         umode_t mode = file_inode(file)->i_mode;
2108         unsigned int res = 0;
2109
2110         if (S_ISREG(mode))
2111                 res |= FFS_ISREG;
2112         if (__io_file_supports_nowait(file, mode))
2113                 res |= FFS_NOWAIT;
2114         if (io_file_need_scm(file))
2115                 res |= FFS_SCM;
2116         return res;
2117 }
2118
2119 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2120 {
2121         return req->flags & REQ_F_SUPPORT_NOWAIT;
2122 }
2123
2124 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2125 {
2126         struct io_rw *rw = io_kiocb_to_cmd(req);
2127         unsigned ioprio;
2128         int ret;
2129
2130         rw->kiocb.ki_pos = READ_ONCE(sqe->off);
2131         /* used for fixed read/write too - just read unconditionally */
2132         req->buf_index = READ_ONCE(sqe->buf_index);
2133
2134         if (req->opcode == IORING_OP_READ_FIXED ||
2135             req->opcode == IORING_OP_WRITE_FIXED) {
2136                 struct io_ring_ctx *ctx = req->ctx;
2137                 u16 index;
2138
2139                 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2140                         return -EFAULT;
2141                 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2142                 req->imu = ctx->user_bufs[index];
2143                 io_req_set_rsrc_node(req, ctx, 0);
2144         }
2145
2146         ioprio = READ_ONCE(sqe->ioprio);
2147         if (ioprio) {
2148                 ret = ioprio_check_cap(ioprio);
2149                 if (ret)
2150                         return ret;
2151
2152                 rw->kiocb.ki_ioprio = ioprio;
2153         } else {
2154                 rw->kiocb.ki_ioprio = get_current_ioprio();
2155         }
2156
2157         rw->addr = READ_ONCE(sqe->addr);
2158         rw->len = READ_ONCE(sqe->len);
2159         rw->flags = READ_ONCE(sqe->rw_flags);
2160         return 0;
2161 }
2162
2163 static void io_readv_writev_cleanup(struct io_kiocb *req)
2164 {
2165         struct io_async_rw *io = req->async_data;
2166
2167         kfree(io->free_iovec);
2168 }
2169
2170 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2171 {
2172         switch (ret) {
2173         case -EIOCBQUEUED:
2174                 break;
2175         case -ERESTARTSYS:
2176         case -ERESTARTNOINTR:
2177         case -ERESTARTNOHAND:
2178         case -ERESTART_RESTARTBLOCK:
2179                 /*
2180                  * We can't just restart the syscall, since previously
2181                  * submitted sqes may already be in progress. Just fail this
2182                  * IO with EINTR.
2183                  */
2184                 ret = -EINTR;
2185                 fallthrough;
2186         default:
2187                 kiocb->ki_complete(kiocb, ret);
2188         }
2189 }
2190
2191 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2192 {
2193         struct io_rw *rw = io_kiocb_to_cmd(req);
2194
2195         if (rw->kiocb.ki_pos != -1)
2196                 return &rw->kiocb.ki_pos;
2197
2198         if (!(req->file->f_mode & FMODE_STREAM)) {
2199                 req->flags |= REQ_F_CUR_POS;
2200                 rw->kiocb.ki_pos = req->file->f_pos;
2201                 return &rw->kiocb.ki_pos;
2202         }
2203
2204         rw->kiocb.ki_pos = 0;
2205         return NULL;
2206 }
2207
2208 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2209                        unsigned int issue_flags)
2210 {
2211         struct io_async_rw *io = req->async_data;
2212         struct io_rw *rw = io_kiocb_to_cmd(req);
2213
2214         /* add previously done IO, if any */
2215         if (req_has_async_data(req) && io->bytes_done > 0) {
2216                 if (ret < 0)
2217                         ret = io->bytes_done;
2218                 else
2219                         ret += io->bytes_done;
2220         }
2221
2222         if (req->flags & REQ_F_CUR_POS)
2223                 req->file->f_pos = rw->kiocb.ki_pos;
2224         if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2225                 __io_complete_rw(req, ret, issue_flags);
2226         else
2227                 io_rw_done(&rw->kiocb, ret);
2228
2229         if (req->flags & REQ_F_REISSUE) {
2230                 req->flags &= ~REQ_F_REISSUE;
2231                 if (io_resubmit_prep(req))
2232                         io_req_task_queue_reissue(req);
2233                 else
2234                         io_req_task_queue_fail(req, ret);
2235         }
2236 }
2237
2238 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2239                              struct iov_iter *iter, struct io_mapped_ubuf *imu)
2240 {
2241         struct io_rw *rw = io_kiocb_to_cmd(req);
2242         size_t len = rw->len;
2243         u64 buf_end, buf_addr = rw->addr;
2244         size_t offset;
2245
2246         if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2247                 return -EFAULT;
2248         /* not inside the mapped region */
2249         if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2250                 return -EFAULT;
2251
2252         /*
2253          * May not be a start of buffer, set size appropriately
2254          * and advance us to the beginning.
2255          */
2256         offset = buf_addr - imu->ubuf;
2257         iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2258
2259         if (offset) {
2260                 /*
2261                  * Don't use iov_iter_advance() here, as it's really slow for
2262                  * using the latter parts of a big fixed buffer - it iterates
2263                  * over each segment manually. We can cheat a bit here, because
2264                  * we know that:
2265                  *
2266                  * 1) it's a BVEC iter, we set it up
2267                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2268                  *    first and last bvec
2269                  *
2270                  * So just find our index, and adjust the iterator afterwards.
2271                  * If the offset is within the first bvec (or the whole first
2272                  * bvec, just use iov_iter_advance(). This makes it easier
2273                  * since we can just skip the first segment, which may not
2274                  * be PAGE_SIZE aligned.
2275                  */
2276                 const struct bio_vec *bvec = imu->bvec;
2277
2278                 if (offset <= bvec->bv_len) {
2279                         iov_iter_advance(iter, offset);
2280                 } else {
2281                         unsigned long seg_skip;
2282
2283                         /* skip first vec */
2284                         offset -= bvec->bv_len;
2285                         seg_skip = 1 + (offset >> PAGE_SHIFT);
2286
2287                         iter->bvec = bvec + seg_skip;
2288                         iter->nr_segs -= seg_skip;
2289                         iter->count -= bvec->bv_len + offset;
2290                         iter->iov_offset = offset & ~PAGE_MASK;
2291                 }
2292         }
2293
2294         return 0;
2295 }
2296
2297 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2298                            unsigned int issue_flags)
2299 {
2300         if (WARN_ON_ONCE(!req->imu))
2301                 return -EFAULT;
2302         return __io_import_fixed(req, rw, iter, req->imu);
2303 }
2304
2305 static int io_buffer_add_list(struct io_ring_ctx *ctx,
2306                               struct io_buffer_list *bl, unsigned int bgid)
2307 {
2308         bl->bgid = bgid;
2309         if (bgid < BGID_ARRAY)
2310                 return 0;
2311
2312         return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
2313 }
2314
2315 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
2316                                               struct io_buffer_list *bl)
2317 {
2318         if (!list_empty(&bl->buf_list)) {
2319                 struct io_buffer *kbuf;
2320
2321                 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
2322                 list_del(&kbuf->list);
2323                 if (*len > kbuf->len)
2324                         *len = kbuf->len;
2325                 req->flags |= REQ_F_BUFFER_SELECTED;
2326                 req->kbuf = kbuf;
2327                 req->buf_index = kbuf->bid;
2328                 return u64_to_user_ptr(kbuf->addr);
2329         }
2330         return NULL;
2331 }
2332
2333 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
2334                                           struct io_buffer_list *bl,
2335                                           unsigned int issue_flags)
2336 {
2337         struct io_uring_buf_ring *br = bl->buf_ring;
2338         struct io_uring_buf *buf;
2339         __u16 head = bl->head;
2340
2341         if (unlikely(smp_load_acquire(&br->tail) == head))
2342                 return NULL;
2343
2344         head &= bl->mask;
2345         if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
2346                 buf = &br->bufs[head];
2347         } else {
2348                 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
2349                 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
2350                 buf = page_address(bl->buf_pages[index]);
2351                 buf += off;
2352         }
2353         if (*len > buf->len)
2354                 *len = buf->len;
2355         req->flags |= REQ_F_BUFFER_RING;
2356         req->buf_list = bl;
2357         req->buf_index = buf->bid;
2358
2359         if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
2360                 /*
2361                  * If we came in unlocked, we have no choice but to consume the
2362                  * buffer here. This does mean it'll be pinned until the IO
2363                  * completes. But coming in unlocked means we're in io-wq
2364                  * context, hence there should be no further retry. For the
2365                  * locked case, the caller must ensure to call the commit when
2366                  * the transfer completes (or if we get -EAGAIN and must poll
2367                  * or retry).
2368                  */
2369                 req->buf_list = NULL;
2370                 bl->head++;
2371         }
2372         return u64_to_user_ptr(buf->addr);
2373 }
2374
2375 void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
2376                               unsigned int issue_flags)
2377 {
2378         struct io_ring_ctx *ctx = req->ctx;
2379         struct io_buffer_list *bl;
2380         void __user *ret = NULL;
2381
2382         io_ring_submit_lock(req->ctx, issue_flags);
2383
2384         bl = io_buffer_get_list(ctx, req->buf_index);
2385         if (likely(bl)) {
2386                 if (bl->buf_nr_pages)
2387                         ret = io_ring_buffer_select(req, len, bl, issue_flags);
2388                 else
2389                         ret = io_provided_buffer_select(req, len, bl);
2390         }
2391         io_ring_submit_unlock(req->ctx, issue_flags);
2392         return ret;
2393 }
2394
2395 #ifdef CONFIG_COMPAT
2396 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2397                                 unsigned int issue_flags)
2398 {
2399         struct io_rw *rw = io_kiocb_to_cmd(req);
2400         struct compat_iovec __user *uiov;
2401         compat_ssize_t clen;
2402         void __user *buf;
2403         size_t len;
2404
2405         uiov = u64_to_user_ptr(rw->addr);
2406         if (!access_ok(uiov, sizeof(*uiov)))
2407                 return -EFAULT;
2408         if (__get_user(clen, &uiov->iov_len))
2409                 return -EFAULT;
2410         if (clen < 0)
2411                 return -EINVAL;
2412
2413         len = clen;
2414         buf = io_buffer_select(req, &len, issue_flags);
2415         if (!buf)
2416                 return -ENOBUFS;
2417         rw->addr = (unsigned long) buf;
2418         iov[0].iov_base = buf;
2419         rw->len = iov[0].iov_len = (compat_size_t) len;
2420         return 0;
2421 }
2422 #endif
2423
2424 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2425                                       unsigned int issue_flags)
2426 {
2427         struct io_rw *rw = io_kiocb_to_cmd(req);
2428         struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
2429         void __user *buf;
2430         ssize_t len;
2431
2432         if (copy_from_user(iov, uiov, sizeof(*uiov)))
2433                 return -EFAULT;
2434
2435         len = iov[0].iov_len;
2436         if (len < 0)
2437                 return -EINVAL;
2438         buf = io_buffer_select(req, &len, issue_flags);
2439         if (!buf)
2440                 return -ENOBUFS;
2441         rw->addr = (unsigned long) buf;
2442         iov[0].iov_base = buf;
2443         rw->len = iov[0].iov_len = len;
2444         return 0;
2445 }
2446
2447 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2448                                     unsigned int issue_flags)
2449 {
2450         struct io_rw *rw = io_kiocb_to_cmd(req);
2451
2452         if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
2453                 iov[0].iov_base = u64_to_user_ptr(rw->addr);
2454                 iov[0].iov_len = rw->len;
2455                 return 0;
2456         }
2457         if (rw->len != 1)
2458                 return -EINVAL;
2459
2460 #ifdef CONFIG_COMPAT
2461         if (req->ctx->compat)
2462                 return io_compat_import(req, iov, issue_flags);
2463 #endif
2464
2465         return __io_iov_buffer_select(req, iov, issue_flags);
2466 }
2467
2468 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
2469                                        struct io_rw_state *s,
2470                                        unsigned int issue_flags)
2471 {
2472         struct io_rw *rw = io_kiocb_to_cmd(req);
2473         struct iov_iter *iter = &s->iter;
2474         u8 opcode = req->opcode;
2475         struct iovec *iovec;
2476         void __user *buf;
2477         size_t sqe_len;
2478         ssize_t ret;
2479
2480         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2481                 ret = io_import_fixed(req, ddir, iter, issue_flags);
2482                 if (ret)
2483                         return ERR_PTR(ret);
2484                 return NULL;
2485         }
2486
2487         buf = u64_to_user_ptr(rw->addr);
2488         sqe_len = rw->len;
2489
2490         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2491                 if (io_do_buffer_select(req)) {
2492                         buf = io_buffer_select(req, &sqe_len, issue_flags);
2493                         if (!buf)
2494                                 return ERR_PTR(-ENOBUFS);
2495                         rw->addr = (unsigned long) buf;
2496                         rw->len = sqe_len;
2497                 }
2498
2499                 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
2500                 if (ret)
2501                         return ERR_PTR(ret);
2502                 return NULL;
2503         }
2504
2505         iovec = s->fast_iov;
2506         if (req->flags & REQ_F_BUFFER_SELECT) {
2507                 ret = io_iov_buffer_select(req, iovec, issue_flags);
2508                 if (ret)
2509                         return ERR_PTR(ret);
2510                 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
2511                 return NULL;
2512         }
2513
2514         ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
2515                               req->ctx->compat);
2516         if (unlikely(ret < 0))
2517                 return ERR_PTR(ret);
2518         return iovec;
2519 }
2520
2521 static inline int io_import_iovec(int rw, struct io_kiocb *req,
2522                                   struct iovec **iovec, struct io_rw_state *s,
2523                                   unsigned int issue_flags)
2524 {
2525         *iovec = __io_import_iovec(rw, req, s, issue_flags);
2526         if (unlikely(IS_ERR(*iovec)))
2527                 return PTR_ERR(*iovec);
2528
2529         iov_iter_save_state(&s->iter, &s->iter_state);
2530         return 0;
2531 }
2532
2533 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2534 {
2535         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2536 }
2537
2538 /*
2539  * For files that don't have ->read_iter() and ->write_iter(), handle them
2540  * by looping over ->read() or ->write() manually.
2541  */
2542 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
2543 {
2544         struct kiocb *kiocb = &rw->kiocb;
2545         struct file *file = kiocb->ki_filp;
2546         ssize_t ret = 0;
2547         loff_t *ppos;
2548
2549         /*
2550          * Don't support polled IO through this interface, and we can't
2551          * support non-blocking either. For the latter, this just causes
2552          * the kiocb to be handled from an async context.
2553          */
2554         if (kiocb->ki_flags & IOCB_HIPRI)
2555                 return -EOPNOTSUPP;
2556         if ((kiocb->ki_flags & IOCB_NOWAIT) &&
2557             !(kiocb->ki_filp->f_flags & O_NONBLOCK))
2558                 return -EAGAIN;
2559
2560         ppos = io_kiocb_ppos(kiocb);
2561
2562         while (iov_iter_count(iter)) {
2563                 struct iovec iovec;
2564                 ssize_t nr;
2565
2566                 if (!iov_iter_is_bvec(iter)) {
2567                         iovec = iov_iter_iovec(iter);
2568                 } else {
2569                         iovec.iov_base = u64_to_user_ptr(rw->addr);
2570                         iovec.iov_len = rw->len;
2571                 }
2572
2573                 if (ddir == READ) {
2574                         nr = file->f_op->read(file, iovec.iov_base,
2575                                               iovec.iov_len, ppos);
2576                 } else {
2577                         nr = file->f_op->write(file, iovec.iov_base,
2578                                                iovec.iov_len, ppos);
2579                 }
2580
2581                 if (nr < 0) {
2582                         if (!ret)
2583                                 ret = nr;
2584                         break;
2585                 }
2586                 ret += nr;
2587                 if (!iov_iter_is_bvec(iter)) {
2588                         iov_iter_advance(iter, nr);
2589                 } else {
2590                         rw->addr += nr;
2591                         rw->len -= nr;
2592                         if (!rw->len)
2593                                 break;
2594                 }
2595                 if (nr != iovec.iov_len)
2596                         break;
2597         }
2598
2599         return ret;
2600 }
2601
2602 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
2603                           const struct iovec *fast_iov, struct iov_iter *iter)
2604 {
2605         struct io_async_rw *io = req->async_data;
2606
2607         memcpy(&io->s.iter, iter, sizeof(*iter));
2608         io->free_iovec = iovec;
2609         io->bytes_done = 0;
2610         /* can only be fixed buffers, no need to do anything */
2611         if (iov_iter_is_bvec(iter))
2612                 return;
2613         if (!iovec) {
2614                 unsigned iov_off = 0;
2615
2616                 io->s.iter.iov = io->s.fast_iov;
2617                 if (iter->iov != fast_iov) {
2618                         iov_off = iter->iov - fast_iov;
2619                         io->s.iter.iov += iov_off;
2620                 }
2621                 if (io->s.fast_iov != fast_iov)
2622                         memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
2623                                sizeof(struct iovec) * iter->nr_segs);
2624         } else {
2625                 req->flags |= REQ_F_NEED_CLEANUP;
2626         }
2627 }
2628
2629 bool io_alloc_async_data(struct io_kiocb *req)
2630 {
2631         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
2632         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
2633         if (req->async_data) {
2634                 req->flags |= REQ_F_ASYNC_DATA;
2635                 return false;
2636         }
2637         return true;
2638 }
2639
2640 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
2641                              struct io_rw_state *s, bool force)
2642 {
2643         if (!force && !io_op_defs[req->opcode].prep_async)
2644                 return 0;
2645         if (!req_has_async_data(req)) {
2646                 struct io_async_rw *iorw;
2647
2648                 if (io_alloc_async_data(req)) {
2649                         kfree(iovec);
2650                         return -ENOMEM;
2651                 }
2652
2653                 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
2654                 iorw = req->async_data;
2655                 /* we've copied and mapped the iter, ensure state is saved */
2656                 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
2657         }
2658         return 0;
2659 }
2660
2661 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
2662 {
2663         struct io_async_rw *iorw = req->async_data;
2664         struct iovec *iov;
2665         int ret;
2666
2667         /* submission path, ->uring_lock should already be taken */
2668         ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
2669         if (unlikely(ret < 0))
2670                 return ret;
2671
2672         iorw->bytes_done = 0;
2673         iorw->free_iovec = iov;
2674         if (iov)
2675                 req->flags |= REQ_F_NEED_CLEANUP;
2676         return 0;
2677 }
2678
2679 static int io_readv_prep_async(struct io_kiocb *req)
2680 {
2681         return io_rw_prep_async(req, READ);
2682 }
2683
2684 static int io_writev_prep_async(struct io_kiocb *req)
2685 {
2686         return io_rw_prep_async(req, WRITE);
2687 }
2688
2689 /*
2690  * This is our waitqueue callback handler, registered through __folio_lock_async()
2691  * when we initially tried to do the IO with the iocb armed our waitqueue.
2692  * This gets called when the page is unlocked, and we generally expect that to
2693  * happen when the page IO is completed and the page is now uptodate. This will
2694  * queue a task_work based retry of the operation, attempting to copy the data
2695  * again. If the latter fails because the page was NOT uptodate, then we will
2696  * do a thread based blocking retry of the operation. That's the unexpected
2697  * slow path.
2698  */
2699 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2700                              int sync, void *arg)
2701 {
2702         struct wait_page_queue *wpq;
2703         struct io_kiocb *req = wait->private;
2704         struct io_rw *rw = io_kiocb_to_cmd(req);
2705         struct wait_page_key *key = arg;
2706
2707         wpq = container_of(wait, struct wait_page_queue, wait);
2708
2709         if (!wake_page_match(wpq, key))
2710                 return 0;
2711
2712         rw->kiocb.ki_flags &= ~IOCB_WAITQ;
2713         list_del_init(&wait->entry);
2714         io_req_task_queue(req);
2715         return 1;
2716 }
2717
2718 /*
2719  * This controls whether a given IO request should be armed for async page
2720  * based retry. If we return false here, the request is handed to the async
2721  * worker threads for retry. If we're doing buffered reads on a regular file,
2722  * we prepare a private wait_page_queue entry and retry the operation. This
2723  * will either succeed because the page is now uptodate and unlocked, or it
2724  * will register a callback when the page is unlocked at IO completion. Through
2725  * that callback, io_uring uses task_work to setup a retry of the operation.
2726  * That retry will attempt the buffered read again. The retry will generally
2727  * succeed, or in rare cases where it fails, we then fall back to using the
2728  * async worker threads for a blocking retry.
2729  */
2730 static bool io_rw_should_retry(struct io_kiocb *req)
2731 {
2732         struct io_async_rw *io = req->async_data;
2733         struct wait_page_queue *wait = &io->wpq;
2734         struct io_rw *rw = io_kiocb_to_cmd(req);
2735         struct kiocb *kiocb = &rw->kiocb;
2736
2737         /* never retry for NOWAIT, we just complete with -EAGAIN */
2738         if (req->flags & REQ_F_NOWAIT)
2739                 return false;
2740
2741         /* Only for buffered IO */
2742         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
2743                 return false;
2744
2745         /*
2746          * just use poll if we can, and don't attempt if the fs doesn't
2747          * support callback based unlocks
2748          */
2749         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2750                 return false;
2751
2752         wait->wait.func = io_async_buf_func;
2753         wait->wait.private = req;
2754         wait->wait.flags = 0;
2755         INIT_LIST_HEAD(&wait->wait.entry);
2756         kiocb->ki_flags |= IOCB_WAITQ;
2757         kiocb->ki_flags &= ~IOCB_NOWAIT;
2758         kiocb->ki_waitq = wait;
2759         return true;
2760 }
2761
2762 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
2763 {
2764         struct file *file = rw->kiocb.ki_filp;
2765
2766         if (likely(file->f_op->read_iter))
2767                 return call_read_iter(file, &rw->kiocb, iter);
2768         else if (file->f_op->read)
2769                 return loop_rw_iter(READ, rw, iter);
2770         else
2771                 return -EINVAL;
2772 }
2773
2774 static bool need_read_all(struct io_kiocb *req)
2775 {
2776         return req->flags & REQ_F_ISREG ||
2777                 S_ISBLK(file_inode(req->file)->i_mode);
2778 }
2779
2780 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
2781 {
2782         struct io_rw *rw = io_kiocb_to_cmd(req);
2783         struct kiocb *kiocb = &rw->kiocb;
2784         struct io_ring_ctx *ctx = req->ctx;
2785         struct file *file = req->file;
2786         int ret;
2787
2788         if (unlikely(!file || !(file->f_mode & mode)))
2789                 return -EBADF;
2790
2791         if (!io_req_ffs_set(req))
2792                 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
2793
2794         kiocb->ki_flags = iocb_flags(file);
2795         ret = kiocb_set_rw_flags(kiocb, rw->flags);
2796         if (unlikely(ret))
2797                 return ret;
2798
2799         /*
2800          * If the file is marked O_NONBLOCK, still allow retry for it if it
2801          * supports async. Otherwise it's impossible to use O_NONBLOCK files
2802          * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2803          */
2804         if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2805             ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
2806                 req->flags |= REQ_F_NOWAIT;
2807
2808         if (ctx->flags & IORING_SETUP_IOPOLL) {
2809                 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
2810                         return -EOPNOTSUPP;
2811
2812                 kiocb->private = NULL;
2813                 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2814                 kiocb->ki_complete = io_complete_rw_iopoll;
2815                 req->iopoll_completed = 0;
2816         } else {
2817                 if (kiocb->ki_flags & IOCB_HIPRI)
2818                         return -EINVAL;
2819                 kiocb->ki_complete = io_complete_rw;
2820         }
2821
2822         return 0;
2823 }
2824
2825 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
2826 {
2827         struct io_rw *rw = io_kiocb_to_cmd(req);
2828         struct io_rw_state __s, *s = &__s;
2829         struct iovec *iovec;
2830         struct kiocb *kiocb = &rw->kiocb;
2831         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2832         struct io_async_rw *io;
2833         ssize_t ret, ret2;
2834         loff_t *ppos;
2835
2836         if (!req_has_async_data(req)) {
2837                 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2838                 if (unlikely(ret < 0))
2839                         return ret;
2840         } else {
2841                 io = req->async_data;
2842                 s = &io->s;
2843
2844                 /*
2845                  * Safe and required to re-import if we're using provided
2846                  * buffers, as we dropped the selected one before retry.
2847                  */
2848                 if (io_do_buffer_select(req)) {
2849                         ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
2850                         if (unlikely(ret < 0))
2851                                 return ret;
2852                 }
2853
2854                 /*
2855                  * We come here from an earlier attempt, restore our state to
2856                  * match in case it doesn't. It's cheap enough that we don't
2857                  * need to make this conditional.
2858                  */
2859                 iov_iter_restore(&s->iter, &s->iter_state);
2860                 iovec = NULL;
2861         }
2862         ret = io_rw_init_file(req, FMODE_READ);
2863         if (unlikely(ret)) {
2864                 kfree(iovec);
2865                 return ret;
2866         }
2867         req->cqe.res = iov_iter_count(&s->iter);
2868
2869         if (force_nonblock) {
2870                 /* If the file doesn't support async, just async punt */
2871                 if (unlikely(!io_file_supports_nowait(req))) {
2872                         ret = io_setup_async_rw(req, iovec, s, true);
2873                         return ret ?: -EAGAIN;
2874                 }
2875                 kiocb->ki_flags |= IOCB_NOWAIT;
2876         } else {
2877                 /* Ensure we clear previously set non-block flag */
2878                 kiocb->ki_flags &= ~IOCB_NOWAIT;
2879         }
2880
2881         ppos = io_kiocb_update_pos(req);
2882
2883         ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
2884         if (unlikely(ret)) {
2885                 kfree(iovec);
2886                 return ret;
2887         }
2888
2889         ret = io_iter_do_read(rw, &s->iter);
2890
2891         if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
2892                 req->flags &= ~REQ_F_REISSUE;
2893                 /* if we can poll, just do that */
2894                 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
2895                         return -EAGAIN;
2896                 /* IOPOLL retry should happen for io-wq threads */
2897                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
2898                         goto done;
2899                 /* no retry on NONBLOCK nor RWF_NOWAIT */
2900                 if (req->flags & REQ_F_NOWAIT)
2901                         goto done;
2902                 ret = 0;
2903         } else if (ret == -EIOCBQUEUED) {
2904                 goto out_free;
2905         } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
2906                    (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
2907                 /* read all, failed, already did sync or don't want to retry */
2908                 goto done;
2909         }
2910
2911         /*
2912          * Don't depend on the iter state matching what was consumed, or being
2913          * untouched in case of error. Restore it and we'll advance it
2914          * manually if we need to.
2915          */
2916         iov_iter_restore(&s->iter, &s->iter_state);
2917
2918         ret2 = io_setup_async_rw(req, iovec, s, true);
2919         if (ret2)
2920                 return ret2;
2921
2922         iovec = NULL;
2923         io = req->async_data;
2924         s = &io->s;
2925         /*
2926          * Now use our persistent iterator and state, if we aren't already.
2927          * We've restored and mapped the iter to match.
2928          */
2929
2930         do {
2931                 /*
2932                  * We end up here because of a partial read, either from
2933                  * above or inside this loop. Advance the iter by the bytes
2934                  * that were consumed.
2935                  */
2936                 iov_iter_advance(&s->iter, ret);
2937                 if (!iov_iter_count(&s->iter))
2938                         break;
2939                 io->bytes_done += ret;
2940                 iov_iter_save_state(&s->iter, &s->iter_state);
2941
2942                 /* if we can retry, do so with the callbacks armed */
2943                 if (!io_rw_should_retry(req)) {
2944                         kiocb->ki_flags &= ~IOCB_WAITQ;
2945                         return -EAGAIN;
2946                 }
2947
2948                 /*
2949                  * Now retry read with the IOCB_WAITQ parts set in the iocb. If
2950                  * we get -EIOCBQUEUED, then we'll get a notification when the
2951                  * desired page gets unlocked. We can also get a partial read
2952                  * here, and if we do, then just retry at the new offset.
2953                  */
2954                 ret = io_iter_do_read(rw, &s->iter);
2955                 if (ret == -EIOCBQUEUED)
2956                         return IOU_ISSUE_SKIP_COMPLETE;
2957                 /* we got some bytes, but not all. retry. */
2958                 kiocb->ki_flags &= ~IOCB_WAITQ;
2959                 iov_iter_restore(&s->iter, &s->iter_state);
2960         } while (ret > 0);
2961 done:
2962         kiocb_done(req, ret, issue_flags);
2963 out_free:
2964         /* it's faster to check here then delegate to kfree */
2965         if (iovec)
2966                 kfree(iovec);
2967         return IOU_ISSUE_SKIP_COMPLETE;
2968 }
2969
2970 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
2971 {
2972         struct io_rw *rw = io_kiocb_to_cmd(req);
2973         struct io_rw_state __s, *s = &__s;
2974         struct iovec *iovec;
2975         struct kiocb *kiocb = &rw->kiocb;
2976         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
2977         ssize_t ret, ret2;
2978         loff_t *ppos;
2979
2980         if (!req_has_async_data(req)) {
2981                 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
2982                 if (unlikely(ret < 0))
2983                         return ret;
2984         } else {
2985                 struct io_async_rw *io = req->async_data;
2986
2987                 s = &io->s;
2988                 iov_iter_restore(&s->iter, &s->iter_state);
2989                 iovec = NULL;
2990         }
2991         ret = io_rw_init_file(req, FMODE_WRITE);
2992         if (unlikely(ret)) {
2993                 kfree(iovec);
2994                 return ret;
2995         }
2996         req->cqe.res = iov_iter_count(&s->iter);
2997
2998         if (force_nonblock) {
2999                 /* If the file doesn't support async, just async punt */
3000                 if (unlikely(!io_file_supports_nowait(req)))
3001                         goto copy_iov;
3002
3003                 /* file path doesn't support NOWAIT for non-direct_IO */
3004                 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3005                     (req->flags & REQ_F_ISREG))
3006                         goto copy_iov;
3007
3008                 kiocb->ki_flags |= IOCB_NOWAIT;
3009         } else {
3010                 /* Ensure we clear previously set non-block flag */
3011                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3012         }
3013
3014         ppos = io_kiocb_update_pos(req);
3015
3016         ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
3017         if (unlikely(ret))
3018                 goto out_free;
3019
3020         /*
3021          * Open-code file_start_write here to grab freeze protection,
3022          * which will be released by another thread in
3023          * io_complete_rw().  Fool lockdep by telling it the lock got
3024          * released so that it doesn't complain about the held lock when
3025          * we return to userspace.
3026          */
3027         if (req->flags & REQ_F_ISREG) {
3028                 sb_start_write(file_inode(req->file)->i_sb);
3029                 __sb_writers_release(file_inode(req->file)->i_sb,
3030                                         SB_FREEZE_WRITE);
3031         }
3032         kiocb->ki_flags |= IOCB_WRITE;
3033
3034         if (likely(req->file->f_op->write_iter))
3035                 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3036         else if (req->file->f_op->write)
3037                 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
3038         else
3039                 ret2 = -EINVAL;
3040
3041         if (req->flags & REQ_F_REISSUE) {
3042                 req->flags &= ~REQ_F_REISSUE;
3043                 ret2 = -EAGAIN;
3044         }
3045
3046         /*
3047          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3048          * retry them without IOCB_NOWAIT.
3049          */
3050         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3051                 ret2 = -EAGAIN;
3052         /* no retry on NONBLOCK nor RWF_NOWAIT */
3053         if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3054                 goto done;
3055         if (!force_nonblock || ret2 != -EAGAIN) {
3056                 /* IOPOLL retry should happen for io-wq threads */
3057                 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3058                         goto copy_iov;
3059 done:
3060                 kiocb_done(req, ret2, issue_flags);
3061                 ret = IOU_ISSUE_SKIP_COMPLETE;
3062         } else {
3063 copy_iov:
3064                 iov_iter_restore(&s->iter, &s->iter_state);
3065                 ret = io_setup_async_rw(req, iovec, s, false);
3066                 return ret ?: -EAGAIN;
3067         }
3068 out_free:
3069         /* it's reportedly faster than delegating the null check to kfree() */
3070         if (iovec)
3071                 kfree(iovec);
3072         return ret;
3073 }
3074
3075 /*
3076  * Note when io_fixed_fd_install() returns error value, it will ensure
3077  * fput() is called correspondingly.
3078  */
3079 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
3080                         struct file *file, unsigned int file_slot)
3081 {
3082         bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
3083         struct io_ring_ctx *ctx = req->ctx;
3084         int ret;
3085
3086         io_ring_submit_lock(ctx, issue_flags);
3087
3088         if (alloc_slot) {
3089                 ret = io_file_bitmap_get(ctx);
3090                 if (unlikely(ret < 0))
3091                         goto err;
3092                 file_slot = ret;
3093         } else {
3094                 file_slot--;
3095         }
3096
3097         ret = io_install_fixed_file(req, file, issue_flags, file_slot);
3098         if (!ret && alloc_slot)
3099                 ret = file_slot;
3100 err:
3101         io_ring_submit_unlock(ctx, issue_flags);
3102         if (unlikely(ret < 0))
3103                 fput(file);
3104         return ret;
3105 }
3106
3107 static int io_remove_buffers_prep(struct io_kiocb *req,
3108                                   const struct io_uring_sqe *sqe)
3109 {
3110         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3111         u64 tmp;
3112
3113         if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
3114             sqe->splice_fd_in)
3115                 return -EINVAL;
3116
3117         tmp = READ_ONCE(sqe->fd);
3118         if (!tmp || tmp > USHRT_MAX)
3119                 return -EINVAL;
3120
3121         memset(p, 0, sizeof(*p));
3122         p->nbufs = tmp;
3123         p->bgid = READ_ONCE(sqe->buf_group);
3124         return 0;
3125 }
3126
3127 static int __io_remove_buffers(struct io_ring_ctx *ctx,
3128                                struct io_buffer_list *bl, unsigned nbufs)
3129 {
3130         unsigned i = 0;
3131
3132         /* shouldn't happen */
3133         if (!nbufs)
3134                 return 0;
3135
3136         if (bl->buf_nr_pages) {
3137                 int j;
3138
3139                 i = bl->buf_ring->tail - bl->head;
3140                 for (j = 0; j < bl->buf_nr_pages; j++)
3141                         unpin_user_page(bl->buf_pages[j]);
3142                 kvfree(bl->buf_pages);
3143                 bl->buf_pages = NULL;
3144                 bl->buf_nr_pages = 0;
3145                 /* make sure it's seen as empty */
3146                 INIT_LIST_HEAD(&bl->buf_list);
3147                 return i;
3148         }
3149
3150         /* the head kbuf is the list itself */
3151         while (!list_empty(&bl->buf_list)) {
3152                 struct io_buffer *nxt;
3153
3154                 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
3155                 list_del(&nxt->list);
3156                 if (++i == nbufs)
3157                         return i;
3158                 cond_resched();
3159         }
3160         i++;
3161
3162         return i;
3163 }
3164
3165 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3166 {
3167         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3168         struct io_ring_ctx *ctx = req->ctx;
3169         struct io_buffer_list *bl;
3170         int ret = 0;
3171
3172         io_ring_submit_lock(ctx, issue_flags);
3173
3174         ret = -ENOENT;
3175         bl = io_buffer_get_list(ctx, p->bgid);
3176         if (bl) {
3177                 ret = -EINVAL;
3178                 /* can't use provide/remove buffers command on mapped buffers */
3179                 if (!bl->buf_nr_pages)
3180                         ret = __io_remove_buffers(ctx, bl, p->nbufs);
3181         }
3182         if (ret < 0)
3183                 req_set_fail(req);
3184
3185         /* complete before unlock, IOPOLL may need the lock */
3186         io_req_set_res(req, ret, 0);
3187         __io_req_complete(req, issue_flags);
3188         io_ring_submit_unlock(ctx, issue_flags);
3189         return IOU_ISSUE_SKIP_COMPLETE;
3190 }
3191
3192 static int io_provide_buffers_prep(struct io_kiocb *req,
3193                                    const struct io_uring_sqe *sqe)
3194 {
3195         unsigned long size, tmp_check;
3196         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3197         u64 tmp;
3198
3199         if (sqe->rw_flags || sqe->splice_fd_in)
3200                 return -EINVAL;
3201
3202         tmp = READ_ONCE(sqe->fd);
3203         if (!tmp || tmp > USHRT_MAX)
3204                 return -E2BIG;
3205         p->nbufs = tmp;
3206         p->addr = READ_ONCE(sqe->addr);
3207         p->len = READ_ONCE(sqe->len);
3208
3209         if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3210                                 &size))
3211                 return -EOVERFLOW;
3212         if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3213                 return -EOVERFLOW;
3214
3215         size = (unsigned long)p->len * p->nbufs;
3216         if (!access_ok(u64_to_user_ptr(p->addr), size))
3217                 return -EFAULT;
3218
3219         p->bgid = READ_ONCE(sqe->buf_group);
3220         tmp = READ_ONCE(sqe->off);
3221         if (tmp > USHRT_MAX)
3222                 return -E2BIG;
3223         p->bid = tmp;
3224         return 0;
3225 }
3226
3227 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
3228 {
3229         struct io_buffer *buf;
3230         struct page *page;
3231         int bufs_in_page;
3232
3233         /*
3234          * Completions that don't happen inline (eg not under uring_lock) will
3235          * add to ->io_buffers_comp. If we don't have any free buffers, check
3236          * the completion list and splice those entries first.
3237          */
3238         if (!list_empty_careful(&ctx->io_buffers_comp)) {
3239                 spin_lock(&ctx->completion_lock);
3240                 if (!list_empty(&ctx->io_buffers_comp)) {
3241                         list_splice_init(&ctx->io_buffers_comp,
3242                                                 &ctx->io_buffers_cache);
3243                         spin_unlock(&ctx->completion_lock);
3244                         return 0;
3245                 }
3246                 spin_unlock(&ctx->completion_lock);
3247         }
3248
3249         /*
3250          * No free buffers and no completion entries either. Allocate a new
3251          * page worth of buffer entries and add those to our freelist.
3252          */
3253         page = alloc_page(GFP_KERNEL_ACCOUNT);
3254         if (!page)
3255                 return -ENOMEM;
3256
3257         list_add(&page->lru, &ctx->io_buffers_pages);
3258
3259         buf = page_address(page);
3260         bufs_in_page = PAGE_SIZE / sizeof(*buf);
3261         while (bufs_in_page) {
3262                 list_add_tail(&buf->list, &ctx->io_buffers_cache);
3263                 buf++;
3264                 bufs_in_page--;
3265         }
3266
3267         return 0;
3268 }
3269
3270 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
3271                           struct io_buffer_list *bl)
3272 {
3273         struct io_buffer *buf;
3274         u64 addr = pbuf->addr;
3275         int i, bid = pbuf->bid;
3276
3277         for (i = 0; i < pbuf->nbufs; i++) {
3278                 if (list_empty(&ctx->io_buffers_cache) &&
3279                     io_refill_buffer_cache(ctx))
3280                         break;
3281                 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
3282                                         list);
3283                 list_move_tail(&buf->list, &bl->buf_list);
3284                 buf->addr = addr;
3285                 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3286                 buf->bid = bid;
3287                 buf->bgid = pbuf->bgid;
3288                 addr += pbuf->len;
3289                 bid++;
3290                 cond_resched();
3291         }
3292
3293         return i ? 0 : -ENOMEM;
3294 }
3295
3296 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
3297 {
3298         int i;
3299
3300         ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
3301                                 GFP_KERNEL);
3302         if (!ctx->io_bl)
3303                 return -ENOMEM;
3304
3305         for (i = 0; i < BGID_ARRAY; i++) {
3306                 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
3307                 ctx->io_bl[i].bgid = i;
3308         }
3309
3310         return 0;
3311 }
3312
3313 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3314 {
3315         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3316         struct io_ring_ctx *ctx = req->ctx;
3317         struct io_buffer_list *bl;
3318         int ret = 0;
3319
3320         io_ring_submit_lock(ctx, issue_flags);
3321
3322         if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
3323                 ret = io_init_bl_list(ctx);
3324                 if (ret)
3325                         goto err;
3326         }
3327
3328         bl = io_buffer_get_list(ctx, p->bgid);
3329         if (unlikely(!bl)) {
3330                 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
3331                 if (!bl) {
3332                         ret = -ENOMEM;
3333                         goto err;
3334                 }
3335                 INIT_LIST_HEAD(&bl->buf_list);
3336                 ret = io_buffer_add_list(ctx, bl, p->bgid);
3337                 if (ret) {
3338                         kfree(bl);
3339                         goto err;
3340                 }
3341         }
3342         /* can't add buffers via this command for a mapped buffer ring */
3343         if (bl->buf_nr_pages) {
3344                 ret = -EINVAL;
3345                 goto err;
3346         }
3347
3348         ret = io_add_buffers(ctx, p, bl);
3349 err:
3350         if (ret < 0)
3351                 req_set_fail(req);
3352         /* complete before unlock, IOPOLL may need the lock */
3353         io_req_set_res(req, ret, 0);
3354         __io_req_complete(req, issue_flags);
3355         io_ring_submit_unlock(ctx, issue_flags);
3356         return IOU_ISSUE_SKIP_COMPLETE;
3357 }
3358
3359 static __maybe_unused int io_eopnotsupp_prep(struct io_kiocb *kiocb,
3360                                              const struct io_uring_sqe *sqe)
3361 {
3362         return -EOPNOTSUPP;
3363 }
3364
3365 static bool io_cancel_cb(struct io_wq_work *work, void *data)
3366 {
3367         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3368         struct io_cancel_data *cd = data;
3369
3370         if (req->ctx != cd->ctx)
3371                 return false;
3372         if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
3373                 ;
3374         } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
3375                 if (req->file != cd->file)
3376                         return false;
3377         } else {
3378                 if (req->cqe.user_data != cd->data)
3379                         return false;
3380         }
3381         if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
3382                 if (cd->seq == req->work.cancel_seq)
3383                         return false;
3384                 req->work.cancel_seq = cd->seq;
3385         }
3386         return true;
3387 }
3388
3389 static int io_async_cancel_one(struct io_uring_task *tctx,
3390                                struct io_cancel_data *cd)
3391 {
3392         enum io_wq_cancel cancel_ret;
3393         int ret = 0;
3394         bool all;
3395
3396         if (!tctx || !tctx->io_wq)
3397                 return -ENOENT;
3398
3399         all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
3400         cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
3401         switch (cancel_ret) {
3402         case IO_WQ_CANCEL_OK:
3403                 ret = 0;
3404                 break;
3405         case IO_WQ_CANCEL_RUNNING:
3406                 ret = -EALREADY;
3407                 break;
3408         case IO_WQ_CANCEL_NOTFOUND:
3409                 ret = -ENOENT;
3410                 break;
3411         }
3412
3413         return ret;
3414 }
3415
3416 int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
3417 {
3418         struct io_ring_ctx *ctx = req->ctx;
3419         int ret;
3420
3421         WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
3422
3423         ret = io_async_cancel_one(req->task->io_uring, cd);
3424         /*
3425          * Fall-through even for -EALREADY, as we may have poll armed
3426          * that need unarming.
3427          */
3428         if (!ret)
3429                 return 0;
3430
3431         spin_lock(&ctx->completion_lock);
3432         ret = io_poll_cancel(ctx, cd);
3433         if (ret != -ENOENT)
3434                 goto out;
3435         if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
3436                 ret = io_timeout_cancel(ctx, cd);
3437 out:
3438         spin_unlock(&ctx->completion_lock);
3439         return ret;
3440 }
3441
3442 #define CANCEL_FLAGS    (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
3443                          IORING_ASYNC_CANCEL_ANY)
3444
3445 static int io_async_cancel_prep(struct io_kiocb *req,
3446                                 const struct io_uring_sqe *sqe)
3447 {
3448         struct io_cancel *cancel = io_kiocb_to_cmd(req);
3449
3450         if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
3451                 return -EINVAL;
3452         if (sqe->off || sqe->len || sqe->splice_fd_in)
3453                 return -EINVAL;
3454
3455         cancel->addr = READ_ONCE(sqe->addr);
3456         cancel->flags = READ_ONCE(sqe->cancel_flags);
3457         if (cancel->flags & ~CANCEL_FLAGS)
3458                 return -EINVAL;
3459         if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
3460                 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
3461                         return -EINVAL;
3462                 cancel->fd = READ_ONCE(sqe->fd);
3463         }
3464
3465         return 0;
3466 }
3467
3468 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
3469                              unsigned int issue_flags)
3470 {
3471         bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
3472         struct io_ring_ctx *ctx = cd->ctx;
3473         struct io_tctx_node *node;
3474         int ret, nr = 0;
3475
3476         do {
3477                 ret = io_try_cancel(req, cd);
3478                 if (ret == -ENOENT)
3479                         break;
3480                 if (!all)
3481                         return ret;
3482                 nr++;
3483         } while (1);
3484
3485         /* slow path, try all io-wq's */
3486         io_ring_submit_lock(ctx, issue_flags);
3487         ret = -ENOENT;
3488         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
3489                 struct io_uring_task *tctx = node->task->io_uring;
3490
3491                 ret = io_async_cancel_one(tctx, cd);
3492                 if (ret != -ENOENT) {
3493                         if (!all)
3494                                 break;
3495                         nr++;
3496                 }
3497         }
3498         io_ring_submit_unlock(ctx, issue_flags);
3499         return all ? nr : ret;
3500 }
3501
3502 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
3503 {
3504         struct io_cancel *cancel = io_kiocb_to_cmd(req);
3505         struct io_cancel_data cd = {
3506                 .ctx    = req->ctx,
3507                 .data   = cancel->addr,
3508                 .flags  = cancel->flags,
3509                 .seq    = atomic_inc_return(&req->ctx->cancel_seq),
3510         };
3511         int ret;
3512
3513         if (cd.flags & IORING_ASYNC_CANCEL_FD) {
3514                 if (req->flags & REQ_F_FIXED_FILE)
3515                         req->file = io_file_get_fixed(req, cancel->fd,
3516                                                         issue_flags);
3517                 else
3518                         req->file = io_file_get_normal(req, cancel->fd);
3519                 if (!req->file) {
3520                         ret = -EBADF;
3521                         goto done;
3522                 }
3523                 cd.file = req->file;
3524         }
3525
3526         ret = __io_async_cancel(&cd, req, issue_flags);
3527 done:
3528         if (ret < 0)
3529                 req_set_fail(req);
3530         io_req_set_res(req, ret, 0);
3531         return IOU_OK;
3532 }
3533
3534 static int io_files_update_prep(struct io_kiocb *req,
3535                                 const struct io_uring_sqe *sqe)
3536 {
3537         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
3538
3539         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
3540                 return -EINVAL;
3541         if (sqe->rw_flags || sqe->splice_fd_in)
3542                 return -EINVAL;
3543
3544         up->offset = READ_ONCE(sqe->off);
3545         up->nr_args = READ_ONCE(sqe->len);
3546         if (!up->nr_args)
3547                 return -EINVAL;
3548         up->arg = READ_ONCE(sqe->addr);
3549         return 0;
3550 }
3551
3552 static int io_files_update_with_index_alloc(struct io_kiocb *req,
3553                                             unsigned int issue_flags)
3554 {
3555         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
3556         __s32 __user *fds = u64_to_user_ptr(up->arg);
3557         unsigned int done;
3558         struct file *file;
3559         int ret, fd;
3560
3561         if (!req->ctx->file_data)
3562                 return -ENXIO;
3563
3564         for (done = 0; done < up->nr_args; done++) {
3565                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
3566                         ret = -EFAULT;
3567                         break;
3568                 }
3569
3570                 file = fget(fd);
3571                 if (!file) {
3572                         ret = -EBADF;
3573                         break;
3574                 }
3575                 ret = io_fixed_fd_install(req, issue_flags, file,
3576                                           IORING_FILE_INDEX_ALLOC);
3577                 if (ret < 0)
3578                         break;
3579                 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
3580                         __io_close_fixed(req, issue_flags, ret);
3581                         ret = -EFAULT;
3582                         break;
3583                 }
3584         }
3585
3586         if (done)
3587                 return done;
3588         return ret;
3589 }
3590
3591 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
3592 {
3593         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
3594         struct io_ring_ctx *ctx = req->ctx;
3595         struct io_uring_rsrc_update2 up2;
3596         int ret;
3597
3598         up2.offset = up->offset;
3599         up2.data = up->arg;
3600         up2.nr = 0;
3601         up2.tags = 0;
3602         up2.resv = 0;
3603         up2.resv2 = 0;
3604
3605         if (up->offset == IORING_FILE_INDEX_ALLOC) {
3606                 ret = io_files_update_with_index_alloc(req, issue_flags);
3607         } else {
3608                 io_ring_submit_lock(ctx, issue_flags);
3609                 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
3610                                                 &up2, up->nr_args);
3611                 io_ring_submit_unlock(ctx, issue_flags);
3612         }
3613
3614         if (ret < 0)
3615                 req_set_fail(req);
3616         io_req_set_res(req, ret, 0);
3617         return IOU_OK;
3618 }
3619
3620 static int io_req_prep_async(struct io_kiocb *req)
3621 {
3622         const struct io_op_def *def = &io_op_defs[req->opcode];
3623
3624         /* assign early for deferred execution for non-fixed file */
3625         if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
3626                 req->file = io_file_get_normal(req, req->cqe.fd);
3627         if (!def->prep_async)
3628                 return 0;
3629         if (WARN_ON_ONCE(req_has_async_data(req)))
3630                 return -EFAULT;
3631         if (io_alloc_async_data(req))
3632                 return -EAGAIN;
3633
3634         return def->prep_async(req);
3635 }
3636
3637 static u32 io_get_sequence(struct io_kiocb *req)
3638 {
3639         u32 seq = req->ctx->cached_sq_head;
3640         struct io_kiocb *cur;
3641
3642         /* need original cached_sq_head, but it was increased for each req */
3643         io_for_each_link(cur, req)
3644                 seq--;
3645         return seq;
3646 }
3647
3648 static __cold void io_drain_req(struct io_kiocb *req)
3649 {
3650         struct io_ring_ctx *ctx = req->ctx;
3651         struct io_defer_entry *de;
3652         int ret;
3653         u32 seq = io_get_sequence(req);
3654
3655         /* Still need defer if there is pending req in defer list. */
3656         spin_lock(&ctx->completion_lock);
3657         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
3658                 spin_unlock(&ctx->completion_lock);
3659 queue:
3660                 ctx->drain_active = false;
3661                 io_req_task_queue(req);
3662                 return;
3663         }
3664         spin_unlock(&ctx->completion_lock);
3665
3666         ret = io_req_prep_async(req);
3667         if (ret) {
3668 fail:
3669                 io_req_complete_failed(req, ret);
3670                 return;
3671         }
3672         io_prep_async_link(req);
3673         de = kmalloc(sizeof(*de), GFP_KERNEL);
3674         if (!de) {
3675                 ret = -ENOMEM;
3676                 goto fail;
3677         }
3678
3679         spin_lock(&ctx->completion_lock);
3680         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
3681                 spin_unlock(&ctx->completion_lock);
3682                 kfree(de);
3683                 goto queue;
3684         }
3685
3686         trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
3687         de->req = req;
3688         de->seq = seq;
3689         list_add_tail(&de->list, &ctx->defer_list);
3690         spin_unlock(&ctx->completion_lock);
3691 }
3692
3693 static void io_clean_op(struct io_kiocb *req)
3694 {
3695         if (req->flags & REQ_F_BUFFER_SELECTED) {
3696                 spin_lock(&req->ctx->completion_lock);
3697                 io_put_kbuf_comp(req);
3698                 spin_unlock(&req->ctx->completion_lock);
3699         }
3700
3701         if (req->flags & REQ_F_NEED_CLEANUP) {
3702                 const struct io_op_def *def = &io_op_defs[req->opcode];
3703
3704                 if (def->cleanup)
3705                         def->cleanup(req);
3706         }
3707         if ((req->flags & REQ_F_POLLED) && req->apoll) {
3708                 kfree(req->apoll->double_poll);
3709                 kfree(req->apoll);
3710                 req->apoll = NULL;
3711         }
3712         if (req->flags & REQ_F_INFLIGHT) {
3713                 struct io_uring_task *tctx = req->task->io_uring;
3714
3715                 atomic_dec(&tctx->inflight_tracked);
3716         }
3717         if (req->flags & REQ_F_CREDS)
3718                 put_cred(req->creds);
3719         if (req->flags & REQ_F_ASYNC_DATA) {
3720                 kfree(req->async_data);
3721                 req->async_data = NULL;
3722         }
3723         req->flags &= ~IO_REQ_CLEAN_FLAGS;
3724 }
3725
3726 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
3727 {
3728         if (req->file || !io_op_defs[req->opcode].needs_file)
3729                 return true;
3730
3731         if (req->flags & REQ_F_FIXED_FILE)
3732                 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
3733         else
3734                 req->file = io_file_get_normal(req, req->cqe.fd);
3735
3736         return !!req->file;
3737 }
3738
3739 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
3740 {
3741         const struct io_op_def *def = &io_op_defs[req->opcode];
3742         const struct cred *creds = NULL;
3743         int ret;
3744
3745         if (unlikely(!io_assign_file(req, issue_flags)))
3746                 return -EBADF;
3747
3748         if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
3749                 creds = override_creds(req->creds);
3750
3751         if (!def->audit_skip)
3752                 audit_uring_entry(req->opcode);
3753
3754         ret = def->issue(req, issue_flags);
3755
3756         if (!def->audit_skip)
3757                 audit_uring_exit(!ret, ret);
3758
3759         if (creds)
3760                 revert_creds(creds);
3761
3762         if (ret == IOU_OK)
3763                 __io_req_complete(req, issue_flags);
3764         else if (ret != IOU_ISSUE_SKIP_COMPLETE)
3765                 return ret;
3766
3767         /* If the op doesn't have a file, we're not polling for it */
3768         if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
3769                 io_iopoll_req_issued(req, issue_flags);
3770
3771         return 0;
3772 }
3773
3774 int io_poll_issue(struct io_kiocb *req, bool *locked)
3775 {
3776         io_tw_lock(req->ctx, locked);
3777         if (unlikely(req->task->flags & PF_EXITING))
3778                 return -EFAULT;
3779         return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3780 }
3781
3782 struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
3783 {
3784         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3785
3786         req = io_put_req_find_next(req);
3787         return req ? &req->work : NULL;
3788 }
3789
3790 void io_wq_submit_work(struct io_wq_work *work)
3791 {
3792         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
3793         const struct io_op_def *def = &io_op_defs[req->opcode];
3794         unsigned int issue_flags = IO_URING_F_UNLOCKED;
3795         bool needs_poll = false;
3796         int ret = 0, err = -ECANCELED;
3797
3798         /* one will be dropped by ->io_free_work() after returning to io-wq */
3799         if (!(req->flags & REQ_F_REFCOUNT))
3800                 __io_req_set_refcount(req, 2);
3801         else
3802                 req_ref_get(req);
3803
3804         io_arm_ltimeout(req);
3805
3806         /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
3807         if (work->flags & IO_WQ_WORK_CANCEL) {
3808 fail:
3809                 io_req_task_queue_fail(req, err);
3810                 return;
3811         }
3812         if (!io_assign_file(req, issue_flags)) {
3813                 err = -EBADF;
3814                 work->flags |= IO_WQ_WORK_CANCEL;
3815                 goto fail;
3816         }
3817
3818         if (req->flags & REQ_F_FORCE_ASYNC) {
3819                 bool opcode_poll = def->pollin || def->pollout;
3820
3821                 if (opcode_poll && file_can_poll(req->file)) {
3822                         needs_poll = true;
3823                         issue_flags |= IO_URING_F_NONBLOCK;
3824                 }
3825         }
3826
3827         do {
3828                 ret = io_issue_sqe(req, issue_flags);
3829                 if (ret != -EAGAIN)
3830                         break;
3831                 /*
3832                  * We can get EAGAIN for iopolled IO even though we're
3833                  * forcing a sync submission from here, since we can't
3834                  * wait for request slots on the block side.
3835                  */
3836                 if (!needs_poll) {
3837                         if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
3838                                 break;
3839                         cond_resched();
3840                         continue;
3841                 }
3842
3843                 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
3844                         return;
3845                 /* aborted or ready, in either case retry blocking */
3846                 needs_poll = false;
3847                 issue_flags &= ~IO_URING_F_NONBLOCK;
3848         } while (1);
3849
3850         /* avoid locking problems by failing it from a clean context */
3851         if (ret < 0)
3852                 io_req_task_queue_fail(req, ret);
3853 }
3854
3855 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
3856                                       unsigned int issue_flags)
3857 {
3858         struct io_ring_ctx *ctx = req->ctx;
3859         struct file *file = NULL;
3860         unsigned long file_ptr;
3861
3862         io_ring_submit_lock(ctx, issue_flags);
3863
3864         if (unlikely((unsigned int)fd >= ctx->nr_user_files))
3865                 goto out;
3866         fd = array_index_nospec(fd, ctx->nr_user_files);
3867         file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
3868         file = (struct file *) (file_ptr & FFS_MASK);
3869         file_ptr &= ~FFS_MASK;
3870         /* mask in overlapping REQ_F and FFS bits */
3871         req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
3872         io_req_set_rsrc_node(req, ctx, 0);
3873         WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
3874 out:
3875         io_ring_submit_unlock(ctx, issue_flags);
3876         return file;
3877 }
3878
3879 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
3880 {
3881         struct file *file = fget(fd);
3882
3883         trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
3884
3885         /* we don't allow fixed io_uring files */
3886         if (file && io_is_uring_fops(file))
3887                 io_req_track_inflight(req);
3888         return file;
3889 }
3890
3891 static void io_queue_async(struct io_kiocb *req, int ret)
3892         __must_hold(&req->ctx->uring_lock)
3893 {
3894         struct io_kiocb *linked_timeout;
3895
3896         if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
3897                 io_req_complete_failed(req, ret);
3898                 return;
3899         }
3900
3901         linked_timeout = io_prep_linked_timeout(req);
3902
3903         switch (io_arm_poll_handler(req, 0)) {
3904         case IO_APOLL_READY:
3905                 io_req_task_queue(req);
3906                 break;
3907         case IO_APOLL_ABORTED:
3908                 /*
3909                  * Queued up for async execution, worker will release
3910                  * submit reference when the iocb is actually submitted.
3911                  */
3912                 io_kbuf_recycle(req, 0);
3913                 io_queue_iowq(req, NULL);
3914                 break;
3915         case IO_APOLL_OK:
3916                 break;
3917         }
3918
3919         if (linked_timeout)
3920                 io_queue_linked_timeout(linked_timeout);
3921 }
3922
3923 static inline void io_queue_sqe(struct io_kiocb *req)
3924         __must_hold(&req->ctx->uring_lock)
3925 {
3926         int ret;
3927
3928         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
3929
3930         if (req->flags & REQ_F_COMPLETE_INLINE) {
3931                 io_req_add_compl_list(req);
3932                 return;
3933         }
3934         /*
3935          * We async punt it if the file wasn't marked NOWAIT, or if the file
3936          * doesn't support non-blocking read/write attempts
3937          */
3938         if (likely(!ret))
3939                 io_arm_ltimeout(req);
3940         else
3941                 io_queue_async(req, ret);
3942 }
3943
3944 static void io_queue_sqe_fallback(struct io_kiocb *req)
3945         __must_hold(&req->ctx->uring_lock)
3946 {
3947         if (unlikely(req->flags & REQ_F_FAIL)) {
3948                 /*
3949                  * We don't submit, fail them all, for that replace hardlinks
3950                  * with normal links. Extra REQ_F_LINK is tolerated.
3951                  */
3952                 req->flags &= ~REQ_F_HARDLINK;
3953                 req->flags |= REQ_F_LINK;
3954                 io_req_complete_failed(req, req->cqe.res);
3955         } else if (unlikely(req->ctx->drain_active)) {
3956                 io_drain_req(req);
3957         } else {
3958                 int ret = io_req_prep_async(req);
3959
3960                 if (unlikely(ret))
3961                         io_req_complete_failed(req, ret);
3962                 else
3963                         io_queue_iowq(req, NULL);
3964         }
3965 }
3966
3967 /*
3968  * Check SQE restrictions (opcode and flags).
3969  *
3970  * Returns 'true' if SQE is allowed, 'false' otherwise.
3971  */
3972 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
3973                                         struct io_kiocb *req,
3974                                         unsigned int sqe_flags)
3975 {
3976         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
3977                 return false;
3978
3979         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
3980             ctx->restrictions.sqe_flags_required)
3981                 return false;
3982
3983         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
3984                           ctx->restrictions.sqe_flags_required))
3985                 return false;
3986
3987         return true;
3988 }
3989
3990 static void io_init_req_drain(struct io_kiocb *req)
3991 {
3992         struct io_ring_ctx *ctx = req->ctx;
3993         struct io_kiocb *head = ctx->submit_state.link.head;
3994
3995         ctx->drain_active = true;
3996         if (head) {
3997                 /*
3998                  * If we need to drain a request in the middle of a link, drain
3999                  * the head request and the next request/link after the current
4000                  * link. Considering sequential execution of links,
4001                  * REQ_F_IO_DRAIN will be maintained for every request of our
4002                  * link.
4003                  */
4004                 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
4005                 ctx->drain_next = true;
4006         }
4007 }
4008
4009 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
4010                        const struct io_uring_sqe *sqe)
4011         __must_hold(&ctx->uring_lock)
4012 {
4013         const struct io_op_def *def;
4014         unsigned int sqe_flags;
4015         int personality;
4016         u8 opcode;
4017
4018         /* req is partially pre-initialised, see io_preinit_req() */
4019         req->opcode = opcode = READ_ONCE(sqe->opcode);
4020         /* same numerical values with corresponding REQ_F_*, safe to copy */
4021         req->flags = sqe_flags = READ_ONCE(sqe->flags);
4022         req->cqe.user_data = READ_ONCE(sqe->user_data);
4023         req->file = NULL;
4024         req->rsrc_node = NULL;
4025         req->task = current;
4026
4027         if (unlikely(opcode >= IORING_OP_LAST)) {
4028                 req->opcode = 0;
4029                 return -EINVAL;
4030         }
4031         def = &io_op_defs[opcode];
4032         if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
4033                 /* enforce forwards compatibility on users */
4034                 if (sqe_flags & ~SQE_VALID_FLAGS)
4035                         return -EINVAL;
4036                 if (sqe_flags & IOSQE_BUFFER_SELECT) {
4037                         if (!def->buffer_select)
4038                                 return -EOPNOTSUPP;
4039                         req->buf_index = READ_ONCE(sqe->buf_group);
4040                 }
4041                 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
4042                         ctx->drain_disabled = true;
4043                 if (sqe_flags & IOSQE_IO_DRAIN) {
4044                         if (ctx->drain_disabled)
4045                                 return -EOPNOTSUPP;
4046                         io_init_req_drain(req);
4047                 }
4048         }
4049         if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
4050                 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
4051                         return -EACCES;
4052                 /* knock it to the slow queue path, will be drained there */
4053                 if (ctx->drain_active)
4054                         req->flags |= REQ_F_FORCE_ASYNC;
4055                 /* if there is no link, we're at "next" request and need to drain */
4056                 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
4057                         ctx->drain_next = false;
4058                         ctx->drain_active = true;
4059                         req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
4060                 }
4061         }
4062
4063         if (!def->ioprio && sqe->ioprio)
4064                 return -EINVAL;
4065         if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
4066                 return -EINVAL;
4067
4068         if (def->needs_file) {
4069                 struct io_submit_state *state = &ctx->submit_state;
4070
4071                 req->cqe.fd = READ_ONCE(sqe->fd);
4072
4073                 /*
4074                  * Plug now if we have more than 2 IO left after this, and the
4075                  * target is potentially a read/write to block based storage.
4076                  */
4077                 if (state->need_plug && def->plug) {
4078                         state->plug_started = true;
4079                         state->need_plug = false;
4080                         blk_start_plug_nr_ios(&state->plug, state->submit_nr);
4081                 }
4082         }
4083
4084         personality = READ_ONCE(sqe->personality);
4085         if (personality) {
4086                 int ret;
4087
4088                 req->creds = xa_load(&ctx->personalities, personality);
4089                 if (!req->creds)
4090                         return -EINVAL;
4091                 get_cred(req->creds);
4092                 ret = security_uring_override_creds(req->creds);
4093                 if (ret) {
4094                         put_cred(req->creds);
4095                         return ret;
4096                 }
4097                 req->flags |= REQ_F_CREDS;
4098         }
4099
4100         return def->prep(req, sqe);
4101 }
4102
4103 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
4104                                       struct io_kiocb *req, int ret)
4105 {
4106         struct io_ring_ctx *ctx = req->ctx;
4107         struct io_submit_link *link = &ctx->submit_state.link;
4108         struct io_kiocb *head = link->head;
4109
4110         trace_io_uring_req_failed(sqe, ctx, req, ret);
4111
4112         /*
4113          * Avoid breaking links in the middle as it renders links with SQPOLL
4114          * unusable. Instead of failing eagerly, continue assembling the link if
4115          * applicable and mark the head with REQ_F_FAIL. The link flushing code
4116          * should find the flag and handle the rest.
4117          */
4118         req_fail_link_node(req, ret);
4119         if (head && !(head->flags & REQ_F_FAIL))
4120                 req_fail_link_node(head, -ECANCELED);
4121
4122         if (!(req->flags & IO_REQ_LINK_FLAGS)) {
4123                 if (head) {
4124                         link->last->link = req;
4125                         link->head = NULL;
4126                         req = head;
4127                 }
4128                 io_queue_sqe_fallback(req);
4129                 return ret;
4130         }
4131
4132         if (head)
4133                 link->last->link = req;
4134         else
4135                 link->head = req;
4136         link->last = req;
4137         return 0;
4138 }
4139
4140 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
4141                          const struct io_uring_sqe *sqe)
4142         __must_hold(&ctx->uring_lock)
4143 {
4144         struct io_submit_link *link = &ctx->submit_state.link;
4145         int ret;
4146
4147         ret = io_init_req(ctx, req, sqe);
4148         if (unlikely(ret))
4149                 return io_submit_fail_init(sqe, req, ret);
4150
4151         /* don't need @sqe from now on */
4152         trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
4153                                   req->flags, true,
4154                                   ctx->flags & IORING_SETUP_SQPOLL);
4155
4156         /*
4157          * If we already have a head request, queue this one for async
4158          * submittal once the head completes. If we don't have a head but
4159          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
4160          * submitted sync once the chain is complete. If none of those
4161          * conditions are true (normal request), then just queue it.
4162          */
4163         if (unlikely(link->head)) {
4164                 ret = io_req_prep_async(req);
4165                 if (unlikely(ret))
4166                         return io_submit_fail_init(sqe, req, ret);
4167
4168                 trace_io_uring_link(ctx, req, link->head);
4169                 link->last->link = req;
4170                 link->last = req;
4171
4172                 if (req->flags & IO_REQ_LINK_FLAGS)
4173                         return 0;
4174                 /* last request of the link, flush it */
4175                 req = link->head;
4176                 link->head = NULL;
4177                 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
4178                         goto fallback;
4179
4180         } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
4181                                           REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
4182                 if (req->flags & IO_REQ_LINK_FLAGS) {
4183                         link->head = req;
4184                         link->last = req;
4185                 } else {
4186 fallback:
4187                         io_queue_sqe_fallback(req);
4188                 }
4189                 return 0;
4190         }
4191
4192         io_queue_sqe(req);
4193         return 0;
4194 }
4195
4196 /*
4197  * Batched submission is done, ensure local IO is flushed out.
4198  */
4199 static void io_submit_state_end(struct io_ring_ctx *ctx)
4200 {
4201         struct io_submit_state *state = &ctx->submit_state;
4202
4203         if (unlikely(state->link.head))
4204                 io_queue_sqe_fallback(state->link.head);
4205         /* flush only after queuing links as they can generate completions */
4206         io_submit_flush_completions(ctx);
4207         if (state->plug_started)
4208                 blk_finish_plug(&state->plug);
4209 }
4210
4211 /*
4212  * Start submission side cache.
4213  */
4214 static void io_submit_state_start(struct io_submit_state *state,
4215                                   unsigned int max_ios)
4216 {
4217         state->plug_started = false;
4218         state->need_plug = max_ios > 2;
4219         state->submit_nr = max_ios;
4220         /* set only head, no need to init link_last in advance */
4221         state->link.head = NULL;
4222 }
4223
4224 static void io_commit_sqring(struct io_ring_ctx *ctx)
4225 {
4226         struct io_rings *rings = ctx->rings;
4227
4228         /*
4229          * Ensure any loads from the SQEs are done at this point,
4230          * since once we write the new head, the application could
4231          * write new data to them.
4232          */
4233         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
4234 }
4235
4236 /*
4237  * Fetch an sqe, if one is available. Note this returns a pointer to memory
4238  * that is mapped by userspace. This means that care needs to be taken to
4239  * ensure that reads are stable, as we cannot rely on userspace always
4240  * being a good citizen. If members of the sqe are validated and then later
4241  * used, it's important that those reads are done through READ_ONCE() to
4242  * prevent a re-load down the line.
4243  */
4244 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
4245 {
4246         unsigned head, mask = ctx->sq_entries - 1;
4247         unsigned sq_idx = ctx->cached_sq_head++ & mask;
4248
4249         /*
4250          * The cached sq head (or cq tail) serves two purposes:
4251          *
4252          * 1) allows us to batch the cost of updating the user visible
4253          *    head updates.
4254          * 2) allows the kernel side to track the head on its own, even
4255          *    though the application is the one updating it.
4256          */
4257         head = READ_ONCE(ctx->sq_array[sq_idx]);
4258         if (likely(head < ctx->sq_entries)) {
4259                 /* double index for 128-byte SQEs, twice as long */
4260                 if (ctx->flags & IORING_SETUP_SQE128)
4261                         head <<= 1;
4262                 return &ctx->sq_sqes[head];
4263         }
4264
4265         /* drop invalid entries */
4266         ctx->cq_extra--;
4267         WRITE_ONCE(ctx->rings->sq_dropped,
4268                    READ_ONCE(ctx->rings->sq_dropped) + 1);
4269         return NULL;
4270 }
4271
4272 int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
4273         __must_hold(&ctx->uring_lock)
4274 {
4275         unsigned int entries = io_sqring_entries(ctx);
4276         unsigned int left;
4277         int ret;
4278
4279         if (unlikely(!entries))
4280                 return 0;
4281         /* make sure SQ entry isn't read before tail */
4282         ret = left = min3(nr, ctx->sq_entries, entries);
4283         io_get_task_refs(left);
4284         io_submit_state_start(&ctx->submit_state, left);
4285
4286         do {
4287                 const struct io_uring_sqe *sqe;
4288                 struct io_kiocb *req;
4289
4290                 if (unlikely(!io_alloc_req_refill(ctx)))
4291                         break;
4292                 req = io_alloc_req(ctx);
4293                 sqe = io_get_sqe(ctx);
4294                 if (unlikely(!sqe)) {
4295                         io_req_add_to_cache(req, ctx);
4296                         break;
4297                 }
4298
4299                 /*
4300                  * Continue submitting even for sqe failure if the
4301                  * ring was setup with IORING_SETUP_SUBMIT_ALL
4302                  */
4303                 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
4304                     !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
4305                         left--;
4306                         break;
4307                 }
4308         } while (--left);
4309
4310         if (unlikely(left)) {
4311                 ret -= left;
4312                 /* try again if it submitted nothing and can't allocate a req */
4313                 if (!ret && io_req_cache_empty(ctx))
4314                         ret = -EAGAIN;
4315                 current->io_uring->cached_refs += left;
4316         }
4317
4318         io_submit_state_end(ctx);
4319          /* Commit SQ ring head once we've consumed and submitted all SQEs */
4320         io_commit_sqring(ctx);
4321         return ret;
4322 }
4323
4324 struct io_wait_queue {
4325         struct wait_queue_entry wq;
4326         struct io_ring_ctx *ctx;
4327         unsigned cq_tail;
4328         unsigned nr_timeouts;
4329 };
4330
4331 static inline bool io_should_wake(struct io_wait_queue *iowq)
4332 {
4333         struct io_ring_ctx *ctx = iowq->ctx;
4334         int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
4335
4336         /*
4337          * Wake up if we have enough events, or if a timeout occurred since we
4338          * started waiting. For timeouts, we always want to return to userspace,
4339          * regardless of event count.
4340          */
4341         return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
4342 }
4343
4344 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
4345                             int wake_flags, void *key)
4346 {
4347         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
4348                                                         wq);
4349
4350         /*
4351          * Cannot safely flush overflowed CQEs from here, ensure we wake up
4352          * the task, and the next invocation will do it.
4353          */
4354         if (io_should_wake(iowq) ||
4355             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
4356                 return autoremove_wake_function(curr, mode, wake_flags, key);
4357         return -1;
4358 }
4359
4360 static int io_run_task_work_sig(void)
4361 {
4362         if (io_run_task_work())
4363                 return 1;
4364         if (test_thread_flag(TIF_NOTIFY_SIGNAL))
4365                 return -ERESTARTSYS;
4366         if (task_sigpending(current))
4367                 return -EINTR;
4368         return 0;
4369 }
4370
4371 /* when returns >0, the caller should retry */
4372 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
4373                                           struct io_wait_queue *iowq,
4374                                           ktime_t timeout)
4375 {
4376         int ret;
4377         unsigned long check_cq;
4378
4379         /* make sure we run task_work before checking for signals */
4380         ret = io_run_task_work_sig();
4381         if (ret || io_should_wake(iowq))
4382                 return ret;
4383         check_cq = READ_ONCE(ctx->check_cq);
4384         /* let the caller flush overflows, retry */
4385         if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
4386                 return 1;
4387         if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
4388                 return -EBADR;
4389         if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
4390                 return -ETIME;
4391         return 1;
4392 }
4393
4394 /*
4395  * Wait until events become available, if we don't already have some. The
4396  * application must reap them itself, as they reside on the shared cq ring.
4397  */
4398 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
4399                           const sigset_t __user *sig, size_t sigsz,
4400                           struct __kernel_timespec __user *uts)
4401 {
4402         struct io_wait_queue iowq;
4403         struct io_rings *rings = ctx->rings;
4404         ktime_t timeout = KTIME_MAX;
4405         int ret;
4406
4407         do {
4408                 io_cqring_overflow_flush(ctx);
4409                 if (io_cqring_events(ctx) >= min_events)
4410                         return 0;
4411                 if (!io_run_task_work())
4412                         break;
4413         } while (1);
4414
4415         if (sig) {
4416 #ifdef CONFIG_COMPAT
4417                 if (in_compat_syscall())
4418                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
4419                                                       sigsz);
4420                 else
4421 #endif
4422                         ret = set_user_sigmask(sig, sigsz);
4423
4424                 if (ret)
4425                         return ret;
4426         }
4427
4428         if (uts) {
4429                 struct timespec64 ts;
4430
4431                 if (get_timespec64(&ts, uts))
4432                         return -EFAULT;
4433                 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
4434         }
4435
4436         init_waitqueue_func_entry(&iowq.wq, io_wake_function);
4437         iowq.wq.private = current;
4438         INIT_LIST_HEAD(&iowq.wq.entry);
4439         iowq.ctx = ctx;
4440         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
4441         iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
4442
4443         trace_io_uring_cqring_wait(ctx, min_events);
4444         do {
4445                 /* if we can't even flush overflow, don't wait for more */
4446                 if (!io_cqring_overflow_flush(ctx)) {
4447                         ret = -EBUSY;
4448                         break;
4449                 }
4450                 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
4451                                                 TASK_INTERRUPTIBLE);
4452                 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
4453                 cond_resched();
4454         } while (ret > 0);
4455
4456         finish_wait(&ctx->cq_wait, &iowq.wq);
4457         restore_saved_sigmask_unless(ret == -EINTR);
4458
4459         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
4460 }
4461
4462 static void io_free_page_table(void **table, size_t size)
4463 {
4464         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
4465
4466         for (i = 0; i < nr_tables; i++)
4467                 kfree(table[i]);
4468         kfree(table);
4469 }
4470
4471 static __cold void **io_alloc_page_table(size_t size)
4472 {
4473         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
4474         size_t init_size = size;
4475         void **table;
4476
4477         table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
4478         if (!table)
4479                 return NULL;
4480
4481         for (i = 0; i < nr_tables; i++) {
4482                 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
4483
4484                 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
4485                 if (!table[i]) {
4486                         io_free_page_table(table, init_size);
4487                         return NULL;
4488                 }
4489                 size -= this_size;
4490         }
4491         return table;
4492 }
4493
4494 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
4495 {
4496         percpu_ref_exit(&ref_node->refs);
4497         kfree(ref_node);
4498 }
4499
4500 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
4501 {
4502         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
4503         struct io_ring_ctx *ctx = node->rsrc_data->ctx;
4504         unsigned long flags;
4505         bool first_add = false;
4506         unsigned long delay = HZ;
4507
4508         spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
4509         node->done = true;
4510
4511         /* if we are mid-quiesce then do not delay */
4512         if (node->rsrc_data->quiesce)
4513                 delay = 0;
4514
4515         while (!list_empty(&ctx->rsrc_ref_list)) {
4516                 node = list_first_entry(&ctx->rsrc_ref_list,
4517                                             struct io_rsrc_node, node);
4518                 /* recycle ref nodes in order */
4519                 if (!node->done)
4520                         break;
4521                 list_del(&node->node);
4522                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
4523         }
4524         spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
4525
4526         if (first_add)
4527                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
4528 }
4529
4530 static struct io_rsrc_node *io_rsrc_node_alloc(void)
4531 {
4532         struct io_rsrc_node *ref_node;
4533
4534         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
4535         if (!ref_node)
4536                 return NULL;
4537
4538         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
4539                             0, GFP_KERNEL)) {
4540                 kfree(ref_node);
4541                 return NULL;
4542         }
4543         INIT_LIST_HEAD(&ref_node->node);
4544         INIT_LIST_HEAD(&ref_node->rsrc_list);
4545         ref_node->done = false;
4546         return ref_node;
4547 }
4548
4549 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
4550                          struct io_rsrc_data *data_to_kill)
4551         __must_hold(&ctx->uring_lock)
4552 {
4553         WARN_ON_ONCE(!ctx->rsrc_backup_node);
4554         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
4555
4556         io_rsrc_refs_drop(ctx);
4557
4558         if (data_to_kill) {
4559                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
4560
4561                 rsrc_node->rsrc_data = data_to_kill;
4562                 spin_lock_irq(&ctx->rsrc_ref_lock);
4563                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
4564                 spin_unlock_irq(&ctx->rsrc_ref_lock);
4565
4566                 atomic_inc(&data_to_kill->refs);
4567                 percpu_ref_kill(&rsrc_node->refs);
4568                 ctx->rsrc_node = NULL;
4569         }
4570
4571         if (!ctx->rsrc_node) {
4572                 ctx->rsrc_node = ctx->rsrc_backup_node;
4573                 ctx->rsrc_backup_node = NULL;
4574         }
4575 }
4576
4577 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
4578 {
4579         if (ctx->rsrc_backup_node)
4580                 return 0;
4581         ctx->rsrc_backup_node = io_rsrc_node_alloc();
4582         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
4583 }
4584
4585 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
4586                                       struct io_ring_ctx *ctx)
4587 {
4588         int ret;
4589
4590         /* As we may drop ->uring_lock, other task may have started quiesce */
4591         if (data->quiesce)
4592                 return -ENXIO;
4593
4594         data->quiesce = true;
4595         do {
4596                 ret = io_rsrc_node_switch_start(ctx);
4597                 if (ret)
4598                         break;
4599                 io_rsrc_node_switch(ctx, data);
4600
4601                 /* kill initial ref, already quiesced if zero */
4602                 if (atomic_dec_and_test(&data->refs))
4603                         break;
4604                 mutex_unlock(&ctx->uring_lock);
4605                 flush_delayed_work(&ctx->rsrc_put_work);
4606                 ret = wait_for_completion_interruptible(&data->done);
4607                 if (!ret) {
4608                         mutex_lock(&ctx->uring_lock);
4609                         if (atomic_read(&data->refs) > 0) {
4610                                 /*
4611                                  * it has been revived by another thread while
4612                                  * we were unlocked
4613                                  */
4614                                 mutex_unlock(&ctx->uring_lock);
4615                         } else {
4616                                 break;
4617                         }
4618                 }
4619
4620                 atomic_inc(&data->refs);
4621                 /* wait for all works potentially completing data->done */
4622                 flush_delayed_work(&ctx->rsrc_put_work);
4623                 reinit_completion(&data->done);
4624
4625                 ret = io_run_task_work_sig();
4626                 mutex_lock(&ctx->uring_lock);
4627         } while (ret >= 0);
4628         data->quiesce = false;
4629
4630         return ret;
4631 }
4632
4633 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
4634 {
4635         unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
4636         unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
4637
4638         return &data->tags[table_idx][off];
4639 }
4640
4641 static void io_rsrc_data_free(struct io_rsrc_data *data)
4642 {
4643         size_t size = data->nr * sizeof(data->tags[0][0]);
4644
4645         if (data->tags)
4646                 io_free_page_table((void **)data->tags, size);
4647         kfree(data);
4648 }
4649
4650 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
4651                                      u64 __user *utags, unsigned nr,
4652                                      struct io_rsrc_data **pdata)
4653 {
4654         struct io_rsrc_data *data;
4655         int ret = -ENOMEM;
4656         unsigned i;
4657
4658         data = kzalloc(sizeof(*data), GFP_KERNEL);
4659         if (!data)
4660                 return -ENOMEM;
4661         data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
4662         if (!data->tags) {
4663                 kfree(data);
4664                 return -ENOMEM;
4665         }
4666
4667         data->nr = nr;
4668         data->ctx = ctx;
4669         data->do_put = do_put;
4670         if (utags) {
4671                 ret = -EFAULT;
4672                 for (i = 0; i < nr; i++) {
4673                         u64 *tag_slot = io_get_tag_slot(data, i);
4674
4675                         if (copy_from_user(tag_slot, &utags[i],
4676                                            sizeof(*tag_slot)))
4677                                 goto fail;
4678                 }
4679         }
4680
4681         atomic_set(&data->refs, 1);
4682         init_completion(&data->done);
4683         *pdata = data;
4684         return 0;
4685 fail:
4686         io_rsrc_data_free(data);
4687         return ret;
4688 }
4689
4690 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
4691 {
4692 #if !defined(IO_URING_SCM_ALL)
4693         int i;
4694
4695         for (i = 0; i < ctx->nr_user_files; i++) {
4696                 struct file *file = io_file_from_index(&ctx->file_table, i);
4697
4698                 if (!file)
4699                         continue;
4700                 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
4701                         continue;
4702                 io_file_bitmap_clear(&ctx->file_table, i);
4703                 fput(file);
4704         }
4705 #endif
4706
4707 #if defined(CONFIG_UNIX)
4708         if (ctx->ring_sock) {
4709                 struct sock *sock = ctx->ring_sock->sk;
4710                 struct sk_buff *skb;
4711
4712                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
4713                         kfree_skb(skb);
4714         }
4715 #endif
4716         io_free_file_tables(&ctx->file_table);
4717         io_rsrc_data_free(ctx->file_data);
4718         ctx->file_data = NULL;
4719         ctx->nr_user_files = 0;
4720 }
4721
4722 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
4723 {
4724         unsigned nr = ctx->nr_user_files;
4725         int ret;
4726
4727         if (!ctx->file_data)
4728                 return -ENXIO;
4729
4730         /*
4731          * Quiesce may unlock ->uring_lock, and while it's not held
4732          * prevent new requests using the table.
4733          */
4734         ctx->nr_user_files = 0;
4735         ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
4736         ctx->nr_user_files = nr;
4737         if (!ret)
4738                 __io_sqe_files_unregister(ctx);
4739         return ret;
4740 }
4741
4742 /*
4743  * Ensure the UNIX gc is aware of our file set, so we are certain that
4744  * the io_uring can be safely unregistered on process exit, even if we have
4745  * loops in the file referencing. We account only files that can hold other
4746  * files because otherwise they can't form a loop and so are not interesting
4747  * for GC.
4748  */
4749 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
4750 {
4751 #if defined(CONFIG_UNIX)
4752         struct sock *sk = ctx->ring_sock->sk;
4753         struct sk_buff_head *head = &sk->sk_receive_queue;
4754         struct scm_fp_list *fpl;
4755         struct sk_buff *skb;
4756
4757         if (likely(!io_file_need_scm(file)))
4758                 return 0;
4759
4760         /*
4761          * See if we can merge this file into an existing skb SCM_RIGHTS
4762          * file set. If there's no room, fall back to allocating a new skb
4763          * and filling it in.
4764          */
4765         spin_lock_irq(&head->lock);
4766         skb = skb_peek(head);
4767         if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
4768                 __skb_unlink(skb, head);
4769         else
4770                 skb = NULL;
4771         spin_unlock_irq(&head->lock);
4772
4773         if (!skb) {
4774                 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
4775                 if (!fpl)
4776                         return -ENOMEM;
4777
4778                 skb = alloc_skb(0, GFP_KERNEL);
4779                 if (!skb) {
4780                         kfree(fpl);
4781                         return -ENOMEM;
4782                 }
4783
4784                 fpl->user = get_uid(current_user());
4785                 fpl->max = SCM_MAX_FD;
4786                 fpl->count = 0;
4787
4788                 UNIXCB(skb).fp = fpl;
4789                 skb->sk = sk;
4790                 skb->destructor = unix_destruct_scm;
4791                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
4792         }
4793
4794         fpl = UNIXCB(skb).fp;
4795         fpl->fp[fpl->count++] = get_file(file);
4796         unix_inflight(fpl->user, file);
4797         skb_queue_head(head, skb);
4798         fput(file);
4799 #endif
4800         return 0;
4801 }
4802
4803 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
4804 {
4805         struct file *file = prsrc->file;
4806 #if defined(CONFIG_UNIX)
4807         struct sock *sock = ctx->ring_sock->sk;
4808         struct sk_buff_head list, *head = &sock->sk_receive_queue;
4809         struct sk_buff *skb;
4810         int i;
4811
4812         if (!io_file_need_scm(file)) {
4813                 fput(file);
4814                 return;
4815         }
4816
4817         __skb_queue_head_init(&list);
4818
4819         /*
4820          * Find the skb that holds this file in its SCM_RIGHTS. When found,
4821          * remove this entry and rearrange the file array.
4822          */
4823         skb = skb_dequeue(head);
4824         while (skb) {
4825                 struct scm_fp_list *fp;
4826
4827                 fp = UNIXCB(skb).fp;
4828                 for (i = 0; i < fp->count; i++) {
4829                         int left;
4830
4831                         if (fp->fp[i] != file)
4832                                 continue;
4833
4834                         unix_notinflight(fp->user, fp->fp[i]);
4835                         left = fp->count - 1 - i;
4836                         if (left) {
4837                                 memmove(&fp->fp[i], &fp->fp[i + 1],
4838                                                 left * sizeof(struct file *));
4839                         }
4840                         fp->count--;
4841                         if (!fp->count) {
4842                                 kfree_skb(skb);
4843                                 skb = NULL;
4844                         } else {
4845                                 __skb_queue_tail(&list, skb);
4846                         }
4847                         fput(file);
4848                         file = NULL;
4849                         break;
4850                 }
4851
4852                 if (!file)
4853                         break;
4854
4855                 __skb_queue_tail(&list, skb);
4856
4857                 skb = skb_dequeue(head);
4858         }
4859
4860         if (skb_peek(&list)) {
4861                 spin_lock_irq(&head->lock);
4862                 while ((skb = __skb_dequeue(&list)) != NULL)
4863                         __skb_queue_tail(head, skb);
4864                 spin_unlock_irq(&head->lock);
4865         }
4866 #else
4867         fput(file);
4868 #endif
4869 }
4870
4871 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
4872 {
4873         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
4874         struct io_ring_ctx *ctx = rsrc_data->ctx;
4875         struct io_rsrc_put *prsrc, *tmp;
4876
4877         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
4878                 list_del(&prsrc->list);
4879
4880                 if (prsrc->tag) {
4881                         if (ctx->flags & IORING_SETUP_IOPOLL)
4882                                 mutex_lock(&ctx->uring_lock);
4883
4884                         spin_lock(&ctx->completion_lock);
4885                         io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
4886                         io_commit_cqring(ctx);
4887                         spin_unlock(&ctx->completion_lock);
4888                         io_cqring_ev_posted(ctx);
4889
4890                         if (ctx->flags & IORING_SETUP_IOPOLL)
4891                                 mutex_unlock(&ctx->uring_lock);
4892                 }
4893
4894                 rsrc_data->do_put(ctx, prsrc);
4895                 kfree(prsrc);
4896         }
4897
4898         io_rsrc_node_destroy(ref_node);
4899         if (atomic_dec_and_test(&rsrc_data->refs))
4900                 complete(&rsrc_data->done);
4901 }
4902
4903 static void io_rsrc_put_work(struct work_struct *work)
4904 {
4905         struct io_ring_ctx *ctx;
4906         struct llist_node *node;
4907
4908         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
4909         node = llist_del_all(&ctx->rsrc_put_llist);
4910
4911         while (node) {
4912                 struct io_rsrc_node *ref_node;
4913                 struct llist_node *next = node->next;
4914
4915                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
4916                 __io_rsrc_put_work(ref_node);
4917                 node = next;
4918         }
4919 }
4920
4921 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
4922                                  unsigned nr_args, u64 __user *tags)
4923 {
4924         __s32 __user *fds = (__s32 __user *) arg;
4925         struct file *file;
4926         int fd, ret;
4927         unsigned i;
4928
4929         if (ctx->file_data)
4930                 return -EBUSY;
4931         if (!nr_args)
4932                 return -EINVAL;
4933         if (nr_args > IORING_MAX_FIXED_FILES)
4934                 return -EMFILE;
4935         if (nr_args > rlimit(RLIMIT_NOFILE))
4936                 return -EMFILE;
4937         ret = io_rsrc_node_switch_start(ctx);
4938         if (ret)
4939                 return ret;
4940         ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
4941                                  &ctx->file_data);
4942         if (ret)
4943                 return ret;
4944
4945         if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
4946                 io_rsrc_data_free(ctx->file_data);
4947                 ctx->file_data = NULL;
4948                 return -ENOMEM;
4949         }
4950
4951         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
4952                 struct io_fixed_file *file_slot;
4953
4954                 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
4955                         ret = -EFAULT;
4956                         goto fail;
4957                 }
4958                 /* allow sparse sets */
4959                 if (!fds || fd == -1) {
4960                         ret = -EINVAL;
4961                         if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
4962                                 goto fail;
4963                         continue;
4964                 }
4965
4966                 file = fget(fd);
4967                 ret = -EBADF;
4968                 if (unlikely(!file))
4969                         goto fail;
4970
4971                 /*
4972                  * Don't allow io_uring instances to be registered. If UNIX
4973                  * isn't enabled, then this causes a reference cycle and this
4974                  * instance can never get freed. If UNIX is enabled we'll
4975                  * handle it just fine, but there's still no point in allowing
4976                  * a ring fd as it doesn't support regular read/write anyway.
4977                  */
4978                 if (io_is_uring_fops(file)) {
4979                         fput(file);
4980                         goto fail;
4981                 }
4982                 ret = io_scm_file_account(ctx, file);
4983                 if (ret) {
4984                         fput(file);
4985                         goto fail;
4986                 }
4987                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
4988                 io_fixed_file_set(file_slot, file);
4989                 io_file_bitmap_set(&ctx->file_table, i);
4990         }
4991
4992         io_rsrc_node_switch(ctx, NULL);
4993         return 0;
4994 fail:
4995         __io_sqe_files_unregister(ctx);
4996         return ret;
4997 }
4998
4999 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
5000                           struct io_rsrc_node *node, void *rsrc)
5001 {
5002         u64 *tag_slot = io_get_tag_slot(data, idx);
5003         struct io_rsrc_put *prsrc;
5004
5005         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
5006         if (!prsrc)
5007                 return -ENOMEM;
5008
5009         prsrc->tag = *tag_slot;
5010         *tag_slot = 0;
5011         prsrc->rsrc = rsrc;
5012         list_add(&prsrc->list, &node->rsrc_list);
5013         return 0;
5014 }
5015
5016 int io_install_fixed_file(struct io_kiocb *req, struct file *file,
5017                           unsigned int issue_flags, u32 slot_index)
5018         __must_hold(&req->ctx->uring_lock)
5019 {
5020         struct io_ring_ctx *ctx = req->ctx;
5021         bool needs_switch = false;
5022         struct io_fixed_file *file_slot;
5023         int ret;
5024
5025         if (io_is_uring_fops(file))
5026                 return -EBADF;
5027         if (!ctx->file_data)
5028                 return -ENXIO;
5029         if (slot_index >= ctx->nr_user_files)
5030                 return -EINVAL;
5031
5032         slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
5033         file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
5034
5035         if (file_slot->file_ptr) {
5036                 struct file *old_file;
5037
5038                 ret = io_rsrc_node_switch_start(ctx);
5039                 if (ret)
5040                         goto err;
5041
5042                 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
5043                 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
5044                                             ctx->rsrc_node, old_file);
5045                 if (ret)
5046                         goto err;
5047                 file_slot->file_ptr = 0;
5048                 io_file_bitmap_clear(&ctx->file_table, slot_index);
5049                 needs_switch = true;
5050         }
5051
5052         ret = io_scm_file_account(ctx, file);
5053         if (!ret) {
5054                 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
5055                 io_fixed_file_set(file_slot, file);
5056                 io_file_bitmap_set(&ctx->file_table, slot_index);
5057         }
5058 err:
5059         if (needs_switch)
5060                 io_rsrc_node_switch(ctx, ctx->file_data);
5061         if (ret)
5062                 fput(file);
5063         return ret;
5064 }
5065
5066 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
5067                                  struct io_uring_rsrc_update2 *up,
5068                                  unsigned nr_args)
5069 {
5070         u64 __user *tags = u64_to_user_ptr(up->tags);
5071         __s32 __user *fds = u64_to_user_ptr(up->data);
5072         struct io_rsrc_data *data = ctx->file_data;
5073         struct io_fixed_file *file_slot;
5074         struct file *file;
5075         int fd, i, err = 0;
5076         unsigned int done;
5077         bool needs_switch = false;
5078
5079         if (!ctx->file_data)
5080                 return -ENXIO;
5081         if (up->offset + nr_args > ctx->nr_user_files)
5082                 return -EINVAL;
5083
5084         for (done = 0; done < nr_args; done++) {
5085                 u64 tag = 0;
5086
5087                 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
5088                     copy_from_user(&fd, &fds[done], sizeof(fd))) {
5089                         err = -EFAULT;
5090                         break;
5091                 }
5092                 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
5093                         err = -EINVAL;
5094                         break;
5095                 }
5096                 if (fd == IORING_REGISTER_FILES_SKIP)
5097                         continue;
5098
5099                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
5100                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
5101
5102                 if (file_slot->file_ptr) {
5103                         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
5104                         err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
5105                         if (err)
5106                                 break;
5107                         file_slot->file_ptr = 0;
5108                         io_file_bitmap_clear(&ctx->file_table, i);
5109                         needs_switch = true;
5110                 }
5111                 if (fd != -1) {
5112                         file = fget(fd);
5113                         if (!file) {
5114                                 err = -EBADF;
5115                                 break;
5116                         }
5117                         /*
5118                          * Don't allow io_uring instances to be registered. If
5119                          * UNIX isn't enabled, then this causes a reference
5120                          * cycle and this instance can never get freed. If UNIX
5121                          * is enabled we'll handle it just fine, but there's
5122                          * still no point in allowing a ring fd as it doesn't
5123                          * support regular read/write anyway.
5124                          */
5125                         if (io_is_uring_fops(file)) {
5126                                 fput(file);
5127                                 err = -EBADF;
5128                                 break;
5129                         }
5130                         err = io_scm_file_account(ctx, file);
5131                         if (err) {
5132                                 fput(file);
5133                                 break;
5134                         }
5135                         *io_get_tag_slot(data, i) = tag;
5136                         io_fixed_file_set(file_slot, file);
5137                         io_file_bitmap_set(&ctx->file_table, i);
5138                 }
5139         }
5140
5141         if (needs_switch)
5142                 io_rsrc_node_switch(ctx, data);
5143         return done ? done : err;
5144 }
5145
5146 static inline void __io_unaccount_mem(struct user_struct *user,
5147                                       unsigned long nr_pages)
5148 {
5149         atomic_long_sub(nr_pages, &user->locked_vm);
5150 }
5151
5152 static inline int __io_account_mem(struct user_struct *user,
5153                                    unsigned long nr_pages)
5154 {
5155         unsigned long page_limit, cur_pages, new_pages;
5156
5157         /* Don't allow more pages than we can safely lock */
5158         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
5159
5160         do {
5161                 cur_pages = atomic_long_read(&user->locked_vm);
5162                 new_pages = cur_pages + nr_pages;
5163                 if (new_pages > page_limit)
5164                         return -ENOMEM;
5165         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
5166                                         new_pages) != cur_pages);
5167
5168         return 0;
5169 }
5170
5171 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
5172 {
5173         if (ctx->user)
5174                 __io_unaccount_mem(ctx->user, nr_pages);
5175
5176         if (ctx->mm_account)
5177                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
5178 }
5179
5180 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
5181 {
5182         int ret;
5183
5184         if (ctx->user) {
5185                 ret = __io_account_mem(ctx->user, nr_pages);
5186                 if (ret)
5187                         return ret;
5188         }
5189
5190         if (ctx->mm_account)
5191                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
5192
5193         return 0;
5194 }
5195
5196 static void io_mem_free(void *ptr)
5197 {
5198         struct page *page;
5199
5200         if (!ptr)
5201                 return;
5202
5203         page = virt_to_head_page(ptr);
5204         if (put_page_testzero(page))
5205                 free_compound_page(page);
5206 }
5207
5208 static void *io_mem_alloc(size_t size)
5209 {
5210         gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
5211
5212         return (void *) __get_free_pages(gfp, get_order(size));
5213 }
5214
5215 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
5216                                 unsigned int cq_entries, size_t *sq_offset)
5217 {
5218         struct io_rings *rings;
5219         size_t off, sq_array_size;
5220
5221         off = struct_size(rings, cqes, cq_entries);
5222         if (off == SIZE_MAX)
5223                 return SIZE_MAX;
5224         if (ctx->flags & IORING_SETUP_CQE32) {
5225                 if (check_shl_overflow(off, 1, &off))
5226                         return SIZE_MAX;
5227         }
5228
5229 #ifdef CONFIG_SMP
5230         off = ALIGN(off, SMP_CACHE_BYTES);
5231         if (off == 0)
5232                 return SIZE_MAX;
5233 #endif
5234
5235         if (sq_offset)
5236                 *sq_offset = off;
5237
5238         sq_array_size = array_size(sizeof(u32), sq_entries);
5239         if (sq_array_size == SIZE_MAX)
5240                 return SIZE_MAX;
5241
5242         if (check_add_overflow(off, sq_array_size, &off))
5243                 return SIZE_MAX;
5244
5245         return off;
5246 }
5247
5248 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
5249 {
5250         struct io_mapped_ubuf *imu = *slot;
5251         unsigned int i;
5252
5253         if (imu != ctx->dummy_ubuf) {
5254                 for (i = 0; i < imu->nr_bvecs; i++)
5255                         unpin_user_page(imu->bvec[i].bv_page);
5256                 if (imu->acct_pages)
5257                         io_unaccount_mem(ctx, imu->acct_pages);
5258                 kvfree(imu);
5259         }
5260         *slot = NULL;
5261 }
5262
5263 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
5264 {
5265         io_buffer_unmap(ctx, &prsrc->buf);
5266         prsrc->buf = NULL;
5267 }
5268
5269 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
5270 {
5271         unsigned int i;
5272
5273         for (i = 0; i < ctx->nr_user_bufs; i++)
5274                 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
5275         kfree(ctx->user_bufs);
5276         io_rsrc_data_free(ctx->buf_data);
5277         ctx->user_bufs = NULL;
5278         ctx->buf_data = NULL;
5279         ctx->nr_user_bufs = 0;
5280 }
5281
5282 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
5283 {
5284         unsigned nr = ctx->nr_user_bufs;
5285         int ret;
5286
5287         if (!ctx->buf_data)
5288                 return -ENXIO;
5289
5290         /*
5291          * Quiesce may unlock ->uring_lock, and while it's not held
5292          * prevent new requests using the table.
5293          */
5294         ctx->nr_user_bufs = 0;
5295         ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
5296         ctx->nr_user_bufs = nr;
5297         if (!ret)
5298                 __io_sqe_buffers_unregister(ctx);
5299         return ret;
5300 }
5301
5302 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
5303                        void __user *arg, unsigned index)
5304 {
5305         struct iovec __user *src;
5306
5307 #ifdef CONFIG_COMPAT
5308         if (ctx->compat) {
5309                 struct compat_iovec __user *ciovs;
5310                 struct compat_iovec ciov;
5311
5312                 ciovs = (struct compat_iovec __user *) arg;
5313                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
5314                         return -EFAULT;
5315
5316                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
5317                 dst->iov_len = ciov.iov_len;
5318                 return 0;
5319         }
5320 #endif
5321         src = (struct iovec __user *) arg;
5322         if (copy_from_user(dst, &src[index], sizeof(*dst)))
5323                 return -EFAULT;
5324         return 0;
5325 }
5326
5327 /*
5328  * Not super efficient, but this is just a registration time. And we do cache
5329  * the last compound head, so generally we'll only do a full search if we don't
5330  * match that one.
5331  *
5332  * We check if the given compound head page has already been accounted, to
5333  * avoid double accounting it. This allows us to account the full size of the
5334  * page, not just the constituent pages of a huge page.
5335  */
5336 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
5337                                   int nr_pages, struct page *hpage)
5338 {
5339         int i, j;
5340
5341         /* check current page array */
5342         for (i = 0; i < nr_pages; i++) {
5343                 if (!PageCompound(pages[i]))
5344                         continue;
5345                 if (compound_head(pages[i]) == hpage)
5346                         return true;
5347         }
5348
5349         /* check previously registered pages */
5350         for (i = 0; i < ctx->nr_user_bufs; i++) {
5351                 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
5352
5353                 for (j = 0; j < imu->nr_bvecs; j++) {
5354                         if (!PageCompound(imu->bvec[j].bv_page))
5355                                 continue;
5356                         if (compound_head(imu->bvec[j].bv_page) == hpage)
5357                                 return true;
5358                 }
5359         }
5360
5361         return false;
5362 }
5363
5364 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
5365                                  int nr_pages, struct io_mapped_ubuf *imu,
5366                                  struct page **last_hpage)
5367 {
5368         int i, ret;
5369
5370         imu->acct_pages = 0;
5371         for (i = 0; i < nr_pages; i++) {
5372                 if (!PageCompound(pages[i])) {
5373                         imu->acct_pages++;
5374                 } else {
5375                         struct page *hpage;
5376
5377                         hpage = compound_head(pages[i]);
5378                         if (hpage == *last_hpage)
5379                                 continue;
5380                         *last_hpage = hpage;
5381                         if (headpage_already_acct(ctx, pages, i, hpage))
5382                                 continue;
5383                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
5384                 }
5385         }
5386
5387         if (!imu->acct_pages)
5388                 return 0;
5389
5390         ret = io_account_mem(ctx, imu->acct_pages);
5391         if (ret)
5392                 imu->acct_pages = 0;
5393         return ret;
5394 }
5395
5396 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
5397                                   int *npages)
5398 {
5399         unsigned long start, end, nr_pages;
5400         struct vm_area_struct **vmas = NULL;
5401         struct page **pages = NULL;
5402         int i, pret, ret = -ENOMEM;
5403
5404         end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
5405         start = ubuf >> PAGE_SHIFT;
5406         nr_pages = end - start;
5407
5408         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
5409         if (!pages)
5410                 goto done;
5411
5412         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
5413                               GFP_KERNEL);
5414         if (!vmas)
5415                 goto done;
5416
5417         ret = 0;
5418         mmap_read_lock(current->mm);
5419         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
5420                               pages, vmas);
5421         if (pret == nr_pages) {
5422                 /* don't support file backed memory */
5423                 for (i = 0; i < nr_pages; i++) {
5424                         struct vm_area_struct *vma = vmas[i];
5425
5426                         if (vma_is_shmem(vma))
5427                                 continue;
5428                         if (vma->vm_file &&
5429                             !is_file_hugepages(vma->vm_file)) {
5430                                 ret = -EOPNOTSUPP;
5431                                 break;
5432                         }
5433                 }
5434                 *npages = nr_pages;
5435         } else {
5436                 ret = pret < 0 ? pret : -EFAULT;
5437         }
5438         mmap_read_unlock(current->mm);
5439         if (ret) {
5440                 /*
5441                  * if we did partial map, or found file backed vmas,
5442                  * release any pages we did get
5443                  */
5444                 if (pret > 0)
5445                         unpin_user_pages(pages, pret);
5446                 goto done;
5447         }
5448         ret = 0;
5449 done:
5450         kvfree(vmas);
5451         if (ret < 0) {
5452                 kvfree(pages);
5453                 pages = ERR_PTR(ret);
5454         }
5455         return pages;
5456 }
5457
5458 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
5459                                   struct io_mapped_ubuf **pimu,
5460                                   struct page **last_hpage)
5461 {
5462         struct io_mapped_ubuf *imu = NULL;
5463         struct page **pages = NULL;
5464         unsigned long off;
5465         size_t size;
5466         int ret, nr_pages, i;
5467
5468         if (!iov->iov_base) {
5469                 *pimu = ctx->dummy_ubuf;
5470                 return 0;
5471         }
5472
5473         *pimu = NULL;
5474         ret = -ENOMEM;
5475
5476         pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
5477                                 &nr_pages);
5478         if (IS_ERR(pages)) {
5479                 ret = PTR_ERR(pages);
5480                 pages = NULL;
5481                 goto done;
5482         }
5483
5484         imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
5485         if (!imu)
5486                 goto done;
5487
5488         ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
5489         if (ret) {
5490                 unpin_user_pages(pages, nr_pages);
5491                 goto done;
5492         }
5493
5494         off = (unsigned long) iov->iov_base & ~PAGE_MASK;
5495         size = iov->iov_len;
5496         for (i = 0; i < nr_pages; i++) {
5497                 size_t vec_len;
5498
5499                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
5500                 imu->bvec[i].bv_page = pages[i];
5501                 imu->bvec[i].bv_len = vec_len;
5502                 imu->bvec[i].bv_offset = off;
5503                 off = 0;
5504                 size -= vec_len;
5505         }
5506         /* store original address for later verification */
5507         imu->ubuf = (unsigned long) iov->iov_base;
5508         imu->ubuf_end = imu->ubuf + iov->iov_len;
5509         imu->nr_bvecs = nr_pages;
5510         *pimu = imu;
5511         ret = 0;
5512 done:
5513         if (ret)
5514                 kvfree(imu);
5515         kvfree(pages);
5516         return ret;
5517 }
5518
5519 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
5520 {
5521         ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
5522         return ctx->user_bufs ? 0 : -ENOMEM;
5523 }
5524
5525 static int io_buffer_validate(struct iovec *iov)
5526 {
5527         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
5528
5529         /*
5530          * Don't impose further limits on the size and buffer
5531          * constraints here, we'll -EINVAL later when IO is
5532          * submitted if they are wrong.
5533          */
5534         if (!iov->iov_base)
5535                 return iov->iov_len ? -EFAULT : 0;
5536         if (!iov->iov_len)
5537                 return -EFAULT;
5538
5539         /* arbitrary limit, but we need something */
5540         if (iov->iov_len > SZ_1G)
5541                 return -EFAULT;
5542
5543         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
5544                 return -EOVERFLOW;
5545
5546         return 0;
5547 }
5548
5549 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
5550                                    unsigned int nr_args, u64 __user *tags)
5551 {
5552         struct page *last_hpage = NULL;
5553         struct io_rsrc_data *data;
5554         int i, ret;
5555         struct iovec iov;
5556
5557         if (ctx->user_bufs)
5558                 return -EBUSY;
5559         if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
5560                 return -EINVAL;
5561         ret = io_rsrc_node_switch_start(ctx);
5562         if (ret)
5563                 return ret;
5564         ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
5565         if (ret)
5566                 return ret;
5567         ret = io_buffers_map_alloc(ctx, nr_args);
5568         if (ret) {
5569                 io_rsrc_data_free(data);
5570                 return ret;
5571         }
5572
5573         for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
5574                 if (arg) {
5575                         ret = io_copy_iov(ctx, &iov, arg, i);
5576                         if (ret)
5577                                 break;
5578                         ret = io_buffer_validate(&iov);
5579                         if (ret)
5580                                 break;
5581                 } else {
5582                         memset(&iov, 0, sizeof(iov));
5583                 }
5584
5585                 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
5586                         ret = -EINVAL;
5587                         break;
5588                 }
5589
5590                 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
5591                                              &last_hpage);
5592                 if (ret)
5593                         break;
5594         }
5595
5596         WARN_ON_ONCE(ctx->buf_data);
5597
5598         ctx->buf_data = data;
5599         if (ret)
5600                 __io_sqe_buffers_unregister(ctx);
5601         else
5602                 io_rsrc_node_switch(ctx, NULL);
5603         return ret;
5604 }
5605
5606 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
5607                                    struct io_uring_rsrc_update2 *up,
5608                                    unsigned int nr_args)
5609 {
5610         u64 __user *tags = u64_to_user_ptr(up->tags);
5611         struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
5612         struct page *last_hpage = NULL;
5613         bool needs_switch = false;
5614         __u32 done;
5615         int i, err;
5616
5617         if (!ctx->buf_data)
5618                 return -ENXIO;
5619         if (up->offset + nr_args > ctx->nr_user_bufs)
5620                 return -EINVAL;
5621
5622         for (done = 0; done < nr_args; done++) {
5623                 struct io_mapped_ubuf *imu;
5624                 int offset = up->offset + done;
5625                 u64 tag = 0;
5626
5627                 err = io_copy_iov(ctx, &iov, iovs, done);
5628                 if (err)
5629                         break;
5630                 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
5631                         err = -EFAULT;
5632                         break;
5633                 }
5634                 err = io_buffer_validate(&iov);
5635                 if (err)
5636                         break;
5637                 if (!iov.iov_base && tag) {
5638                         err = -EINVAL;
5639                         break;
5640                 }
5641                 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
5642                 if (err)
5643                         break;
5644
5645                 i = array_index_nospec(offset, ctx->nr_user_bufs);
5646                 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
5647                         err = io_queue_rsrc_removal(ctx->buf_data, i,
5648                                                     ctx->rsrc_node, ctx->user_bufs[i]);
5649                         if (unlikely(err)) {
5650                                 io_buffer_unmap(ctx, &imu);
5651                                 break;
5652                         }
5653                         ctx->user_bufs[i] = NULL;
5654                         needs_switch = true;
5655                 }
5656
5657                 ctx->user_bufs[i] = imu;
5658                 *io_get_tag_slot(ctx->buf_data, offset) = tag;
5659         }
5660
5661         if (needs_switch)
5662                 io_rsrc_node_switch(ctx, ctx->buf_data);
5663         return done ? done : err;
5664 }
5665
5666 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
5667                                unsigned int eventfd_async)
5668 {
5669         struct io_ev_fd *ev_fd;
5670         __s32 __user *fds = arg;
5671         int fd;
5672
5673         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5674                                         lockdep_is_held(&ctx->uring_lock));
5675         if (ev_fd)
5676                 return -EBUSY;
5677
5678         if (copy_from_user(&fd, fds, sizeof(*fds)))
5679                 return -EFAULT;
5680
5681         ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
5682         if (!ev_fd)
5683                 return -ENOMEM;
5684
5685         ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
5686         if (IS_ERR(ev_fd->cq_ev_fd)) {
5687                 int ret = PTR_ERR(ev_fd->cq_ev_fd);
5688                 kfree(ev_fd);
5689                 return ret;
5690         }
5691         ev_fd->eventfd_async = eventfd_async;
5692         ctx->has_evfd = true;
5693         rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
5694         return 0;
5695 }
5696
5697 static void io_eventfd_put(struct rcu_head *rcu)
5698 {
5699         struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
5700
5701         eventfd_ctx_put(ev_fd->cq_ev_fd);
5702         kfree(ev_fd);
5703 }
5704
5705 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
5706 {
5707         struct io_ev_fd *ev_fd;
5708
5709         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
5710                                         lockdep_is_held(&ctx->uring_lock));
5711         if (ev_fd) {
5712                 ctx->has_evfd = false;
5713                 rcu_assign_pointer(ctx->io_ev_fd, NULL);
5714                 call_rcu(&ev_fd->rcu, io_eventfd_put);
5715                 return 0;
5716         }
5717
5718         return -ENXIO;
5719 }
5720
5721 static void io_destroy_buffers(struct io_ring_ctx *ctx)
5722 {
5723         struct io_buffer_list *bl;
5724         unsigned long index;
5725         int i;
5726
5727         for (i = 0; i < BGID_ARRAY; i++) {
5728                 if (!ctx->io_bl)
5729                         break;
5730                 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
5731         }
5732
5733         xa_for_each(&ctx->io_bl_xa, index, bl) {
5734                 xa_erase(&ctx->io_bl_xa, bl->bgid);
5735                 __io_remove_buffers(ctx, bl, -1U);
5736                 kfree(bl);
5737         }
5738
5739         while (!list_empty(&ctx->io_buffers_pages)) {
5740                 struct page *page;
5741
5742                 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
5743                 list_del_init(&page->lru);
5744                 __free_page(page);
5745         }
5746 }
5747
5748 static void io_req_caches_free(struct io_ring_ctx *ctx)
5749 {
5750         struct io_submit_state *state = &ctx->submit_state;
5751         int nr = 0;
5752
5753         mutex_lock(&ctx->uring_lock);
5754         io_flush_cached_locked_reqs(ctx, state);
5755
5756         while (!io_req_cache_empty(ctx)) {
5757                 struct io_wq_work_node *node;
5758                 struct io_kiocb *req;
5759
5760                 node = wq_stack_extract(&state->free_list);
5761                 req = container_of(node, struct io_kiocb, comp_list);
5762                 kmem_cache_free(req_cachep, req);
5763                 nr++;
5764         }
5765         if (nr)
5766                 percpu_ref_put_many(&ctx->refs, nr);
5767         mutex_unlock(&ctx->uring_lock);
5768 }
5769
5770 static void io_wait_rsrc_data(struct io_rsrc_data *data)
5771 {
5772         if (data && !atomic_dec_and_test(&data->refs))
5773                 wait_for_completion(&data->done);
5774 }
5775
5776 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
5777 {
5778         struct async_poll *apoll;
5779
5780         while (!list_empty(&ctx->apoll_cache)) {
5781                 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5782                                                 poll.wait.entry);
5783                 list_del(&apoll->poll.wait.entry);
5784                 kfree(apoll);
5785         }
5786 }
5787
5788 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
5789 {
5790         io_sq_thread_finish(ctx);
5791
5792         if (ctx->mm_account) {
5793                 mmdrop(ctx->mm_account);
5794                 ctx->mm_account = NULL;
5795         }
5796
5797         io_rsrc_refs_drop(ctx);
5798         /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
5799         io_wait_rsrc_data(ctx->buf_data);
5800         io_wait_rsrc_data(ctx->file_data);
5801
5802         mutex_lock(&ctx->uring_lock);
5803         if (ctx->buf_data)
5804                 __io_sqe_buffers_unregister(ctx);
5805         if (ctx->file_data)
5806                 __io_sqe_files_unregister(ctx);
5807         if (ctx->rings)
5808                 __io_cqring_overflow_flush(ctx, true);
5809         io_eventfd_unregister(ctx);
5810         io_flush_apoll_cache(ctx);
5811         mutex_unlock(&ctx->uring_lock);
5812         io_destroy_buffers(ctx);
5813         if (ctx->sq_creds)
5814                 put_cred(ctx->sq_creds);
5815
5816         /* there are no registered resources left, nobody uses it */
5817         if (ctx->rsrc_node)
5818                 io_rsrc_node_destroy(ctx->rsrc_node);
5819         if (ctx->rsrc_backup_node)
5820                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
5821         flush_delayed_work(&ctx->rsrc_put_work);
5822         flush_delayed_work(&ctx->fallback_work);
5823
5824         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
5825         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
5826
5827 #if defined(CONFIG_UNIX)
5828         if (ctx->ring_sock) {
5829                 ctx->ring_sock->file = NULL; /* so that iput() is called */
5830                 sock_release(ctx->ring_sock);
5831         }
5832 #endif
5833         WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
5834
5835         io_mem_free(ctx->rings);
5836         io_mem_free(ctx->sq_sqes);
5837
5838         percpu_ref_exit(&ctx->refs);
5839         free_uid(ctx->user);
5840         io_req_caches_free(ctx);
5841         if (ctx->hash_map)
5842                 io_wq_put_hash(ctx->hash_map);
5843         kfree(ctx->cancel_hash);
5844         kfree(ctx->dummy_ubuf);
5845         kfree(ctx->io_bl);
5846         xa_destroy(&ctx->io_bl_xa);
5847         kfree(ctx);
5848 }
5849
5850 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
5851 {
5852         struct io_ring_ctx *ctx = file->private_data;
5853         __poll_t mask = 0;
5854
5855         poll_wait(file, &ctx->cq_wait, wait);
5856         /*
5857          * synchronizes with barrier from wq_has_sleeper call in
5858          * io_commit_cqring
5859          */
5860         smp_rmb();
5861         if (!io_sqring_full(ctx))
5862                 mask |= EPOLLOUT | EPOLLWRNORM;
5863
5864         /*
5865          * Don't flush cqring overflow list here, just do a simple check.
5866          * Otherwise there could possible be ABBA deadlock:
5867          *      CPU0                    CPU1
5868          *      ----                    ----
5869          * lock(&ctx->uring_lock);
5870          *                              lock(&ep->mtx);
5871          *                              lock(&ctx->uring_lock);
5872          * lock(&ep->mtx);
5873          *
5874          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
5875          * pushs them to do the flush.
5876          */
5877         if (io_cqring_events(ctx) ||
5878             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
5879                 mask |= EPOLLIN | EPOLLRDNORM;
5880
5881         return mask;
5882 }
5883
5884 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
5885 {
5886         const struct cred *creds;
5887
5888         creds = xa_erase(&ctx->personalities, id);
5889         if (creds) {
5890                 put_cred(creds);
5891                 return 0;
5892         }
5893
5894         return -EINVAL;
5895 }
5896
5897 struct io_tctx_exit {
5898         struct callback_head            task_work;
5899         struct completion               completion;
5900         struct io_ring_ctx              *ctx;
5901 };
5902
5903 static __cold void io_tctx_exit_cb(struct callback_head *cb)
5904 {
5905         struct io_uring_task *tctx = current->io_uring;
5906         struct io_tctx_exit *work;
5907
5908         work = container_of(cb, struct io_tctx_exit, task_work);
5909         /*
5910          * When @in_idle, we're in cancellation and it's racy to remove the
5911          * node. It'll be removed by the end of cancellation, just ignore it.
5912          */
5913         if (!atomic_read(&tctx->in_idle))
5914                 io_uring_del_tctx_node((unsigned long)work->ctx);
5915         complete(&work->completion);
5916 }
5917
5918 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
5919 {
5920         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5921
5922         return req->ctx == data;
5923 }
5924
5925 static __cold void io_ring_exit_work(struct work_struct *work)
5926 {
5927         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
5928         unsigned long timeout = jiffies + HZ * 60 * 5;
5929         unsigned long interval = HZ / 20;
5930         struct io_tctx_exit exit;
5931         struct io_tctx_node *node;
5932         int ret;
5933
5934         /*
5935          * If we're doing polled IO and end up having requests being
5936          * submitted async (out-of-line), then completions can come in while
5937          * we're waiting for refs to drop. We need to reap these manually,
5938          * as nobody else will be looking for them.
5939          */
5940         do {
5941                 io_uring_try_cancel_requests(ctx, NULL, true);
5942                 if (ctx->sq_data) {
5943                         struct io_sq_data *sqd = ctx->sq_data;
5944                         struct task_struct *tsk;
5945
5946                         io_sq_thread_park(sqd);
5947                         tsk = sqd->thread;
5948                         if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
5949                                 io_wq_cancel_cb(tsk->io_uring->io_wq,
5950                                                 io_cancel_ctx_cb, ctx, true);
5951                         io_sq_thread_unpark(sqd);
5952                 }
5953
5954                 io_req_caches_free(ctx);
5955
5956                 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
5957                         /* there is little hope left, don't run it too often */
5958                         interval = HZ * 60;
5959                 }
5960         } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
5961
5962         init_completion(&exit.completion);
5963         init_task_work(&exit.task_work, io_tctx_exit_cb);
5964         exit.ctx = ctx;
5965         /*
5966          * Some may use context even when all refs and requests have been put,
5967          * and they are free to do so while still holding uring_lock or
5968          * completion_lock, see io_req_task_submit(). Apart from other work,
5969          * this lock/unlock section also waits them to finish.
5970          */
5971         mutex_lock(&ctx->uring_lock);
5972         while (!list_empty(&ctx->tctx_list)) {
5973                 WARN_ON_ONCE(time_after(jiffies, timeout));
5974
5975                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
5976                                         ctx_node);
5977                 /* don't spin on a single task if cancellation failed */
5978                 list_rotate_left(&ctx->tctx_list);
5979                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
5980                 if (WARN_ON_ONCE(ret))
5981                         continue;
5982
5983                 mutex_unlock(&ctx->uring_lock);
5984                 wait_for_completion(&exit.completion);
5985                 mutex_lock(&ctx->uring_lock);
5986         }
5987         mutex_unlock(&ctx->uring_lock);
5988         spin_lock(&ctx->completion_lock);
5989         spin_unlock(&ctx->completion_lock);
5990
5991         io_ring_ctx_free(ctx);
5992 }
5993
5994 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
5995 {
5996         unsigned long index;
5997         struct creds *creds;
5998
5999         mutex_lock(&ctx->uring_lock);
6000         percpu_ref_kill(&ctx->refs);
6001         if (ctx->rings)
6002                 __io_cqring_overflow_flush(ctx, true);
6003         xa_for_each(&ctx->personalities, index, creds)
6004                 io_unregister_personality(ctx, index);
6005         mutex_unlock(&ctx->uring_lock);
6006
6007         /* failed during ring init, it couldn't have issued any requests */
6008         if (ctx->rings) {
6009                 io_kill_timeouts(ctx, NULL, true);
6010                 io_poll_remove_all(ctx, NULL, true);
6011                 /* if we failed setting up the ctx, we might not have any rings */
6012                 io_iopoll_try_reap_events(ctx);
6013         }
6014
6015         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
6016         /*
6017          * Use system_unbound_wq to avoid spawning tons of event kworkers
6018          * if we're exiting a ton of rings at the same time. It just adds
6019          * noise and overhead, there's no discernable change in runtime
6020          * over using system_wq.
6021          */
6022         queue_work(system_unbound_wq, &ctx->exit_work);
6023 }
6024
6025 static int io_uring_release(struct inode *inode, struct file *file)
6026 {
6027         struct io_ring_ctx *ctx = file->private_data;
6028
6029         file->private_data = NULL;
6030         io_ring_ctx_wait_and_kill(ctx);
6031         return 0;
6032 }
6033
6034 struct io_task_cancel {
6035         struct task_struct *task;
6036         bool all;
6037 };
6038
6039 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
6040 {
6041         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6042         struct io_task_cancel *cancel = data;
6043
6044         return io_match_task_safe(req, cancel->task, cancel->all);
6045 }
6046
6047 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
6048                                          struct task_struct *task,
6049                                          bool cancel_all)
6050 {
6051         struct io_defer_entry *de;
6052         LIST_HEAD(list);
6053
6054         spin_lock(&ctx->completion_lock);
6055         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
6056                 if (io_match_task_safe(de->req, task, cancel_all)) {
6057                         list_cut_position(&list, &ctx->defer_list, &de->list);
6058                         break;
6059                 }
6060         }
6061         spin_unlock(&ctx->completion_lock);
6062         if (list_empty(&list))
6063                 return false;
6064
6065         while (!list_empty(&list)) {
6066                 de = list_first_entry(&list, struct io_defer_entry, list);
6067                 list_del_init(&de->list);
6068                 io_req_complete_failed(de->req, -ECANCELED);
6069                 kfree(de);
6070         }
6071         return true;
6072 }
6073
6074 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
6075 {
6076         struct io_tctx_node *node;
6077         enum io_wq_cancel cret;
6078         bool ret = false;
6079
6080         mutex_lock(&ctx->uring_lock);
6081         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6082                 struct io_uring_task *tctx = node->task->io_uring;
6083
6084                 /*
6085                  * io_wq will stay alive while we hold uring_lock, because it's
6086                  * killed after ctx nodes, which requires to take the lock.
6087                  */
6088                 if (!tctx || !tctx->io_wq)
6089                         continue;
6090                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
6091                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
6092         }
6093         mutex_unlock(&ctx->uring_lock);
6094
6095         return ret;
6096 }
6097
6098 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
6099                                                 struct task_struct *task,
6100                                                 bool cancel_all)
6101 {
6102         struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
6103         struct io_uring_task *tctx = task ? task->io_uring : NULL;
6104
6105         /* failed during ring init, it couldn't have issued any requests */
6106         if (!ctx->rings)
6107                 return;
6108
6109         while (1) {
6110                 enum io_wq_cancel cret;
6111                 bool ret = false;
6112
6113                 if (!task) {
6114                         ret |= io_uring_try_cancel_iowq(ctx);
6115                 } else if (tctx && tctx->io_wq) {
6116                         /*
6117                          * Cancels requests of all rings, not only @ctx, but
6118                          * it's fine as the task is in exit/exec.
6119                          */
6120                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
6121                                                &cancel, true);
6122                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
6123                 }
6124
6125                 /* SQPOLL thread does its own polling */
6126                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
6127                     (ctx->sq_data && ctx->sq_data->thread == current)) {
6128                         while (!wq_list_empty(&ctx->iopoll_list)) {
6129                                 io_iopoll_try_reap_events(ctx);
6130                                 ret = true;
6131                         }
6132                 }
6133
6134                 ret |= io_cancel_defer_files(ctx, task, cancel_all);
6135                 ret |= io_poll_remove_all(ctx, task, cancel_all);
6136                 ret |= io_kill_timeouts(ctx, task, cancel_all);
6137                 if (task)
6138                         ret |= io_run_task_work();
6139                 if (!ret)
6140                         break;
6141                 cond_resched();
6142         }
6143 }
6144
6145 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
6146 {
6147         if (tracked)
6148                 return atomic_read(&tctx->inflight_tracked);
6149         return percpu_counter_sum(&tctx->inflight);
6150 }
6151
6152 /*
6153  * Find any io_uring ctx that this task has registered or done IO on, and cancel
6154  * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
6155  */
6156 __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
6157 {
6158         struct io_uring_task *tctx = current->io_uring;
6159         struct io_ring_ctx *ctx;
6160         s64 inflight;
6161         DEFINE_WAIT(wait);
6162
6163         WARN_ON_ONCE(sqd && sqd->thread != current);
6164
6165         if (!current->io_uring)
6166                 return;
6167         if (tctx->io_wq)
6168                 io_wq_exit_start(tctx->io_wq);
6169
6170         atomic_inc(&tctx->in_idle);
6171         do {
6172                 io_uring_drop_tctx_refs(current);
6173                 /* read completions before cancelations */
6174                 inflight = tctx_inflight(tctx, !cancel_all);
6175                 if (!inflight)
6176                         break;
6177
6178                 if (!sqd) {
6179                         struct io_tctx_node *node;
6180                         unsigned long index;
6181
6182                         xa_for_each(&tctx->xa, index, node) {
6183                                 /* sqpoll task will cancel all its requests */
6184                                 if (node->ctx->sq_data)
6185                                         continue;
6186                                 io_uring_try_cancel_requests(node->ctx, current,
6187                                                              cancel_all);
6188                         }
6189                 } else {
6190                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6191                                 io_uring_try_cancel_requests(ctx, current,
6192                                                              cancel_all);
6193                 }
6194
6195                 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
6196                 io_run_task_work();
6197                 io_uring_drop_tctx_refs(current);
6198
6199                 /*
6200                  * If we've seen completions, retry without waiting. This
6201                  * avoids a race where a completion comes in before we did
6202                  * prepare_to_wait().
6203                  */
6204                 if (inflight == tctx_inflight(tctx, !cancel_all))
6205                         schedule();
6206                 finish_wait(&tctx->wait, &wait);
6207         } while (1);
6208
6209         io_uring_clean_tctx(tctx);
6210         if (cancel_all) {
6211                 /*
6212                  * We shouldn't run task_works after cancel, so just leave
6213                  * ->in_idle set for normal exit.
6214                  */
6215                 atomic_dec(&tctx->in_idle);
6216                 /* for exec all current's requests should be gone, kill tctx */
6217                 __io_uring_free(current);
6218         }
6219 }
6220
6221 void __io_uring_cancel(bool cancel_all)
6222 {
6223         io_uring_cancel_generic(cancel_all, NULL);
6224 }
6225
6226 static void *io_uring_validate_mmap_request(struct file *file,
6227                                             loff_t pgoff, size_t sz)
6228 {
6229         struct io_ring_ctx *ctx = file->private_data;
6230         loff_t offset = pgoff << PAGE_SHIFT;
6231         struct page *page;
6232         void *ptr;
6233
6234         switch (offset) {
6235         case IORING_OFF_SQ_RING:
6236         case IORING_OFF_CQ_RING:
6237                 ptr = ctx->rings;
6238                 break;
6239         case IORING_OFF_SQES:
6240                 ptr = ctx->sq_sqes;
6241                 break;
6242         default:
6243                 return ERR_PTR(-EINVAL);
6244         }
6245
6246         page = virt_to_head_page(ptr);
6247         if (sz > page_size(page))
6248                 return ERR_PTR(-EINVAL);
6249
6250         return ptr;
6251 }
6252
6253 #ifdef CONFIG_MMU
6254
6255 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6256 {
6257         size_t sz = vma->vm_end - vma->vm_start;
6258         unsigned long pfn;
6259         void *ptr;
6260
6261         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
6262         if (IS_ERR(ptr))
6263                 return PTR_ERR(ptr);
6264
6265         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
6266         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
6267 }
6268
6269 #else /* !CONFIG_MMU */
6270
6271 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6272 {
6273         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
6274 }
6275
6276 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
6277 {
6278         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
6279 }
6280
6281 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
6282         unsigned long addr, unsigned long len,
6283         unsigned long pgoff, unsigned long flags)
6284 {
6285         void *ptr;
6286
6287         ptr = io_uring_validate_mmap_request(file, pgoff, len);
6288         if (IS_ERR(ptr))
6289                 return PTR_ERR(ptr);
6290
6291         return (unsigned long) ptr;
6292 }
6293
6294 #endif /* !CONFIG_MMU */
6295
6296 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
6297 {
6298         if (flags & IORING_ENTER_EXT_ARG) {
6299                 struct io_uring_getevents_arg arg;
6300
6301                 if (argsz != sizeof(arg))
6302                         return -EINVAL;
6303                 if (copy_from_user(&arg, argp, sizeof(arg)))
6304                         return -EFAULT;
6305         }
6306         return 0;
6307 }
6308
6309 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
6310                           struct __kernel_timespec __user **ts,
6311                           const sigset_t __user **sig)
6312 {
6313         struct io_uring_getevents_arg arg;
6314
6315         /*
6316          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
6317          * is just a pointer to the sigset_t.
6318          */
6319         if (!(flags & IORING_ENTER_EXT_ARG)) {
6320                 *sig = (const sigset_t __user *) argp;
6321                 *ts = NULL;
6322                 return 0;
6323         }
6324
6325         /*
6326          * EXT_ARG is set - ensure we agree on the size of it and copy in our
6327          * timespec and sigset_t pointers if good.
6328          */
6329         if (*argsz != sizeof(arg))
6330                 return -EINVAL;
6331         if (copy_from_user(&arg, argp, sizeof(arg)))
6332                 return -EFAULT;
6333         if (arg.pad)
6334                 return -EINVAL;
6335         *sig = u64_to_user_ptr(arg.sigmask);
6336         *argsz = arg.sigmask_sz;
6337         *ts = u64_to_user_ptr(arg.ts);
6338         return 0;
6339 }
6340
6341 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
6342                 u32, min_complete, u32, flags, const void __user *, argp,
6343                 size_t, argsz)
6344 {
6345         struct io_ring_ctx *ctx;
6346         struct fd f;
6347         long ret;
6348
6349         io_run_task_work();
6350
6351         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
6352                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
6353                                IORING_ENTER_REGISTERED_RING)))
6354                 return -EINVAL;
6355
6356         /*
6357          * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
6358          * need only dereference our task private array to find it.
6359          */
6360         if (flags & IORING_ENTER_REGISTERED_RING) {
6361                 struct io_uring_task *tctx = current->io_uring;
6362
6363                 if (!tctx || fd >= IO_RINGFD_REG_MAX)
6364                         return -EINVAL;
6365                 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
6366                 f.file = tctx->registered_rings[fd];
6367                 f.flags = 0;
6368         } else {
6369                 f = fdget(fd);
6370         }
6371
6372         if (unlikely(!f.file))
6373                 return -EBADF;
6374
6375         ret = -EOPNOTSUPP;
6376         if (unlikely(!io_is_uring_fops(f.file)))
6377                 goto out_fput;
6378
6379         ret = -ENXIO;
6380         ctx = f.file->private_data;
6381         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
6382                 goto out_fput;
6383
6384         ret = -EBADFD;
6385         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
6386                 goto out;
6387
6388         /*
6389          * For SQ polling, the thread will do all submissions and completions.
6390          * Just return the requested submit count, and wake the thread if
6391          * we were asked to.
6392          */
6393         ret = 0;
6394         if (ctx->flags & IORING_SETUP_SQPOLL) {
6395                 io_cqring_overflow_flush(ctx);
6396
6397                 if (unlikely(ctx->sq_data->thread == NULL)) {
6398                         ret = -EOWNERDEAD;
6399                         goto out;
6400                 }
6401                 if (flags & IORING_ENTER_SQ_WAKEUP)
6402                         wake_up(&ctx->sq_data->wait);
6403                 if (flags & IORING_ENTER_SQ_WAIT) {
6404                         ret = io_sqpoll_wait_sq(ctx);
6405                         if (ret)
6406                                 goto out;
6407                 }
6408                 ret = to_submit;
6409         } else if (to_submit) {
6410                 ret = io_uring_add_tctx_node(ctx);
6411                 if (unlikely(ret))
6412                         goto out;
6413
6414                 mutex_lock(&ctx->uring_lock);
6415                 ret = io_submit_sqes(ctx, to_submit);
6416                 if (ret != to_submit) {
6417                         mutex_unlock(&ctx->uring_lock);
6418                         goto out;
6419                 }
6420                 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
6421                         goto iopoll_locked;
6422                 mutex_unlock(&ctx->uring_lock);
6423         }
6424         if (flags & IORING_ENTER_GETEVENTS) {
6425                 int ret2;
6426                 if (ctx->syscall_iopoll) {
6427                         /*
6428                          * We disallow the app entering submit/complete with
6429                          * polling, but we still need to lock the ring to
6430                          * prevent racing with polled issue that got punted to
6431                          * a workqueue.
6432                          */
6433                         mutex_lock(&ctx->uring_lock);
6434 iopoll_locked:
6435                         ret2 = io_validate_ext_arg(flags, argp, argsz);
6436                         if (likely(!ret2)) {
6437                                 min_complete = min(min_complete,
6438                                                    ctx->cq_entries);
6439                                 ret2 = io_iopoll_check(ctx, min_complete);
6440                         }
6441                         mutex_unlock(&ctx->uring_lock);
6442                 } else {
6443                         const sigset_t __user *sig;
6444                         struct __kernel_timespec __user *ts;
6445
6446                         ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
6447                         if (likely(!ret2)) {
6448                                 min_complete = min(min_complete,
6449                                                    ctx->cq_entries);
6450                                 ret2 = io_cqring_wait(ctx, min_complete, sig,
6451                                                       argsz, ts);
6452                         }
6453                 }
6454
6455                 if (!ret) {
6456                         ret = ret2;
6457
6458                         /*
6459                          * EBADR indicates that one or more CQE were dropped.
6460                          * Once the user has been informed we can clear the bit
6461                          * as they are obviously ok with those drops.
6462                          */
6463                         if (unlikely(ret2 == -EBADR))
6464                                 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
6465                                           &ctx->check_cq);
6466                 }
6467         }
6468
6469 out:
6470         percpu_ref_put(&ctx->refs);
6471 out_fput:
6472         fdput(f);
6473         return ret;
6474 }
6475
6476 static const struct file_operations io_uring_fops = {
6477         .release        = io_uring_release,
6478         .mmap           = io_uring_mmap,
6479 #ifndef CONFIG_MMU
6480         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
6481         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
6482 #endif
6483         .poll           = io_uring_poll,
6484 #ifdef CONFIG_PROC_FS
6485         .show_fdinfo    = io_uring_show_fdinfo,
6486 #endif
6487 };
6488
6489 bool io_is_uring_fops(struct file *file)
6490 {
6491         return file->f_op == &io_uring_fops;
6492 }
6493
6494 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
6495                                          struct io_uring_params *p)
6496 {
6497         struct io_rings *rings;
6498         size_t size, sq_array_offset;
6499
6500         /* make sure these are sane, as we already accounted them */
6501         ctx->sq_entries = p->sq_entries;
6502         ctx->cq_entries = p->cq_entries;
6503
6504         size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
6505         if (size == SIZE_MAX)
6506                 return -EOVERFLOW;
6507
6508         rings = io_mem_alloc(size);
6509         if (!rings)
6510                 return -ENOMEM;
6511
6512         ctx->rings = rings;
6513         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
6514         rings->sq_ring_mask = p->sq_entries - 1;
6515         rings->cq_ring_mask = p->cq_entries - 1;
6516         rings->sq_ring_entries = p->sq_entries;
6517         rings->cq_ring_entries = p->cq_entries;
6518
6519         if (p->flags & IORING_SETUP_SQE128)
6520                 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
6521         else
6522                 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
6523         if (size == SIZE_MAX) {
6524                 io_mem_free(ctx->rings);
6525                 ctx->rings = NULL;
6526                 return -EOVERFLOW;
6527         }
6528
6529         ctx->sq_sqes = io_mem_alloc(size);
6530         if (!ctx->sq_sqes) {
6531                 io_mem_free(ctx->rings);
6532                 ctx->rings = NULL;
6533                 return -ENOMEM;
6534         }
6535
6536         return 0;
6537 }
6538
6539 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
6540 {
6541         int ret, fd;
6542
6543         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
6544         if (fd < 0)
6545                 return fd;
6546
6547         ret = io_uring_add_tctx_node(ctx);
6548         if (ret) {
6549                 put_unused_fd(fd);
6550                 return ret;
6551         }
6552         fd_install(fd, file);
6553         return fd;
6554 }
6555
6556 /*
6557  * Allocate an anonymous fd, this is what constitutes the application
6558  * visible backing of an io_uring instance. The application mmaps this
6559  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
6560  * we have to tie this fd to a socket for file garbage collection purposes.
6561  */
6562 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
6563 {
6564         struct file *file;
6565 #if defined(CONFIG_UNIX)
6566         int ret;
6567
6568         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
6569                                 &ctx->ring_sock);
6570         if (ret)
6571                 return ERR_PTR(ret);
6572 #endif
6573
6574         file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
6575                                          O_RDWR | O_CLOEXEC, NULL);
6576 #if defined(CONFIG_UNIX)
6577         if (IS_ERR(file)) {
6578                 sock_release(ctx->ring_sock);
6579                 ctx->ring_sock = NULL;
6580         } else {
6581                 ctx->ring_sock->file = file;
6582         }
6583 #endif
6584         return file;
6585 }
6586
6587 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
6588                                   struct io_uring_params __user *params)
6589 {
6590         struct io_ring_ctx *ctx;
6591         struct file *file;
6592         int ret;
6593
6594         if (!entries)
6595                 return -EINVAL;
6596         if (entries > IORING_MAX_ENTRIES) {
6597                 if (!(p->flags & IORING_SETUP_CLAMP))
6598                         return -EINVAL;
6599                 entries = IORING_MAX_ENTRIES;
6600         }
6601
6602         /*
6603          * Use twice as many entries for the CQ ring. It's possible for the
6604          * application to drive a higher depth than the size of the SQ ring,
6605          * since the sqes are only used at submission time. This allows for
6606          * some flexibility in overcommitting a bit. If the application has
6607          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
6608          * of CQ ring entries manually.
6609          */
6610         p->sq_entries = roundup_pow_of_two(entries);
6611         if (p->flags & IORING_SETUP_CQSIZE) {
6612                 /*
6613                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
6614                  * to a power-of-two, if it isn't already. We do NOT impose
6615                  * any cq vs sq ring sizing.
6616                  */
6617                 if (!p->cq_entries)
6618                         return -EINVAL;
6619                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
6620                         if (!(p->flags & IORING_SETUP_CLAMP))
6621                                 return -EINVAL;
6622                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
6623                 }
6624                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
6625                 if (p->cq_entries < p->sq_entries)
6626                         return -EINVAL;
6627         } else {
6628                 p->cq_entries = 2 * p->sq_entries;
6629         }
6630
6631         ctx = io_ring_ctx_alloc(p);
6632         if (!ctx)
6633                 return -ENOMEM;
6634
6635         /*
6636          * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
6637          * space applications don't need to do io completion events
6638          * polling again, they can rely on io_sq_thread to do polling
6639          * work, which can reduce cpu usage and uring_lock contention.
6640          */
6641         if (ctx->flags & IORING_SETUP_IOPOLL &&
6642             !(ctx->flags & IORING_SETUP_SQPOLL))
6643                 ctx->syscall_iopoll = 1;
6644
6645         ctx->compat = in_compat_syscall();
6646         if (!capable(CAP_IPC_LOCK))
6647                 ctx->user = get_uid(current_user());
6648
6649         /*
6650          * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
6651          * COOP_TASKRUN is set, then IPIs are never needed by the app.
6652          */
6653         ret = -EINVAL;
6654         if (ctx->flags & IORING_SETUP_SQPOLL) {
6655                 /* IPI related flags don't make sense with SQPOLL */
6656                 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
6657                                   IORING_SETUP_TASKRUN_FLAG))
6658                         goto err;
6659                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
6660         } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
6661                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
6662         } else {
6663                 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
6664                         goto err;
6665                 ctx->notify_method = TWA_SIGNAL;
6666         }
6667
6668         /*
6669          * This is just grabbed for accounting purposes. When a process exits,
6670          * the mm is exited and dropped before the files, hence we need to hang
6671          * on to this mm purely for the purposes of being able to unaccount
6672          * memory (locked/pinned vm). It's not used for anything else.
6673          */
6674         mmgrab(current->mm);
6675         ctx->mm_account = current->mm;
6676
6677         ret = io_allocate_scq_urings(ctx, p);
6678         if (ret)
6679                 goto err;
6680
6681         ret = io_sq_offload_create(ctx, p);
6682         if (ret)
6683                 goto err;
6684         /* always set a rsrc node */
6685         ret = io_rsrc_node_switch_start(ctx);
6686         if (ret)
6687                 goto err;
6688         io_rsrc_node_switch(ctx, NULL);
6689
6690         memset(&p->sq_off, 0, sizeof(p->sq_off));
6691         p->sq_off.head = offsetof(struct io_rings, sq.head);
6692         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
6693         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
6694         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
6695         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
6696         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
6697         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
6698
6699         memset(&p->cq_off, 0, sizeof(p->cq_off));
6700         p->cq_off.head = offsetof(struct io_rings, cq.head);
6701         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
6702         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
6703         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
6704         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
6705         p->cq_off.cqes = offsetof(struct io_rings, cqes);
6706         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
6707
6708         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
6709                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
6710                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
6711                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
6712                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
6713                         IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
6714                         IORING_FEAT_LINKED_FILE;
6715
6716         if (copy_to_user(params, p, sizeof(*p))) {
6717                 ret = -EFAULT;
6718                 goto err;
6719         }
6720
6721         file = io_uring_get_file(ctx);
6722         if (IS_ERR(file)) {
6723                 ret = PTR_ERR(file);
6724                 goto err;
6725         }
6726
6727         /*
6728          * Install ring fd as the very last thing, so we don't risk someone
6729          * having closed it before we finish setup
6730          */
6731         ret = io_uring_install_fd(ctx, file);
6732         if (ret < 0) {
6733                 /* fput will clean it up */
6734                 fput(file);
6735                 return ret;
6736         }
6737
6738         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
6739         return ret;
6740 err:
6741         io_ring_ctx_wait_and_kill(ctx);
6742         return ret;
6743 }
6744
6745 /*
6746  * Sets up an aio uring context, and returns the fd. Applications asks for a
6747  * ring size, we return the actual sq/cq ring sizes (among other things) in the
6748  * params structure passed in.
6749  */
6750 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
6751 {
6752         struct io_uring_params p;
6753         int i;
6754
6755         if (copy_from_user(&p, params, sizeof(p)))
6756                 return -EFAULT;
6757         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
6758                 if (p.resv[i])
6759                         return -EINVAL;
6760         }
6761
6762         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
6763                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
6764                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
6765                         IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
6766                         IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
6767                         IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
6768                 return -EINVAL;
6769
6770         return io_uring_create(entries, &p, params);
6771 }
6772
6773 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
6774                 struct io_uring_params __user *, params)
6775 {
6776         return io_uring_setup(entries, params);
6777 }
6778
6779 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
6780                            unsigned nr_args)
6781 {
6782         struct io_uring_probe *p;
6783         size_t size;
6784         int i, ret;
6785
6786         size = struct_size(p, ops, nr_args);
6787         if (size == SIZE_MAX)
6788                 return -EOVERFLOW;
6789         p = kzalloc(size, GFP_KERNEL);
6790         if (!p)
6791                 return -ENOMEM;
6792
6793         ret = -EFAULT;
6794         if (copy_from_user(p, arg, size))
6795                 goto out;
6796         ret = -EINVAL;
6797         if (memchr_inv(p, 0, size))
6798                 goto out;
6799
6800         p->last_op = IORING_OP_LAST - 1;
6801         if (nr_args > IORING_OP_LAST)
6802                 nr_args = IORING_OP_LAST;
6803
6804         for (i = 0; i < nr_args; i++) {
6805                 p->ops[i].op = i;
6806                 if (!io_op_defs[i].not_supported)
6807                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
6808         }
6809         p->ops_len = i;
6810
6811         ret = 0;
6812         if (copy_to_user(arg, p, size))
6813                 ret = -EFAULT;
6814 out:
6815         kfree(p);
6816         return ret;
6817 }
6818
6819 static int io_register_personality(struct io_ring_ctx *ctx)
6820 {
6821         const struct cred *creds;
6822         u32 id;
6823         int ret;
6824
6825         creds = get_current_cred();
6826
6827         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
6828                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
6829         if (ret < 0) {
6830                 put_cred(creds);
6831                 return ret;
6832         }
6833         return id;
6834 }
6835
6836 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
6837                                            void __user *arg, unsigned int nr_args)
6838 {
6839         struct io_uring_restriction *res;
6840         size_t size;
6841         int i, ret;
6842
6843         /* Restrictions allowed only if rings started disabled */
6844         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6845                 return -EBADFD;
6846
6847         /* We allow only a single restrictions registration */
6848         if (ctx->restrictions.registered)
6849                 return -EBUSY;
6850
6851         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
6852                 return -EINVAL;
6853
6854         size = array_size(nr_args, sizeof(*res));
6855         if (size == SIZE_MAX)
6856                 return -EOVERFLOW;
6857
6858         res = memdup_user(arg, size);
6859         if (IS_ERR(res))
6860                 return PTR_ERR(res);
6861
6862         ret = 0;
6863
6864         for (i = 0; i < nr_args; i++) {
6865                 switch (res[i].opcode) {
6866                 case IORING_RESTRICTION_REGISTER_OP:
6867                         if (res[i].register_op >= IORING_REGISTER_LAST) {
6868                                 ret = -EINVAL;
6869                                 goto out;
6870                         }
6871
6872                         __set_bit(res[i].register_op,
6873                                   ctx->restrictions.register_op);
6874                         break;
6875                 case IORING_RESTRICTION_SQE_OP:
6876                         if (res[i].sqe_op >= IORING_OP_LAST) {
6877                                 ret = -EINVAL;
6878                                 goto out;
6879                         }
6880
6881                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
6882                         break;
6883                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
6884                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
6885                         break;
6886                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
6887                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
6888                         break;
6889                 default:
6890                         ret = -EINVAL;
6891                         goto out;
6892                 }
6893         }
6894
6895 out:
6896         /* Reset all restrictions if an error happened */
6897         if (ret != 0)
6898                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
6899         else
6900                 ctx->restrictions.registered = true;
6901
6902         kfree(res);
6903         return ret;
6904 }
6905
6906 static int io_register_enable_rings(struct io_ring_ctx *ctx)
6907 {
6908         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
6909                 return -EBADFD;
6910
6911         if (ctx->restrictions.registered)
6912                 ctx->restricted = 1;
6913
6914         ctx->flags &= ~IORING_SETUP_R_DISABLED;
6915         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
6916                 wake_up(&ctx->sq_data->wait);
6917         return 0;
6918 }
6919
6920 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
6921                                      struct io_uring_rsrc_update2 *up,
6922                                      unsigned nr_args)
6923 {
6924         __u32 tmp;
6925         int err;
6926
6927         if (check_add_overflow(up->offset, nr_args, &tmp))
6928                 return -EOVERFLOW;
6929         err = io_rsrc_node_switch_start(ctx);
6930         if (err)
6931                 return err;
6932
6933         switch (type) {
6934         case IORING_RSRC_FILE:
6935                 return __io_sqe_files_update(ctx, up, nr_args);
6936         case IORING_RSRC_BUFFER:
6937                 return __io_sqe_buffers_update(ctx, up, nr_args);
6938         }
6939         return -EINVAL;
6940 }
6941
6942 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
6943                                     unsigned nr_args)
6944 {
6945         struct io_uring_rsrc_update2 up;
6946
6947         if (!nr_args)
6948                 return -EINVAL;
6949         memset(&up, 0, sizeof(up));
6950         if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
6951                 return -EFAULT;
6952         if (up.resv || up.resv2)
6953                 return -EINVAL;
6954         return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
6955 }
6956
6957 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
6958                                    unsigned size, unsigned type)
6959 {
6960         struct io_uring_rsrc_update2 up;
6961
6962         if (size != sizeof(up))
6963                 return -EINVAL;
6964         if (copy_from_user(&up, arg, sizeof(up)))
6965                 return -EFAULT;
6966         if (!up.nr || up.resv || up.resv2)
6967                 return -EINVAL;
6968         return __io_register_rsrc_update(ctx, type, &up, up.nr);
6969 }
6970
6971 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
6972                             unsigned int size, unsigned int type)
6973 {
6974         struct io_uring_rsrc_register rr;
6975
6976         /* keep it extendible */
6977         if (size != sizeof(rr))
6978                 return -EINVAL;
6979
6980         memset(&rr, 0, sizeof(rr));
6981         if (copy_from_user(&rr, arg, size))
6982                 return -EFAULT;
6983         if (!rr.nr || rr.resv2)
6984                 return -EINVAL;
6985         if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
6986                 return -EINVAL;
6987
6988         switch (type) {
6989         case IORING_RSRC_FILE:
6990                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6991                         break;
6992                 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
6993                                              rr.nr, u64_to_user_ptr(rr.tags));
6994         case IORING_RSRC_BUFFER:
6995                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
6996                         break;
6997                 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
6998                                                rr.nr, u64_to_user_ptr(rr.tags));
6999         }
7000         return -EINVAL;
7001 }
7002
7003 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
7004                                        void __user *arg, unsigned len)
7005 {
7006         struct io_uring_task *tctx = current->io_uring;
7007         cpumask_var_t new_mask;
7008         int ret;
7009
7010         if (!tctx || !tctx->io_wq)
7011                 return -EINVAL;
7012
7013         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
7014                 return -ENOMEM;
7015
7016         cpumask_clear(new_mask);
7017         if (len > cpumask_size())
7018                 len = cpumask_size();
7019
7020         if (in_compat_syscall()) {
7021                 ret = compat_get_bitmap(cpumask_bits(new_mask),
7022                                         (const compat_ulong_t __user *)arg,
7023                                         len * 8 /* CHAR_BIT */);
7024         } else {
7025                 ret = copy_from_user(new_mask, arg, len);
7026         }
7027
7028         if (ret) {
7029                 free_cpumask_var(new_mask);
7030                 return -EFAULT;
7031         }
7032
7033         ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
7034         free_cpumask_var(new_mask);
7035         return ret;
7036 }
7037
7038 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
7039 {
7040         struct io_uring_task *tctx = current->io_uring;
7041
7042         if (!tctx || !tctx->io_wq)
7043                 return -EINVAL;
7044
7045         return io_wq_cpu_affinity(tctx->io_wq, NULL);
7046 }
7047
7048 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
7049                                                void __user *arg)
7050         __must_hold(&ctx->uring_lock)
7051 {
7052         struct io_tctx_node *node;
7053         struct io_uring_task *tctx = NULL;
7054         struct io_sq_data *sqd = NULL;
7055         __u32 new_count[2];
7056         int i, ret;
7057
7058         if (copy_from_user(new_count, arg, sizeof(new_count)))
7059                 return -EFAULT;
7060         for (i = 0; i < ARRAY_SIZE(new_count); i++)
7061                 if (new_count[i] > INT_MAX)
7062                         return -EINVAL;
7063
7064         if (ctx->flags & IORING_SETUP_SQPOLL) {
7065                 sqd = ctx->sq_data;
7066                 if (sqd) {
7067                         /*
7068                          * Observe the correct sqd->lock -> ctx->uring_lock
7069                          * ordering. Fine to drop uring_lock here, we hold
7070                          * a ref to the ctx.
7071                          */
7072                         refcount_inc(&sqd->refs);
7073                         mutex_unlock(&ctx->uring_lock);
7074                         mutex_lock(&sqd->lock);
7075                         mutex_lock(&ctx->uring_lock);
7076                         if (sqd->thread)
7077                                 tctx = sqd->thread->io_uring;
7078                 }
7079         } else {
7080                 tctx = current->io_uring;
7081         }
7082
7083         BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
7084
7085         for (i = 0; i < ARRAY_SIZE(new_count); i++)
7086                 if (new_count[i])
7087                         ctx->iowq_limits[i] = new_count[i];
7088         ctx->iowq_limits_set = true;
7089
7090         if (tctx && tctx->io_wq) {
7091                 ret = io_wq_max_workers(tctx->io_wq, new_count);
7092                 if (ret)
7093                         goto err;
7094         } else {
7095                 memset(new_count, 0, sizeof(new_count));
7096         }
7097
7098         if (sqd) {
7099                 mutex_unlock(&sqd->lock);
7100                 io_put_sq_data(sqd);
7101         }
7102
7103         if (copy_to_user(arg, new_count, sizeof(new_count)))
7104                 return -EFAULT;
7105
7106         /* that's it for SQPOLL, only the SQPOLL task creates requests */
7107         if (sqd)
7108                 return 0;
7109
7110         /* now propagate the restriction to all registered users */
7111         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7112                 struct io_uring_task *tctx = node->task->io_uring;
7113
7114                 if (WARN_ON_ONCE(!tctx->io_wq))
7115                         continue;
7116
7117                 for (i = 0; i < ARRAY_SIZE(new_count); i++)
7118                         new_count[i] = ctx->iowq_limits[i];
7119                 /* ignore errors, it always returns zero anyway */
7120                 (void)io_wq_max_workers(tctx->io_wq, new_count);
7121         }
7122         return 0;
7123 err:
7124         if (sqd) {
7125                 mutex_unlock(&sqd->lock);
7126                 io_put_sq_data(sqd);
7127         }
7128         return ret;
7129 }
7130
7131 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
7132 {
7133         struct io_uring_buf_ring *br;
7134         struct io_uring_buf_reg reg;
7135         struct io_buffer_list *bl, *free_bl = NULL;
7136         struct page **pages;
7137         int nr_pages;
7138
7139         if (copy_from_user(&reg, arg, sizeof(reg)))
7140                 return -EFAULT;
7141
7142         if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
7143                 return -EINVAL;
7144         if (!reg.ring_addr)
7145                 return -EFAULT;
7146         if (reg.ring_addr & ~PAGE_MASK)
7147                 return -EINVAL;
7148         if (!is_power_of_2(reg.ring_entries))
7149                 return -EINVAL;
7150
7151         /* cannot disambiguate full vs empty due to head/tail size */
7152         if (reg.ring_entries >= 65536)
7153                 return -EINVAL;
7154
7155         if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
7156                 int ret = io_init_bl_list(ctx);
7157                 if (ret)
7158                         return ret;
7159         }
7160
7161         bl = io_buffer_get_list(ctx, reg.bgid);
7162         if (bl) {
7163                 /* if mapped buffer ring OR classic exists, don't allow */
7164                 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
7165                         return -EEXIST;
7166         } else {
7167                 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
7168                 if (!bl)
7169                         return -ENOMEM;
7170         }
7171
7172         pages = io_pin_pages(reg.ring_addr,
7173                              struct_size(br, bufs, reg.ring_entries),
7174                              &nr_pages);
7175         if (IS_ERR(pages)) {
7176                 kfree(free_bl);
7177                 return PTR_ERR(pages);
7178         }
7179
7180         br = page_address(pages[0]);
7181         bl->buf_pages = pages;
7182         bl->buf_nr_pages = nr_pages;
7183         bl->nr_entries = reg.ring_entries;
7184         bl->buf_ring = br;
7185         bl->mask = reg.ring_entries - 1;
7186         io_buffer_add_list(ctx, bl, reg.bgid);
7187         return 0;
7188 }
7189
7190 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
7191 {
7192         struct io_uring_buf_reg reg;
7193         struct io_buffer_list *bl;
7194
7195         if (copy_from_user(&reg, arg, sizeof(reg)))
7196                 return -EFAULT;
7197         if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
7198                 return -EINVAL;
7199
7200         bl = io_buffer_get_list(ctx, reg.bgid);
7201         if (!bl)
7202                 return -ENOENT;
7203         if (!bl->buf_nr_pages)
7204                 return -EINVAL;
7205
7206         __io_remove_buffers(ctx, bl, -1U);
7207         if (bl->bgid >= BGID_ARRAY) {
7208                 xa_erase(&ctx->io_bl_xa, bl->bgid);
7209                 kfree(bl);
7210         }
7211         return 0;
7212 }
7213
7214 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
7215                                void __user *arg, unsigned nr_args)
7216         __releases(ctx->uring_lock)
7217         __acquires(ctx->uring_lock)
7218 {
7219         int ret;
7220
7221         /*
7222          * We're inside the ring mutex, if the ref is already dying, then
7223          * someone else killed the ctx or is already going through
7224          * io_uring_register().
7225          */
7226         if (percpu_ref_is_dying(&ctx->refs))
7227                 return -ENXIO;
7228
7229         if (ctx->restricted) {
7230                 if (opcode >= IORING_REGISTER_LAST)
7231                         return -EINVAL;
7232                 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
7233                 if (!test_bit(opcode, ctx->restrictions.register_op))
7234                         return -EACCES;
7235         }
7236
7237         switch (opcode) {
7238         case IORING_REGISTER_BUFFERS:
7239                 ret = -EFAULT;
7240                 if (!arg)
7241                         break;
7242                 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
7243                 break;
7244         case IORING_UNREGISTER_BUFFERS:
7245                 ret = -EINVAL;
7246                 if (arg || nr_args)
7247                         break;
7248                 ret = io_sqe_buffers_unregister(ctx);
7249                 break;
7250         case IORING_REGISTER_FILES:
7251                 ret = -EFAULT;
7252                 if (!arg)
7253                         break;
7254                 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
7255                 break;
7256         case IORING_UNREGISTER_FILES:
7257                 ret = -EINVAL;
7258                 if (arg || nr_args)
7259                         break;
7260                 ret = io_sqe_files_unregister(ctx);
7261                 break;
7262         case IORING_REGISTER_FILES_UPDATE:
7263                 ret = io_register_files_update(ctx, arg, nr_args);
7264                 break;
7265         case IORING_REGISTER_EVENTFD:
7266                 ret = -EINVAL;
7267                 if (nr_args != 1)
7268                         break;
7269                 ret = io_eventfd_register(ctx, arg, 0);
7270                 break;
7271         case IORING_REGISTER_EVENTFD_ASYNC:
7272                 ret = -EINVAL;
7273                 if (nr_args != 1)
7274                         break;
7275                 ret = io_eventfd_register(ctx, arg, 1);
7276                 break;
7277         case IORING_UNREGISTER_EVENTFD:
7278                 ret = -EINVAL;
7279                 if (arg || nr_args)
7280                         break;
7281                 ret = io_eventfd_unregister(ctx);
7282                 break;
7283         case IORING_REGISTER_PROBE:
7284                 ret = -EINVAL;
7285                 if (!arg || nr_args > 256)
7286                         break;
7287                 ret = io_probe(ctx, arg, nr_args);
7288                 break;
7289         case IORING_REGISTER_PERSONALITY:
7290                 ret = -EINVAL;
7291                 if (arg || nr_args)
7292                         break;
7293                 ret = io_register_personality(ctx);
7294                 break;
7295         case IORING_UNREGISTER_PERSONALITY:
7296                 ret = -EINVAL;
7297                 if (arg)
7298                         break;
7299                 ret = io_unregister_personality(ctx, nr_args);
7300                 break;
7301         case IORING_REGISTER_ENABLE_RINGS:
7302                 ret = -EINVAL;
7303                 if (arg || nr_args)
7304                         break;
7305                 ret = io_register_enable_rings(ctx);
7306                 break;
7307         case IORING_REGISTER_RESTRICTIONS:
7308                 ret = io_register_restrictions(ctx, arg, nr_args);
7309                 break;
7310         case IORING_REGISTER_FILES2:
7311                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
7312                 break;
7313         case IORING_REGISTER_FILES_UPDATE2:
7314                 ret = io_register_rsrc_update(ctx, arg, nr_args,
7315                                               IORING_RSRC_FILE);
7316                 break;
7317         case IORING_REGISTER_BUFFERS2:
7318                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
7319                 break;
7320         case IORING_REGISTER_BUFFERS_UPDATE:
7321                 ret = io_register_rsrc_update(ctx, arg, nr_args,
7322                                               IORING_RSRC_BUFFER);
7323                 break;
7324         case IORING_REGISTER_IOWQ_AFF:
7325                 ret = -EINVAL;
7326                 if (!arg || !nr_args)
7327                         break;
7328                 ret = io_register_iowq_aff(ctx, arg, nr_args);
7329                 break;
7330         case IORING_UNREGISTER_IOWQ_AFF:
7331                 ret = -EINVAL;
7332                 if (arg || nr_args)
7333                         break;
7334                 ret = io_unregister_iowq_aff(ctx);
7335                 break;
7336         case IORING_REGISTER_IOWQ_MAX_WORKERS:
7337                 ret = -EINVAL;
7338                 if (!arg || nr_args != 2)
7339                         break;
7340                 ret = io_register_iowq_max_workers(ctx, arg);
7341                 break;
7342         case IORING_REGISTER_RING_FDS:
7343                 ret = io_ringfd_register(ctx, arg, nr_args);
7344                 break;
7345         case IORING_UNREGISTER_RING_FDS:
7346                 ret = io_ringfd_unregister(ctx, arg, nr_args);
7347                 break;
7348         case IORING_REGISTER_PBUF_RING:
7349                 ret = -EINVAL;
7350                 if (!arg || nr_args != 1)
7351                         break;
7352                 ret = io_register_pbuf_ring(ctx, arg);
7353                 break;
7354         case IORING_UNREGISTER_PBUF_RING:
7355                 ret = -EINVAL;
7356                 if (!arg || nr_args != 1)
7357                         break;
7358                 ret = io_unregister_pbuf_ring(ctx, arg);
7359                 break;
7360         default:
7361                 ret = -EINVAL;
7362                 break;
7363         }
7364
7365         return ret;
7366 }
7367
7368 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
7369                 void __user *, arg, unsigned int, nr_args)
7370 {
7371         struct io_ring_ctx *ctx;
7372         long ret = -EBADF;
7373         struct fd f;
7374
7375         f = fdget(fd);
7376         if (!f.file)
7377                 return -EBADF;
7378
7379         ret = -EOPNOTSUPP;
7380         if (!io_is_uring_fops(f.file))
7381                 goto out_fput;
7382
7383         ctx = f.file->private_data;
7384
7385         io_run_task_work();
7386
7387         mutex_lock(&ctx->uring_lock);
7388         ret = __io_uring_register(ctx, opcode, arg, nr_args);
7389         mutex_unlock(&ctx->uring_lock);
7390         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
7391 out_fput:
7392         fdput(f);
7393         return ret;
7394 }
7395
7396 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
7397 {
7398         WARN_ON_ONCE(1);
7399         return -ECANCELED;
7400 }
7401
7402 const struct io_op_def io_op_defs[] = {
7403         [IORING_OP_NOP] = {
7404                 .audit_skip             = 1,
7405                 .iopoll                 = 1,
7406                 .name                   = "NOP",
7407                 .prep                   = io_nop_prep,
7408                 .issue                  = io_nop,
7409         },
7410         [IORING_OP_READV] = {
7411                 .needs_file             = 1,
7412                 .unbound_nonreg_file    = 1,
7413                 .pollin                 = 1,
7414                 .buffer_select          = 1,
7415                 .plug                   = 1,
7416                 .audit_skip             = 1,
7417                 .ioprio                 = 1,
7418                 .iopoll                 = 1,
7419                 .async_size             = sizeof(struct io_async_rw),
7420                 .name                   = "READV",
7421                 .prep                   = io_prep_rw,
7422                 .issue                  = io_read,
7423                 .prep_async             = io_readv_prep_async,
7424                 .cleanup                = io_readv_writev_cleanup,
7425         },
7426         [IORING_OP_WRITEV] = {
7427                 .needs_file             = 1,
7428                 .hash_reg_file          = 1,
7429                 .unbound_nonreg_file    = 1,
7430                 .pollout                = 1,
7431                 .plug                   = 1,
7432                 .audit_skip             = 1,
7433                 .ioprio                 = 1,
7434                 .iopoll                 = 1,
7435                 .async_size             = sizeof(struct io_async_rw),
7436                 .name                   = "WRITEV",
7437                 .prep                   = io_prep_rw,
7438                 .issue                  = io_write,
7439                 .prep_async             = io_writev_prep_async,
7440                 .cleanup                = io_readv_writev_cleanup,
7441         },
7442         [IORING_OP_FSYNC] = {
7443                 .needs_file             = 1,
7444                 .audit_skip             = 1,
7445                 .name                   = "FSYNC",
7446                 .prep                   = io_fsync_prep,
7447                 .issue                  = io_fsync,
7448         },
7449         [IORING_OP_READ_FIXED] = {
7450                 .needs_file             = 1,
7451                 .unbound_nonreg_file    = 1,
7452                 .pollin                 = 1,
7453                 .plug                   = 1,
7454                 .audit_skip             = 1,
7455                 .ioprio                 = 1,
7456                 .iopoll                 = 1,
7457                 .async_size             = sizeof(struct io_async_rw),
7458                 .name                   = "READ_FIXED",
7459                 .prep                   = io_prep_rw,
7460                 .issue                  = io_read,
7461         },
7462         [IORING_OP_WRITE_FIXED] = {
7463                 .needs_file             = 1,
7464                 .hash_reg_file          = 1,
7465                 .unbound_nonreg_file    = 1,
7466                 .pollout                = 1,
7467                 .plug                   = 1,
7468                 .audit_skip             = 1,
7469                 .ioprio                 = 1,
7470                 .iopoll                 = 1,
7471                 .async_size             = sizeof(struct io_async_rw),
7472                 .name                   = "WRITE_FIXED",
7473                 .prep                   = io_prep_rw,
7474                 .issue                  = io_write,
7475         },
7476         [IORING_OP_POLL_ADD] = {
7477                 .needs_file             = 1,
7478                 .unbound_nonreg_file    = 1,
7479                 .audit_skip             = 1,
7480                 .name                   = "POLL_ADD",
7481                 .prep                   = io_poll_add_prep,
7482                 .issue                  = io_poll_add,
7483         },
7484         [IORING_OP_POLL_REMOVE] = {
7485                 .audit_skip             = 1,
7486                 .name                   = "POLL_REMOVE",
7487                 .prep                   = io_poll_remove_prep,
7488                 .issue                  = io_poll_remove,
7489         },
7490         [IORING_OP_SYNC_FILE_RANGE] = {
7491                 .needs_file             = 1,
7492                 .audit_skip             = 1,
7493                 .name                   = "SYNC_FILE_RANGE",
7494                 .prep                   = io_sfr_prep,
7495                 .issue                  = io_sync_file_range,
7496         },
7497         [IORING_OP_SENDMSG] = {
7498                 .needs_file             = 1,
7499                 .unbound_nonreg_file    = 1,
7500                 .pollout                = 1,
7501                 .ioprio                 = 1,
7502                 .name                   = "SENDMSG",
7503 #if defined(CONFIG_NET)
7504                 .async_size             = sizeof(struct io_async_msghdr),
7505                 .prep                   = io_sendmsg_prep,
7506                 .issue                  = io_sendmsg,
7507                 .prep_async             = io_sendmsg_prep_async,
7508                 .cleanup                = io_sendmsg_recvmsg_cleanup,
7509 #else
7510                 .prep                   = io_eopnotsupp_prep,
7511 #endif
7512         },
7513         [IORING_OP_RECVMSG] = {
7514                 .needs_file             = 1,
7515                 .unbound_nonreg_file    = 1,
7516                 .pollin                 = 1,
7517                 .buffer_select          = 1,
7518                 .ioprio                 = 1,
7519                 .name                   = "RECVMSG",
7520 #if defined(CONFIG_NET)
7521                 .async_size             = sizeof(struct io_async_msghdr),
7522                 .prep                   = io_recvmsg_prep,
7523                 .issue                  = io_recvmsg,
7524                 .prep_async             = io_recvmsg_prep_async,
7525                 .cleanup                = io_sendmsg_recvmsg_cleanup,
7526 #else
7527                 .prep                   = io_eopnotsupp_prep,
7528 #endif
7529         },
7530         [IORING_OP_TIMEOUT] = {
7531                 .audit_skip             = 1,
7532                 .async_size             = sizeof(struct io_timeout_data),
7533                 .name                   = "TIMEOUT",
7534                 .prep                   = io_timeout_prep,
7535                 .issue                  = io_timeout,
7536         },
7537         [IORING_OP_TIMEOUT_REMOVE] = {
7538                 /* used by timeout updates' prep() */
7539                 .audit_skip             = 1,
7540                 .name                   = "TIMEOUT_REMOVE",
7541                 .prep                   = io_timeout_remove_prep,
7542                 .issue                  = io_timeout_remove,
7543         },
7544         [IORING_OP_ACCEPT] = {
7545                 .needs_file             = 1,
7546                 .unbound_nonreg_file    = 1,
7547                 .pollin                 = 1,
7548                 .poll_exclusive         = 1,
7549                 .ioprio                 = 1,    /* used for flags */
7550                 .name                   = "ACCEPT",
7551 #if defined(CONFIG_NET)
7552                 .prep                   = io_accept_prep,
7553                 .issue                  = io_accept,
7554 #else
7555                 .prep                   = io_eopnotsupp_prep,
7556 #endif
7557         },
7558         [IORING_OP_ASYNC_CANCEL] = {
7559                 .audit_skip             = 1,
7560                 .name                   = "ASYNC_CANCEL",
7561                 .prep                   = io_async_cancel_prep,
7562                 .issue                  = io_async_cancel,
7563         },
7564         [IORING_OP_LINK_TIMEOUT] = {
7565                 .audit_skip             = 1,
7566                 .async_size             = sizeof(struct io_timeout_data),
7567                 .name                   = "LINK_TIMEOUT",
7568                 .prep                   = io_link_timeout_prep,
7569                 .issue                  = io_no_issue,
7570         },
7571         [IORING_OP_CONNECT] = {
7572                 .needs_file             = 1,
7573                 .unbound_nonreg_file    = 1,
7574                 .pollout                = 1,
7575                 .name                   = "CONNECT",
7576 #if defined(CONFIG_NET)
7577                 .async_size             = sizeof(struct io_async_connect),
7578                 .prep                   = io_connect_prep,
7579                 .issue                  = io_connect,
7580                 .prep_async             = io_connect_prep_async,
7581 #else
7582                 .prep                   = io_eopnotsupp_prep,
7583 #endif
7584         },
7585         [IORING_OP_FALLOCATE] = {
7586                 .needs_file             = 1,
7587                 .name                   = "FALLOCATE",
7588                 .prep                   = io_fallocate_prep,
7589                 .issue                  = io_fallocate,
7590         },
7591         [IORING_OP_OPENAT] = {
7592                 .name                   = "OPENAT",
7593                 .prep                   = io_openat_prep,
7594                 .issue                  = io_openat,
7595                 .cleanup                = io_open_cleanup,
7596         },
7597         [IORING_OP_CLOSE] = {
7598                 .name                   = "CLOSE",
7599                 .prep                   = io_close_prep,
7600                 .issue                  = io_close,
7601         },
7602         [IORING_OP_FILES_UPDATE] = {
7603                 .audit_skip             = 1,
7604                 .iopoll                 = 1,
7605                 .name                   = "FILES_UPDATE",
7606                 .prep                   = io_files_update_prep,
7607                 .issue                  = io_files_update,
7608         },
7609         [IORING_OP_STATX] = {
7610                 .audit_skip             = 1,
7611                 .name                   = "STATX",
7612                 .prep                   = io_statx_prep,
7613                 .issue                  = io_statx,
7614                 .cleanup                = io_statx_cleanup,
7615         },
7616         [IORING_OP_READ] = {
7617                 .needs_file             = 1,
7618                 .unbound_nonreg_file    = 1,
7619                 .pollin                 = 1,
7620                 .buffer_select          = 1,
7621                 .plug                   = 1,
7622                 .audit_skip             = 1,
7623                 .ioprio                 = 1,
7624                 .iopoll                 = 1,
7625                 .async_size             = sizeof(struct io_async_rw),
7626                 .name                   = "READ",
7627                 .prep                   = io_prep_rw,
7628                 .issue                  = io_read,
7629         },
7630         [IORING_OP_WRITE] = {
7631                 .needs_file             = 1,
7632                 .hash_reg_file          = 1,
7633                 .unbound_nonreg_file    = 1,
7634                 .pollout                = 1,
7635                 .plug                   = 1,
7636                 .audit_skip             = 1,
7637                 .ioprio                 = 1,
7638                 .iopoll                 = 1,
7639                 .async_size             = sizeof(struct io_async_rw),
7640                 .name                   = "WRITE",
7641                 .prep                   = io_prep_rw,
7642                 .issue                  = io_write,
7643         },
7644         [IORING_OP_FADVISE] = {
7645                 .needs_file             = 1,
7646                 .audit_skip             = 1,
7647                 .name                   = "FADVISE",
7648                 .prep                   = io_fadvise_prep,
7649                 .issue                  = io_fadvise,
7650         },
7651         [IORING_OP_MADVISE] = {
7652                 .name                   = "MADVISE",
7653                 .prep                   = io_madvise_prep,
7654                 .issue                  = io_madvise,
7655         },
7656         [IORING_OP_SEND] = {
7657                 .needs_file             = 1,
7658                 .unbound_nonreg_file    = 1,
7659                 .pollout                = 1,
7660                 .audit_skip             = 1,
7661                 .ioprio                 = 1,
7662                 .name                   = "SEND",
7663 #if defined(CONFIG_NET)
7664                 .prep                   = io_sendmsg_prep,
7665                 .issue                  = io_send,
7666 #else
7667                 .prep                   = io_eopnotsupp_prep,
7668 #endif
7669         },
7670         [IORING_OP_RECV] = {
7671                 .needs_file             = 1,
7672                 .unbound_nonreg_file    = 1,
7673                 .pollin                 = 1,
7674                 .buffer_select          = 1,
7675                 .audit_skip             = 1,
7676                 .ioprio                 = 1,
7677                 .name                   = "RECV",
7678 #if defined(CONFIG_NET)
7679                 .prep                   = io_recvmsg_prep,
7680                 .issue                  = io_recv,
7681 #else
7682                 .prep                   = io_eopnotsupp_prep,
7683 #endif
7684         },
7685         [IORING_OP_OPENAT2] = {
7686                 .name                   = "OPENAT2",
7687                 .prep                   = io_openat2_prep,
7688                 .issue                  = io_openat2,
7689                 .cleanup                = io_open_cleanup,
7690         },
7691         [IORING_OP_EPOLL_CTL] = {
7692                 .unbound_nonreg_file    = 1,
7693                 .audit_skip             = 1,
7694                 .name                   = "EPOLL",
7695 #if defined(CONFIG_EPOLL)
7696                 .prep                   = io_epoll_ctl_prep,
7697                 .issue                  = io_epoll_ctl,
7698 #else
7699                 .prep                   = io_eopnotsupp_prep,
7700 #endif
7701         },
7702         [IORING_OP_SPLICE] = {
7703                 .needs_file             = 1,
7704                 .hash_reg_file          = 1,
7705                 .unbound_nonreg_file    = 1,
7706                 .audit_skip             = 1,
7707                 .name                   = "SPLICE",
7708                 .prep                   = io_splice_prep,
7709                 .issue                  = io_splice,
7710         },
7711         [IORING_OP_PROVIDE_BUFFERS] = {
7712                 .audit_skip             = 1,
7713                 .iopoll                 = 1,
7714                 .name                   = "PROVIDE_BUFFERS",
7715                 .prep                   = io_provide_buffers_prep,
7716                 .issue                  = io_provide_buffers,
7717         },
7718         [IORING_OP_REMOVE_BUFFERS] = {
7719                 .audit_skip             = 1,
7720                 .iopoll                 = 1,
7721                 .name                   = "REMOVE_BUFFERS",
7722                 .prep                   = io_remove_buffers_prep,
7723                 .issue                  = io_remove_buffers,
7724         },
7725         [IORING_OP_TEE] = {
7726                 .needs_file             = 1,
7727                 .hash_reg_file          = 1,
7728                 .unbound_nonreg_file    = 1,
7729                 .audit_skip             = 1,
7730                 .name                   = "TEE",
7731                 .prep                   = io_tee_prep,
7732                 .issue                  = io_tee,
7733         },
7734         [IORING_OP_SHUTDOWN] = {
7735                 .needs_file             = 1,
7736                 .name                   = "SHUTDOWN",
7737 #if defined(CONFIG_NET)
7738                 .prep                   = io_shutdown_prep,
7739                 .issue                  = io_shutdown,
7740 #else
7741                 .prep                   = io_eopnotsupp_prep,
7742 #endif
7743         },
7744         [IORING_OP_RENAMEAT] = {
7745                 .name                   = "RENAMEAT",
7746                 .prep                   = io_renameat_prep,
7747                 .issue                  = io_renameat,
7748                 .cleanup                = io_renameat_cleanup,
7749         },
7750         [IORING_OP_UNLINKAT] = {
7751                 .name                   = "UNLINKAT",
7752                 .prep                   = io_unlinkat_prep,
7753                 .issue                  = io_unlinkat,
7754                 .cleanup                = io_unlinkat_cleanup,
7755         },
7756         [IORING_OP_MKDIRAT] = {
7757                 .name                   = "MKDIRAT",
7758                 .prep                   = io_mkdirat_prep,
7759                 .issue                  = io_mkdirat,
7760                 .cleanup                = io_mkdirat_cleanup,
7761         },
7762         [IORING_OP_SYMLINKAT] = {
7763                 .name                   = "SYMLINKAT",
7764                 .prep                   = io_symlinkat_prep,
7765                 .issue                  = io_symlinkat,
7766                 .cleanup                = io_link_cleanup,
7767         },
7768         [IORING_OP_LINKAT] = {
7769                 .name                   = "LINKAT",
7770                 .prep                   = io_linkat_prep,
7771                 .issue                  = io_linkat,
7772                 .cleanup                = io_link_cleanup,
7773         },
7774         [IORING_OP_MSG_RING] = {
7775                 .needs_file             = 1,
7776                 .iopoll                 = 1,
7777                 .name                   = "MSG_RING",
7778                 .prep                   = io_msg_ring_prep,
7779                 .issue                  = io_msg_ring,
7780         },
7781         [IORING_OP_FSETXATTR] = {
7782                 .needs_file = 1,
7783                 .name                   = "FSETXATTR",
7784                 .prep                   = io_fsetxattr_prep,
7785                 .issue                  = io_fsetxattr,
7786                 .cleanup                = io_xattr_cleanup,
7787         },
7788         [IORING_OP_SETXATTR] = {
7789                 .name                   = "SETXATTR",
7790                 .prep                   = io_setxattr_prep,
7791                 .issue                  = io_setxattr,
7792                 .cleanup                = io_xattr_cleanup,
7793         },
7794         [IORING_OP_FGETXATTR] = {
7795                 .needs_file = 1,
7796                 .name                   = "FGETXATTR",
7797                 .prep                   = io_fgetxattr_prep,
7798                 .issue                  = io_fgetxattr,
7799                 .cleanup                = io_xattr_cleanup,
7800         },
7801         [IORING_OP_GETXATTR] = {
7802                 .name                   = "GETXATTR",
7803                 .prep                   = io_getxattr_prep,
7804                 .issue                  = io_getxattr,
7805                 .cleanup                = io_xattr_cleanup,
7806         },
7807         [IORING_OP_SOCKET] = {
7808                 .audit_skip             = 1,
7809                 .name                   = "SOCKET",
7810 #if defined(CONFIG_NET)
7811                 .prep                   = io_socket_prep,
7812                 .issue                  = io_socket,
7813 #else
7814                 .prep                   = io_eopnotsupp_prep,
7815 #endif
7816         },
7817         [IORING_OP_URING_CMD] = {
7818                 .needs_file             = 1,
7819                 .plug                   = 1,
7820                 .name                   = "URING_CMD",
7821                 .async_size             = uring_cmd_pdu_size(1),
7822                 .prep                   = io_uring_cmd_prep,
7823                 .issue                  = io_uring_cmd,
7824                 .prep_async             = io_uring_cmd_prep_async,
7825         },
7826 };
7827
7828 static int __init io_uring_init(void)
7829 {
7830         int i;
7831
7832 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
7833         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
7834         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
7835 } while (0)
7836
7837 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
7838         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
7839         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
7840         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
7841         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
7842         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
7843         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
7844         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
7845         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
7846         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
7847         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
7848         BUILD_BUG_SQE_ELEM(24, __u32,  len);
7849         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
7850         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
7851         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
7852         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
7853         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
7854         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
7855         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
7856         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
7857         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
7858         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
7859         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
7860         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
7861         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
7862         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
7863         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
7864         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
7865         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
7866         BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
7867         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
7868         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
7869         BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
7870         BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
7871
7872         BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
7873                      sizeof(struct io_uring_rsrc_update));
7874         BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
7875                      sizeof(struct io_uring_rsrc_update2));
7876
7877         /* ->buf_index is u16 */
7878         BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
7879         BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
7880         BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
7881         BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
7882                      offsetof(struct io_uring_buf_ring, tail));
7883
7884         /* should fit into one byte */
7885         BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
7886         BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
7887         BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
7888
7889         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
7890         BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
7891
7892         BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
7893
7894         for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
7895                 BUG_ON(!io_op_defs[i].prep);
7896                 if (io_op_defs[i].prep != io_eopnotsupp_prep)
7897                         BUG_ON(!io_op_defs[i].issue);
7898                 WARN_ON_ONCE(!io_op_defs[i].name);
7899         }
7900
7901         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
7902                                 SLAB_ACCOUNT);
7903         return 0;
7904 };
7905 __initcall(io_uring_init);