io_uring: move statx handling to 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/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/audit.h>
82 #include <linux/security.h>
83
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
86
87 #include <uapi/linux/io_uring.h>
88
89 #include "../fs/internal.h"
90 #include "io-wq.h"
91
92 #include "io_uring_types.h"
93 #include "io_uring.h"
94
95 #include "xattr.h"
96 #include "nop.h"
97 #include "fs.h"
98 #include "splice.h"
99 #include "sync.h"
100 #include "advise.h"
101 #include "openclose.h"
102 #include "uring_cmd.h"
103 #include "epoll.h"
104 #include "statx.h"
105
106 #define IORING_MAX_ENTRIES      32768
107 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
108 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
109
110 /* only define max */
111 #define IORING_MAX_FIXED_FILES  (1U << 20)
112 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
113                                  IORING_REGISTER_LAST + IORING_OP_LAST)
114
115 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
116 #define IO_RSRC_TAG_TABLE_MAX   (1U << IO_RSRC_TAG_TABLE_SHIFT)
117 #define IO_RSRC_TAG_TABLE_MASK  (IO_RSRC_TAG_TABLE_MAX - 1)
118
119 #define IORING_MAX_REG_BUFFERS  (1U << 14)
120
121 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
122                           IOSQE_IO_HARDLINK | IOSQE_ASYNC)
123
124 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
125                         IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
126
127 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
128                                 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
129                                 REQ_F_ASYNC_DATA)
130
131 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
132                                  IO_REQ_CLEAN_FLAGS)
133
134 #define IO_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
135
136 #define IO_TCTX_REFS_CACHE_NR   (1U << 10)
137
138 struct io_mapped_ubuf {
139         u64             ubuf;
140         u64             ubuf_end;
141         unsigned int    nr_bvecs;
142         unsigned long   acct_pages;
143         struct bio_vec  bvec[];
144 };
145
146 struct io_ring_ctx;
147
148 struct io_overflow_cqe {
149         struct list_head list;
150         struct io_uring_cqe cqe;
151 };
152
153 struct io_rsrc_put {
154         struct list_head list;
155         u64 tag;
156         union {
157                 void *rsrc;
158                 struct file *file;
159                 struct io_mapped_ubuf *buf;
160         };
161 };
162
163 struct io_rsrc_node {
164         struct percpu_ref               refs;
165         struct list_head                node;
166         struct list_head                rsrc_list;
167         struct io_rsrc_data             *rsrc_data;
168         struct llist_node               llist;
169         bool                            done;
170 };
171
172 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
173
174 struct io_rsrc_data {
175         struct io_ring_ctx              *ctx;
176
177         u64                             **tags;
178         unsigned int                    nr;
179         rsrc_put_fn                     *do_put;
180         atomic_t                        refs;
181         struct completion               done;
182         bool                            quiesce;
183 };
184
185 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
186 struct io_buffer_list {
187         /*
188          * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
189          * then these are classic provided buffers and ->buf_list is used.
190          */
191         union {
192                 struct list_head buf_list;
193                 struct {
194                         struct page **buf_pages;
195                         struct io_uring_buf_ring *buf_ring;
196                 };
197         };
198         __u16 bgid;
199
200         /* below is for ring provided buffers */
201         __u16 buf_nr_pages;
202         __u16 nr_entries;
203         __u16 head;
204         __u16 mask;
205 };
206
207 struct io_buffer {
208         struct list_head list;
209         __u64 addr;
210         __u32 len;
211         __u16 bid;
212         __u16 bgid;
213 };
214
215 enum {
216         IO_SQ_THREAD_SHOULD_STOP = 0,
217         IO_SQ_THREAD_SHOULD_PARK,
218 };
219
220 struct io_sq_data {
221         refcount_t              refs;
222         atomic_t                park_pending;
223         struct mutex            lock;
224
225         /* ctx's that are using this sqd */
226         struct list_head        ctx_list;
227
228         struct task_struct      *thread;
229         struct wait_queue_head  wait;
230
231         unsigned                sq_thread_idle;
232         int                     sq_cpu;
233         pid_t                   task_pid;
234         pid_t                   task_tgid;
235
236         unsigned long           state;
237         struct completion       exited;
238 };
239
240 #define IO_COMPL_BATCH                  32
241 #define IO_REQ_CACHE_SIZE               32
242 #define IO_REQ_ALLOC_BATCH              8
243
244 #define BGID_ARRAY                      64
245
246 /*
247  * Arbitrary limit, can be raised if need be
248  */
249 #define IO_RINGFD_REG_MAX 16
250
251 struct io_uring_task {
252         /* submission side */
253         int                     cached_refs;
254         struct xarray           xa;
255         struct wait_queue_head  wait;
256         const struct io_ring_ctx *last;
257         struct io_wq            *io_wq;
258         struct percpu_counter   inflight;
259         atomic_t                inflight_tracked;
260         atomic_t                in_idle;
261
262         spinlock_t              task_lock;
263         struct io_wq_work_list  task_list;
264         struct io_wq_work_list  prio_task_list;
265         struct callback_head    task_work;
266         struct file             **registered_rings;
267         bool                    task_running;
268 };
269
270 /*
271  * First field must be the file pointer in all the
272  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
273  */
274 struct io_poll {
275         struct file                     *file;
276         struct wait_queue_head          *head;
277         __poll_t                        events;
278         struct wait_queue_entry         wait;
279 };
280
281 struct io_poll_update {
282         struct file                     *file;
283         u64                             old_user_data;
284         u64                             new_user_data;
285         __poll_t                        events;
286         bool                            update_events;
287         bool                            update_user_data;
288 };
289
290 struct io_timeout_data {
291         struct io_kiocb                 *req;
292         struct hrtimer                  timer;
293         struct timespec64               ts;
294         enum hrtimer_mode               mode;
295         u32                             flags;
296 };
297
298 struct io_accept {
299         struct file                     *file;
300         struct sockaddr __user          *addr;
301         int __user                      *addr_len;
302         int                             flags;
303         u32                             file_slot;
304         unsigned long                   nofile;
305 };
306
307 struct io_socket {
308         struct file                     *file;
309         int                             domain;
310         int                             type;
311         int                             protocol;
312         int                             flags;
313         u32                             file_slot;
314         unsigned long                   nofile;
315 };
316
317 struct io_cancel {
318         struct file                     *file;
319         u64                             addr;
320         u32                             flags;
321         s32                             fd;
322 };
323
324 struct io_timeout {
325         struct file                     *file;
326         u32                             off;
327         u32                             target_seq;
328         struct list_head                list;
329         /* head of the link, used by linked timeouts only */
330         struct io_kiocb                 *head;
331         /* for linked completions */
332         struct io_kiocb                 *prev;
333 };
334
335 struct io_timeout_rem {
336         struct file                     *file;
337         u64                             addr;
338
339         /* timeout update */
340         struct timespec64               ts;
341         u32                             flags;
342         bool                            ltimeout;
343 };
344
345 struct io_rw {
346         /* NOTE: kiocb has the file as the first member, so don't do it here */
347         struct kiocb                    kiocb;
348         u64                             addr;
349         u32                             len;
350         rwf_t                           flags;
351 };
352
353 struct io_connect {
354         struct file                     *file;
355         struct sockaddr __user          *addr;
356         int                             addr_len;
357 };
358
359 struct io_sr_msg {
360         struct file                     *file;
361         union {
362                 struct compat_msghdr __user     *umsg_compat;
363                 struct user_msghdr __user       *umsg;
364                 void __user                     *buf;
365         };
366         int                             msg_flags;
367         size_t                          len;
368         size_t                          done_io;
369         unsigned int                    flags;
370 };
371
372 struct io_rsrc_update {
373         struct file                     *file;
374         u64                             arg;
375         u32                             nr_args;
376         u32                             offset;
377 };
378
379 struct io_provide_buf {
380         struct file                     *file;
381         __u64                           addr;
382         __u32                           len;
383         __u32                           bgid;
384         __u16                           nbufs;
385         __u16                           bid;
386 };
387
388 struct io_shutdown {
389         struct file                     *file;
390         int                             how;
391 };
392
393 struct io_msg {
394         struct file                     *file;
395         u64 user_data;
396         u32 len;
397 };
398
399 struct io_async_connect {
400         struct sockaddr_storage         address;
401 };
402
403 struct io_async_msghdr {
404         struct iovec                    fast_iov[UIO_FASTIOV];
405         /* points to an allocated iov, if NULL we use fast_iov instead */
406         struct iovec                    *free_iov;
407         struct sockaddr __user          *uaddr;
408         struct msghdr                   msg;
409         struct sockaddr_storage         addr;
410 };
411
412 struct io_rw_state {
413         struct iov_iter                 iter;
414         struct iov_iter_state           iter_state;
415         struct iovec                    fast_iov[UIO_FASTIOV];
416 };
417
418 struct io_async_rw {
419         struct io_rw_state              s;
420         const struct iovec              *free_iovec;
421         size_t                          bytes_done;
422         struct wait_page_queue          wpq;
423 };
424
425 struct async_poll {
426         struct io_poll          poll;
427         struct io_poll          *double_poll;
428 };
429
430 enum {
431         IORING_RSRC_FILE                = 0,
432         IORING_RSRC_BUFFER              = 1,
433 };
434
435 enum {
436         IO_CHECK_CQ_OVERFLOW_BIT,
437         IO_CHECK_CQ_DROPPED_BIT,
438 };
439
440 struct io_tctx_node {
441         struct list_head        ctx_node;
442         struct task_struct      *task;
443         struct io_ring_ctx      *ctx;
444 };
445
446 struct io_defer_entry {
447         struct list_head        list;
448         struct io_kiocb         *req;
449         u32                     seq;
450 };
451
452 struct io_cancel_data {
453         struct io_ring_ctx *ctx;
454         union {
455                 u64 data;
456                 struct file *file;
457         };
458         u32 flags;
459         int seq;
460 };
461
462 struct io_op_def {
463         /* needs req->file assigned */
464         unsigned                needs_file : 1;
465         /* should block plug */
466         unsigned                plug : 1;
467         /* hash wq insertion if file is a regular file */
468         unsigned                hash_reg_file : 1;
469         /* unbound wq insertion if file is a non-regular file */
470         unsigned                unbound_nonreg_file : 1;
471         /* set if opcode supports polled "wait" */
472         unsigned                pollin : 1;
473         unsigned                pollout : 1;
474         unsigned                poll_exclusive : 1;
475         /* op supports buffer selection */
476         unsigned                buffer_select : 1;
477         /* opcode is not supported by this kernel */
478         unsigned                not_supported : 1;
479         /* skip auditing */
480         unsigned                audit_skip : 1;
481         /* supports ioprio */
482         unsigned                ioprio : 1;
483         /* supports iopoll */
484         unsigned                iopoll : 1;
485         /* size of async data needed, if any */
486         unsigned short          async_size;
487
488         int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
489         int (*issue)(struct io_kiocb *, unsigned int);
490         int (*prep_async)(struct io_kiocb *);
491         void (*cleanup)(struct io_kiocb *);
492 };
493
494 static const struct io_op_def io_op_defs[];
495
496 /* requests with any of those set should undergo io_disarm_next() */
497 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
498 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
499
500 static bool io_disarm_next(struct io_kiocb *req);
501 static void io_uring_del_tctx_node(unsigned long index);
502 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
503                                          struct task_struct *task,
504                                          bool cancel_all);
505 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
506
507 static void io_dismantle_req(struct io_kiocb *req);
508 static void io_queue_linked_timeout(struct io_kiocb *req);
509 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
510                                      struct io_uring_rsrc_update2 *up,
511                                      unsigned nr_args);
512 static void io_clean_op(struct io_kiocb *req);
513 static void io_queue_sqe(struct io_kiocb *req);
514 static void io_rsrc_put_work(struct work_struct *work);
515
516 static void io_req_task_queue(struct io_kiocb *req);
517 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
518 static int io_req_prep_async(struct io_kiocb *req);
519
520 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
521                                  unsigned int issue_flags, u32 slot_index);
522
523 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
524 static void io_eventfd_signal(struct io_ring_ctx *ctx);
525 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
526
527 static struct kmem_cache *req_cachep;
528
529 static const struct file_operations io_uring_fops;
530
531 const char *io_uring_get_opcode(u8 opcode)
532 {
533         switch ((enum io_uring_op)opcode) {
534         case IORING_OP_NOP:
535                 return "NOP";
536         case IORING_OP_READV:
537                 return "READV";
538         case IORING_OP_WRITEV:
539                 return "WRITEV";
540         case IORING_OP_FSYNC:
541                 return "FSYNC";
542         case IORING_OP_READ_FIXED:
543                 return "READ_FIXED";
544         case IORING_OP_WRITE_FIXED:
545                 return "WRITE_FIXED";
546         case IORING_OP_POLL_ADD:
547                 return "POLL_ADD";
548         case IORING_OP_POLL_REMOVE:
549                 return "POLL_REMOVE";
550         case IORING_OP_SYNC_FILE_RANGE:
551                 return "SYNC_FILE_RANGE";
552         case IORING_OP_SENDMSG:
553                 return "SENDMSG";
554         case IORING_OP_RECVMSG:
555                 return "RECVMSG";
556         case IORING_OP_TIMEOUT:
557                 return "TIMEOUT";
558         case IORING_OP_TIMEOUT_REMOVE:
559                 return "TIMEOUT_REMOVE";
560         case IORING_OP_ACCEPT:
561                 return "ACCEPT";
562         case IORING_OP_ASYNC_CANCEL:
563                 return "ASYNC_CANCEL";
564         case IORING_OP_LINK_TIMEOUT:
565                 return "LINK_TIMEOUT";
566         case IORING_OP_CONNECT:
567                 return "CONNECT";
568         case IORING_OP_FALLOCATE:
569                 return "FALLOCATE";
570         case IORING_OP_OPENAT:
571                 return "OPENAT";
572         case IORING_OP_CLOSE:
573                 return "CLOSE";
574         case IORING_OP_FILES_UPDATE:
575                 return "FILES_UPDATE";
576         case IORING_OP_STATX:
577                 return "STATX";
578         case IORING_OP_READ:
579                 return "READ";
580         case IORING_OP_WRITE:
581                 return "WRITE";
582         case IORING_OP_FADVISE:
583                 return "FADVISE";
584         case IORING_OP_MADVISE:
585                 return "MADVISE";
586         case IORING_OP_SEND:
587                 return "SEND";
588         case IORING_OP_RECV:
589                 return "RECV";
590         case IORING_OP_OPENAT2:
591                 return "OPENAT2";
592         case IORING_OP_EPOLL_CTL:
593                 return "EPOLL_CTL";
594         case IORING_OP_SPLICE:
595                 return "SPLICE";
596         case IORING_OP_PROVIDE_BUFFERS:
597                 return "PROVIDE_BUFFERS";
598         case IORING_OP_REMOVE_BUFFERS:
599                 return "REMOVE_BUFFERS";
600         case IORING_OP_TEE:
601                 return "TEE";
602         case IORING_OP_SHUTDOWN:
603                 return "SHUTDOWN";
604         case IORING_OP_RENAMEAT:
605                 return "RENAMEAT";
606         case IORING_OP_UNLINKAT:
607                 return "UNLINKAT";
608         case IORING_OP_MKDIRAT:
609                 return "MKDIRAT";
610         case IORING_OP_SYMLINKAT:
611                 return "SYMLINKAT";
612         case IORING_OP_LINKAT:
613                 return "LINKAT";
614         case IORING_OP_MSG_RING:
615                 return "MSG_RING";
616         case IORING_OP_FSETXATTR:
617                 return "FSETXATTR";
618         case IORING_OP_SETXATTR:
619                 return "SETXATTR";
620         case IORING_OP_FGETXATTR:
621                 return "FGETXATTR";
622         case IORING_OP_GETXATTR:
623                 return "GETXATTR";
624         case IORING_OP_SOCKET:
625                 return "SOCKET";
626         case IORING_OP_URING_CMD:
627                 return "URING_CMD";
628         case IORING_OP_LAST:
629                 return "INVALID";
630         }
631         return "INVALID";
632 }
633
634 bool io_is_uring_fops(struct file *file)
635 {
636         return file->f_op == &io_uring_fops;
637 }
638
639 struct sock *io_uring_get_socket(struct file *file)
640 {
641 #if defined(CONFIG_UNIX)
642         if (io_is_uring_fops(file)) {
643                 struct io_ring_ctx *ctx = file->private_data;
644
645                 return ctx->ring_sock->sk;
646         }
647 #endif
648         return NULL;
649 }
650 EXPORT_SYMBOL(io_uring_get_socket);
651
652 #if defined(CONFIG_UNIX)
653 static inline bool io_file_need_scm(struct file *filp)
654 {
655 #if defined(IO_URING_SCM_ALL)
656         return true;
657 #else
658         return !!unix_get_socket(filp);
659 #endif
660 }
661 #else
662 static inline bool io_file_need_scm(struct file *filp)
663 {
664         return false;
665 }
666 #endif
667
668 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
669 {
670         if (!*locked) {
671                 mutex_lock(&ctx->uring_lock);
672                 *locked = true;
673         }
674 }
675
676 #define io_for_each_link(pos, head) \
677         for (pos = (head); pos; pos = pos->link)
678
679 /*
680  * Shamelessly stolen from the mm implementation of page reference checking,
681  * see commit f958d7b528b1 for details.
682  */
683 #define req_ref_zero_or_close_to_overflow(req)  \
684         ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
685
686 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
687 {
688         WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
689         return atomic_inc_not_zero(&req->refs);
690 }
691
692 static inline bool req_ref_put_and_test(struct io_kiocb *req)
693 {
694         if (likely(!(req->flags & REQ_F_REFCOUNT)))
695                 return true;
696
697         WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
698         return atomic_dec_and_test(&req->refs);
699 }
700
701 static inline void req_ref_get(struct io_kiocb *req)
702 {
703         WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
704         WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
705         atomic_inc(&req->refs);
706 }
707
708 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
709 {
710         if (!wq_list_empty(&ctx->submit_state.compl_reqs))
711                 __io_submit_flush_completions(ctx);
712 }
713
714 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
715 {
716         if (!(req->flags & REQ_F_REFCOUNT)) {
717                 req->flags |= REQ_F_REFCOUNT;
718                 atomic_set(&req->refs, nr);
719         }
720 }
721
722 static inline void io_req_set_refcount(struct io_kiocb *req)
723 {
724         __io_req_set_refcount(req, 1);
725 }
726
727 #define IO_RSRC_REF_BATCH       100
728
729 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
730 {
731         percpu_ref_put_many(&node->refs, nr);
732 }
733
734 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
735                                           struct io_ring_ctx *ctx)
736         __must_hold(&ctx->uring_lock)
737 {
738         struct io_rsrc_node *node = req->rsrc_node;
739
740         if (node) {
741                 if (node == ctx->rsrc_node)
742                         ctx->rsrc_cached_refs++;
743                 else
744                         io_rsrc_put_node(node, 1);
745         }
746 }
747
748 static inline void io_req_put_rsrc(struct io_kiocb *req)
749 {
750         if (req->rsrc_node)
751                 io_rsrc_put_node(req->rsrc_node, 1);
752 }
753
754 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
755         __must_hold(&ctx->uring_lock)
756 {
757         if (ctx->rsrc_cached_refs) {
758                 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
759                 ctx->rsrc_cached_refs = 0;
760         }
761 }
762
763 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
764         __must_hold(&ctx->uring_lock)
765 {
766         ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
767         percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
768 }
769
770 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
771                                         struct io_ring_ctx *ctx,
772                                         unsigned int issue_flags)
773 {
774         if (!req->rsrc_node) {
775                 req->rsrc_node = ctx->rsrc_node;
776
777                 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
778                         lockdep_assert_held(&ctx->uring_lock);
779                         ctx->rsrc_cached_refs--;
780                         if (unlikely(ctx->rsrc_cached_refs < 0))
781                                 io_rsrc_refs_refill(ctx);
782                 } else {
783                         percpu_ref_get(&req->rsrc_node->refs);
784                 }
785         }
786 }
787
788 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
789 {
790         if (req->flags & REQ_F_BUFFER_RING) {
791                 if (req->buf_list)
792                         req->buf_list->head++;
793                 req->flags &= ~REQ_F_BUFFER_RING;
794         } else {
795                 list_add(&req->kbuf->list, list);
796                 req->flags &= ~REQ_F_BUFFER_SELECTED;
797         }
798
799         return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
800 }
801
802 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
803 {
804         lockdep_assert_held(&req->ctx->completion_lock);
805
806         if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
807                 return 0;
808         return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
809 }
810
811 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
812                                        unsigned issue_flags)
813 {
814         unsigned int cflags;
815
816         if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
817                 return 0;
818
819         /*
820          * We can add this buffer back to two lists:
821          *
822          * 1) The io_buffers_cache list. This one is protected by the
823          *    ctx->uring_lock. If we already hold this lock, add back to this
824          *    list as we can grab it from issue as well.
825          * 2) The io_buffers_comp list. This one is protected by the
826          *    ctx->completion_lock.
827          *
828          * We migrate buffers from the comp_list to the issue cache list
829          * when we need one.
830          */
831         if (req->flags & REQ_F_BUFFER_RING) {
832                 /* no buffers to recycle for this case */
833                 cflags = __io_put_kbuf(req, NULL);
834         } else if (issue_flags & IO_URING_F_UNLOCKED) {
835                 struct io_ring_ctx *ctx = req->ctx;
836
837                 spin_lock(&ctx->completion_lock);
838                 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
839                 spin_unlock(&ctx->completion_lock);
840         } else {
841                 lockdep_assert_held(&req->ctx->uring_lock);
842
843                 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
844         }
845
846         return cflags;
847 }
848
849 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
850                                                  unsigned int bgid)
851 {
852         if (ctx->io_bl && bgid < BGID_ARRAY)
853                 return &ctx->io_bl[bgid];
854
855         return xa_load(&ctx->io_bl_xa, bgid);
856 }
857
858 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
859 {
860         struct io_ring_ctx *ctx = req->ctx;
861         struct io_buffer_list *bl;
862         struct io_buffer *buf;
863
864         if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
865                 return;
866         /*
867          * For legacy provided buffer mode, don't recycle if we already did
868          * IO to this buffer. For ring-mapped provided buffer mode, we should
869          * increment ring->head to explicitly monopolize the buffer to avoid
870          * multiple use.
871          */
872         if ((req->flags & REQ_F_BUFFER_SELECTED) &&
873             (req->flags & REQ_F_PARTIAL_IO))
874                 return;
875
876         /*
877          * READV uses fields in `struct io_rw` (len/addr) to stash the selected
878          * buffer data. However if that buffer is recycled the original request
879          * data stored in addr is lost. Therefore forbid recycling for now.
880          */
881         if (req->opcode == IORING_OP_READV)
882                 return;
883
884         /*
885          * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
886          * the flag and hence ensure that bl->head doesn't get incremented.
887          * If the tail has already been incremented, hang on to it.
888          */
889         if (req->flags & REQ_F_BUFFER_RING) {
890                 if (req->buf_list) {
891                         if (req->flags & REQ_F_PARTIAL_IO) {
892                                 req->buf_list->head++;
893                                 req->buf_list = NULL;
894                         } else {
895                                 req->buf_index = req->buf_list->bgid;
896                                 req->flags &= ~REQ_F_BUFFER_RING;
897                         }
898                 }
899                 return;
900         }
901
902         io_ring_submit_lock(ctx, issue_flags);
903
904         buf = req->kbuf;
905         bl = io_buffer_get_list(ctx, buf->bgid);
906         list_add(&buf->list, &bl->buf_list);
907         req->flags &= ~REQ_F_BUFFER_SELECTED;
908         req->buf_index = buf->bgid;
909
910         io_ring_submit_unlock(ctx, issue_flags);
911 }
912
913 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
914                           bool cancel_all)
915         __must_hold(&req->ctx->timeout_lock)
916 {
917         struct io_kiocb *req;
918
919         if (task && head->task != task)
920                 return false;
921         if (cancel_all)
922                 return true;
923
924         io_for_each_link(req, head) {
925                 if (req->flags & REQ_F_INFLIGHT)
926                         return true;
927         }
928         return false;
929 }
930
931 static bool io_match_linked(struct io_kiocb *head)
932 {
933         struct io_kiocb *req;
934
935         io_for_each_link(req, head) {
936                 if (req->flags & REQ_F_INFLIGHT)
937                         return true;
938         }
939         return false;
940 }
941
942 /*
943  * As io_match_task() but protected against racing with linked timeouts.
944  * User must not hold timeout_lock.
945  */
946 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
947                                bool cancel_all)
948 {
949         bool matched;
950
951         if (task && head->task != task)
952                 return false;
953         if (cancel_all)
954                 return true;
955
956         if (head->flags & REQ_F_LINK_TIMEOUT) {
957                 struct io_ring_ctx *ctx = head->ctx;
958
959                 /* protect against races with linked timeouts */
960                 spin_lock_irq(&ctx->timeout_lock);
961                 matched = io_match_linked(head);
962                 spin_unlock_irq(&ctx->timeout_lock);
963         } else {
964                 matched = io_match_linked(head);
965         }
966         return matched;
967 }
968
969 static inline void req_fail_link_node(struct io_kiocb *req, int res)
970 {
971         req_set_fail(req);
972         io_req_set_res(req, res, 0);
973 }
974
975 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
976 {
977         wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
978 }
979
980 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
981 {
982         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
983
984         complete(&ctx->ref_comp);
985 }
986
987 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
988 {
989         struct io_timeout *timeout = io_kiocb_to_cmd(req);
990
991         return !timeout->off;
992 }
993
994 static __cold void io_fallback_req_func(struct work_struct *work)
995 {
996         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
997                                                 fallback_work.work);
998         struct llist_node *node = llist_del_all(&ctx->fallback_llist);
999         struct io_kiocb *req, *tmp;
1000         bool locked = false;
1001
1002         percpu_ref_get(&ctx->refs);
1003         llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1004                 req->io_task_work.func(req, &locked);
1005
1006         if (locked) {
1007                 io_submit_flush_completions(ctx);
1008                 mutex_unlock(&ctx->uring_lock);
1009         }
1010         percpu_ref_put(&ctx->refs);
1011 }
1012
1013 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1014 {
1015         struct io_ring_ctx *ctx;
1016         int hash_bits;
1017
1018         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1019         if (!ctx)
1020                 return NULL;
1021
1022         xa_init(&ctx->io_bl_xa);
1023
1024         /*
1025          * Use 5 bits less than the max cq entries, that should give us around
1026          * 32 entries per hash list if totally full and uniformly spread.
1027          */
1028         hash_bits = ilog2(p->cq_entries);
1029         hash_bits -= 5;
1030         if (hash_bits <= 0)
1031                 hash_bits = 1;
1032         ctx->cancel_hash_bits = hash_bits;
1033         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1034                                         GFP_KERNEL);
1035         if (!ctx->cancel_hash)
1036                 goto err;
1037         __hash_init(ctx->cancel_hash, 1U << hash_bits);
1038
1039         ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1040         if (!ctx->dummy_ubuf)
1041                 goto err;
1042         /* set invalid range, so io_import_fixed() fails meeting it */
1043         ctx->dummy_ubuf->ubuf = -1UL;
1044
1045         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1046                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1047                 goto err;
1048
1049         ctx->flags = p->flags;
1050         init_waitqueue_head(&ctx->sqo_sq_wait);
1051         INIT_LIST_HEAD(&ctx->sqd_list);
1052         INIT_LIST_HEAD(&ctx->cq_overflow_list);
1053         INIT_LIST_HEAD(&ctx->io_buffers_cache);
1054         INIT_LIST_HEAD(&ctx->apoll_cache);
1055         init_completion(&ctx->ref_comp);
1056         xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1057         mutex_init(&ctx->uring_lock);
1058         init_waitqueue_head(&ctx->cq_wait);
1059         spin_lock_init(&ctx->completion_lock);
1060         spin_lock_init(&ctx->timeout_lock);
1061         INIT_WQ_LIST(&ctx->iopoll_list);
1062         INIT_LIST_HEAD(&ctx->io_buffers_pages);
1063         INIT_LIST_HEAD(&ctx->io_buffers_comp);
1064         INIT_LIST_HEAD(&ctx->defer_list);
1065         INIT_LIST_HEAD(&ctx->timeout_list);
1066         INIT_LIST_HEAD(&ctx->ltimeout_list);
1067         spin_lock_init(&ctx->rsrc_ref_lock);
1068         INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1069         INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1070         init_llist_head(&ctx->rsrc_put_llist);
1071         INIT_LIST_HEAD(&ctx->tctx_list);
1072         ctx->submit_state.free_list.next = NULL;
1073         INIT_WQ_LIST(&ctx->locked_free_list);
1074         INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1075         INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1076         return ctx;
1077 err:
1078         kfree(ctx->dummy_ubuf);
1079         kfree(ctx->cancel_hash);
1080         kfree(ctx->io_bl);
1081         xa_destroy(&ctx->io_bl_xa);
1082         kfree(ctx);
1083         return NULL;
1084 }
1085
1086 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1087 {
1088         struct io_rings *r = ctx->rings;
1089
1090         WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1091         ctx->cq_extra--;
1092 }
1093
1094 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1095 {
1096         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1097                 struct io_ring_ctx *ctx = req->ctx;
1098
1099                 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1100         }
1101
1102         return false;
1103 }
1104
1105 static inline bool io_req_ffs_set(struct io_kiocb *req)
1106 {
1107         return req->flags & REQ_F_FIXED_FILE;
1108 }
1109
1110 static inline void io_req_track_inflight(struct io_kiocb *req)
1111 {
1112         if (!(req->flags & REQ_F_INFLIGHT)) {
1113                 req->flags |= REQ_F_INFLIGHT;
1114                 atomic_inc(&req->task->io_uring->inflight_tracked);
1115         }
1116 }
1117
1118 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1119 {
1120         if (WARN_ON_ONCE(!req->link))
1121                 return NULL;
1122
1123         req->flags &= ~REQ_F_ARM_LTIMEOUT;
1124         req->flags |= REQ_F_LINK_TIMEOUT;
1125
1126         /* linked timeouts should have two refs once prep'ed */
1127         io_req_set_refcount(req);
1128         __io_req_set_refcount(req->link, 2);
1129         return req->link;
1130 }
1131
1132 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1133 {
1134         if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1135                 return NULL;
1136         return __io_prep_linked_timeout(req);
1137 }
1138
1139 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1140 {
1141         io_queue_linked_timeout(__io_prep_linked_timeout(req));
1142 }
1143
1144 static inline void io_arm_ltimeout(struct io_kiocb *req)
1145 {
1146         if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1147                 __io_arm_ltimeout(req);
1148 }
1149
1150 static void io_prep_async_work(struct io_kiocb *req)
1151 {
1152         const struct io_op_def *def = &io_op_defs[req->opcode];
1153         struct io_ring_ctx *ctx = req->ctx;
1154
1155         if (!(req->flags & REQ_F_CREDS)) {
1156                 req->flags |= REQ_F_CREDS;
1157                 req->creds = get_current_cred();
1158         }
1159
1160         req->work.list.next = NULL;
1161         req->work.flags = 0;
1162         req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1163         if (req->flags & REQ_F_FORCE_ASYNC)
1164                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1165
1166         if (req->flags & REQ_F_ISREG) {
1167                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1168                         io_wq_hash_work(&req->work, file_inode(req->file));
1169         } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1170                 if (def->unbound_nonreg_file)
1171                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1172         }
1173 }
1174
1175 static void io_prep_async_link(struct io_kiocb *req)
1176 {
1177         struct io_kiocb *cur;
1178
1179         if (req->flags & REQ_F_LINK_TIMEOUT) {
1180                 struct io_ring_ctx *ctx = req->ctx;
1181
1182                 spin_lock_irq(&ctx->timeout_lock);
1183                 io_for_each_link(cur, req)
1184                         io_prep_async_work(cur);
1185                 spin_unlock_irq(&ctx->timeout_lock);
1186         } else {
1187                 io_for_each_link(cur, req)
1188                         io_prep_async_work(cur);
1189         }
1190 }
1191
1192 static inline void io_req_add_compl_list(struct io_kiocb *req)
1193 {
1194         struct io_submit_state *state = &req->ctx->submit_state;
1195
1196         if (!(req->flags & REQ_F_CQE_SKIP))
1197                 state->flush_cqes = true;
1198         wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1199 }
1200
1201 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1202 {
1203         struct io_kiocb *link = io_prep_linked_timeout(req);
1204         struct io_uring_task *tctx = req->task->io_uring;
1205
1206         BUG_ON(!tctx);
1207         BUG_ON(!tctx->io_wq);
1208
1209         /* init ->work of the whole link before punting */
1210         io_prep_async_link(req);
1211
1212         /*
1213          * Not expected to happen, but if we do have a bug where this _can_
1214          * happen, catch it here and ensure the request is marked as
1215          * canceled. That will make io-wq go through the usual work cancel
1216          * procedure rather than attempt to run this request (or create a new
1217          * worker for it).
1218          */
1219         if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1220                 req->work.flags |= IO_WQ_WORK_CANCEL;
1221
1222         trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1223                                         req->opcode, req->flags, &req->work,
1224                                         io_wq_is_hashed(&req->work));
1225         io_wq_enqueue(tctx->io_wq, &req->work);
1226         if (link)
1227                 io_queue_linked_timeout(link);
1228 }
1229
1230 static void io_kill_timeout(struct io_kiocb *req, int status)
1231         __must_hold(&req->ctx->completion_lock)
1232         __must_hold(&req->ctx->timeout_lock)
1233 {
1234         struct io_timeout_data *io = req->async_data;
1235
1236         if (hrtimer_try_to_cancel(&io->timer) != -1) {
1237                 struct io_timeout *timeout = io_kiocb_to_cmd(req);
1238
1239                 if (status)
1240                         req_set_fail(req);
1241                 atomic_set(&req->ctx->cq_timeouts,
1242                         atomic_read(&req->ctx->cq_timeouts) + 1);
1243                 list_del_init(&timeout->list);
1244                 io_req_tw_post_queue(req, status, 0);
1245         }
1246 }
1247
1248 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1249 {
1250         while (!list_empty(&ctx->defer_list)) {
1251                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1252                                                 struct io_defer_entry, list);
1253
1254                 if (req_need_defer(de->req, de->seq))
1255                         break;
1256                 list_del_init(&de->list);
1257                 io_req_task_queue(de->req);
1258                 kfree(de);
1259         }
1260 }
1261
1262 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1263         __must_hold(&ctx->completion_lock)
1264 {
1265         u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1266         struct io_timeout *timeout, *tmp;
1267
1268         spin_lock_irq(&ctx->timeout_lock);
1269         list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
1270                 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
1271                 u32 events_needed, events_got;
1272
1273                 if (io_is_timeout_noseq(req))
1274                         break;
1275
1276                 /*
1277                  * Since seq can easily wrap around over time, subtract
1278                  * the last seq at which timeouts were flushed before comparing.
1279                  * Assuming not more than 2^31-1 events have happened since,
1280                  * these subtractions won't have wrapped, so we can check if
1281                  * target is in [last_seq, current_seq] by comparing the two.
1282                  */
1283                 events_needed = timeout->target_seq - ctx->cq_last_tm_flush;
1284                 events_got = seq - ctx->cq_last_tm_flush;
1285                 if (events_got < events_needed)
1286                         break;
1287
1288                 io_kill_timeout(req, 0);
1289         }
1290         ctx->cq_last_tm_flush = seq;
1291         spin_unlock_irq(&ctx->timeout_lock);
1292 }
1293
1294 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1295 {
1296         /* order cqe stores with ring update */
1297         smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1298 }
1299
1300 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1301 {
1302         if (ctx->off_timeout_used || ctx->drain_active) {
1303                 spin_lock(&ctx->completion_lock);
1304                 if (ctx->off_timeout_used)
1305                         io_flush_timeouts(ctx);
1306                 if (ctx->drain_active)
1307                         io_queue_deferred(ctx);
1308                 io_commit_cqring(ctx);
1309                 spin_unlock(&ctx->completion_lock);
1310         }
1311         if (ctx->has_evfd)
1312                 io_eventfd_signal(ctx);
1313 }
1314
1315 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1316 {
1317         struct io_rings *r = ctx->rings;
1318
1319         return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1320 }
1321
1322 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1323 {
1324         return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1325 }
1326
1327 /*
1328  * writes to the cq entry need to come after reading head; the
1329  * control dependency is enough as we're using WRITE_ONCE to
1330  * fill the cq entry
1331  */
1332 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1333 {
1334         struct io_rings *rings = ctx->rings;
1335         unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1336         unsigned int shift = 0;
1337         unsigned int free, queued, len;
1338
1339         if (ctx->flags & IORING_SETUP_CQE32)
1340                 shift = 1;
1341
1342         /* userspace may cheat modifying the tail, be safe and do min */
1343         queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1344         free = ctx->cq_entries - queued;
1345         /* we need a contiguous range, limit based on the current array offset */
1346         len = min(free, ctx->cq_entries - off);
1347         if (!len)
1348                 return NULL;
1349
1350         ctx->cached_cq_tail++;
1351         ctx->cqe_cached = &rings->cqes[off];
1352         ctx->cqe_sentinel = ctx->cqe_cached + len;
1353         ctx->cqe_cached++;
1354         return &rings->cqes[off << shift];
1355 }
1356
1357 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1358 {
1359         if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
1360                 struct io_uring_cqe *cqe = ctx->cqe_cached;
1361
1362                 if (ctx->flags & IORING_SETUP_CQE32) {
1363                         unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
1364
1365                         cqe += off;
1366                 }
1367
1368                 ctx->cached_cq_tail++;
1369                 ctx->cqe_cached++;
1370                 return cqe;
1371         }
1372
1373         return __io_get_cqe(ctx);
1374 }
1375
1376 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1377 {
1378         struct io_ev_fd *ev_fd;
1379
1380         rcu_read_lock();
1381         /*
1382          * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1383          * and eventfd_signal
1384          */
1385         ev_fd = rcu_dereference(ctx->io_ev_fd);
1386
1387         /*
1388          * Check again if ev_fd exists incase an io_eventfd_unregister call
1389          * completed between the NULL check of ctx->io_ev_fd at the start of
1390          * the function and rcu_read_lock.
1391          */
1392         if (unlikely(!ev_fd))
1393                 goto out;
1394         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1395                 goto out;
1396
1397         if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1398                 eventfd_signal(ev_fd->cq_ev_fd, 1);
1399 out:
1400         rcu_read_unlock();
1401 }
1402
1403 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1404 {
1405         /*
1406          * wake_up_all() may seem excessive, but io_wake_function() and
1407          * io_should_wake() handle the termination of the loop and only
1408          * wake as many waiters as we need to.
1409          */
1410         if (wq_has_sleeper(&ctx->cq_wait))
1411                 wake_up_all(&ctx->cq_wait);
1412 }
1413
1414 /*
1415  * This should only get called when at least one event has been posted.
1416  * Some applications rely on the eventfd notification count only changing
1417  * IFF a new CQE has been added to the CQ ring. There's no depedency on
1418  * 1:1 relationship between how many times this function is called (and
1419  * hence the eventfd count) and number of CQEs posted to the CQ ring.
1420  */
1421 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1422 {
1423         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1424                      ctx->has_evfd))
1425                 __io_commit_cqring_flush(ctx);
1426
1427         io_cqring_wake(ctx);
1428 }
1429
1430 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1431 {
1432         if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1433                      ctx->has_evfd))
1434                 __io_commit_cqring_flush(ctx);
1435
1436         if (ctx->flags & IORING_SETUP_SQPOLL)
1437                 io_cqring_wake(ctx);
1438 }
1439
1440 /* Returns true if there are no backlogged entries after the flush */
1441 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1442 {
1443         bool all_flushed, posted;
1444         size_t cqe_size = sizeof(struct io_uring_cqe);
1445
1446         if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1447                 return false;
1448
1449         if (ctx->flags & IORING_SETUP_CQE32)
1450                 cqe_size <<= 1;
1451
1452         posted = false;
1453         spin_lock(&ctx->completion_lock);
1454         while (!list_empty(&ctx->cq_overflow_list)) {
1455                 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1456                 struct io_overflow_cqe *ocqe;
1457
1458                 if (!cqe && !force)
1459                         break;
1460                 ocqe = list_first_entry(&ctx->cq_overflow_list,
1461                                         struct io_overflow_cqe, list);
1462                 if (cqe)
1463                         memcpy(cqe, &ocqe->cqe, cqe_size);
1464                 else
1465                         io_account_cq_overflow(ctx);
1466
1467                 posted = true;
1468                 list_del(&ocqe->list);
1469                 kfree(ocqe);
1470         }
1471
1472         all_flushed = list_empty(&ctx->cq_overflow_list);
1473         if (all_flushed) {
1474                 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1475                 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1476         }
1477
1478         io_commit_cqring(ctx);
1479         spin_unlock(&ctx->completion_lock);
1480         if (posted)
1481                 io_cqring_ev_posted(ctx);
1482         return all_flushed;
1483 }
1484
1485 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1486 {
1487         bool ret = true;
1488
1489         if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
1490                 /* iopoll syncs against uring_lock, not completion_lock */
1491                 if (ctx->flags & IORING_SETUP_IOPOLL)
1492                         mutex_lock(&ctx->uring_lock);
1493                 ret = __io_cqring_overflow_flush(ctx, false);
1494                 if (ctx->flags & IORING_SETUP_IOPOLL)
1495                         mutex_unlock(&ctx->uring_lock);
1496         }
1497
1498         return ret;
1499 }
1500
1501 static void __io_put_task(struct task_struct *task, int nr)
1502 {
1503         struct io_uring_task *tctx = task->io_uring;
1504
1505         percpu_counter_sub(&tctx->inflight, nr);
1506         if (unlikely(atomic_read(&tctx->in_idle)))
1507                 wake_up(&tctx->wait);
1508         put_task_struct_many(task, nr);
1509 }
1510
1511 /* must to be called somewhat shortly after putting a request */
1512 static inline void io_put_task(struct task_struct *task, int nr)
1513 {
1514         if (likely(task == current))
1515                 task->io_uring->cached_refs += nr;
1516         else
1517                 __io_put_task(task, nr);
1518 }
1519
1520 static void io_task_refs_refill(struct io_uring_task *tctx)
1521 {
1522         unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1523
1524         percpu_counter_add(&tctx->inflight, refill);
1525         refcount_add(refill, &current->usage);
1526         tctx->cached_refs += refill;
1527 }
1528
1529 static inline void io_get_task_refs(int nr)
1530 {
1531         struct io_uring_task *tctx = current->io_uring;
1532
1533         tctx->cached_refs -= nr;
1534         if (unlikely(tctx->cached_refs < 0))
1535                 io_task_refs_refill(tctx);
1536 }
1537
1538 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1539 {
1540         struct io_uring_task *tctx = task->io_uring;
1541         unsigned int refs = tctx->cached_refs;
1542
1543         if (refs) {
1544                 tctx->cached_refs = 0;
1545                 percpu_counter_sub(&tctx->inflight, refs);
1546                 put_task_struct_many(task, refs);
1547         }
1548 }
1549
1550 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1551                                      s32 res, u32 cflags, u64 extra1,
1552                                      u64 extra2)
1553 {
1554         struct io_overflow_cqe *ocqe;
1555         size_t ocq_size = sizeof(struct io_overflow_cqe);
1556         bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
1557
1558         if (is_cqe32)
1559                 ocq_size += sizeof(struct io_uring_cqe);
1560
1561         ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
1562         trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
1563         if (!ocqe) {
1564                 /*
1565                  * If we're in ring overflow flush mode, or in task cancel mode,
1566                  * or cannot allocate an overflow entry, then we need to drop it
1567                  * on the floor.
1568                  */
1569                 io_account_cq_overflow(ctx);
1570                 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
1571                 return false;
1572         }
1573         if (list_empty(&ctx->cq_overflow_list)) {
1574                 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
1575                 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
1576
1577         }
1578         ocqe->cqe.user_data = user_data;
1579         ocqe->cqe.res = res;
1580         ocqe->cqe.flags = cflags;
1581         if (is_cqe32) {
1582                 ocqe->cqe.big_cqe[0] = extra1;
1583                 ocqe->cqe.big_cqe[1] = extra2;
1584         }
1585         list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1586         return true;
1587 }
1588
1589 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
1590                                      struct io_kiocb *req)
1591 {
1592         struct io_uring_cqe *cqe;
1593
1594         if (!(ctx->flags & IORING_SETUP_CQE32)) {
1595                 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1596                                         req->cqe.res, req->cqe.flags, 0, 0);
1597
1598                 /*
1599                  * If we can't get a cq entry, userspace overflowed the
1600                  * submission (by quite a lot). Increment the overflow count in
1601                  * the ring.
1602                  */
1603                 cqe = io_get_cqe(ctx);
1604                 if (likely(cqe)) {
1605                         memcpy(cqe, &req->cqe, sizeof(*cqe));
1606                         return true;
1607                 }
1608
1609                 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1610                                                 req->cqe.res, req->cqe.flags,
1611                                                 0, 0);
1612         } else {
1613                 u64 extra1 = 0, extra2 = 0;
1614
1615                 if (req->flags & REQ_F_CQE32_INIT) {
1616                         extra1 = req->extra1;
1617                         extra2 = req->extra2;
1618                 }
1619
1620                 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
1621                                         req->cqe.res, req->cqe.flags, extra1, extra2);
1622
1623                 /*
1624                  * If we can't get a cq entry, userspace overflowed the
1625                  * submission (by quite a lot). Increment the overflow count in
1626                  * the ring.
1627                  */
1628                 cqe = io_get_cqe(ctx);
1629                 if (likely(cqe)) {
1630                         memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
1631                         WRITE_ONCE(cqe->big_cqe[0], extra1);
1632                         WRITE_ONCE(cqe->big_cqe[1], extra2);
1633                         return true;
1634                 }
1635
1636                 return io_cqring_event_overflow(ctx, req->cqe.user_data,
1637                                 req->cqe.res, req->cqe.flags,
1638                                 extra1, extra2);
1639         }
1640 }
1641
1642 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1643                                      s32 res, u32 cflags)
1644 {
1645         struct io_uring_cqe *cqe;
1646
1647         ctx->cq_extra++;
1648         trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
1649
1650         /*
1651          * If we can't get a cq entry, userspace overflowed the
1652          * submission (by quite a lot). Increment the overflow count in
1653          * the ring.
1654          */
1655         cqe = io_get_cqe(ctx);
1656         if (likely(cqe)) {
1657                 WRITE_ONCE(cqe->user_data, user_data);
1658                 WRITE_ONCE(cqe->res, res);
1659                 WRITE_ONCE(cqe->flags, cflags);
1660
1661                 if (ctx->flags & IORING_SETUP_CQE32) {
1662                         WRITE_ONCE(cqe->big_cqe[0], 0);
1663                         WRITE_ONCE(cqe->big_cqe[1], 0);
1664                 }
1665                 return true;
1666         }
1667         return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
1668 }
1669
1670 static void __io_req_complete_put(struct io_kiocb *req)
1671 {
1672         /*
1673          * If we're the last reference to this request, add to our locked
1674          * free_list cache.
1675          */
1676         if (req_ref_put_and_test(req)) {
1677                 struct io_ring_ctx *ctx = req->ctx;
1678
1679                 if (req->flags & IO_REQ_LINK_FLAGS) {
1680                         if (req->flags & IO_DISARM_MASK)
1681                                 io_disarm_next(req);
1682                         if (req->link) {
1683                                 io_req_task_queue(req->link);
1684                                 req->link = NULL;
1685                         }
1686                 }
1687                 io_req_put_rsrc(req);
1688                 /*
1689                  * Selected buffer deallocation in io_clean_op() assumes that
1690                  * we don't hold ->completion_lock. Clean them here to avoid
1691                  * deadlocks.
1692                  */
1693                 io_put_kbuf_comp(req);
1694                 io_dismantle_req(req);
1695                 io_put_task(req->task, 1);
1696                 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1697                 ctx->locked_free_nr++;
1698         }
1699 }
1700
1701 static void __io_req_complete_post(struct io_kiocb *req)
1702 {
1703         if (!(req->flags & REQ_F_CQE_SKIP))
1704                 __io_fill_cqe_req(req->ctx, req);
1705         __io_req_complete_put(req);
1706 }
1707
1708 static void io_req_complete_post(struct io_kiocb *req)
1709 {
1710         struct io_ring_ctx *ctx = req->ctx;
1711
1712         spin_lock(&ctx->completion_lock);
1713         __io_req_complete_post(req);
1714         io_commit_cqring(ctx);
1715         spin_unlock(&ctx->completion_lock);
1716         io_cqring_ev_posted(ctx);
1717 }
1718
1719 inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags)
1720 {
1721         if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1722                 req->flags |= REQ_F_COMPLETE_INLINE;
1723         else
1724                 io_req_complete_post(req);
1725 }
1726
1727 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1728 {
1729         req_set_fail(req);
1730         io_req_set_res(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
1731         io_req_complete_post(req);
1732 }
1733
1734 /*
1735  * Don't initialise the fields below on every allocation, but do that in
1736  * advance and keep them valid across allocations.
1737  */
1738 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1739 {
1740         req->ctx = ctx;
1741         req->link = NULL;
1742         req->async_data = NULL;
1743         /* not necessary, but safer to zero */
1744         req->cqe.res = 0;
1745 }
1746
1747 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1748                                         struct io_submit_state *state)
1749 {
1750         spin_lock(&ctx->completion_lock);
1751         wq_list_splice(&ctx->locked_free_list, &state->free_list);
1752         ctx->locked_free_nr = 0;
1753         spin_unlock(&ctx->completion_lock);
1754 }
1755
1756 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
1757 {
1758         return !ctx->submit_state.free_list.next;
1759 }
1760
1761 /*
1762  * A request might get retired back into the request caches even before opcode
1763  * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1764  * Because of that, io_alloc_req() should be called only under ->uring_lock
1765  * and with extra caution to not get a request that is still worked on.
1766  */
1767 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
1768         __must_hold(&ctx->uring_lock)
1769 {
1770         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1771         void *reqs[IO_REQ_ALLOC_BATCH];
1772         int ret, i;
1773
1774         /*
1775          * If we have more than a batch's worth of requests in our IRQ side
1776          * locked cache, grab the lock and move them over to our submission
1777          * side cache.
1778          */
1779         if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
1780                 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
1781                 if (!io_req_cache_empty(ctx))
1782                         return true;
1783         }
1784
1785         ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
1786
1787         /*
1788          * Bulk alloc is all-or-nothing. If we fail to get a batch,
1789          * retry single alloc to be on the safe side.
1790          */
1791         if (unlikely(ret <= 0)) {
1792                 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1793                 if (!reqs[0])
1794                         return false;
1795                 ret = 1;
1796         }
1797
1798         percpu_ref_get_many(&ctx->refs, ret);
1799         for (i = 0; i < ret; i++) {
1800                 struct io_kiocb *req = reqs[i];
1801
1802                 io_preinit_req(req, ctx);
1803                 io_req_add_to_cache(req, ctx);
1804         }
1805         return true;
1806 }
1807
1808 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
1809 {
1810         if (unlikely(io_req_cache_empty(ctx)))
1811                 return __io_alloc_req_refill(ctx);
1812         return true;
1813 }
1814
1815 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1816 {
1817         struct io_wq_work_node *node;
1818
1819         node = wq_stack_extract(&ctx->submit_state.free_list);
1820         return container_of(node, struct io_kiocb, comp_list);
1821 }
1822
1823 static inline void io_dismantle_req(struct io_kiocb *req)
1824 {
1825         unsigned int flags = req->flags;
1826
1827         if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
1828                 io_clean_op(req);
1829         if (!(flags & REQ_F_FIXED_FILE))
1830                 io_put_file(req->file);
1831 }
1832
1833 static __cold void io_free_req(struct io_kiocb *req)
1834 {
1835         struct io_ring_ctx *ctx = req->ctx;
1836
1837         io_req_put_rsrc(req);
1838         io_dismantle_req(req);
1839         io_put_task(req->task, 1);
1840
1841         spin_lock(&ctx->completion_lock);
1842         wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1843         ctx->locked_free_nr++;
1844         spin_unlock(&ctx->completion_lock);
1845 }
1846
1847 static inline void io_remove_next_linked(struct io_kiocb *req)
1848 {
1849         struct io_kiocb *nxt = req->link;
1850
1851         req->link = nxt->link;
1852         nxt->link = NULL;
1853 }
1854
1855 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
1856         __must_hold(&req->ctx->completion_lock)
1857         __must_hold(&req->ctx->timeout_lock)
1858 {
1859         struct io_kiocb *link = req->link;
1860
1861         if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1862                 struct io_timeout_data *io = link->async_data;
1863                 struct io_timeout *timeout = io_kiocb_to_cmd(link);
1864
1865                 io_remove_next_linked(req);
1866                 timeout->head = NULL;
1867                 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1868                         list_del(&timeout->list);
1869                         return link;
1870                 }
1871         }
1872         return NULL;
1873 }
1874
1875 static void io_fail_links(struct io_kiocb *req)
1876         __must_hold(&req->ctx->completion_lock)
1877 {
1878         struct io_kiocb *nxt, *link = req->link;
1879         bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
1880
1881         req->link = NULL;
1882         while (link) {
1883                 long res = -ECANCELED;
1884
1885                 if (link->flags & REQ_F_FAIL)
1886                         res = link->cqe.res;
1887
1888                 nxt = link->link;
1889                 link->link = NULL;
1890
1891                 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
1892                                         req->opcode, link);
1893
1894                 if (ignore_cqes)
1895                         link->flags |= REQ_F_CQE_SKIP;
1896                 else
1897                         link->flags &= ~REQ_F_CQE_SKIP;
1898                 io_req_set_res(link, res, 0);
1899                 __io_req_complete_post(link);
1900                 link = nxt;
1901         }
1902 }
1903
1904 static bool io_disarm_next(struct io_kiocb *req)
1905         __must_hold(&req->ctx->completion_lock)
1906 {
1907         struct io_kiocb *link = NULL;
1908         bool posted = false;
1909
1910         if (req->flags & REQ_F_ARM_LTIMEOUT) {
1911                 link = req->link;
1912                 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1913                 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1914                         io_remove_next_linked(req);
1915                         io_req_tw_post_queue(link, -ECANCELED, 0);
1916                         posted = true;
1917                 }
1918         } else if (req->flags & REQ_F_LINK_TIMEOUT) {
1919                 struct io_ring_ctx *ctx = req->ctx;
1920
1921                 spin_lock_irq(&ctx->timeout_lock);
1922                 link = io_disarm_linked_timeout(req);
1923                 spin_unlock_irq(&ctx->timeout_lock);
1924                 if (link) {
1925                         posted = true;
1926                         io_req_tw_post_queue(link, -ECANCELED, 0);
1927                 }
1928         }
1929         if (unlikely((req->flags & REQ_F_FAIL) &&
1930                      !(req->flags & REQ_F_HARDLINK))) {
1931                 posted |= (req->link != NULL);
1932                 io_fail_links(req);
1933         }
1934         return posted;
1935 }
1936
1937 static void __io_req_find_next_prep(struct io_kiocb *req)
1938 {
1939         struct io_ring_ctx *ctx = req->ctx;
1940         bool posted;
1941
1942         spin_lock(&ctx->completion_lock);
1943         posted = io_disarm_next(req);
1944         io_commit_cqring(ctx);
1945         spin_unlock(&ctx->completion_lock);
1946         if (posted)
1947                 io_cqring_ev_posted(ctx);
1948 }
1949
1950 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1951 {
1952         struct io_kiocb *nxt;
1953
1954         /*
1955          * If LINK is set, we have dependent requests in this chain. If we
1956          * didn't fail this request, queue the first one up, moving any other
1957          * dependencies to the next request. In case of failure, fail the rest
1958          * of the chain.
1959          */
1960         if (unlikely(req->flags & IO_DISARM_MASK))
1961                 __io_req_find_next_prep(req);
1962         nxt = req->link;
1963         req->link = NULL;
1964         return nxt;
1965 }
1966
1967 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
1968 {
1969         if (!ctx)
1970                 return;
1971         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
1972                 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
1973         if (*locked) {
1974                 io_submit_flush_completions(ctx);
1975                 mutex_unlock(&ctx->uring_lock);
1976                 *locked = false;
1977         }
1978         percpu_ref_put(&ctx->refs);
1979 }
1980
1981 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
1982 {
1983         io_commit_cqring(ctx);
1984         spin_unlock(&ctx->completion_lock);
1985         io_cqring_ev_posted(ctx);
1986 }
1987
1988 static void handle_prev_tw_list(struct io_wq_work_node *node,
1989                                 struct io_ring_ctx **ctx, bool *uring_locked)
1990 {
1991         if (*ctx && !*uring_locked)
1992                 spin_lock(&(*ctx)->completion_lock);
1993
1994         do {
1995                 struct io_wq_work_node *next = node->next;
1996                 struct io_kiocb *req = container_of(node, struct io_kiocb,
1997                                                     io_task_work.node);
1998
1999                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2000
2001                 if (req->ctx != *ctx) {
2002                         if (unlikely(!*uring_locked && *ctx))
2003                                 ctx_commit_and_unlock(*ctx);
2004
2005                         ctx_flush_and_put(*ctx, uring_locked);
2006                         *ctx = req->ctx;
2007                         /* if not contended, grab and improve batching */
2008                         *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2009                         percpu_ref_get(&(*ctx)->refs);
2010                         if (unlikely(!*uring_locked))
2011                                 spin_lock(&(*ctx)->completion_lock);
2012                 }
2013                 if (likely(*uring_locked)) {
2014                         req->io_task_work.func(req, uring_locked);
2015                 } else {
2016                         req->cqe.flags = io_put_kbuf_comp(req);
2017                         __io_req_complete_post(req);
2018                 }
2019                 node = next;
2020         } while (node);
2021
2022         if (unlikely(!*uring_locked))
2023                 ctx_commit_and_unlock(*ctx);
2024 }
2025
2026 static void handle_tw_list(struct io_wq_work_node *node,
2027                            struct io_ring_ctx **ctx, bool *locked)
2028 {
2029         do {
2030                 struct io_wq_work_node *next = node->next;
2031                 struct io_kiocb *req = container_of(node, struct io_kiocb,
2032                                                     io_task_work.node);
2033
2034                 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2035
2036                 if (req->ctx != *ctx) {
2037                         ctx_flush_and_put(*ctx, locked);
2038                         *ctx = req->ctx;
2039                         /* if not contended, grab and improve batching */
2040                         *locked = mutex_trylock(&(*ctx)->uring_lock);
2041                         percpu_ref_get(&(*ctx)->refs);
2042                 }
2043                 req->io_task_work.func(req, locked);
2044                 node = next;
2045         } while (node);
2046 }
2047
2048 static void tctx_task_work(struct callback_head *cb)
2049 {
2050         bool uring_locked = false;
2051         struct io_ring_ctx *ctx = NULL;
2052         struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2053                                                   task_work);
2054
2055         while (1) {
2056                 struct io_wq_work_node *node1, *node2;
2057
2058                 spin_lock_irq(&tctx->task_lock);
2059                 node1 = tctx->prio_task_list.first;
2060                 node2 = tctx->task_list.first;
2061                 INIT_WQ_LIST(&tctx->task_list);
2062                 INIT_WQ_LIST(&tctx->prio_task_list);
2063                 if (!node2 && !node1)
2064                         tctx->task_running = false;
2065                 spin_unlock_irq(&tctx->task_lock);
2066                 if (!node2 && !node1)
2067                         break;
2068
2069                 if (node1)
2070                         handle_prev_tw_list(node1, &ctx, &uring_locked);
2071                 if (node2)
2072                         handle_tw_list(node2, &ctx, &uring_locked);
2073                 cond_resched();
2074
2075                 if (data_race(!tctx->task_list.first) &&
2076                     data_race(!tctx->prio_task_list.first) && uring_locked)
2077                         io_submit_flush_completions(ctx);
2078         }
2079
2080         ctx_flush_and_put(ctx, &uring_locked);
2081
2082         /* relaxed read is enough as only the task itself sets ->in_idle */
2083         if (unlikely(atomic_read(&tctx->in_idle)))
2084                 io_uring_drop_tctx_refs(current);
2085 }
2086
2087 static void __io_req_task_work_add(struct io_kiocb *req,
2088                                    struct io_uring_task *tctx,
2089                                    struct io_wq_work_list *list)
2090 {
2091         struct io_ring_ctx *ctx = req->ctx;
2092         struct io_wq_work_node *node;
2093         unsigned long flags;
2094         bool running;
2095
2096         spin_lock_irqsave(&tctx->task_lock, flags);
2097         wq_list_add_tail(&req->io_task_work.node, list);
2098         running = tctx->task_running;
2099         if (!running)
2100                 tctx->task_running = true;
2101         spin_unlock_irqrestore(&tctx->task_lock, flags);
2102
2103         /* task_work already pending, we're done */
2104         if (running)
2105                 return;
2106
2107         if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2108                 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2109
2110         if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2111                 return;
2112
2113         spin_lock_irqsave(&tctx->task_lock, flags);
2114         tctx->task_running = false;
2115         node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2116         spin_unlock_irqrestore(&tctx->task_lock, flags);
2117
2118         while (node) {
2119                 req = container_of(node, struct io_kiocb, io_task_work.node);
2120                 node = node->next;
2121                 if (llist_add(&req->io_task_work.fallback_node,
2122                               &req->ctx->fallback_llist))
2123                         schedule_delayed_work(&req->ctx->fallback_work, 1);
2124         }
2125 }
2126
2127 void io_req_task_work_add(struct io_kiocb *req)
2128 {
2129         struct io_uring_task *tctx = req->task->io_uring;
2130
2131         __io_req_task_work_add(req, tctx, &tctx->task_list);
2132 }
2133
2134 static void io_req_task_prio_work_add(struct io_kiocb *req)
2135 {
2136         struct io_uring_task *tctx = req->task->io_uring;
2137
2138         if (req->ctx->flags & IORING_SETUP_SQPOLL)
2139                 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2140         else
2141                 __io_req_task_work_add(req, tctx, &tctx->task_list);
2142 }
2143
2144 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2145 {
2146         io_req_complete_post(req);
2147 }
2148
2149 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2150 {
2151         io_req_set_res(req, res, cflags);
2152         req->io_task_work.func = io_req_tw_post;
2153         io_req_task_work_add(req);
2154 }
2155
2156 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2157 {
2158         /* not needed for normal modes, but SQPOLL depends on it */
2159         io_tw_lock(req->ctx, locked);
2160         io_req_complete_failed(req, req->cqe.res);
2161 }
2162
2163 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2164 {
2165         io_tw_lock(req->ctx, locked);
2166         /* req->task == current here, checking PF_EXITING is safe */
2167         if (likely(!(req->task->flags & PF_EXITING)))
2168                 io_queue_sqe(req);
2169         else
2170                 io_req_complete_failed(req, -EFAULT);
2171 }
2172
2173 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2174 {
2175         io_req_set_res(req, ret, 0);
2176         req->io_task_work.func = io_req_task_cancel;
2177         io_req_task_work_add(req);
2178 }
2179
2180 static void io_req_task_queue(struct io_kiocb *req)
2181 {
2182         req->io_task_work.func = io_req_task_submit;
2183         io_req_task_work_add(req);
2184 }
2185
2186 static void io_req_task_queue_reissue(struct io_kiocb *req)
2187 {
2188         req->io_task_work.func = io_queue_iowq;
2189         io_req_task_work_add(req);
2190 }
2191
2192 static void io_queue_next(struct io_kiocb *req)
2193 {
2194         struct io_kiocb *nxt = io_req_find_next(req);
2195
2196         if (nxt)
2197                 io_req_task_queue(nxt);
2198 }
2199
2200 static void io_free_batch_list(struct io_ring_ctx *ctx,
2201                                 struct io_wq_work_node *node)
2202         __must_hold(&ctx->uring_lock)
2203 {
2204         struct task_struct *task = NULL;
2205         int task_refs = 0;
2206
2207         do {
2208                 struct io_kiocb *req = container_of(node, struct io_kiocb,
2209                                                     comp_list);
2210
2211                 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2212                         if (req->flags & REQ_F_REFCOUNT) {
2213                                 node = req->comp_list.next;
2214                                 if (!req_ref_put_and_test(req))
2215                                         continue;
2216                         }
2217                         if ((req->flags & REQ_F_POLLED) && req->apoll) {
2218                                 struct async_poll *apoll = req->apoll;
2219
2220                                 if (apoll->double_poll)
2221                                         kfree(apoll->double_poll);
2222                                 list_add(&apoll->poll.wait.entry,
2223                                                 &ctx->apoll_cache);
2224                                 req->flags &= ~REQ_F_POLLED;
2225                         }
2226                         if (req->flags & IO_REQ_LINK_FLAGS)
2227                                 io_queue_next(req);
2228                         if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2229                                 io_clean_op(req);
2230                 }
2231                 if (!(req->flags & REQ_F_FIXED_FILE))
2232                         io_put_file(req->file);
2233
2234                 io_req_put_rsrc_locked(req, ctx);
2235
2236                 if (req->task != task) {
2237                         if (task)
2238                                 io_put_task(task, task_refs);
2239                         task = req->task;
2240                         task_refs = 0;
2241                 }
2242                 task_refs++;
2243                 node = req->comp_list.next;
2244                 io_req_add_to_cache(req, ctx);
2245         } while (node);
2246
2247         if (task)
2248                 io_put_task(task, task_refs);
2249 }
2250
2251 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2252         __must_hold(&ctx->uring_lock)
2253 {
2254         struct io_wq_work_node *node, *prev;
2255         struct io_submit_state *state = &ctx->submit_state;
2256
2257         if (state->flush_cqes) {
2258                 spin_lock(&ctx->completion_lock);
2259                 wq_list_for_each(node, prev, &state->compl_reqs) {
2260                         struct io_kiocb *req = container_of(node, struct io_kiocb,
2261                                                     comp_list);
2262
2263                         if (!(req->flags & REQ_F_CQE_SKIP))
2264                                 __io_fill_cqe_req(ctx, req);
2265                 }
2266
2267                 io_commit_cqring(ctx);
2268                 spin_unlock(&ctx->completion_lock);
2269                 io_cqring_ev_posted(ctx);
2270                 state->flush_cqes = false;
2271         }
2272
2273         io_free_batch_list(ctx, state->compl_reqs.first);
2274         INIT_WQ_LIST(&state->compl_reqs);
2275 }
2276
2277 /*
2278  * Drop reference to request, return next in chain (if there is one) if this
2279  * was the last reference to this request.
2280  */
2281 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2282 {
2283         struct io_kiocb *nxt = NULL;
2284
2285         if (req_ref_put_and_test(req)) {
2286                 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2287                         nxt = io_req_find_next(req);
2288                 io_free_req(req);
2289         }
2290         return nxt;
2291 }
2292
2293 static inline void io_put_req(struct io_kiocb *req)
2294 {
2295         if (req_ref_put_and_test(req)) {
2296                 io_queue_next(req);
2297                 io_free_req(req);
2298         }
2299 }
2300
2301 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2302 {
2303         /* See comment at the top of this file */
2304         smp_rmb();
2305         return __io_cqring_events(ctx);
2306 }
2307
2308 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2309 {
2310         struct io_rings *rings = ctx->rings;
2311
2312         /* make sure SQ entry isn't read before tail */
2313         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2314 }
2315
2316 static inline bool io_run_task_work(void)
2317 {
2318         if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2319                 __set_current_state(TASK_RUNNING);
2320                 clear_notify_signal();
2321                 if (task_work_pending(current))
2322                         task_work_run();
2323                 return true;
2324         }
2325
2326         return false;
2327 }
2328
2329 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2330 {
2331         struct io_wq_work_node *pos, *start, *prev;
2332         unsigned int poll_flags = BLK_POLL_NOSLEEP;
2333         DEFINE_IO_COMP_BATCH(iob);
2334         int nr_events = 0;
2335
2336         /*
2337          * Only spin for completions if we don't have multiple devices hanging
2338          * off our complete list.
2339          */
2340         if (ctx->poll_multi_queue || force_nonspin)
2341                 poll_flags |= BLK_POLL_ONESHOT;
2342
2343         wq_list_for_each(pos, start, &ctx->iopoll_list) {
2344                 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2345                 struct io_rw *rw = io_kiocb_to_cmd(req);
2346                 int ret;
2347
2348                 /*
2349                  * Move completed and retryable entries to our local lists.
2350                  * If we find a request that requires polling, break out
2351                  * and complete those lists first, if we have entries there.
2352                  */
2353                 if (READ_ONCE(req->iopoll_completed))
2354                         break;
2355
2356                 ret = rw->kiocb.ki_filp->f_op->iopoll(&rw->kiocb, &iob, poll_flags);
2357                 if (unlikely(ret < 0))
2358                         return ret;
2359                 else if (ret)
2360                         poll_flags |= BLK_POLL_ONESHOT;
2361
2362                 /* iopoll may have completed current req */
2363                 if (!rq_list_empty(iob.req_list) ||
2364                     READ_ONCE(req->iopoll_completed))
2365                         break;
2366         }
2367
2368         if (!rq_list_empty(iob.req_list))
2369                 iob.complete(&iob);
2370         else if (!pos)
2371                 return 0;
2372
2373         prev = start;
2374         wq_list_for_each_resume(pos, prev) {
2375                 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2376
2377                 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2378                 if (!smp_load_acquire(&req->iopoll_completed))
2379                         break;
2380                 nr_events++;
2381                 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2382                         continue;
2383
2384                 req->cqe.flags = io_put_kbuf(req, 0);
2385                 __io_fill_cqe_req(req->ctx, req);
2386         }
2387
2388         if (unlikely(!nr_events))
2389                 return 0;
2390
2391         io_commit_cqring(ctx);
2392         io_cqring_ev_posted_iopoll(ctx);
2393         pos = start ? start->next : ctx->iopoll_list.first;
2394         wq_list_cut(&ctx->iopoll_list, prev, start);
2395         io_free_batch_list(ctx, pos);
2396         return nr_events;
2397 }
2398
2399 /*
2400  * We can't just wait for polled events to come to us, we have to actively
2401  * find and complete them.
2402  */
2403 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2404 {
2405         if (!(ctx->flags & IORING_SETUP_IOPOLL))
2406                 return;
2407
2408         mutex_lock(&ctx->uring_lock);
2409         while (!wq_list_empty(&ctx->iopoll_list)) {
2410                 /* let it sleep and repeat later if can't complete a request */
2411                 if (io_do_iopoll(ctx, true) == 0)
2412                         break;
2413                 /*
2414                  * Ensure we allow local-to-the-cpu processing to take place,
2415                  * in this case we need to ensure that we reap all events.
2416                  * Also let task_work, etc. to progress by releasing the mutex
2417                  */
2418                 if (need_resched()) {
2419                         mutex_unlock(&ctx->uring_lock);
2420                         cond_resched();
2421                         mutex_lock(&ctx->uring_lock);
2422                 }
2423         }
2424         mutex_unlock(&ctx->uring_lock);
2425 }
2426
2427 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2428 {
2429         unsigned int nr_events = 0;
2430         int ret = 0;
2431         unsigned long check_cq;
2432
2433         /*
2434          * Don't enter poll loop if we already have events pending.
2435          * If we do, we can potentially be spinning for commands that
2436          * already triggered a CQE (eg in error).
2437          */
2438         check_cq = READ_ONCE(ctx->check_cq);
2439         if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
2440                 __io_cqring_overflow_flush(ctx, false);
2441         if (io_cqring_events(ctx))
2442                 return 0;
2443
2444         /*
2445          * Similarly do not spin if we have not informed the user of any
2446          * dropped CQE.
2447          */
2448         if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
2449                 return -EBADR;
2450
2451         do {
2452                 /*
2453                  * If a submit got punted to a workqueue, we can have the
2454                  * application entering polling for a command before it gets
2455                  * issued. That app will hold the uring_lock for the duration
2456                  * of the poll right here, so we need to take a breather every
2457                  * now and then to ensure that the issue has a chance to add
2458                  * the poll to the issued list. Otherwise we can spin here
2459                  * forever, while the workqueue is stuck trying to acquire the
2460                  * very same mutex.
2461                  */
2462                 if (wq_list_empty(&ctx->iopoll_list)) {
2463                         u32 tail = ctx->cached_cq_tail;
2464
2465                         mutex_unlock(&ctx->uring_lock);
2466                         io_run_task_work();
2467                         mutex_lock(&ctx->uring_lock);
2468
2469                         /* some requests don't go through iopoll_list */
2470                         if (tail != ctx->cached_cq_tail ||
2471                             wq_list_empty(&ctx->iopoll_list))
2472                                 break;
2473                 }
2474                 ret = io_do_iopoll(ctx, !min);
2475                 if (ret < 0)
2476                         break;
2477                 nr_events += ret;
2478                 ret = 0;
2479         } while (nr_events < min && !need_resched());
2480
2481         return ret;
2482 }
2483
2484 static void kiocb_end_write(struct io_kiocb *req)
2485 {
2486         /*
2487          * Tell lockdep we inherited freeze protection from submission
2488          * thread.
2489          */
2490         if (req->flags & REQ_F_ISREG) {
2491                 struct super_block *sb = file_inode(req->file)->i_sb;
2492
2493                 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2494                 sb_end_write(sb);
2495         }
2496 }
2497
2498 #ifdef CONFIG_BLOCK
2499 static bool io_resubmit_prep(struct io_kiocb *req)
2500 {
2501         struct io_async_rw *io = req->async_data;
2502
2503         if (!req_has_async_data(req))
2504                 return !io_req_prep_async(req);
2505         iov_iter_restore(&io->s.iter, &io->s.iter_state);
2506         return true;
2507 }
2508
2509 static bool io_rw_should_reissue(struct io_kiocb *req)
2510 {
2511         umode_t mode = file_inode(req->file)->i_mode;
2512         struct io_ring_ctx *ctx = req->ctx;
2513
2514         if (!S_ISBLK(mode) && !S_ISREG(mode))
2515                 return false;
2516         if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2517             !(ctx->flags & IORING_SETUP_IOPOLL)))
2518                 return false;
2519         /*
2520          * If ref is dying, we might be running poll reap from the exit work.
2521          * Don't attempt to reissue from that path, just let it fail with
2522          * -EAGAIN.
2523          */
2524         if (percpu_ref_is_dying(&ctx->refs))
2525                 return false;
2526         /*
2527          * Play it safe and assume not safe to re-import and reissue if we're
2528          * not in the original thread group (or in task context).
2529          */
2530         if (!same_thread_group(req->task, current) || !in_task())
2531                 return false;
2532         return true;
2533 }
2534 #else
2535 static bool io_resubmit_prep(struct io_kiocb *req)
2536 {
2537         return false;
2538 }
2539 static bool io_rw_should_reissue(struct io_kiocb *req)
2540 {
2541         return false;
2542 }
2543 #endif
2544
2545 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2546 {
2547         struct io_rw *rw = io_kiocb_to_cmd(req);
2548
2549         if (rw->kiocb.ki_flags & IOCB_WRITE) {
2550                 kiocb_end_write(req);
2551                 fsnotify_modify(req->file);
2552         } else {
2553                 fsnotify_access(req->file);
2554         }
2555         if (unlikely(res != req->cqe.res)) {
2556                 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2557                     io_rw_should_reissue(req)) {
2558                         req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2559                         return true;
2560                 }
2561                 req_set_fail(req);
2562                 req->cqe.res = res;
2563         }
2564         return false;
2565 }
2566
2567 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2568 {
2569         if (*locked) {
2570                 req->cqe.flags |= io_put_kbuf(req, 0);
2571                 req->flags |= REQ_F_COMPLETE_INLINE;
2572                 io_req_add_compl_list(req);
2573         } else {
2574                 req->cqe.flags |= io_put_kbuf(req, IO_URING_F_UNLOCKED);
2575                 io_req_complete_post(req);
2576         }
2577 }
2578
2579 static void __io_complete_rw(struct io_kiocb *req, long res,
2580                              unsigned int issue_flags)
2581 {
2582         if (__io_complete_rw_common(req, res))
2583                 return;
2584         io_req_set_res(req, req->cqe.res, io_put_kbuf(req, issue_flags));
2585         __io_req_complete(req, issue_flags);
2586 }
2587
2588 static void io_complete_rw(struct kiocb *kiocb, long res)
2589 {
2590         struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
2591         struct io_kiocb *req = cmd_to_io_kiocb(rw);
2592
2593         if (__io_complete_rw_common(req, res))
2594                 return;
2595         io_req_set_res(req, res, 0);
2596         req->io_task_work.func = io_req_task_complete;
2597         io_req_task_prio_work_add(req);
2598 }
2599
2600 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
2601 {
2602         struct io_rw *rw = container_of(kiocb, struct io_rw, kiocb);
2603         struct io_kiocb *req = cmd_to_io_kiocb(rw);
2604
2605         if (kiocb->ki_flags & IOCB_WRITE)
2606                 kiocb_end_write(req);
2607         if (unlikely(res != req->cqe.res)) {
2608                 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2609                         req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
2610                         return;
2611                 }
2612                 req->cqe.res = res;
2613         }
2614
2615         /* order with io_iopoll_complete() checking ->iopoll_completed */
2616         smp_store_release(&req->iopoll_completed, 1);
2617 }
2618
2619 /*
2620  * After the iocb has been issued, it's safe to be found on the poll list.
2621  * Adding the kiocb to the list AFTER submission ensures that we don't
2622  * find it from a io_do_iopoll() thread before the issuer is done
2623  * accessing the kiocb cookie.
2624  */
2625 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2626 {
2627         struct io_ring_ctx *ctx = req->ctx;
2628         const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2629
2630         /* workqueue context doesn't hold uring_lock, grab it now */
2631         if (unlikely(needs_lock))
2632                 mutex_lock(&ctx->uring_lock);
2633
2634         /*
2635          * Track whether we have multiple files in our lists. This will impact
2636          * how we do polling eventually, not spinning if we're on potentially
2637          * different devices.
2638          */
2639         if (wq_list_empty(&ctx->iopoll_list)) {
2640                 ctx->poll_multi_queue = false;
2641         } else if (!ctx->poll_multi_queue) {
2642                 struct io_kiocb *list_req;
2643
2644                 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2645                                         comp_list);
2646                 if (list_req->file != req->file)
2647                         ctx->poll_multi_queue = true;
2648         }
2649
2650         /*
2651          * For fast devices, IO may have already completed. If it has, add
2652          * it to the front so we find it first.
2653          */
2654         if (READ_ONCE(req->iopoll_completed))
2655                 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2656         else
2657                 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2658
2659         if (unlikely(needs_lock)) {
2660                 /*
2661                  * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2662                  * in sq thread task context or in io worker task context. If
2663                  * current task context is sq thread, we don't need to check
2664                  * whether should wake up sq thread.
2665                  */
2666                 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2667                     wq_has_sleeper(&ctx->sq_data->wait))
2668                         wake_up(&ctx->sq_data->wait);
2669
2670                 mutex_unlock(&ctx->uring_lock);
2671         }
2672 }
2673
2674 static bool io_bdev_nowait(struct block_device *bdev)
2675 {
2676         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2677 }
2678
2679 /*
2680  * If we tracked the file through the SCM inflight mechanism, we could support
2681  * any file. For now, just ensure that anything potentially problematic is done
2682  * inline.
2683  */
2684 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2685 {
2686         if (S_ISBLK(mode)) {
2687                 if (IS_ENABLED(CONFIG_BLOCK) &&
2688                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2689                         return true;
2690                 return false;
2691         }
2692         if (S_ISSOCK(mode))
2693                 return true;
2694         if (S_ISREG(mode)) {
2695                 if (IS_ENABLED(CONFIG_BLOCK) &&
2696                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2697                     file->f_op != &io_uring_fops)
2698                         return true;
2699                 return false;
2700         }
2701
2702         /* any ->read/write should understand O_NONBLOCK */
2703         if (file->f_flags & O_NONBLOCK)
2704                 return true;
2705         return file->f_mode & FMODE_NOWAIT;
2706 }
2707
2708 /*
2709  * If we tracked the file through the SCM inflight mechanism, we could support
2710  * any file. For now, just ensure that anything potentially problematic is done
2711  * inline.
2712  */
2713 static unsigned int io_file_get_flags(struct file *file)
2714 {
2715         umode_t mode = file_inode(file)->i_mode;
2716         unsigned int res = 0;
2717
2718         if (S_ISREG(mode))
2719                 res |= FFS_ISREG;
2720         if (__io_file_supports_nowait(file, mode))
2721                 res |= FFS_NOWAIT;
2722         if (io_file_need_scm(file))
2723                 res |= FFS_SCM;
2724         return res;
2725 }
2726
2727 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2728 {
2729         return req->flags & REQ_F_SUPPORT_NOWAIT;
2730 }
2731
2732 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2733 {
2734         struct io_rw *rw = io_kiocb_to_cmd(req);
2735         unsigned ioprio;
2736         int ret;
2737
2738         rw->kiocb.ki_pos = READ_ONCE(sqe->off);
2739         /* used for fixed read/write too - just read unconditionally */
2740         req->buf_index = READ_ONCE(sqe->buf_index);
2741
2742         if (req->opcode == IORING_OP_READ_FIXED ||
2743             req->opcode == IORING_OP_WRITE_FIXED) {
2744                 struct io_ring_ctx *ctx = req->ctx;
2745                 u16 index;
2746
2747                 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2748                         return -EFAULT;
2749                 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2750                 req->imu = ctx->user_bufs[index];
2751                 io_req_set_rsrc_node(req, ctx, 0);
2752         }
2753
2754         ioprio = READ_ONCE(sqe->ioprio);
2755         if (ioprio) {
2756                 ret = ioprio_check_cap(ioprio);
2757                 if (ret)
2758                         return ret;
2759
2760                 rw->kiocb.ki_ioprio = ioprio;
2761         } else {
2762                 rw->kiocb.ki_ioprio = get_current_ioprio();
2763         }
2764
2765         rw->addr = READ_ONCE(sqe->addr);
2766         rw->len = READ_ONCE(sqe->len);
2767         rw->flags = READ_ONCE(sqe->rw_flags);
2768         return 0;
2769 }
2770
2771 static void io_readv_writev_cleanup(struct io_kiocb *req)
2772 {
2773         struct io_async_rw *io = req->async_data;
2774
2775         kfree(io->free_iovec);
2776 }
2777
2778 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2779 {
2780         switch (ret) {
2781         case -EIOCBQUEUED:
2782                 break;
2783         case -ERESTARTSYS:
2784         case -ERESTARTNOINTR:
2785         case -ERESTARTNOHAND:
2786         case -ERESTART_RESTARTBLOCK:
2787                 /*
2788                  * We can't just restart the syscall, since previously
2789                  * submitted sqes may already be in progress. Just fail this
2790                  * IO with EINTR.
2791                  */
2792                 ret = -EINTR;
2793                 fallthrough;
2794         default:
2795                 kiocb->ki_complete(kiocb, ret);
2796         }
2797 }
2798
2799 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
2800 {
2801         struct io_rw *rw = io_kiocb_to_cmd(req);
2802
2803         if (rw->kiocb.ki_pos != -1)
2804                 return &rw->kiocb.ki_pos;
2805
2806         if (!(req->file->f_mode & FMODE_STREAM)) {
2807                 req->flags |= REQ_F_CUR_POS;
2808                 rw->kiocb.ki_pos = req->file->f_pos;
2809                 return &rw->kiocb.ki_pos;
2810         }
2811
2812         rw->kiocb.ki_pos = 0;
2813         return NULL;
2814 }
2815
2816 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
2817                        unsigned int issue_flags)
2818 {
2819         struct io_async_rw *io = req->async_data;
2820         struct io_rw *rw = io_kiocb_to_cmd(req);
2821
2822         /* add previously done IO, if any */
2823         if (req_has_async_data(req) && io->bytes_done > 0) {
2824                 if (ret < 0)
2825                         ret = io->bytes_done;
2826                 else
2827                         ret += io->bytes_done;
2828         }
2829
2830         if (req->flags & REQ_F_CUR_POS)
2831                 req->file->f_pos = rw->kiocb.ki_pos;
2832         if (ret >= 0 && (rw->kiocb.ki_complete == io_complete_rw))
2833                 __io_complete_rw(req, ret, issue_flags);
2834         else
2835                 io_rw_done(&rw->kiocb, ret);
2836
2837         if (req->flags & REQ_F_REISSUE) {
2838                 req->flags &= ~REQ_F_REISSUE;
2839                 if (io_resubmit_prep(req))
2840                         io_req_task_queue_reissue(req);
2841                 else
2842                         io_req_task_queue_fail(req, ret);
2843         }
2844 }
2845
2846 static int __io_import_fixed(struct io_kiocb *req, int ddir,
2847                              struct iov_iter *iter, struct io_mapped_ubuf *imu)
2848 {
2849         struct io_rw *rw = io_kiocb_to_cmd(req);
2850         size_t len = rw->len;
2851         u64 buf_end, buf_addr = rw->addr;
2852         size_t offset;
2853
2854         if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2855                 return -EFAULT;
2856         /* not inside the mapped region */
2857         if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2858                 return -EFAULT;
2859
2860         /*
2861          * May not be a start of buffer, set size appropriately
2862          * and advance us to the beginning.
2863          */
2864         offset = buf_addr - imu->ubuf;
2865         iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
2866
2867         if (offset) {
2868                 /*
2869                  * Don't use iov_iter_advance() here, as it's really slow for
2870                  * using the latter parts of a big fixed buffer - it iterates
2871                  * over each segment manually. We can cheat a bit here, because
2872                  * we know that:
2873                  *
2874                  * 1) it's a BVEC iter, we set it up
2875                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2876                  *    first and last bvec
2877                  *
2878                  * So just find our index, and adjust the iterator afterwards.
2879                  * If the offset is within the first bvec (or the whole first
2880                  * bvec, just use iov_iter_advance(). This makes it easier
2881                  * since we can just skip the first segment, which may not
2882                  * be PAGE_SIZE aligned.
2883                  */
2884                 const struct bio_vec *bvec = imu->bvec;
2885
2886                 if (offset <= bvec->bv_len) {
2887                         iov_iter_advance(iter, offset);
2888                 } else {
2889                         unsigned long seg_skip;
2890
2891                         /* skip first vec */
2892                         offset -= bvec->bv_len;
2893                         seg_skip = 1 + (offset >> PAGE_SHIFT);
2894
2895                         iter->bvec = bvec + seg_skip;
2896                         iter->nr_segs -= seg_skip;
2897                         iter->count -= bvec->bv_len + offset;
2898                         iter->iov_offset = offset & ~PAGE_MASK;
2899                 }
2900         }
2901
2902         return 0;
2903 }
2904
2905 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2906                            unsigned int issue_flags)
2907 {
2908         if (WARN_ON_ONCE(!req->imu))
2909                 return -EFAULT;
2910         return __io_import_fixed(req, rw, iter, req->imu);
2911 }
2912
2913 static int io_buffer_add_list(struct io_ring_ctx *ctx,
2914                               struct io_buffer_list *bl, unsigned int bgid)
2915 {
2916         bl->bgid = bgid;
2917         if (bgid < BGID_ARRAY)
2918                 return 0;
2919
2920         return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
2921 }
2922
2923 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
2924                                               struct io_buffer_list *bl)
2925 {
2926         if (!list_empty(&bl->buf_list)) {
2927                 struct io_buffer *kbuf;
2928
2929                 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
2930                 list_del(&kbuf->list);
2931                 if (*len > kbuf->len)
2932                         *len = kbuf->len;
2933                 req->flags |= REQ_F_BUFFER_SELECTED;
2934                 req->kbuf = kbuf;
2935                 req->buf_index = kbuf->bid;
2936                 return u64_to_user_ptr(kbuf->addr);
2937         }
2938         return NULL;
2939 }
2940
2941 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
2942                                           struct io_buffer_list *bl,
2943                                           unsigned int issue_flags)
2944 {
2945         struct io_uring_buf_ring *br = bl->buf_ring;
2946         struct io_uring_buf *buf;
2947         __u16 head = bl->head;
2948
2949         if (unlikely(smp_load_acquire(&br->tail) == head))
2950                 return NULL;
2951
2952         head &= bl->mask;
2953         if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
2954                 buf = &br->bufs[head];
2955         } else {
2956                 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
2957                 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
2958                 buf = page_address(bl->buf_pages[index]);
2959                 buf += off;
2960         }
2961         if (*len > buf->len)
2962                 *len = buf->len;
2963         req->flags |= REQ_F_BUFFER_RING;
2964         req->buf_list = bl;
2965         req->buf_index = buf->bid;
2966
2967         if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
2968                 /*
2969                  * If we came in unlocked, we have no choice but to consume the
2970                  * buffer here. This does mean it'll be pinned until the IO
2971                  * completes. But coming in unlocked means we're in io-wq
2972                  * context, hence there should be no further retry. For the
2973                  * locked case, the caller must ensure to call the commit when
2974                  * the transfer completes (or if we get -EAGAIN and must poll
2975                  * or retry).
2976                  */
2977                 req->buf_list = NULL;
2978                 bl->head++;
2979         }
2980         return u64_to_user_ptr(buf->addr);
2981 }
2982
2983 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
2984                                      unsigned int issue_flags)
2985 {
2986         struct io_ring_ctx *ctx = req->ctx;
2987         struct io_buffer_list *bl;
2988         void __user *ret = NULL;
2989
2990         io_ring_submit_lock(req->ctx, issue_flags);
2991
2992         bl = io_buffer_get_list(ctx, req->buf_index);
2993         if (likely(bl)) {
2994                 if (bl->buf_nr_pages)
2995                         ret = io_ring_buffer_select(req, len, bl, issue_flags);
2996                 else
2997                         ret = io_provided_buffer_select(req, len, bl);
2998         }
2999         io_ring_submit_unlock(req->ctx, issue_flags);
3000         return ret;
3001 }
3002
3003 #ifdef CONFIG_COMPAT
3004 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3005                                 unsigned int issue_flags)
3006 {
3007         struct io_rw *rw = io_kiocb_to_cmd(req);
3008         struct compat_iovec __user *uiov;
3009         compat_ssize_t clen;
3010         void __user *buf;
3011         size_t len;
3012
3013         uiov = u64_to_user_ptr(rw->addr);
3014         if (!access_ok(uiov, sizeof(*uiov)))
3015                 return -EFAULT;
3016         if (__get_user(clen, &uiov->iov_len))
3017                 return -EFAULT;
3018         if (clen < 0)
3019                 return -EINVAL;
3020
3021         len = clen;
3022         buf = io_buffer_select(req, &len, issue_flags);
3023         if (!buf)
3024                 return -ENOBUFS;
3025         rw->addr = (unsigned long) buf;
3026         iov[0].iov_base = buf;
3027         rw->len = iov[0].iov_len = (compat_size_t) len;
3028         return 0;
3029 }
3030 #endif
3031
3032 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3033                                       unsigned int issue_flags)
3034 {
3035         struct io_rw *rw = io_kiocb_to_cmd(req);
3036         struct iovec __user *uiov = u64_to_user_ptr(rw->addr);
3037         void __user *buf;
3038         ssize_t len;
3039
3040         if (copy_from_user(iov, uiov, sizeof(*uiov)))
3041                 return -EFAULT;
3042
3043         len = iov[0].iov_len;
3044         if (len < 0)
3045                 return -EINVAL;
3046         buf = io_buffer_select(req, &len, issue_flags);
3047         if (!buf)
3048                 return -ENOBUFS;
3049         rw->addr = (unsigned long) buf;
3050         iov[0].iov_base = buf;
3051         rw->len = iov[0].iov_len = len;
3052         return 0;
3053 }
3054
3055 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3056                                     unsigned int issue_flags)
3057 {
3058         struct io_rw *rw = io_kiocb_to_cmd(req);
3059
3060         if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3061                 iov[0].iov_base = u64_to_user_ptr(rw->addr);
3062                 iov[0].iov_len = rw->len;
3063                 return 0;
3064         }
3065         if (rw->len != 1)
3066                 return -EINVAL;
3067
3068 #ifdef CONFIG_COMPAT
3069         if (req->ctx->compat)
3070                 return io_compat_import(req, iov, issue_flags);
3071 #endif
3072
3073         return __io_iov_buffer_select(req, iov, issue_flags);
3074 }
3075
3076 static inline bool io_do_buffer_select(struct io_kiocb *req)
3077 {
3078         if (!(req->flags & REQ_F_BUFFER_SELECT))
3079                 return false;
3080         return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3081 }
3082
3083 static struct iovec *__io_import_iovec(int ddir, struct io_kiocb *req,
3084                                        struct io_rw_state *s,
3085                                        unsigned int issue_flags)
3086 {
3087         struct io_rw *rw = io_kiocb_to_cmd(req);
3088         struct iov_iter *iter = &s->iter;
3089         u8 opcode = req->opcode;
3090         struct iovec *iovec;
3091         void __user *buf;
3092         size_t sqe_len;
3093         ssize_t ret;
3094
3095         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3096                 ret = io_import_fixed(req, ddir, iter, issue_flags);
3097                 if (ret)
3098                         return ERR_PTR(ret);
3099                 return NULL;
3100         }
3101
3102         buf = u64_to_user_ptr(rw->addr);
3103         sqe_len = rw->len;
3104
3105         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3106                 if (io_do_buffer_select(req)) {
3107                         buf = io_buffer_select(req, &sqe_len, issue_flags);
3108                         if (!buf)
3109                                 return ERR_PTR(-ENOBUFS);
3110                         rw->addr = (unsigned long) buf;
3111                         rw->len = sqe_len;
3112                 }
3113
3114                 ret = import_single_range(ddir, buf, sqe_len, s->fast_iov, iter);
3115                 if (ret)
3116                         return ERR_PTR(ret);
3117                 return NULL;
3118         }
3119
3120         iovec = s->fast_iov;
3121         if (req->flags & REQ_F_BUFFER_SELECT) {
3122                 ret = io_iov_buffer_select(req, iovec, issue_flags);
3123                 if (ret)
3124                         return ERR_PTR(ret);
3125                 iov_iter_init(iter, ddir, iovec, 1, iovec->iov_len);
3126                 return NULL;
3127         }
3128
3129         ret = __import_iovec(ddir, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3130                               req->ctx->compat);
3131         if (unlikely(ret < 0))
3132                 return ERR_PTR(ret);
3133         return iovec;
3134 }
3135
3136 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3137                                   struct iovec **iovec, struct io_rw_state *s,
3138                                   unsigned int issue_flags)
3139 {
3140         *iovec = __io_import_iovec(rw, req, s, issue_flags);
3141         if (unlikely(IS_ERR(*iovec)))
3142                 return PTR_ERR(*iovec);
3143
3144         iov_iter_save_state(&s->iter, &s->iter_state);
3145         return 0;
3146 }
3147
3148 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3149 {
3150         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3151 }
3152
3153 /*
3154  * For files that don't have ->read_iter() and ->write_iter(), handle them
3155  * by looping over ->read() or ->write() manually.
3156  */
3157 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
3158 {
3159         struct kiocb *kiocb = &rw->kiocb;
3160         struct file *file = kiocb->ki_filp;
3161         ssize_t ret = 0;
3162         loff_t *ppos;
3163
3164         /*
3165          * Don't support polled IO through this interface, and we can't
3166          * support non-blocking either. For the latter, this just causes
3167          * the kiocb to be handled from an async context.
3168          */
3169         if (kiocb->ki_flags & IOCB_HIPRI)
3170                 return -EOPNOTSUPP;
3171         if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3172             !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3173                 return -EAGAIN;
3174
3175         ppos = io_kiocb_ppos(kiocb);
3176
3177         while (iov_iter_count(iter)) {
3178                 struct iovec iovec;
3179                 ssize_t nr;
3180
3181                 if (!iov_iter_is_bvec(iter)) {
3182                         iovec = iov_iter_iovec(iter);
3183                 } else {
3184                         iovec.iov_base = u64_to_user_ptr(rw->addr);
3185                         iovec.iov_len = rw->len;
3186                 }
3187
3188                 if (ddir == READ) {
3189                         nr = file->f_op->read(file, iovec.iov_base,
3190                                               iovec.iov_len, ppos);
3191                 } else {
3192                         nr = file->f_op->write(file, iovec.iov_base,
3193                                                iovec.iov_len, ppos);
3194                 }
3195
3196                 if (nr < 0) {
3197                         if (!ret)
3198                                 ret = nr;
3199                         break;
3200                 }
3201                 ret += nr;
3202                 if (!iov_iter_is_bvec(iter)) {
3203                         iov_iter_advance(iter, nr);
3204                 } else {
3205                         rw->addr += nr;
3206                         rw->len -= nr;
3207                         if (!rw->len)
3208                                 break;
3209                 }
3210                 if (nr != iovec.iov_len)
3211                         break;
3212         }
3213
3214         return ret;
3215 }
3216
3217 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3218                           const struct iovec *fast_iov, struct iov_iter *iter)
3219 {
3220         struct io_async_rw *io = req->async_data;
3221
3222         memcpy(&io->s.iter, iter, sizeof(*iter));
3223         io->free_iovec = iovec;
3224         io->bytes_done = 0;
3225         /* can only be fixed buffers, no need to do anything */
3226         if (iov_iter_is_bvec(iter))
3227                 return;
3228         if (!iovec) {
3229                 unsigned iov_off = 0;
3230
3231                 io->s.iter.iov = io->s.fast_iov;
3232                 if (iter->iov != fast_iov) {
3233                         iov_off = iter->iov - fast_iov;
3234                         io->s.iter.iov += iov_off;
3235                 }
3236                 if (io->s.fast_iov != fast_iov)
3237                         memcpy(io->s.fast_iov + iov_off, fast_iov + iov_off,
3238                                sizeof(struct iovec) * iter->nr_segs);
3239         } else {
3240                 req->flags |= REQ_F_NEED_CLEANUP;
3241         }
3242 }
3243
3244 bool io_alloc_async_data(struct io_kiocb *req)
3245 {
3246         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3247         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3248         if (req->async_data) {
3249                 req->flags |= REQ_F_ASYNC_DATA;
3250                 return false;
3251         }
3252         return true;
3253 }
3254
3255 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3256                              struct io_rw_state *s, bool force)
3257 {
3258         if (!force && !io_op_defs[req->opcode].prep_async)
3259                 return 0;
3260         if (!req_has_async_data(req)) {
3261                 struct io_async_rw *iorw;
3262
3263                 if (io_alloc_async_data(req)) {
3264                         kfree(iovec);
3265                         return -ENOMEM;
3266                 }
3267
3268                 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3269                 iorw = req->async_data;
3270                 /* we've copied and mapped the iter, ensure state is saved */
3271                 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3272         }
3273         return 0;
3274 }
3275
3276 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3277 {
3278         struct io_async_rw *iorw = req->async_data;
3279         struct iovec *iov;
3280         int ret;
3281
3282         /* submission path, ->uring_lock should already be taken */
3283         ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3284         if (unlikely(ret < 0))
3285                 return ret;
3286
3287         iorw->bytes_done = 0;
3288         iorw->free_iovec = iov;
3289         if (iov)
3290                 req->flags |= REQ_F_NEED_CLEANUP;
3291         return 0;
3292 }
3293
3294 static int io_readv_prep_async(struct io_kiocb *req)
3295 {
3296         return io_rw_prep_async(req, READ);
3297 }
3298
3299 static int io_writev_prep_async(struct io_kiocb *req)
3300 {
3301         return io_rw_prep_async(req, WRITE);
3302 }
3303
3304 /*
3305  * This is our waitqueue callback handler, registered through __folio_lock_async()
3306  * when we initially tried to do the IO with the iocb armed our waitqueue.
3307  * This gets called when the page is unlocked, and we generally expect that to
3308  * happen when the page IO is completed and the page is now uptodate. This will
3309  * queue a task_work based retry of the operation, attempting to copy the data
3310  * again. If the latter fails because the page was NOT uptodate, then we will
3311  * do a thread based blocking retry of the operation. That's the unexpected
3312  * slow path.
3313  */
3314 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3315                              int sync, void *arg)
3316 {
3317         struct wait_page_queue *wpq;
3318         struct io_kiocb *req = wait->private;
3319         struct io_rw *rw = io_kiocb_to_cmd(req);
3320         struct wait_page_key *key = arg;
3321
3322         wpq = container_of(wait, struct wait_page_queue, wait);
3323
3324         if (!wake_page_match(wpq, key))
3325                 return 0;
3326
3327         rw->kiocb.ki_flags &= ~IOCB_WAITQ;
3328         list_del_init(&wait->entry);
3329         io_req_task_queue(req);
3330         return 1;
3331 }
3332
3333 /*
3334  * This controls whether a given IO request should be armed for async page
3335  * based retry. If we return false here, the request is handed to the async
3336  * worker threads for retry. If we're doing buffered reads on a regular file,
3337  * we prepare a private wait_page_queue entry and retry the operation. This
3338  * will either succeed because the page is now uptodate and unlocked, or it
3339  * will register a callback when the page is unlocked at IO completion. Through
3340  * that callback, io_uring uses task_work to setup a retry of the operation.
3341  * That retry will attempt the buffered read again. The retry will generally
3342  * succeed, or in rare cases where it fails, we then fall back to using the
3343  * async worker threads for a blocking retry.
3344  */
3345 static bool io_rw_should_retry(struct io_kiocb *req)
3346 {
3347         struct io_async_rw *io = req->async_data;
3348         struct wait_page_queue *wait = &io->wpq;
3349         struct io_rw *rw = io_kiocb_to_cmd(req);
3350         struct kiocb *kiocb = &rw->kiocb;
3351
3352         /* never retry for NOWAIT, we just complete with -EAGAIN */
3353         if (req->flags & REQ_F_NOWAIT)
3354                 return false;
3355
3356         /* Only for buffered IO */
3357         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3358                 return false;
3359
3360         /*
3361          * just use poll if we can, and don't attempt if the fs doesn't
3362          * support callback based unlocks
3363          */
3364         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3365                 return false;
3366
3367         wait->wait.func = io_async_buf_func;
3368         wait->wait.private = req;
3369         wait->wait.flags = 0;
3370         INIT_LIST_HEAD(&wait->wait.entry);
3371         kiocb->ki_flags |= IOCB_WAITQ;
3372         kiocb->ki_flags &= ~IOCB_NOWAIT;
3373         kiocb->ki_waitq = wait;
3374         return true;
3375 }
3376
3377 static inline int io_iter_do_read(struct io_rw *rw, struct iov_iter *iter)
3378 {
3379         struct file *file = rw->kiocb.ki_filp;
3380
3381         if (likely(file->f_op->read_iter))
3382                 return call_read_iter(file, &rw->kiocb, iter);
3383         else if (file->f_op->read)
3384                 return loop_rw_iter(READ, rw, iter);
3385         else
3386                 return -EINVAL;
3387 }
3388
3389 static bool need_read_all(struct io_kiocb *req)
3390 {
3391         return req->flags & REQ_F_ISREG ||
3392                 S_ISBLK(file_inode(req->file)->i_mode);
3393 }
3394
3395 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3396 {
3397         struct io_rw *rw = io_kiocb_to_cmd(req);
3398         struct kiocb *kiocb = &rw->kiocb;
3399         struct io_ring_ctx *ctx = req->ctx;
3400         struct file *file = req->file;
3401         int ret;
3402
3403         if (unlikely(!file || !(file->f_mode & mode)))
3404                 return -EBADF;
3405
3406         if (!io_req_ffs_set(req))
3407                 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3408
3409         kiocb->ki_flags = iocb_flags(file);
3410         ret = kiocb_set_rw_flags(kiocb, rw->flags);
3411         if (unlikely(ret))
3412                 return ret;
3413
3414         /*
3415          * If the file is marked O_NONBLOCK, still allow retry for it if it
3416          * supports async. Otherwise it's impossible to use O_NONBLOCK files
3417          * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3418          */
3419         if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3420             ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3421                 req->flags |= REQ_F_NOWAIT;
3422
3423         if (ctx->flags & IORING_SETUP_IOPOLL) {
3424                 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3425                         return -EOPNOTSUPP;
3426
3427                 kiocb->private = NULL;
3428                 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3429                 kiocb->ki_complete = io_complete_rw_iopoll;
3430                 req->iopoll_completed = 0;
3431         } else {
3432                 if (kiocb->ki_flags & IOCB_HIPRI)
3433                         return -EINVAL;
3434                 kiocb->ki_complete = io_complete_rw;
3435         }
3436
3437         return 0;
3438 }
3439
3440 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3441 {
3442         struct io_rw *rw = io_kiocb_to_cmd(req);
3443         struct io_rw_state __s, *s = &__s;
3444         struct iovec *iovec;
3445         struct kiocb *kiocb = &rw->kiocb;
3446         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3447         struct io_async_rw *io;
3448         ssize_t ret, ret2;
3449         loff_t *ppos;
3450
3451         if (!req_has_async_data(req)) {
3452                 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3453                 if (unlikely(ret < 0))
3454                         return ret;
3455         } else {
3456                 io = req->async_data;
3457                 s = &io->s;
3458
3459                 /*
3460                  * Safe and required to re-import if we're using provided
3461                  * buffers, as we dropped the selected one before retry.
3462                  */
3463                 if (io_do_buffer_select(req)) {
3464                         ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3465                         if (unlikely(ret < 0))
3466                                 return ret;
3467                 }
3468
3469                 /*
3470                  * We come here from an earlier attempt, restore our state to
3471                  * match in case it doesn't. It's cheap enough that we don't
3472                  * need to make this conditional.
3473                  */
3474                 iov_iter_restore(&s->iter, &s->iter_state);
3475                 iovec = NULL;
3476         }
3477         ret = io_rw_init_file(req, FMODE_READ);
3478         if (unlikely(ret)) {
3479                 kfree(iovec);
3480                 return ret;
3481         }
3482         req->cqe.res = iov_iter_count(&s->iter);
3483
3484         if (force_nonblock) {
3485                 /* If the file doesn't support async, just async punt */
3486                 if (unlikely(!io_file_supports_nowait(req))) {
3487                         ret = io_setup_async_rw(req, iovec, s, true);
3488                         return ret ?: -EAGAIN;
3489                 }
3490                 kiocb->ki_flags |= IOCB_NOWAIT;
3491         } else {
3492                 /* Ensure we clear previously set non-block flag */
3493                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3494         }
3495
3496         ppos = io_kiocb_update_pos(req);
3497
3498         ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
3499         if (unlikely(ret)) {
3500                 kfree(iovec);
3501                 return ret;
3502         }
3503
3504         ret = io_iter_do_read(rw, &s->iter);
3505
3506         if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3507                 req->flags &= ~REQ_F_REISSUE;
3508                 /* if we can poll, just do that */
3509                 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3510                         return -EAGAIN;
3511                 /* IOPOLL retry should happen for io-wq threads */
3512                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3513                         goto done;
3514                 /* no retry on NONBLOCK nor RWF_NOWAIT */
3515                 if (req->flags & REQ_F_NOWAIT)
3516                         goto done;
3517                 ret = 0;
3518         } else if (ret == -EIOCBQUEUED) {
3519                 goto out_free;
3520         } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
3521                    (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3522                 /* read all, failed, already did sync or don't want to retry */
3523                 goto done;
3524         }
3525
3526         /*
3527          * Don't depend on the iter state matching what was consumed, or being
3528          * untouched in case of error. Restore it and we'll advance it
3529          * manually if we need to.
3530          */
3531         iov_iter_restore(&s->iter, &s->iter_state);
3532
3533         ret2 = io_setup_async_rw(req, iovec, s, true);
3534         if (ret2)
3535                 return ret2;
3536
3537         iovec = NULL;
3538         io = req->async_data;
3539         s = &io->s;
3540         /*
3541          * Now use our persistent iterator and state, if we aren't already.
3542          * We've restored and mapped the iter to match.
3543          */
3544
3545         do {
3546                 /*
3547                  * We end up here because of a partial read, either from
3548                  * above or inside this loop. Advance the iter by the bytes
3549                  * that were consumed.
3550                  */
3551                 iov_iter_advance(&s->iter, ret);
3552                 if (!iov_iter_count(&s->iter))
3553                         break;
3554                 io->bytes_done += ret;
3555                 iov_iter_save_state(&s->iter, &s->iter_state);
3556
3557                 /* if we can retry, do so with the callbacks armed */
3558                 if (!io_rw_should_retry(req)) {
3559                         kiocb->ki_flags &= ~IOCB_WAITQ;
3560                         return -EAGAIN;
3561                 }
3562
3563                 /*
3564                  * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3565                  * we get -EIOCBQUEUED, then we'll get a notification when the
3566                  * desired page gets unlocked. We can also get a partial read
3567                  * here, and if we do, then just retry at the new offset.
3568                  */
3569                 ret = io_iter_do_read(rw, &s->iter);
3570                 if (ret == -EIOCBQUEUED)
3571                         return IOU_ISSUE_SKIP_COMPLETE;
3572                 /* we got some bytes, but not all. retry. */
3573                 kiocb->ki_flags &= ~IOCB_WAITQ;
3574                 iov_iter_restore(&s->iter, &s->iter_state);
3575         } while (ret > 0);
3576 done:
3577         kiocb_done(req, ret, issue_flags);
3578 out_free:
3579         /* it's faster to check here then delegate to kfree */
3580         if (iovec)
3581                 kfree(iovec);
3582         return IOU_ISSUE_SKIP_COMPLETE;
3583 }
3584
3585 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3586 {
3587         struct io_rw *rw = io_kiocb_to_cmd(req);
3588         struct io_rw_state __s, *s = &__s;
3589         struct iovec *iovec;
3590         struct kiocb *kiocb = &rw->kiocb;
3591         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3592         ssize_t ret, ret2;
3593         loff_t *ppos;
3594
3595         if (!req_has_async_data(req)) {
3596                 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3597                 if (unlikely(ret < 0))
3598                         return ret;
3599         } else {
3600                 struct io_async_rw *io = req->async_data;
3601
3602                 s = &io->s;
3603                 iov_iter_restore(&s->iter, &s->iter_state);
3604                 iovec = NULL;
3605         }
3606         ret = io_rw_init_file(req, FMODE_WRITE);
3607         if (unlikely(ret)) {
3608                 kfree(iovec);
3609                 return ret;
3610         }
3611         req->cqe.res = iov_iter_count(&s->iter);
3612
3613         if (force_nonblock) {
3614                 /* If the file doesn't support async, just async punt */
3615                 if (unlikely(!io_file_supports_nowait(req)))
3616                         goto copy_iov;
3617
3618                 /* file path doesn't support NOWAIT for non-direct_IO */
3619                 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3620                     (req->flags & REQ_F_ISREG))
3621                         goto copy_iov;
3622
3623                 kiocb->ki_flags |= IOCB_NOWAIT;
3624         } else {
3625                 /* Ensure we clear previously set non-block flag */
3626                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3627         }
3628
3629         ppos = io_kiocb_update_pos(req);
3630
3631         ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
3632         if (unlikely(ret))
3633                 goto out_free;
3634
3635         /*
3636          * Open-code file_start_write here to grab freeze protection,
3637          * which will be released by another thread in
3638          * io_complete_rw().  Fool lockdep by telling it the lock got
3639          * released so that it doesn't complain about the held lock when
3640          * we return to userspace.
3641          */
3642         if (req->flags & REQ_F_ISREG) {
3643                 sb_start_write(file_inode(req->file)->i_sb);
3644                 __sb_writers_release(file_inode(req->file)->i_sb,
3645                                         SB_FREEZE_WRITE);
3646         }
3647         kiocb->ki_flags |= IOCB_WRITE;
3648
3649         if (likely(req->file->f_op->write_iter))
3650                 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3651         else if (req->file->f_op->write)
3652                 ret2 = loop_rw_iter(WRITE, rw, &s->iter);
3653         else
3654                 ret2 = -EINVAL;
3655
3656         if (req->flags & REQ_F_REISSUE) {
3657                 req->flags &= ~REQ_F_REISSUE;
3658                 ret2 = -EAGAIN;
3659         }
3660
3661         /*
3662          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3663          * retry them without IOCB_NOWAIT.
3664          */
3665         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3666                 ret2 = -EAGAIN;
3667         /* no retry on NONBLOCK nor RWF_NOWAIT */
3668         if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3669                 goto done;
3670         if (!force_nonblock || ret2 != -EAGAIN) {
3671                 /* IOPOLL retry should happen for io-wq threads */
3672                 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3673                         goto copy_iov;
3674 done:
3675                 kiocb_done(req, ret2, issue_flags);
3676                 ret = IOU_ISSUE_SKIP_COMPLETE;
3677         } else {
3678 copy_iov:
3679                 iov_iter_restore(&s->iter, &s->iter_state);
3680                 ret = io_setup_async_rw(req, iovec, s, false);
3681                 return ret ?: -EAGAIN;
3682         }
3683 out_free:
3684         /* it's reportedly faster than delegating the null check to kfree() */
3685         if (iovec)
3686                 kfree(iovec);
3687         return ret;
3688 }
3689
3690 static int io_msg_ring_prep(struct io_kiocb *req,
3691                             const struct io_uring_sqe *sqe)
3692 {
3693         struct io_msg *msg = io_kiocb_to_cmd(req);
3694
3695         if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
3696                      sqe->buf_index || sqe->personality))
3697                 return -EINVAL;
3698
3699         msg->user_data = READ_ONCE(sqe->off);
3700         msg->len = READ_ONCE(sqe->len);
3701         return 0;
3702 }
3703
3704 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
3705 {
3706         struct io_msg *msg = io_kiocb_to_cmd(req);
3707         struct io_ring_ctx *target_ctx;
3708         bool filled;
3709         int ret;
3710
3711         ret = -EBADFD;
3712         if (req->file->f_op != &io_uring_fops)
3713                 goto done;
3714
3715         ret = -EOVERFLOW;
3716         target_ctx = req->file->private_data;
3717
3718         spin_lock(&target_ctx->completion_lock);
3719         filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
3720         io_commit_cqring(target_ctx);
3721         spin_unlock(&target_ctx->completion_lock);
3722
3723         if (filled) {
3724                 io_cqring_ev_posted(target_ctx);
3725                 ret = 0;
3726         }
3727
3728 done:
3729         if (ret < 0)
3730                 req_set_fail(req);
3731         io_req_set_res(req, ret, 0);
3732         /* put file to avoid an attempt to IOPOLL the req */
3733         io_put_file(req->file);
3734         req->file = NULL;
3735         return IOU_OK;
3736 }
3737
3738 /*
3739  * Note when io_fixed_fd_install() returns error value, it will ensure
3740  * fput() is called correspondingly.
3741  */
3742 int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
3743                         struct file *file, unsigned int file_slot)
3744 {
3745         bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
3746         struct io_ring_ctx *ctx = req->ctx;
3747         int ret;
3748
3749         io_ring_submit_lock(ctx, issue_flags);
3750
3751         if (alloc_slot) {
3752                 ret = io_file_bitmap_get(ctx);
3753                 if (unlikely(ret < 0))
3754                         goto err;
3755                 file_slot = ret;
3756         } else {
3757                 file_slot--;
3758         }
3759
3760         ret = io_install_fixed_file(req, file, issue_flags, file_slot);
3761         if (!ret && alloc_slot)
3762                 ret = file_slot;
3763 err:
3764         io_ring_submit_unlock(ctx, issue_flags);
3765         if (unlikely(ret < 0))
3766                 fput(file);
3767         return ret;
3768 }
3769
3770 static int io_remove_buffers_prep(struct io_kiocb *req,
3771                                   const struct io_uring_sqe *sqe)
3772 {
3773         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3774         u64 tmp;
3775
3776         if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
3777             sqe->splice_fd_in)
3778                 return -EINVAL;
3779
3780         tmp = READ_ONCE(sqe->fd);
3781         if (!tmp || tmp > USHRT_MAX)
3782                 return -EINVAL;
3783
3784         memset(p, 0, sizeof(*p));
3785         p->nbufs = tmp;
3786         p->bgid = READ_ONCE(sqe->buf_group);
3787         return 0;
3788 }
3789
3790 static int __io_remove_buffers(struct io_ring_ctx *ctx,
3791                                struct io_buffer_list *bl, unsigned nbufs)
3792 {
3793         unsigned i = 0;
3794
3795         /* shouldn't happen */
3796         if (!nbufs)
3797                 return 0;
3798
3799         if (bl->buf_nr_pages) {
3800                 int j;
3801
3802                 i = bl->buf_ring->tail - bl->head;
3803                 for (j = 0; j < bl->buf_nr_pages; j++)
3804                         unpin_user_page(bl->buf_pages[j]);
3805                 kvfree(bl->buf_pages);
3806                 bl->buf_pages = NULL;
3807                 bl->buf_nr_pages = 0;
3808                 /* make sure it's seen as empty */
3809                 INIT_LIST_HEAD(&bl->buf_list);
3810                 return i;
3811         }
3812
3813         /* the head kbuf is the list itself */
3814         while (!list_empty(&bl->buf_list)) {
3815                 struct io_buffer *nxt;
3816
3817                 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
3818                 list_del(&nxt->list);
3819                 if (++i == nbufs)
3820                         return i;
3821                 cond_resched();
3822         }
3823         i++;
3824
3825         return i;
3826 }
3827
3828 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3829 {
3830         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3831         struct io_ring_ctx *ctx = req->ctx;
3832         struct io_buffer_list *bl;
3833         int ret = 0;
3834
3835         io_ring_submit_lock(ctx, issue_flags);
3836
3837         ret = -ENOENT;
3838         bl = io_buffer_get_list(ctx, p->bgid);
3839         if (bl) {
3840                 ret = -EINVAL;
3841                 /* can't use provide/remove buffers command on mapped buffers */
3842                 if (!bl->buf_nr_pages)
3843                         ret = __io_remove_buffers(ctx, bl, p->nbufs);
3844         }
3845         if (ret < 0)
3846                 req_set_fail(req);
3847
3848         /* complete before unlock, IOPOLL may need the lock */
3849         io_req_set_res(req, ret, 0);
3850         __io_req_complete(req, issue_flags);
3851         io_ring_submit_unlock(ctx, issue_flags);
3852         return IOU_ISSUE_SKIP_COMPLETE;
3853 }
3854
3855 static int io_provide_buffers_prep(struct io_kiocb *req,
3856                                    const struct io_uring_sqe *sqe)
3857 {
3858         unsigned long size, tmp_check;
3859         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3860         u64 tmp;
3861
3862         if (sqe->rw_flags || sqe->splice_fd_in)
3863                 return -EINVAL;
3864
3865         tmp = READ_ONCE(sqe->fd);
3866         if (!tmp || tmp > USHRT_MAX)
3867                 return -E2BIG;
3868         p->nbufs = tmp;
3869         p->addr = READ_ONCE(sqe->addr);
3870         p->len = READ_ONCE(sqe->len);
3871
3872         if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3873                                 &size))
3874                 return -EOVERFLOW;
3875         if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3876                 return -EOVERFLOW;
3877
3878         size = (unsigned long)p->len * p->nbufs;
3879         if (!access_ok(u64_to_user_ptr(p->addr), size))
3880                 return -EFAULT;
3881
3882         p->bgid = READ_ONCE(sqe->buf_group);
3883         tmp = READ_ONCE(sqe->off);
3884         if (tmp > USHRT_MAX)
3885                 return -E2BIG;
3886         p->bid = tmp;
3887         return 0;
3888 }
3889
3890 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
3891 {
3892         struct io_buffer *buf;
3893         struct page *page;
3894         int bufs_in_page;
3895
3896         /*
3897          * Completions that don't happen inline (eg not under uring_lock) will
3898          * add to ->io_buffers_comp. If we don't have any free buffers, check
3899          * the completion list and splice those entries first.
3900          */
3901         if (!list_empty_careful(&ctx->io_buffers_comp)) {
3902                 spin_lock(&ctx->completion_lock);
3903                 if (!list_empty(&ctx->io_buffers_comp)) {
3904                         list_splice_init(&ctx->io_buffers_comp,
3905                                                 &ctx->io_buffers_cache);
3906                         spin_unlock(&ctx->completion_lock);
3907                         return 0;
3908                 }
3909                 spin_unlock(&ctx->completion_lock);
3910         }
3911
3912         /*
3913          * No free buffers and no completion entries either. Allocate a new
3914          * page worth of buffer entries and add those to our freelist.
3915          */
3916         page = alloc_page(GFP_KERNEL_ACCOUNT);
3917         if (!page)
3918                 return -ENOMEM;
3919
3920         list_add(&page->lru, &ctx->io_buffers_pages);
3921
3922         buf = page_address(page);
3923         bufs_in_page = PAGE_SIZE / sizeof(*buf);
3924         while (bufs_in_page) {
3925                 list_add_tail(&buf->list, &ctx->io_buffers_cache);
3926                 buf++;
3927                 bufs_in_page--;
3928         }
3929
3930         return 0;
3931 }
3932
3933 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
3934                           struct io_buffer_list *bl)
3935 {
3936         struct io_buffer *buf;
3937         u64 addr = pbuf->addr;
3938         int i, bid = pbuf->bid;
3939
3940         for (i = 0; i < pbuf->nbufs; i++) {
3941                 if (list_empty(&ctx->io_buffers_cache) &&
3942                     io_refill_buffer_cache(ctx))
3943                         break;
3944                 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
3945                                         list);
3946                 list_move_tail(&buf->list, &bl->buf_list);
3947                 buf->addr = addr;
3948                 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3949                 buf->bid = bid;
3950                 buf->bgid = pbuf->bgid;
3951                 addr += pbuf->len;
3952                 bid++;
3953                 cond_resched();
3954         }
3955
3956         return i ? 0 : -ENOMEM;
3957 }
3958
3959 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
3960 {
3961         int i;
3962
3963         ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
3964                                 GFP_KERNEL);
3965         if (!ctx->io_bl)
3966                 return -ENOMEM;
3967
3968         for (i = 0; i < BGID_ARRAY; i++) {
3969                 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
3970                 ctx->io_bl[i].bgid = i;
3971         }
3972
3973         return 0;
3974 }
3975
3976 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3977 {
3978         struct io_provide_buf *p = io_kiocb_to_cmd(req);
3979         struct io_ring_ctx *ctx = req->ctx;
3980         struct io_buffer_list *bl;
3981         int ret = 0;
3982
3983         io_ring_submit_lock(ctx, issue_flags);
3984
3985         if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
3986                 ret = io_init_bl_list(ctx);
3987                 if (ret)
3988                         goto err;
3989         }
3990
3991         bl = io_buffer_get_list(ctx, p->bgid);
3992         if (unlikely(!bl)) {
3993                 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
3994                 if (!bl) {
3995                         ret = -ENOMEM;
3996                         goto err;
3997                 }
3998                 INIT_LIST_HEAD(&bl->buf_list);
3999                 ret = io_buffer_add_list(ctx, bl, p->bgid);
4000                 if (ret) {
4001                         kfree(bl);
4002                         goto err;
4003                 }
4004         }
4005         /* can't add buffers via this command for a mapped buffer ring */
4006         if (bl->buf_nr_pages) {
4007                 ret = -EINVAL;
4008                 goto err;
4009         }
4010
4011         ret = io_add_buffers(ctx, p, bl);
4012 err:
4013         if (ret < 0)
4014                 req_set_fail(req);
4015         /* complete before unlock, IOPOLL may need the lock */
4016         io_req_set_res(req, ret, 0);
4017         __io_req_complete(req, issue_flags);
4018         io_ring_submit_unlock(ctx, issue_flags);
4019         return IOU_ISSUE_SKIP_COMPLETE;
4020 }
4021
4022 static __maybe_unused int io_eopnotsupp_prep(struct io_kiocb *kiocb,
4023                                              const struct io_uring_sqe *sqe)
4024 {
4025         return -EOPNOTSUPP;
4026 }
4027
4028 #if defined(CONFIG_NET)
4029 static int io_shutdown_prep(struct io_kiocb *req,
4030                             const struct io_uring_sqe *sqe)
4031 {
4032         struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
4033
4034         if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
4035                      sqe->buf_index || sqe->splice_fd_in))
4036                 return -EINVAL;
4037
4038         shutdown->how = READ_ONCE(sqe->len);
4039         return 0;
4040 }
4041
4042 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4043 {
4044         struct io_shutdown *shutdown = io_kiocb_to_cmd(req);
4045         struct socket *sock;
4046         int ret;
4047
4048         if (issue_flags & IO_URING_F_NONBLOCK)
4049                 return -EAGAIN;
4050
4051         sock = sock_from_file(req->file);
4052         if (unlikely(!sock))
4053                 return -ENOTSOCK;
4054
4055         ret = __sys_shutdown_sock(sock, shutdown->how);
4056         io_req_set_res(req, ret, 0);
4057         return IOU_OK;
4058 }
4059
4060 static bool io_net_retry(struct socket *sock, int flags)
4061 {
4062         if (!(flags & MSG_WAITALL))
4063                 return false;
4064         return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4065 }
4066
4067 static int io_setup_async_msg(struct io_kiocb *req,
4068                               struct io_async_msghdr *kmsg)
4069 {
4070         struct io_async_msghdr *async_msg = req->async_data;
4071
4072         if (async_msg)
4073                 return -EAGAIN;
4074         if (io_alloc_async_data(req)) {
4075                 kfree(kmsg->free_iov);
4076                 return -ENOMEM;
4077         }
4078         async_msg = req->async_data;
4079         req->flags |= REQ_F_NEED_CLEANUP;
4080         memcpy(async_msg, kmsg, sizeof(*kmsg));
4081         async_msg->msg.msg_name = &async_msg->addr;
4082         /* if were using fast_iov, set it to the new one */
4083         if (!async_msg->free_iov)
4084                 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4085
4086         return -EAGAIN;
4087 }
4088
4089 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4090                                struct io_async_msghdr *iomsg)
4091 {
4092         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4093
4094         iomsg->msg.msg_name = &iomsg->addr;
4095         iomsg->free_iov = iomsg->fast_iov;
4096         return sendmsg_copy_msghdr(&iomsg->msg, sr->umsg, sr->msg_flags,
4097                                         &iomsg->free_iov);
4098 }
4099
4100 static int io_sendmsg_prep_async(struct io_kiocb *req)
4101 {
4102         int ret;
4103
4104         ret = io_sendmsg_copy_hdr(req, req->async_data);
4105         if (!ret)
4106                 req->flags |= REQ_F_NEED_CLEANUP;
4107         return ret;
4108 }
4109
4110 static void io_sendmsg_recvmsg_cleanup(struct io_kiocb *req)
4111 {
4112         struct io_async_msghdr *io = req->async_data;
4113
4114         kfree(io->free_iov);
4115 }
4116
4117 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4118 {
4119         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4120
4121         if (unlikely(sqe->file_index || sqe->addr2))
4122                 return -EINVAL;
4123
4124         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4125         sr->len = READ_ONCE(sqe->len);
4126         sr->flags = READ_ONCE(sqe->ioprio);
4127         if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
4128                 return -EINVAL;
4129         sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4130         if (sr->msg_flags & MSG_DONTWAIT)
4131                 req->flags |= REQ_F_NOWAIT;
4132
4133 #ifdef CONFIG_COMPAT
4134         if (req->ctx->compat)
4135                 sr->msg_flags |= MSG_CMSG_COMPAT;
4136 #endif
4137         sr->done_io = 0;
4138         return 0;
4139 }
4140
4141 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4142 {
4143         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4144         struct io_async_msghdr iomsg, *kmsg;
4145         struct socket *sock;
4146         unsigned flags;
4147         int min_ret = 0;
4148         int ret;
4149
4150         sock = sock_from_file(req->file);
4151         if (unlikely(!sock))
4152                 return -ENOTSOCK;
4153
4154         if (req_has_async_data(req)) {
4155                 kmsg = req->async_data;
4156         } else {
4157                 ret = io_sendmsg_copy_hdr(req, &iomsg);
4158                 if (ret)
4159                         return ret;
4160                 kmsg = &iomsg;
4161         }
4162
4163         if (!(req->flags & REQ_F_POLLED) &&
4164             (sr->flags & IORING_RECVSEND_POLL_FIRST))
4165                 return io_setup_async_msg(req, kmsg);
4166
4167         flags = sr->msg_flags;
4168         if (issue_flags & IO_URING_F_NONBLOCK)
4169                 flags |= MSG_DONTWAIT;
4170         if (flags & MSG_WAITALL)
4171                 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4172
4173         ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4174
4175         if (ret < min_ret) {
4176                 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4177                         return io_setup_async_msg(req, kmsg);
4178                 if (ret == -ERESTARTSYS)
4179                         ret = -EINTR;
4180                 if (ret > 0 && io_net_retry(sock, flags)) {
4181                         sr->done_io += ret;
4182                         req->flags |= REQ_F_PARTIAL_IO;
4183                         return io_setup_async_msg(req, kmsg);
4184                 }
4185                 req_set_fail(req);
4186         }
4187         /* fast path, check for non-NULL to avoid function call */
4188         if (kmsg->free_iov)
4189                 kfree(kmsg->free_iov);
4190         req->flags &= ~REQ_F_NEED_CLEANUP;
4191         if (ret >= 0)
4192                 ret += sr->done_io;
4193         else if (sr->done_io)
4194                 ret = sr->done_io;
4195         io_req_set_res(req, ret, 0);
4196         return IOU_OK;
4197 }
4198
4199 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4200 {
4201         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4202         struct msghdr msg;
4203         struct iovec iov;
4204         struct socket *sock;
4205         unsigned flags;
4206         int min_ret = 0;
4207         int ret;
4208
4209         if (!(req->flags & REQ_F_POLLED) &&
4210             (sr->flags & IORING_RECVSEND_POLL_FIRST))
4211                 return -EAGAIN;
4212
4213         sock = sock_from_file(req->file);
4214         if (unlikely(!sock))
4215                 return -ENOTSOCK;
4216
4217         ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4218         if (unlikely(ret))
4219                 return ret;
4220
4221         msg.msg_name = NULL;
4222         msg.msg_control = NULL;
4223         msg.msg_controllen = 0;
4224         msg.msg_namelen = 0;
4225
4226         flags = sr->msg_flags;
4227         if (issue_flags & IO_URING_F_NONBLOCK)
4228                 flags |= MSG_DONTWAIT;
4229         if (flags & MSG_WAITALL)
4230                 min_ret = iov_iter_count(&msg.msg_iter);
4231
4232         msg.msg_flags = flags;
4233         ret = sock_sendmsg(sock, &msg);
4234         if (ret < min_ret) {
4235                 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4236                         return -EAGAIN;
4237                 if (ret == -ERESTARTSYS)
4238                         ret = -EINTR;
4239                 if (ret > 0 && io_net_retry(sock, flags)) {
4240                         sr->len -= ret;
4241                         sr->buf += ret;
4242                         sr->done_io += ret;
4243                         req->flags |= REQ_F_PARTIAL_IO;
4244                         return -EAGAIN;
4245                 }
4246                 req_set_fail(req);
4247         }
4248         if (ret >= 0)
4249                 ret += sr->done_io;
4250         else if (sr->done_io)
4251                 ret = sr->done_io;
4252         io_req_set_res(req, ret, 0);
4253         return IOU_OK;
4254 }
4255
4256 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4257                                  struct io_async_msghdr *iomsg)
4258 {
4259         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4260         struct iovec __user *uiov;
4261         size_t iov_len;
4262         int ret;
4263
4264         ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4265                                         &iomsg->uaddr, &uiov, &iov_len);
4266         if (ret)
4267                 return ret;
4268
4269         if (req->flags & REQ_F_BUFFER_SELECT) {
4270                 if (iov_len > 1)
4271                         return -EINVAL;
4272                 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4273                         return -EFAULT;
4274                 sr->len = iomsg->fast_iov[0].iov_len;
4275                 iomsg->free_iov = NULL;
4276         } else {
4277                 iomsg->free_iov = iomsg->fast_iov;
4278                 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4279                                      &iomsg->free_iov, &iomsg->msg.msg_iter,
4280                                      false);
4281                 if (ret > 0)
4282                         ret = 0;
4283         }
4284
4285         return ret;
4286 }
4287
4288 #ifdef CONFIG_COMPAT
4289 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4290                                         struct io_async_msghdr *iomsg)
4291 {
4292         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4293         struct compat_iovec __user *uiov;
4294         compat_uptr_t ptr;
4295         compat_size_t len;
4296         int ret;
4297
4298         ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4299                                   &ptr, &len);
4300         if (ret)
4301                 return ret;
4302
4303         uiov = compat_ptr(ptr);
4304         if (req->flags & REQ_F_BUFFER_SELECT) {
4305                 compat_ssize_t clen;
4306
4307                 if (len > 1)
4308                         return -EINVAL;
4309                 if (!access_ok(uiov, sizeof(*uiov)))
4310                         return -EFAULT;
4311                 if (__get_user(clen, &uiov->iov_len))
4312                         return -EFAULT;
4313                 if (clen < 0)
4314                         return -EINVAL;
4315                 sr->len = clen;
4316                 iomsg->free_iov = NULL;
4317         } else {
4318                 iomsg->free_iov = iomsg->fast_iov;
4319                 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4320                                    UIO_FASTIOV, &iomsg->free_iov,
4321                                    &iomsg->msg.msg_iter, true);
4322                 if (ret < 0)
4323                         return ret;
4324         }
4325
4326         return 0;
4327 }
4328 #endif
4329
4330 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4331                                struct io_async_msghdr *iomsg)
4332 {
4333         iomsg->msg.msg_name = &iomsg->addr;
4334
4335 #ifdef CONFIG_COMPAT
4336         if (req->ctx->compat)
4337                 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4338 #endif
4339
4340         return __io_recvmsg_copy_hdr(req, iomsg);
4341 }
4342
4343 static int io_recvmsg_prep_async(struct io_kiocb *req)
4344 {
4345         int ret;
4346
4347         ret = io_recvmsg_copy_hdr(req, req->async_data);
4348         if (!ret)
4349                 req->flags |= REQ_F_NEED_CLEANUP;
4350         return ret;
4351 }
4352
4353 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4354 {
4355         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4356
4357         if (unlikely(sqe->file_index || sqe->addr2))
4358                 return -EINVAL;
4359
4360         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4361         sr->len = READ_ONCE(sqe->len);
4362         sr->flags = READ_ONCE(sqe->ioprio);
4363         if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
4364                 return -EINVAL;
4365         sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4366         if (sr->msg_flags & MSG_DONTWAIT)
4367                 req->flags |= REQ_F_NOWAIT;
4368         if (sr->msg_flags & MSG_ERRQUEUE)
4369                 req->flags |= REQ_F_CLEAR_POLLIN;
4370
4371 #ifdef CONFIG_COMPAT
4372         if (req->ctx->compat)
4373                 sr->msg_flags |= MSG_CMSG_COMPAT;
4374 #endif
4375         sr->done_io = 0;
4376         return 0;
4377 }
4378
4379 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4380 {
4381         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4382         struct io_async_msghdr iomsg, *kmsg;
4383         struct socket *sock;
4384         unsigned int cflags;
4385         unsigned flags;
4386         int ret, min_ret = 0;
4387         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4388
4389         sock = sock_from_file(req->file);
4390         if (unlikely(!sock))
4391                 return -ENOTSOCK;
4392
4393         if (req_has_async_data(req)) {
4394                 kmsg = req->async_data;
4395         } else {
4396                 ret = io_recvmsg_copy_hdr(req, &iomsg);
4397                 if (ret)
4398                         return ret;
4399                 kmsg = &iomsg;
4400         }
4401
4402         if (!(req->flags & REQ_F_POLLED) &&
4403             (sr->flags & IORING_RECVSEND_POLL_FIRST))
4404                 return io_setup_async_msg(req, kmsg);
4405
4406         if (io_do_buffer_select(req)) {
4407                 void __user *buf;
4408
4409                 buf = io_buffer_select(req, &sr->len, issue_flags);
4410                 if (!buf)
4411                         return -ENOBUFS;
4412                 kmsg->fast_iov[0].iov_base = buf;
4413                 kmsg->fast_iov[0].iov_len = sr->len;
4414                 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
4415                                 sr->len);
4416         }
4417
4418         flags = sr->msg_flags;
4419         if (force_nonblock)
4420                 flags |= MSG_DONTWAIT;
4421         if (flags & MSG_WAITALL)
4422                 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4423
4424         kmsg->msg.msg_get_inq = 1;
4425         ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
4426         if (ret < min_ret) {
4427                 if (ret == -EAGAIN && force_nonblock)
4428                         return io_setup_async_msg(req, kmsg);
4429                 if (ret == -ERESTARTSYS)
4430                         ret = -EINTR;
4431                 if (ret > 0 && io_net_retry(sock, flags)) {
4432                         sr->done_io += ret;
4433                         req->flags |= REQ_F_PARTIAL_IO;
4434                         return io_setup_async_msg(req, kmsg);
4435                 }
4436                 req_set_fail(req);
4437         } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
4438                 req_set_fail(req);
4439         }
4440
4441         /* fast path, check for non-NULL to avoid function call */
4442         if (kmsg->free_iov)
4443                 kfree(kmsg->free_iov);
4444         req->flags &= ~REQ_F_NEED_CLEANUP;
4445         if (ret >= 0)
4446                 ret += sr->done_io;
4447         else if (sr->done_io)
4448                 ret = sr->done_io;
4449         cflags = io_put_kbuf(req, issue_flags);
4450         if (kmsg->msg.msg_inq)
4451                 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
4452         io_req_set_res(req, ret, cflags);
4453         return IOU_OK;
4454 }
4455
4456 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4457 {
4458         struct io_sr_msg *sr = io_kiocb_to_cmd(req);
4459         struct msghdr msg;
4460         struct socket *sock;
4461         struct iovec iov;
4462         unsigned int cflags;
4463         unsigned flags;
4464         int ret, min_ret = 0;
4465         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4466
4467         if (!(req->flags & REQ_F_POLLED) &&
4468             (sr->flags & IORING_RECVSEND_POLL_FIRST))
4469                 return -EAGAIN;
4470
4471         sock = sock_from_file(req->file);
4472         if (unlikely(!sock))
4473                 return -ENOTSOCK;
4474
4475         if (io_do_buffer_select(req)) {
4476                 void __user *buf;
4477
4478                 buf = io_buffer_select(req, &sr->len, issue_flags);
4479                 if (!buf)
4480                         return -ENOBUFS;
4481                 sr->buf = buf;
4482         }
4483
4484         ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
4485         if (unlikely(ret))
4486                 goto out_free;
4487
4488         msg.msg_name = NULL;
4489         msg.msg_namelen = 0;
4490         msg.msg_control = NULL;
4491         msg.msg_get_inq = 1;
4492         msg.msg_flags = 0;
4493         msg.msg_controllen = 0;
4494         msg.msg_iocb = NULL;
4495
4496         flags = sr->msg_flags;
4497         if (force_nonblock)
4498                 flags |= MSG_DONTWAIT;
4499         if (flags & MSG_WAITALL)
4500                 min_ret = iov_iter_count(&msg.msg_iter);
4501
4502         ret = sock_recvmsg(sock, &msg, flags);
4503         if (ret < min_ret) {
4504                 if (ret == -EAGAIN && force_nonblock)
4505                         return -EAGAIN;
4506                 if (ret == -ERESTARTSYS)
4507                         ret = -EINTR;
4508                 if (ret > 0 && io_net_retry(sock, flags)) {
4509                         sr->len -= ret;
4510                         sr->buf += ret;
4511                         sr->done_io += ret;
4512                         req->flags |= REQ_F_PARTIAL_IO;
4513                         return -EAGAIN;
4514                 }
4515                 req_set_fail(req);
4516         } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
4517 out_free:
4518                 req_set_fail(req);
4519         }
4520
4521         if (ret >= 0)
4522                 ret += sr->done_io;
4523         else if (sr->done_io)
4524                 ret = sr->done_io;
4525         cflags = io_put_kbuf(req, issue_flags);
4526         if (msg.msg_inq)
4527                 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
4528         io_req_set_res(req, ret, cflags);
4529         return IOU_OK;
4530 }
4531
4532 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4533 {
4534         struct io_accept *accept = io_kiocb_to_cmd(req);
4535         unsigned flags;
4536
4537         if (sqe->len || sqe->buf_index)
4538                 return -EINVAL;
4539
4540         accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4541         accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4542         accept->flags = READ_ONCE(sqe->accept_flags);
4543         accept->nofile = rlimit(RLIMIT_NOFILE);
4544         flags = READ_ONCE(sqe->ioprio);
4545         if (flags & ~IORING_ACCEPT_MULTISHOT)
4546                 return -EINVAL;
4547
4548         accept->file_slot = READ_ONCE(sqe->file_index);
4549         if (accept->file_slot) {
4550                 if (accept->flags & SOCK_CLOEXEC)
4551                         return -EINVAL;
4552                 if (flags & IORING_ACCEPT_MULTISHOT &&
4553                     accept->file_slot != IORING_FILE_INDEX_ALLOC)
4554                         return -EINVAL;
4555         }
4556         if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4557                 return -EINVAL;
4558         if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4559                 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4560         if (flags & IORING_ACCEPT_MULTISHOT)
4561                 req->flags |= REQ_F_APOLL_MULTISHOT;
4562         return 0;
4563 }
4564
4565 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4566 {
4567         struct io_ring_ctx *ctx = req->ctx;
4568         struct io_accept *accept = io_kiocb_to_cmd(req);
4569         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4570         unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4571         bool fixed = !!accept->file_slot;
4572         struct file *file;
4573         int ret, fd;
4574
4575 retry:
4576         if (!fixed) {
4577                 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4578                 if (unlikely(fd < 0))
4579                         return fd;
4580         }
4581         file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4582                          accept->flags);
4583         if (IS_ERR(file)) {
4584                 if (!fixed)
4585                         put_unused_fd(fd);
4586                 ret = PTR_ERR(file);
4587                 if (ret == -EAGAIN && force_nonblock) {
4588                         /*
4589                          * if it's multishot and polled, we don't need to
4590                          * return EAGAIN to arm the poll infra since it
4591                          * has already been done
4592                          */
4593                         if ((req->flags & IO_APOLL_MULTI_POLLED) ==
4594                             IO_APOLL_MULTI_POLLED)
4595                                 ret = IOU_ISSUE_SKIP_COMPLETE;
4596                         return ret;
4597                 }
4598                 if (ret == -ERESTARTSYS)
4599                         ret = -EINTR;
4600                 req_set_fail(req);
4601         } else if (!fixed) {
4602                 fd_install(fd, file);
4603                 ret = fd;
4604         } else {
4605                 ret = io_fixed_fd_install(req, issue_flags, file,
4606                                                 accept->file_slot);
4607         }
4608
4609         if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
4610                 io_req_set_res(req, ret, 0);
4611                 return IOU_OK;
4612         }
4613         if (ret >= 0) {
4614                 bool filled;
4615
4616                 spin_lock(&ctx->completion_lock);
4617                 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
4618                                          IORING_CQE_F_MORE);
4619                 io_commit_cqring(ctx);
4620                 spin_unlock(&ctx->completion_lock);
4621                 if (filled) {
4622                         io_cqring_ev_posted(ctx);
4623                         goto retry;
4624                 }
4625                 ret = -ECANCELED;
4626         }
4627
4628         return ret;
4629 }
4630
4631 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4632 {
4633         struct io_socket *sock = io_kiocb_to_cmd(req);
4634
4635         if (sqe->addr || sqe->rw_flags || sqe->buf_index)
4636                 return -EINVAL;
4637
4638         sock->domain = READ_ONCE(sqe->fd);
4639         sock->type = READ_ONCE(sqe->off);
4640         sock->protocol = READ_ONCE(sqe->len);
4641         sock->file_slot = READ_ONCE(sqe->file_index);
4642         sock->nofile = rlimit(RLIMIT_NOFILE);
4643
4644         sock->flags = sock->type & ~SOCK_TYPE_MASK;
4645         if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
4646                 return -EINVAL;
4647         if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4648                 return -EINVAL;
4649         return 0;
4650 }
4651
4652 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
4653 {
4654         struct io_socket *sock = io_kiocb_to_cmd(req);
4655         bool fixed = !!sock->file_slot;
4656         struct file *file;
4657         int ret, fd;
4658
4659         if (!fixed) {
4660                 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
4661                 if (unlikely(fd < 0))
4662                         return fd;
4663         }
4664         file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
4665         if (IS_ERR(file)) {
4666                 if (!fixed)
4667                         put_unused_fd(fd);
4668                 ret = PTR_ERR(file);
4669                 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4670                         return -EAGAIN;
4671                 if (ret == -ERESTARTSYS)
4672                         ret = -EINTR;
4673                 req_set_fail(req);
4674         } else if (!fixed) {
4675                 fd_install(fd, file);
4676                 ret = fd;
4677         } else {
4678                 ret = io_fixed_fd_install(req, issue_flags, file,
4679                                             sock->file_slot);
4680         }
4681         io_req_set_res(req, ret, 0);
4682         return IOU_OK;
4683 }
4684
4685 static int io_connect_prep_async(struct io_kiocb *req)
4686 {
4687         struct io_async_connect *io = req->async_data;
4688         struct io_connect *conn = io_kiocb_to_cmd(req);
4689
4690         return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4691 }
4692
4693 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4694 {
4695         struct io_connect *conn = io_kiocb_to_cmd(req);
4696
4697         if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
4698                 return -EINVAL;
4699
4700         conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4701         conn->addr_len =  READ_ONCE(sqe->addr2);
4702         return 0;
4703 }
4704
4705 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4706 {
4707         struct io_connect *connect = io_kiocb_to_cmd(req);
4708         struct io_async_connect __io, *io;
4709         unsigned file_flags;
4710         int ret;
4711         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4712
4713         if (req_has_async_data(req)) {
4714                 io = req->async_data;
4715         } else {
4716                 ret = move_addr_to_kernel(connect->addr,
4717                                                 connect->addr_len,
4718                                                 &__io.address);
4719                 if (ret)
4720                         goto out;
4721                 io = &__io;
4722         }
4723
4724         file_flags = force_nonblock ? O_NONBLOCK : 0;
4725
4726         ret = __sys_connect_file(req->file, &io->address,
4727                                         connect->addr_len, file_flags);
4728         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4729                 if (req_has_async_data(req))
4730                         return -EAGAIN;
4731                 if (io_alloc_async_data(req)) {
4732                         ret = -ENOMEM;
4733                         goto out;
4734                 }
4735                 memcpy(req->async_data, &__io, sizeof(__io));
4736                 return -EAGAIN;
4737         }
4738         if (ret == -ERESTARTSYS)
4739                 ret = -EINTR;
4740 out:
4741         if (ret < 0)
4742                 req_set_fail(req);
4743         io_req_set_res(req, ret, 0);
4744         return IOU_OK;
4745 }
4746 #else /* !CONFIG_NET */
4747 #define IO_NETOP_FN(op)                                                 \
4748 static int io_##op(struct io_kiocb *req, unsigned int issue_flags)      \
4749 {                                                                       \
4750         return -EOPNOTSUPP;                                             \
4751 }
4752
4753 #define IO_NETOP_PREP(op)                                               \
4754 IO_NETOP_FN(op)                                                         \
4755 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4756 {                                                                       \
4757         return -EOPNOTSUPP;                                             \
4758 }                                                                       \
4759
4760 #define IO_NETOP_PREP_ASYNC(op)                                         \
4761 IO_NETOP_PREP(op)                                                       \
4762 static int io_##op##_prep_async(struct io_kiocb *req)                   \
4763 {                                                                       \
4764         return -EOPNOTSUPP;                                             \
4765 }
4766
4767 IO_NETOP_PREP_ASYNC(sendmsg);
4768 IO_NETOP_PREP_ASYNC(recvmsg);
4769 IO_NETOP_PREP_ASYNC(connect);
4770 IO_NETOP_PREP(accept);
4771 IO_NETOP_PREP(socket);
4772 IO_NETOP_PREP(shutdown);
4773 IO_NETOP_FN(send);
4774 IO_NETOP_FN(recv);
4775 #endif /* CONFIG_NET */
4776
4777 struct io_poll_table {
4778         struct poll_table_struct pt;
4779         struct io_kiocb *req;
4780         int nr_entries;
4781         int error;
4782 };
4783
4784 #define IO_POLL_CANCEL_FLAG     BIT(31)
4785 #define IO_POLL_REF_MASK        GENMASK(30, 0)
4786
4787 /*
4788  * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
4789  * bump it and acquire ownership. It's disallowed to modify requests while not
4790  * owning it, that prevents from races for enqueueing task_work's and b/w
4791  * arming poll and wakeups.
4792  */
4793 static inline bool io_poll_get_ownership(struct io_kiocb *req)
4794 {
4795         return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
4796 }
4797
4798 static void io_poll_mark_cancelled(struct io_kiocb *req)
4799 {
4800         atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
4801 }
4802
4803 static struct io_poll *io_poll_get_double(struct io_kiocb *req)
4804 {
4805         /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4806         if (req->opcode == IORING_OP_POLL_ADD)
4807                 return req->async_data;
4808         return req->apoll->double_poll;
4809 }
4810
4811 static struct io_poll *io_poll_get_single(struct io_kiocb *req)
4812 {
4813         if (req->opcode == IORING_OP_POLL_ADD)
4814                 return io_kiocb_to_cmd(req);
4815         return &req->apoll->poll;
4816 }
4817
4818 static void io_poll_req_insert(struct io_kiocb *req)
4819 {
4820         struct io_ring_ctx *ctx = req->ctx;
4821         struct hlist_head *list;
4822
4823         list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
4824         hlist_add_head(&req->hash_node, list);
4825 }
4826
4827 static void io_init_poll_iocb(struct io_poll *poll, __poll_t events,
4828                               wait_queue_func_t wake_func)
4829 {
4830         poll->head = NULL;
4831 #define IO_POLL_UNMASK  (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4832         /* mask in events that we always want/need */
4833         poll->events = events | IO_POLL_UNMASK;
4834         INIT_LIST_HEAD(&poll->wait.entry);
4835         init_waitqueue_func_entry(&poll->wait, wake_func);
4836 }
4837
4838 static inline void io_poll_remove_entry(struct io_poll *poll)
4839 {
4840         struct wait_queue_head *head = smp_load_acquire(&poll->head);
4841
4842         if (head) {
4843                 spin_lock_irq(&head->lock);
4844                 list_del_init(&poll->wait.entry);
4845                 poll->head = NULL;
4846                 spin_unlock_irq(&head->lock);
4847         }
4848 }
4849
4850 static void io_poll_remove_entries(struct io_kiocb *req)
4851 {
4852         /*
4853          * Nothing to do if neither of those flags are set. Avoid dipping
4854          * into the poll/apoll/double cachelines if we can.
4855          */
4856         if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
4857                 return;
4858
4859         /*
4860          * While we hold the waitqueue lock and the waitqueue is nonempty,
4861          * wake_up_pollfree() will wait for us.  However, taking the waitqueue
4862          * lock in the first place can race with the waitqueue being freed.
4863          *
4864          * We solve this as eventpoll does: by taking advantage of the fact that
4865          * all users of wake_up_pollfree() will RCU-delay the actual free.  If
4866          * we enter rcu_read_lock() and see that the pointer to the queue is
4867          * non-NULL, we can then lock it without the memory being freed out from
4868          * under us.
4869          *
4870          * Keep holding rcu_read_lock() as long as we hold the queue lock, in
4871          * case the caller deletes the entry from the queue, leaving it empty.
4872          * In that case, only RCU prevents the queue memory from being freed.
4873          */
4874         rcu_read_lock();
4875         if (req->flags & REQ_F_SINGLE_POLL)
4876                 io_poll_remove_entry(io_poll_get_single(req));
4877         if (req->flags & REQ_F_DOUBLE_POLL)
4878                 io_poll_remove_entry(io_poll_get_double(req));
4879         rcu_read_unlock();
4880 }
4881
4882 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
4883 /*
4884  * All poll tw should go through this. Checks for poll events, manages
4885  * references, does rewait, etc.
4886  *
4887  * Returns a negative error on failure. >0 when no action require, which is
4888  * either spurious wakeup or multishot CQE is served. 0 when it's done with
4889  * the request, then the mask is stored in req->cqe.res.
4890  */
4891 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
4892 {
4893         struct io_ring_ctx *ctx = req->ctx;
4894         int v, ret;
4895
4896         /* req->task == current here, checking PF_EXITING is safe */
4897         if (unlikely(req->task->flags & PF_EXITING))
4898                 return -ECANCELED;
4899
4900         do {
4901                 v = atomic_read(&req->poll_refs);
4902
4903                 /* tw handler should be the owner, and so have some references */
4904                 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
4905                         return 0;
4906                 if (v & IO_POLL_CANCEL_FLAG)
4907                         return -ECANCELED;
4908
4909                 if (!req->cqe.res) {
4910                         struct poll_table_struct pt = { ._key = req->apoll_events };
4911                         req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
4912                 }
4913
4914                 if ((unlikely(!req->cqe.res)))
4915                         continue;
4916                 if (req->apoll_events & EPOLLONESHOT)
4917                         return 0;
4918
4919                 /* multishot, just fill a CQE and proceed */
4920                 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
4921                         __poll_t mask = mangle_poll(req->cqe.res &
4922                                                     req->apoll_events);
4923                         bool filled;
4924
4925                         spin_lock(&ctx->completion_lock);
4926                         filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
4927                                                  mask, IORING_CQE_F_MORE);
4928                         io_commit_cqring(ctx);
4929                         spin_unlock(&ctx->completion_lock);
4930                         if (filled) {
4931                                 io_cqring_ev_posted(ctx);
4932                                 continue;
4933                         }
4934                         return -ECANCELED;
4935                 }
4936
4937                 io_tw_lock(req->ctx, locked);
4938                 if (unlikely(req->task->flags & PF_EXITING))
4939                         return -EFAULT;
4940                 ret = io_issue_sqe(req,
4941                                    IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
4942                 if (ret)
4943                         return ret;
4944
4945                 /*
4946                  * Release all references, retry if someone tried to restart
4947                  * task_work while we were executing it.
4948                  */
4949         } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
4950
4951         return 1;
4952 }
4953
4954 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
4955 {
4956         struct io_ring_ctx *ctx = req->ctx;
4957         int ret;
4958
4959         ret = io_poll_check_events(req, locked);
4960         if (ret > 0)
4961                 return;
4962
4963         if (!ret) {
4964                 struct io_poll *poll = io_kiocb_to_cmd(req);
4965
4966                 req->cqe.res = mangle_poll(req->cqe.res & poll->events);
4967         } else {
4968                 req->cqe.res = ret;
4969                 req_set_fail(req);
4970         }
4971
4972         io_poll_remove_entries(req);
4973         spin_lock(&ctx->completion_lock);
4974         hash_del(&req->hash_node);
4975         req->cqe.flags = 0;
4976         __io_req_complete_post(req);
4977         io_commit_cqring(ctx);
4978         spin_unlock(&ctx->completion_lock);
4979         io_cqring_ev_posted(ctx);
4980 }
4981
4982 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
4983 {
4984         struct io_ring_ctx *ctx = req->ctx;
4985         int ret;
4986
4987         ret = io_poll_check_events(req, locked);
4988         if (ret > 0)
4989                 return;
4990
4991         io_poll_remove_entries(req);
4992         spin_lock(&ctx->completion_lock);
4993         hash_del(&req->hash_node);
4994         spin_unlock(&ctx->completion_lock);
4995
4996         if (!ret)
4997                 io_req_task_submit(req, locked);
4998         else
4999                 io_req_complete_failed(req, ret);
5000 }
5001
5002 static void __io_poll_execute(struct io_kiocb *req, int mask,
5003                               __poll_t __maybe_unused events)
5004 {
5005         io_req_set_res(req, mask, 0);
5006         /*
5007          * This is useful for poll that is armed on behalf of another
5008          * request, and where the wakeup path could be on a different
5009          * CPU. We want to avoid pulling in req->apoll->events for that
5010          * case.
5011          */
5012         if (req->opcode == IORING_OP_POLL_ADD)
5013                 req->io_task_work.func = io_poll_task_func;
5014         else
5015                 req->io_task_work.func = io_apoll_task_func;
5016
5017         trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
5018         io_req_task_work_add(req);
5019 }
5020
5021 static inline void io_poll_execute(struct io_kiocb *req, int res,
5022                 __poll_t events)
5023 {
5024         if (io_poll_get_ownership(req))
5025                 __io_poll_execute(req, res, events);
5026 }
5027
5028 static void io_poll_cancel_req(struct io_kiocb *req)
5029 {
5030         io_poll_mark_cancelled(req);
5031         /* kick tw, which should complete the request */
5032         io_poll_execute(req, 0, 0);
5033 }
5034
5035 #define wqe_to_req(wait)        ((void *)((unsigned long) (wait)->private & ~1))
5036 #define wqe_is_double(wait)     ((unsigned long) (wait)->private & 1)
5037 #define IO_ASYNC_POLL_COMMON    (EPOLLONESHOT | EPOLLPRI)
5038
5039 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5040                         void *key)
5041 {
5042         struct io_kiocb *req = wqe_to_req(wait);
5043         struct io_poll *poll = container_of(wait, struct io_poll, wait);
5044         __poll_t mask = key_to_poll(key);
5045
5046         if (unlikely(mask & POLLFREE)) {
5047                 io_poll_mark_cancelled(req);
5048                 /* we have to kick tw in case it's not already */
5049                 io_poll_execute(req, 0, poll->events);
5050
5051                 /*
5052                  * If the waitqueue is being freed early but someone is already
5053                  * holds ownership over it, we have to tear down the request as
5054                  * best we can. That means immediately removing the request from
5055                  * its waitqueue and preventing all further accesses to the
5056                  * waitqueue via the request.
5057                  */
5058                 list_del_init(&poll->wait.entry);
5059
5060                 /*
5061                  * Careful: this *must* be the last step, since as soon
5062                  * as req->head is NULL'ed out, the request can be
5063                  * completed and freed, since aio_poll_complete_work()
5064                  * will no longer need to take the waitqueue lock.
5065                  */
5066                 smp_store_release(&poll->head, NULL);
5067                 return 1;
5068         }
5069
5070         /* for instances that support it check for an event match first */
5071         if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
5072                 return 0;
5073
5074         if (io_poll_get_ownership(req)) {
5075                 /* optional, saves extra locking for removal in tw handler */
5076                 if (mask && poll->events & EPOLLONESHOT) {
5077                         list_del_init(&poll->wait.entry);
5078                         poll->head = NULL;
5079                         if (wqe_is_double(wait))
5080                                 req->flags &= ~REQ_F_DOUBLE_POLL;
5081                         else
5082                                 req->flags &= ~REQ_F_SINGLE_POLL;
5083                 }
5084                 __io_poll_execute(req, mask, poll->events);
5085         }
5086         return 1;
5087 }
5088
5089 static void __io_queue_proc(struct io_poll *poll, struct io_poll_table *pt,
5090                             struct wait_queue_head *head,
5091                             struct io_poll **poll_ptr)
5092 {
5093         struct io_kiocb *req = pt->req;
5094         unsigned long wqe_private = (unsigned long) req;
5095
5096         /*
5097          * The file being polled uses multiple waitqueues for poll handling
5098          * (e.g. one for read, one for write). Setup a separate io_poll
5099          * if this happens.
5100          */
5101         if (unlikely(pt->nr_entries)) {
5102                 struct io_poll *first = poll;
5103
5104                 /* double add on the same waitqueue head, ignore */
5105                 if (first->head == head)
5106                         return;
5107                 /* already have a 2nd entry, fail a third attempt */
5108                 if (*poll_ptr) {
5109                         if ((*poll_ptr)->head == head)
5110                                 return;
5111                         pt->error = -EINVAL;
5112                         return;
5113                 }
5114
5115                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5116                 if (!poll) {
5117                         pt->error = -ENOMEM;
5118                         return;
5119                 }
5120                 /* mark as double wq entry */
5121                 wqe_private |= 1;
5122                 req->flags |= REQ_F_DOUBLE_POLL;
5123                 io_init_poll_iocb(poll, first->events, first->wait.func);
5124                 *poll_ptr = poll;
5125                 if (req->opcode == IORING_OP_POLL_ADD)
5126                         req->flags |= REQ_F_ASYNC_DATA;
5127         }
5128
5129         req->flags |= REQ_F_SINGLE_POLL;
5130         pt->nr_entries++;
5131         poll->head = head;
5132         poll->wait.private = (void *) wqe_private;
5133
5134         if (poll->events & EPOLLEXCLUSIVE)
5135                 add_wait_queue_exclusive(head, &poll->wait);
5136         else
5137                 add_wait_queue(head, &poll->wait);
5138 }
5139
5140 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5141                                struct poll_table_struct *p)
5142 {
5143         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5144         struct io_poll *poll = io_kiocb_to_cmd(pt->req);
5145
5146         __io_queue_proc(poll, pt, head,
5147                         (struct io_poll **) &pt->req->async_data);
5148 }
5149
5150 static int __io_arm_poll_handler(struct io_kiocb *req,
5151                                  struct io_poll *poll,
5152                                  struct io_poll_table *ipt, __poll_t mask)
5153 {
5154         struct io_ring_ctx *ctx = req->ctx;
5155         int v;
5156
5157         INIT_HLIST_NODE(&req->hash_node);
5158         req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
5159         io_init_poll_iocb(poll, mask, io_poll_wake);
5160         poll->file = req->file;
5161
5162         req->apoll_events = poll->events;
5163
5164         ipt->pt._key = mask;
5165         ipt->req = req;
5166         ipt->error = 0;
5167         ipt->nr_entries = 0;
5168
5169         /*
5170          * Take the ownership to delay any tw execution up until we're done
5171          * with poll arming. see io_poll_get_ownership().
5172          */
5173         atomic_set(&req->poll_refs, 1);
5174         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5175
5176         if (mask && (poll->events & EPOLLONESHOT)) {
5177                 io_poll_remove_entries(req);
5178                 /* no one else has access to the req, forget about the ref */
5179                 return mask;
5180         }
5181         if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5182                 io_poll_remove_entries(req);
5183                 if (!ipt->error)
5184                         ipt->error = -EINVAL;
5185                 return 0;
5186         }
5187
5188         spin_lock(&ctx->completion_lock);
5189         io_poll_req_insert(req);
5190         spin_unlock(&ctx->completion_lock);
5191
5192         if (mask) {
5193                 /* can't multishot if failed, just queue the event we've got */
5194                 if (unlikely(ipt->error || !ipt->nr_entries)) {
5195                         poll->events |= EPOLLONESHOT;
5196                         req->apoll_events |= EPOLLONESHOT;
5197                         ipt->error = 0;
5198                 }
5199                 __io_poll_execute(req, mask, poll->events);
5200                 return 0;
5201         }
5202
5203         /*
5204          * Release ownership. If someone tried to queue a tw while it was
5205          * locked, kick it off for them.
5206          */
5207         v = atomic_dec_return(&req->poll_refs);
5208         if (unlikely(v & IO_POLL_REF_MASK))
5209                 __io_poll_execute(req, 0, poll->events);
5210         return 0;
5211 }
5212
5213 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5214                                struct poll_table_struct *p)
5215 {
5216         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5217         struct async_poll *apoll = pt->req->apoll;
5218
5219         __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5220 }
5221
5222 enum {
5223         IO_APOLL_OK,
5224         IO_APOLL_ABORTED,
5225         IO_APOLL_READY
5226 };
5227
5228 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
5229 {
5230         const struct io_op_def *def = &io_op_defs[req->opcode];
5231         struct io_ring_ctx *ctx = req->ctx;
5232         struct async_poll *apoll;
5233         struct io_poll_table ipt;
5234         __poll_t mask = POLLPRI | POLLERR;
5235         int ret;
5236
5237         if (!def->pollin && !def->pollout)
5238                 return IO_APOLL_ABORTED;
5239         if (!file_can_poll(req->file))
5240                 return IO_APOLL_ABORTED;
5241         if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
5242                 return IO_APOLL_ABORTED;
5243         if (!(req->flags & REQ_F_APOLL_MULTISHOT))
5244                 mask |= EPOLLONESHOT;
5245
5246         if (def->pollin) {
5247                 mask |= EPOLLIN | EPOLLRDNORM;
5248
5249                 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5250                 if (req->flags & REQ_F_CLEAR_POLLIN)
5251                         mask &= ~EPOLLIN;
5252         } else {
5253                 mask |= EPOLLOUT | EPOLLWRNORM;
5254         }
5255         if (def->poll_exclusive)
5256                 mask |= EPOLLEXCLUSIVE;
5257         if (req->flags & REQ_F_POLLED) {
5258                 apoll = req->apoll;
5259                 kfree(apoll->double_poll);
5260         } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
5261                    !list_empty(&ctx->apoll_cache)) {
5262                 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
5263                                                 poll.wait.entry);
5264                 list_del_init(&apoll->poll.wait.entry);
5265         } else {
5266                 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5267                 if (unlikely(!apoll))
5268                         return IO_APOLL_ABORTED;
5269         }
5270         apoll->double_poll = NULL;
5271         req->apoll = apoll;
5272         req->flags |= REQ_F_POLLED;
5273         ipt.pt._qproc = io_async_queue_proc;
5274
5275         io_kbuf_recycle(req, issue_flags);
5276
5277         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5278         if (ret || ipt.error)
5279                 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5280
5281         trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
5282                                 mask, apoll->poll.events);
5283         return IO_APOLL_OK;
5284 }
5285
5286 /*
5287  * Returns true if we found and killed one or more poll requests
5288  */
5289 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5290                                       struct task_struct *tsk, bool cancel_all)
5291 {
5292         struct hlist_node *tmp;
5293         struct io_kiocb *req;
5294         bool found = false;
5295         int i;
5296
5297         spin_lock(&ctx->completion_lock);
5298         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5299                 struct hlist_head *list;
5300
5301                 list = &ctx->cancel_hash[i];
5302                 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5303                         if (io_match_task_safe(req, tsk, cancel_all)) {
5304                                 hlist_del_init(&req->hash_node);
5305                                 io_poll_cancel_req(req);
5306                                 found = true;
5307                         }
5308                 }
5309         }
5310         spin_unlock(&ctx->completion_lock);
5311         return found;
5312 }
5313
5314 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
5315                                      struct io_cancel_data *cd)
5316         __must_hold(&ctx->completion_lock)
5317 {
5318         struct hlist_head *list;
5319         struct io_kiocb *req;
5320
5321         list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
5322         hlist_for_each_entry(req, list, hash_node) {
5323                 if (cd->data != req->cqe.user_data)
5324                         continue;
5325                 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5326                         continue;
5327                 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
5328                         if (cd->seq == req->work.cancel_seq)
5329                                 continue;
5330                         req->work.cancel_seq = cd->seq;
5331                 }
5332                 return req;
5333         }
5334         return NULL;
5335 }
5336
5337 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
5338                                           struct io_cancel_data *cd)
5339         __must_hold(&ctx->completion_lock)
5340 {
5341         struct io_kiocb *req;
5342         int i;
5343
5344         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5345                 struct hlist_head *list;
5346
5347                 list = &ctx->cancel_hash[i];
5348                 hlist_for_each_entry(req, list, hash_node) {
5349                         if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
5350                             req->file != cd->file)
5351                                 continue;
5352                         if (cd->seq == req->work.cancel_seq)
5353                                 continue;
5354                         req->work.cancel_seq = cd->seq;
5355                         return req;
5356                 }
5357         }
5358         return NULL;
5359 }
5360
5361 static bool io_poll_disarm(struct io_kiocb *req)
5362         __must_hold(&ctx->completion_lock)
5363 {
5364         if (!io_poll_get_ownership(req))
5365                 return false;
5366         io_poll_remove_entries(req);
5367         hash_del(&req->hash_node);
5368         return true;
5369 }
5370
5371 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
5372         __must_hold(&ctx->completion_lock)
5373 {
5374         struct io_kiocb *req;
5375
5376         if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
5377                 req = io_poll_file_find(ctx, cd);
5378         else
5379                 req = io_poll_find(ctx, false, cd);
5380         if (!req)
5381                 return -ENOENT;
5382         io_poll_cancel_req(req);
5383         return 0;
5384 }
5385
5386 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5387                                      unsigned int flags)
5388 {
5389         u32 events;
5390
5391         events = READ_ONCE(sqe->poll32_events);
5392 #ifdef __BIG_ENDIAN
5393         events = swahw32(events);
5394 #endif
5395         if (!(flags & IORING_POLL_ADD_MULTI))
5396                 events |= EPOLLONESHOT;
5397         return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5398 }
5399
5400 static int io_poll_remove_prep(struct io_kiocb *req,
5401                                const struct io_uring_sqe *sqe)
5402 {
5403         struct io_poll_update *upd = io_kiocb_to_cmd(req);
5404         u32 flags;
5405
5406         if (sqe->buf_index || sqe->splice_fd_in)
5407                 return -EINVAL;
5408         flags = READ_ONCE(sqe->len);
5409         if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5410                       IORING_POLL_ADD_MULTI))
5411                 return -EINVAL;
5412         /* meaningless without update */
5413         if (flags == IORING_POLL_ADD_MULTI)
5414                 return -EINVAL;
5415
5416         upd->old_user_data = READ_ONCE(sqe->addr);
5417         upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5418         upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5419
5420         upd->new_user_data = READ_ONCE(sqe->off);
5421         if (!upd->update_user_data && upd->new_user_data)
5422                 return -EINVAL;
5423         if (upd->update_events)
5424                 upd->events = io_poll_parse_events(sqe, flags);
5425         else if (sqe->poll32_events)
5426                 return -EINVAL;
5427
5428         return 0;
5429 }
5430
5431 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5432 {
5433         struct io_poll *poll = io_kiocb_to_cmd(req);
5434         u32 flags;
5435
5436         if (sqe->buf_index || sqe->off || sqe->addr)
5437                 return -EINVAL;
5438         flags = READ_ONCE(sqe->len);
5439         if (flags & ~IORING_POLL_ADD_MULTI)
5440                 return -EINVAL;
5441         if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
5442                 return -EINVAL;
5443
5444         io_req_set_refcount(req);
5445         poll->events = io_poll_parse_events(sqe, flags);
5446         return 0;
5447 }
5448
5449 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5450 {
5451         struct io_poll *poll = io_kiocb_to_cmd(req);
5452         struct io_poll_table ipt;
5453         int ret;
5454
5455         ipt.pt._qproc = io_poll_queue_proc;
5456
5457         ret = __io_arm_poll_handler(req, poll, &ipt, poll->events);
5458         if (ret) {
5459                 io_req_set_res(req, ret, 0);
5460                 return IOU_OK;
5461         }
5462         if (ipt.error) {
5463                 req_set_fail(req);
5464                 return ipt.error;
5465         }
5466
5467         return IOU_ISSUE_SKIP_COMPLETE;
5468 }
5469
5470 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5471 {
5472         struct io_poll_update *poll_update = io_kiocb_to_cmd(req);
5473         struct io_cancel_data cd = { .data = poll_update->old_user_data, };
5474         struct io_ring_ctx *ctx = req->ctx;
5475         struct io_kiocb *preq;
5476         int ret2, ret = 0;
5477         bool locked;
5478
5479         spin_lock(&ctx->completion_lock);
5480         preq = io_poll_find(ctx, true, &cd);
5481         if (!preq || !io_poll_disarm(preq)) {
5482                 spin_unlock(&ctx->completion_lock);
5483                 ret = preq ? -EALREADY : -ENOENT;
5484                 goto out;
5485         }
5486         spin_unlock(&ctx->completion_lock);
5487
5488         if (poll_update->update_events || poll_update->update_user_data) {
5489                 /* only mask one event flags, keep behavior flags */
5490                 if (poll_update->update_events) {
5491                         struct io_poll *poll = io_kiocb_to_cmd(preq);
5492
5493                         poll->events &= ~0xffff;
5494                         poll->events |= poll_update->events & 0xffff;
5495                         poll->events |= IO_POLL_UNMASK;
5496                 }
5497                 if (poll_update->update_user_data)
5498                         preq->cqe.user_data = poll_update->new_user_data;
5499
5500                 ret2 = io_poll_add(preq, issue_flags);
5501                 /* successfully updated, don't complete poll request */
5502                 if (!ret2 || ret2 == -EIOCBQUEUED)
5503                         goto out;
5504         }
5505
5506         req_set_fail(preq);
5507         io_req_set_res(preq, -ECANCELED, 0);
5508         locked = !(issue_flags & IO_URING_F_UNLOCKED);
5509         io_req_task_complete(preq, &locked);
5510 out:
5511         if (ret < 0) {
5512                 req_set_fail(req);
5513                 return ret;
5514         }
5515         /* complete update request, we're done with it */
5516         io_req_set_res(req, ret, 0);
5517         return IOU_OK;
5518 }
5519
5520 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5521 {
5522         struct io_timeout_data *data = container_of(timer,
5523                                                 struct io_timeout_data, timer);
5524         struct io_kiocb *req = data->req;
5525         struct io_timeout *timeout = io_kiocb_to_cmd(req);
5526         struct io_ring_ctx *ctx = req->ctx;
5527         unsigned long flags;
5528
5529         spin_lock_irqsave(&ctx->timeout_lock, flags);
5530         list_del_init(&timeout->list);
5531         atomic_set(&req->ctx->cq_timeouts,
5532                 atomic_read(&req->ctx->cq_timeouts) + 1);
5533         spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5534
5535         if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
5536                 req_set_fail(req);
5537
5538         io_req_set_res(req, -ETIME, 0);
5539         req->io_task_work.func = io_req_task_complete;
5540         io_req_task_work_add(req);
5541         return HRTIMER_NORESTART;
5542 }
5543
5544 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5545                                            struct io_cancel_data *cd)
5546         __must_hold(&ctx->timeout_lock)
5547 {
5548         struct io_timeout *timeout;
5549         struct io_timeout_data *io;
5550         struct io_kiocb *req = NULL;
5551
5552         list_for_each_entry(timeout, &ctx->timeout_list, list) {
5553                 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
5554
5555                 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
5556                     cd->data != tmp->cqe.user_data)
5557                         continue;
5558                 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
5559                         if (cd->seq == tmp->work.cancel_seq)
5560                                 continue;
5561                         tmp->work.cancel_seq = cd->seq;
5562                 }
5563                 req = tmp;
5564                 break;
5565         }
5566         if (!req)
5567                 return ERR_PTR(-ENOENT);
5568
5569         io = req->async_data;
5570         if (hrtimer_try_to_cancel(&io->timer) == -1)
5571                 return ERR_PTR(-EALREADY);
5572         timeout = io_kiocb_to_cmd(req);
5573         list_del_init(&timeout->list);
5574         return req;
5575 }
5576
5577 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
5578         __must_hold(&ctx->completion_lock)
5579 {
5580         struct io_kiocb *req;
5581
5582         spin_lock_irq(&ctx->timeout_lock);
5583         req = io_timeout_extract(ctx, cd);
5584         spin_unlock_irq(&ctx->timeout_lock);
5585
5586         if (IS_ERR(req))
5587                 return PTR_ERR(req);
5588         io_req_task_queue_fail(req, -ECANCELED);
5589         return 0;
5590 }
5591
5592 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5593 {
5594         switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5595         case IORING_TIMEOUT_BOOTTIME:
5596                 return CLOCK_BOOTTIME;
5597         case IORING_TIMEOUT_REALTIME:
5598                 return CLOCK_REALTIME;
5599         default:
5600                 /* can't happen, vetted at prep time */
5601                 WARN_ON_ONCE(1);
5602                 fallthrough;
5603         case 0:
5604                 return CLOCK_MONOTONIC;
5605         }
5606 }
5607
5608 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5609                                     struct timespec64 *ts, enum hrtimer_mode mode)
5610         __must_hold(&ctx->timeout_lock)
5611 {
5612         struct io_timeout_data *io;
5613         struct io_timeout *timeout;
5614         struct io_kiocb *req = NULL;
5615
5616         list_for_each_entry(timeout, &ctx->ltimeout_list, list) {
5617                 struct io_kiocb *tmp = cmd_to_io_kiocb(timeout);
5618
5619                 if (user_data == tmp->cqe.user_data) {
5620                         req = tmp;
5621                         break;
5622                 }
5623         }
5624         if (!req)
5625                 return -ENOENT;
5626
5627         io = req->async_data;
5628         if (hrtimer_try_to_cancel(&io->timer) == -1)
5629                 return -EALREADY;
5630         hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5631         io->timer.function = io_link_timeout_fn;
5632         hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5633         return 0;
5634 }
5635
5636 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5637                              struct timespec64 *ts, enum hrtimer_mode mode)
5638         __must_hold(&ctx->timeout_lock)
5639 {
5640         struct io_cancel_data cd = { .data = user_data, };
5641         struct io_kiocb *req = io_timeout_extract(ctx, &cd);
5642         struct io_timeout *timeout = io_kiocb_to_cmd(req);
5643         struct io_timeout_data *data;
5644
5645         if (IS_ERR(req))
5646                 return PTR_ERR(req);
5647
5648         timeout->off = 0; /* noseq */
5649         data = req->async_data;
5650         list_add_tail(&timeout->list, &ctx->timeout_list);
5651         hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5652         data->timer.function = io_timeout_fn;
5653         hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5654         return 0;
5655 }
5656
5657 static int io_timeout_remove_prep(struct io_kiocb *req,
5658                                   const struct io_uring_sqe *sqe)
5659 {
5660         struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
5661
5662         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5663                 return -EINVAL;
5664         if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
5665                 return -EINVAL;
5666
5667         tr->ltimeout = false;
5668         tr->addr = READ_ONCE(sqe->addr);
5669         tr->flags = READ_ONCE(sqe->timeout_flags);
5670         if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5671                 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5672                         return -EINVAL;
5673                 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5674                         tr->ltimeout = true;
5675                 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5676                         return -EINVAL;
5677                 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5678                         return -EFAULT;
5679                 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
5680                         return -EINVAL;
5681         } else if (tr->flags) {
5682                 /* timeout removal doesn't support flags */
5683                 return -EINVAL;
5684         }
5685
5686         return 0;
5687 }
5688
5689 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5690 {
5691         return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5692                                             : HRTIMER_MODE_REL;
5693 }
5694
5695 /*
5696  * Remove or update an existing timeout command
5697  */
5698 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5699 {
5700         struct io_timeout_rem *tr = io_kiocb_to_cmd(req);
5701         struct io_ring_ctx *ctx = req->ctx;
5702         int ret;
5703
5704         if (!(tr->flags & IORING_TIMEOUT_UPDATE)) {
5705                 struct io_cancel_data cd = { .data = tr->addr, };
5706
5707                 spin_lock(&ctx->completion_lock);
5708                 ret = io_timeout_cancel(ctx, &cd);
5709                 spin_unlock(&ctx->completion_lock);
5710         } else {
5711                 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5712
5713                 spin_lock_irq(&ctx->timeout_lock);
5714                 if (tr->ltimeout)
5715                         ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5716                 else
5717                         ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5718                 spin_unlock_irq(&ctx->timeout_lock);
5719         }
5720
5721         if (ret < 0)
5722                 req_set_fail(req);
5723         io_req_set_res(req, ret, 0);
5724         return IOU_OK;
5725 }
5726
5727 static int __io_timeout_prep(struct io_kiocb *req,
5728                              const struct io_uring_sqe *sqe,
5729                              bool is_timeout_link)
5730 {
5731         struct io_timeout *timeout = io_kiocb_to_cmd(req);
5732         struct io_timeout_data *data;
5733         unsigned flags;
5734         u32 off = READ_ONCE(sqe->off);
5735
5736         if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
5737                 return -EINVAL;
5738         if (off && is_timeout_link)
5739                 return -EINVAL;
5740         flags = READ_ONCE(sqe->timeout_flags);
5741         if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
5742                       IORING_TIMEOUT_ETIME_SUCCESS))
5743                 return -EINVAL;
5744         /* more than one clock specified is invalid, obviously */
5745         if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5746                 return -EINVAL;
5747
5748         INIT_LIST_HEAD(&timeout->list);
5749         timeout->off = off;
5750         if (unlikely(off && !req->ctx->off_timeout_used))
5751                 req->ctx->off_timeout_used = true;
5752
5753         if (WARN_ON_ONCE(req_has_async_data(req)))
5754                 return -EFAULT;
5755         if (io_alloc_async_data(req))
5756                 return -ENOMEM;
5757
5758         data = req->async_data;
5759         data->req = req;
5760         data->flags = flags;
5761
5762         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5763                 return -EFAULT;
5764
5765         if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
5766                 return -EINVAL;
5767
5768         INIT_LIST_HEAD(&timeout->list);
5769         data->mode = io_translate_timeout_mode(flags);
5770         hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5771
5772         if (is_timeout_link) {
5773                 struct io_submit_link *link = &req->ctx->submit_state.link;
5774
5775                 if (!link->head)
5776                         return -EINVAL;
5777                 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5778                         return -EINVAL;
5779                 timeout->head = link->last;
5780                 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5781         }
5782         return 0;
5783 }
5784
5785 static int io_timeout_prep(struct io_kiocb *req,
5786                            const struct io_uring_sqe *sqe)
5787 {
5788         return __io_timeout_prep(req, sqe, false);
5789 }
5790
5791 static int io_link_timeout_prep(struct io_kiocb *req,
5792                                 const struct io_uring_sqe *sqe)
5793 {
5794         return __io_timeout_prep(req, sqe, true);
5795 }
5796
5797 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5798 {
5799         struct io_timeout *timeout = io_kiocb_to_cmd(req);
5800         struct io_ring_ctx *ctx = req->ctx;
5801         struct io_timeout_data *data = req->async_data;
5802         struct list_head *entry;
5803         u32 tail, off = timeout->off;
5804
5805         spin_lock_irq(&ctx->timeout_lock);
5806
5807         /*
5808          * sqe->off holds how many events that need to occur for this
5809          * timeout event to be satisfied. If it isn't set, then this is
5810          * a pure timeout request, sequence isn't used.
5811          */
5812         if (io_is_timeout_noseq(req)) {
5813                 entry = ctx->timeout_list.prev;
5814                 goto add;
5815         }
5816
5817         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5818         timeout->target_seq = tail + off;
5819
5820         /* Update the last seq here in case io_flush_timeouts() hasn't.
5821          * This is safe because ->completion_lock is held, and submissions
5822          * and completions are never mixed in the same ->completion_lock section.
5823          */
5824         ctx->cq_last_tm_flush = tail;
5825
5826         /*
5827          * Insertion sort, ensuring the first entry in the list is always
5828          * the one we need first.
5829          */
5830         list_for_each_prev(entry, &ctx->timeout_list) {
5831                 struct io_timeout *nextt = list_entry(entry, struct io_timeout, list);
5832                 struct io_kiocb *nxt = cmd_to_io_kiocb(nextt);
5833
5834                 if (io_is_timeout_noseq(nxt))
5835                         continue;
5836                 /* nxt.seq is behind @tail, otherwise would've been completed */
5837                 if (off >= nextt->target_seq - tail)
5838                         break;
5839         }
5840 add:
5841         list_add(&timeout->list, entry);
5842         data->timer.function = io_timeout_fn;
5843         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5844         spin_unlock_irq(&ctx->timeout_lock);
5845         return IOU_ISSUE_SKIP_COMPLETE;
5846 }
5847
5848 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5849 {
5850         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5851         struct io_cancel_data *cd = data;
5852
5853         if (req->ctx != cd->ctx)
5854                 return false;
5855         if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
5856                 ;
5857         } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
5858                 if (req->file != cd->file)
5859                         return false;
5860         } else {
5861                 if (req->cqe.user_data != cd->data)
5862                         return false;
5863         }
5864         if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
5865                 if (cd->seq == req->work.cancel_seq)
5866                         return false;
5867                 req->work.cancel_seq = cd->seq;
5868         }
5869         return true;
5870 }
5871
5872 static int io_async_cancel_one(struct io_uring_task *tctx,
5873                                struct io_cancel_data *cd)
5874 {
5875         enum io_wq_cancel cancel_ret;
5876         int ret = 0;
5877         bool all;
5878
5879         if (!tctx || !tctx->io_wq)
5880                 return -ENOENT;
5881
5882         all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
5883         cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
5884         switch (cancel_ret) {
5885         case IO_WQ_CANCEL_OK:
5886                 ret = 0;
5887                 break;
5888         case IO_WQ_CANCEL_RUNNING:
5889                 ret = -EALREADY;
5890                 break;
5891         case IO_WQ_CANCEL_NOTFOUND:
5892                 ret = -ENOENT;
5893                 break;
5894         }
5895
5896         return ret;
5897 }
5898
5899 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
5900 {
5901         struct io_ring_ctx *ctx = req->ctx;
5902         int ret;
5903
5904         WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
5905
5906         ret = io_async_cancel_one(req->task->io_uring, cd);
5907         /*
5908          * Fall-through even for -EALREADY, as we may have poll armed
5909          * that need unarming.
5910          */
5911         if (!ret)
5912                 return 0;
5913
5914         spin_lock(&ctx->completion_lock);
5915         ret = io_poll_cancel(ctx, cd);
5916         if (ret != -ENOENT)
5917                 goto out;
5918         if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
5919                 ret = io_timeout_cancel(ctx, cd);
5920 out:
5921         spin_unlock(&ctx->completion_lock);
5922         return ret;
5923 }
5924
5925 #define CANCEL_FLAGS    (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
5926                          IORING_ASYNC_CANCEL_ANY)
5927
5928 static int io_async_cancel_prep(struct io_kiocb *req,
5929                                 const struct io_uring_sqe *sqe)
5930 {
5931         struct io_cancel *cancel = io_kiocb_to_cmd(req);
5932
5933         if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
5934                 return -EINVAL;
5935         if (sqe->off || sqe->len || sqe->splice_fd_in)
5936                 return -EINVAL;
5937
5938         cancel->addr = READ_ONCE(sqe->addr);
5939         cancel->flags = READ_ONCE(sqe->cancel_flags);
5940         if (cancel->flags & ~CANCEL_FLAGS)
5941                 return -EINVAL;
5942         if (cancel->flags & IORING_ASYNC_CANCEL_FD) {
5943                 if (cancel->flags & IORING_ASYNC_CANCEL_ANY)
5944                         return -EINVAL;
5945                 cancel->fd = READ_ONCE(sqe->fd);
5946         }
5947
5948         return 0;
5949 }
5950
5951 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
5952                              unsigned int issue_flags)
5953 {
5954         bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
5955         struct io_ring_ctx *ctx = cd->ctx;
5956         struct io_tctx_node *node;
5957         int ret, nr = 0;
5958
5959         do {
5960                 ret = io_try_cancel(req, cd);
5961                 if (ret == -ENOENT)
5962                         break;
5963                 if (!all)
5964                         return ret;
5965                 nr++;
5966         } while (1);
5967
5968         /* slow path, try all io-wq's */
5969         io_ring_submit_lock(ctx, issue_flags);
5970         ret = -ENOENT;
5971         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5972                 struct io_uring_task *tctx = node->task->io_uring;
5973
5974                 ret = io_async_cancel_one(tctx, cd);
5975                 if (ret != -ENOENT) {
5976                         if (!all)
5977                                 break;
5978                         nr++;
5979                 }
5980         }
5981         io_ring_submit_unlock(ctx, issue_flags);
5982         return all ? nr : ret;
5983 }
5984
5985 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5986 {
5987         struct io_cancel *cancel = io_kiocb_to_cmd(req);
5988         struct io_cancel_data cd = {
5989                 .ctx    = req->ctx,
5990                 .data   = cancel->addr,
5991                 .flags  = cancel->flags,
5992                 .seq    = atomic_inc_return(&req->ctx->cancel_seq),
5993         };
5994         int ret;
5995
5996         if (cd.flags & IORING_ASYNC_CANCEL_FD) {
5997                 if (req->flags & REQ_F_FIXED_FILE)
5998                         req->file = io_file_get_fixed(req, cancel->fd,
5999                                                         issue_flags);
6000                 else
6001                         req->file = io_file_get_normal(req, cancel->fd);
6002                 if (!req->file) {
6003                         ret = -EBADF;
6004                         goto done;
6005                 }
6006                 cd.file = req->file;
6007         }
6008
6009         ret = __io_async_cancel(&cd, req, issue_flags);
6010 done:
6011         if (ret < 0)
6012                 req_set_fail(req);
6013         io_req_set_res(req, ret, 0);
6014         return IOU_OK;
6015 }
6016
6017 static int io_files_update_prep(struct io_kiocb *req,
6018                                 const struct io_uring_sqe *sqe)
6019 {
6020         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6021
6022         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6023                 return -EINVAL;
6024         if (sqe->rw_flags || sqe->splice_fd_in)
6025                 return -EINVAL;
6026
6027         up->offset = READ_ONCE(sqe->off);
6028         up->nr_args = READ_ONCE(sqe->len);
6029         if (!up->nr_args)
6030                 return -EINVAL;
6031         up->arg = READ_ONCE(sqe->addr);
6032         return 0;
6033 }
6034
6035 static int io_files_update_with_index_alloc(struct io_kiocb *req,
6036                                             unsigned int issue_flags)
6037 {
6038         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6039         __s32 __user *fds = u64_to_user_ptr(up->arg);
6040         unsigned int done;
6041         struct file *file;
6042         int ret, fd;
6043
6044         if (!req->ctx->file_data)
6045                 return -ENXIO;
6046
6047         for (done = 0; done < up->nr_args; done++) {
6048                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
6049                         ret = -EFAULT;
6050                         break;
6051                 }
6052
6053                 file = fget(fd);
6054                 if (!file) {
6055                         ret = -EBADF;
6056                         break;
6057                 }
6058                 ret = io_fixed_fd_install(req, issue_flags, file,
6059                                           IORING_FILE_INDEX_ALLOC);
6060                 if (ret < 0)
6061                         break;
6062                 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
6063                         __io_close_fixed(req, issue_flags, ret);
6064                         ret = -EFAULT;
6065                         break;
6066                 }
6067         }
6068
6069         if (done)
6070                 return done;
6071         return ret;
6072 }
6073
6074 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6075 {
6076         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
6077         struct io_ring_ctx *ctx = req->ctx;
6078         struct io_uring_rsrc_update2 up2;
6079         int ret;
6080
6081         up2.offset = up->offset;
6082         up2.data = up->arg;
6083         up2.nr = 0;
6084         up2.tags = 0;
6085         up2.resv = 0;
6086         up2.resv2 = 0;
6087
6088         if (up->offset == IORING_FILE_INDEX_ALLOC) {
6089                 ret = io_files_update_with_index_alloc(req, issue_flags);
6090         } else {
6091                 io_ring_submit_lock(ctx, issue_flags);
6092                 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6093                                                 &up2, up->nr_args);
6094                 io_ring_submit_unlock(ctx, issue_flags);
6095         }
6096
6097         if (ret < 0)
6098                 req_set_fail(req);
6099         io_req_set_res(req, ret, 0);
6100         return IOU_OK;
6101 }
6102
6103 static int io_req_prep_async(struct io_kiocb *req)
6104 {
6105         const struct io_op_def *def = &io_op_defs[req->opcode];
6106
6107         /* assign early for deferred execution for non-fixed file */
6108         if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
6109                 req->file = io_file_get_normal(req, req->cqe.fd);
6110         if (!def->prep_async)
6111                 return 0;
6112         if (WARN_ON_ONCE(req_has_async_data(req)))
6113                 return -EFAULT;
6114         if (io_alloc_async_data(req))
6115                 return -EAGAIN;
6116
6117         return def->prep_async(req);
6118 }
6119
6120 static u32 io_get_sequence(struct io_kiocb *req)
6121 {
6122         u32 seq = req->ctx->cached_sq_head;
6123         struct io_kiocb *cur;
6124
6125         /* need original cached_sq_head, but it was increased for each req */
6126         io_for_each_link(cur, req)
6127                 seq--;
6128         return seq;
6129 }
6130
6131 static __cold void io_drain_req(struct io_kiocb *req)
6132 {
6133         struct io_ring_ctx *ctx = req->ctx;
6134         struct io_defer_entry *de;
6135         int ret;
6136         u32 seq = io_get_sequence(req);
6137
6138         /* Still need defer if there is pending req in defer list. */
6139         spin_lock(&ctx->completion_lock);
6140         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6141                 spin_unlock(&ctx->completion_lock);
6142 queue:
6143                 ctx->drain_active = false;
6144                 io_req_task_queue(req);
6145                 return;
6146         }
6147         spin_unlock(&ctx->completion_lock);
6148
6149         ret = io_req_prep_async(req);
6150         if (ret) {
6151 fail:
6152                 io_req_complete_failed(req, ret);
6153                 return;
6154         }
6155         io_prep_async_link(req);
6156         de = kmalloc(sizeof(*de), GFP_KERNEL);
6157         if (!de) {
6158                 ret = -ENOMEM;
6159                 goto fail;
6160         }
6161
6162         spin_lock(&ctx->completion_lock);
6163         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6164                 spin_unlock(&ctx->completion_lock);
6165                 kfree(de);
6166                 goto queue;
6167         }
6168
6169         trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
6170         de->req = req;
6171         de->seq = seq;
6172         list_add_tail(&de->list, &ctx->defer_list);
6173         spin_unlock(&ctx->completion_lock);
6174 }
6175
6176 static void io_clean_op(struct io_kiocb *req)
6177 {
6178         if (req->flags & REQ_F_BUFFER_SELECTED) {
6179                 spin_lock(&req->ctx->completion_lock);
6180                 io_put_kbuf_comp(req);
6181                 spin_unlock(&req->ctx->completion_lock);
6182         }
6183
6184         if (req->flags & REQ_F_NEED_CLEANUP) {
6185                 const struct io_op_def *def = &io_op_defs[req->opcode];
6186
6187                 if (def->cleanup)
6188                         def->cleanup(req);
6189         }
6190         if ((req->flags & REQ_F_POLLED) && req->apoll) {
6191                 kfree(req->apoll->double_poll);
6192                 kfree(req->apoll);
6193                 req->apoll = NULL;
6194         }
6195         if (req->flags & REQ_F_INFLIGHT) {
6196                 struct io_uring_task *tctx = req->task->io_uring;
6197
6198                 atomic_dec(&tctx->inflight_tracked);
6199         }
6200         if (req->flags & REQ_F_CREDS)
6201                 put_cred(req->creds);
6202         if (req->flags & REQ_F_ASYNC_DATA) {
6203                 kfree(req->async_data);
6204                 req->async_data = NULL;
6205         }
6206         req->flags &= ~IO_REQ_CLEAN_FLAGS;
6207 }
6208
6209 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
6210 {
6211         if (req->file || !io_op_defs[req->opcode].needs_file)
6212                 return true;
6213
6214         if (req->flags & REQ_F_FIXED_FILE)
6215                 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
6216         else
6217                 req->file = io_file_get_normal(req, req->cqe.fd);
6218
6219         return !!req->file;
6220 }
6221
6222 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6223 {
6224         const struct io_op_def *def = &io_op_defs[req->opcode];
6225         const struct cred *creds = NULL;
6226         int ret;
6227
6228         if (unlikely(!io_assign_file(req, issue_flags)))
6229                 return -EBADF;
6230
6231         if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6232                 creds = override_creds(req->creds);
6233
6234         if (!def->audit_skip)
6235                 audit_uring_entry(req->opcode);
6236
6237         ret = def->issue(req, issue_flags);
6238
6239         if (!def->audit_skip)
6240                 audit_uring_exit(!ret, ret);
6241
6242         if (creds)
6243                 revert_creds(creds);
6244
6245         if (ret == IOU_OK)
6246                 __io_req_complete(req, issue_flags);
6247         else if (ret != IOU_ISSUE_SKIP_COMPLETE)
6248                 return ret;
6249
6250         /* If the op doesn't have a file, we're not polling for it */
6251         if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6252                 io_iopoll_req_issued(req, issue_flags);
6253
6254         return 0;
6255 }
6256
6257 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6258 {
6259         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6260
6261         req = io_put_req_find_next(req);
6262         return req ? &req->work : NULL;
6263 }
6264
6265 static void io_wq_submit_work(struct io_wq_work *work)
6266 {
6267         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6268         const struct io_op_def *def = &io_op_defs[req->opcode];
6269         unsigned int issue_flags = IO_URING_F_UNLOCKED;
6270         bool needs_poll = false;
6271         int ret = 0, err = -ECANCELED;
6272
6273         /* one will be dropped by ->io_free_work() after returning to io-wq */
6274         if (!(req->flags & REQ_F_REFCOUNT))
6275                 __io_req_set_refcount(req, 2);
6276         else
6277                 req_ref_get(req);
6278
6279         io_arm_ltimeout(req);
6280
6281         /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6282         if (work->flags & IO_WQ_WORK_CANCEL) {
6283 fail:
6284                 io_req_task_queue_fail(req, err);
6285                 return;
6286         }
6287         if (!io_assign_file(req, issue_flags)) {
6288                 err = -EBADF;
6289                 work->flags |= IO_WQ_WORK_CANCEL;
6290                 goto fail;
6291         }
6292
6293         if (req->flags & REQ_F_FORCE_ASYNC) {
6294                 bool opcode_poll = def->pollin || def->pollout;
6295
6296                 if (opcode_poll && file_can_poll(req->file)) {
6297                         needs_poll = true;
6298                         issue_flags |= IO_URING_F_NONBLOCK;
6299                 }
6300         }
6301
6302         do {
6303                 ret = io_issue_sqe(req, issue_flags);
6304                 if (ret != -EAGAIN)
6305                         break;
6306                 /*
6307                  * We can get EAGAIN for iopolled IO even though we're
6308                  * forcing a sync submission from here, since we can't
6309                  * wait for request slots on the block side.
6310                  */
6311                 if (!needs_poll) {
6312                         if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
6313                                 break;
6314                         cond_resched();
6315                         continue;
6316                 }
6317
6318                 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
6319                         return;
6320                 /* aborted or ready, in either case retry blocking */
6321                 needs_poll = false;
6322                 issue_flags &= ~IO_URING_F_NONBLOCK;
6323         } while (1);
6324
6325         /* avoid locking problems by failing it from a clean context */
6326         if (ret < 0)
6327                 io_req_task_queue_fail(req, ret);
6328 }
6329
6330 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6331                                               int index)
6332 {
6333         struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6334
6335         return (struct file *) (slot->file_ptr & FFS_MASK);
6336 }
6337
6338 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6339 {
6340         unsigned long file_ptr = (unsigned long) file;
6341
6342         file_ptr |= io_file_get_flags(file);
6343         file_slot->file_ptr = file_ptr;
6344 }
6345
6346 inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
6347                                       unsigned int issue_flags)
6348 {
6349         struct io_ring_ctx *ctx = req->ctx;
6350         struct file *file = NULL;
6351         unsigned long file_ptr;
6352
6353         io_ring_submit_lock(ctx, issue_flags);
6354
6355         if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6356                 goto out;
6357         fd = array_index_nospec(fd, ctx->nr_user_files);
6358         file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6359         file = (struct file *) (file_ptr & FFS_MASK);
6360         file_ptr &= ~FFS_MASK;
6361         /* mask in overlapping REQ_F and FFS bits */
6362         req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6363         io_req_set_rsrc_node(req, ctx, 0);
6364         WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
6365 out:
6366         io_ring_submit_unlock(ctx, issue_flags);
6367         return file;
6368 }
6369
6370 struct file *io_file_get_normal(struct io_kiocb *req, int fd)
6371 {
6372         struct file *file = fget(fd);
6373
6374         trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
6375
6376         /* we don't allow fixed io_uring files */
6377         if (file && file->f_op == &io_uring_fops)
6378                 io_req_track_inflight(req);
6379         return file;
6380 }
6381
6382 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6383 {
6384         struct io_timeout *timeout = io_kiocb_to_cmd(req);
6385         struct io_kiocb *prev = timeout->prev;
6386         int ret = -ENOENT;
6387
6388         if (prev) {
6389                 if (!(req->task->flags & PF_EXITING)) {
6390                         struct io_cancel_data cd = {
6391                                 .ctx            = req->ctx,
6392                                 .data           = prev->cqe.user_data,
6393                         };
6394
6395                         ret = io_try_cancel(req, &cd);
6396                 }
6397                 io_req_set_res(req, ret ?: -ETIME, 0);
6398                 io_req_complete_post(req);
6399                 io_put_req(prev);
6400         } else {
6401                 io_req_set_res(req, -ETIME, 0);
6402                 io_req_complete_post(req);
6403         }
6404 }
6405
6406 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6407 {
6408         struct io_timeout_data *data = container_of(timer,
6409                                                 struct io_timeout_data, timer);
6410         struct io_kiocb *prev, *req = data->req;
6411         struct io_timeout *timeout = io_kiocb_to_cmd(req);
6412         struct io_ring_ctx *ctx = req->ctx;
6413         unsigned long flags;
6414
6415         spin_lock_irqsave(&ctx->timeout_lock, flags);
6416         prev = timeout->head;
6417         timeout->head = NULL;
6418
6419         /*
6420          * We don't expect the list to be empty, that will only happen if we
6421          * race with the completion of the linked work.
6422          */
6423         if (prev) {
6424                 io_remove_next_linked(prev);
6425                 if (!req_ref_inc_not_zero(prev))
6426                         prev = NULL;
6427         }
6428         list_del(&timeout->list);
6429         timeout->prev = prev;
6430         spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6431
6432         req->io_task_work.func = io_req_task_link_timeout;
6433         io_req_task_work_add(req);
6434         return HRTIMER_NORESTART;
6435 }
6436
6437 static void io_queue_linked_timeout(struct io_kiocb *req)
6438 {
6439         struct io_timeout *timeout = io_kiocb_to_cmd(req);
6440         struct io_ring_ctx *ctx = req->ctx;
6441
6442         spin_lock_irq(&ctx->timeout_lock);
6443         /*
6444          * If the back reference is NULL, then our linked request finished
6445          * before we got a chance to setup the timer
6446          */
6447         if (timeout->head) {
6448                 struct io_timeout_data *data = req->async_data;
6449
6450                 data->timer.function = io_link_timeout_fn;
6451                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6452                                 data->mode);
6453                 list_add_tail(&timeout->list, &ctx->ltimeout_list);
6454         }
6455         spin_unlock_irq(&ctx->timeout_lock);
6456         /* drop submission reference */
6457         io_put_req(req);
6458 }
6459
6460 static void io_queue_async(struct io_kiocb *req, int ret)
6461         __must_hold(&req->ctx->uring_lock)
6462 {
6463         struct io_kiocb *linked_timeout;
6464
6465         if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
6466                 io_req_complete_failed(req, ret);
6467                 return;
6468         }
6469
6470         linked_timeout = io_prep_linked_timeout(req);
6471
6472         switch (io_arm_poll_handler(req, 0)) {
6473         case IO_APOLL_READY:
6474                 io_req_task_queue(req);
6475                 break;
6476         case IO_APOLL_ABORTED:
6477                 /*
6478                  * Queued up for async execution, worker will release
6479                  * submit reference when the iocb is actually submitted.
6480                  */
6481                 io_kbuf_recycle(req, 0);
6482                 io_queue_iowq(req, NULL);
6483                 break;
6484         case IO_APOLL_OK:
6485                 break;
6486         }
6487
6488         if (linked_timeout)
6489                 io_queue_linked_timeout(linked_timeout);
6490 }
6491
6492 static inline void io_queue_sqe(struct io_kiocb *req)
6493         __must_hold(&req->ctx->uring_lock)
6494 {
6495         int ret;
6496
6497         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6498
6499         if (req->flags & REQ_F_COMPLETE_INLINE) {
6500                 io_req_add_compl_list(req);
6501                 return;
6502         }
6503         /*
6504          * We async punt it if the file wasn't marked NOWAIT, or if the file
6505          * doesn't support non-blocking read/write attempts
6506          */
6507         if (likely(!ret))
6508                 io_arm_ltimeout(req);
6509         else
6510                 io_queue_async(req, ret);
6511 }
6512
6513 static void io_queue_sqe_fallback(struct io_kiocb *req)
6514         __must_hold(&req->ctx->uring_lock)
6515 {
6516         if (unlikely(req->flags & REQ_F_FAIL)) {
6517                 /*
6518                  * We don't submit, fail them all, for that replace hardlinks
6519                  * with normal links. Extra REQ_F_LINK is tolerated.
6520                  */
6521                 req->flags &= ~REQ_F_HARDLINK;
6522                 req->flags |= REQ_F_LINK;
6523                 io_req_complete_failed(req, req->cqe.res);
6524         } else if (unlikely(req->ctx->drain_active)) {
6525                 io_drain_req(req);
6526         } else {
6527                 int ret = io_req_prep_async(req);
6528
6529                 if (unlikely(ret))
6530                         io_req_complete_failed(req, ret);
6531                 else
6532                         io_queue_iowq(req, NULL);
6533         }
6534 }
6535
6536 /*
6537  * Check SQE restrictions (opcode and flags).
6538  *
6539  * Returns 'true' if SQE is allowed, 'false' otherwise.
6540  */
6541 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6542                                         struct io_kiocb *req,
6543                                         unsigned int sqe_flags)
6544 {
6545         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6546                 return false;
6547
6548         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6549             ctx->restrictions.sqe_flags_required)
6550                 return false;
6551
6552         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6553                           ctx->restrictions.sqe_flags_required))
6554                 return false;
6555
6556         return true;
6557 }
6558
6559 static void io_init_req_drain(struct io_kiocb *req)
6560 {
6561         struct io_ring_ctx *ctx = req->ctx;
6562         struct io_kiocb *head = ctx->submit_state.link.head;
6563
6564         ctx->drain_active = true;
6565         if (head) {
6566                 /*
6567                  * If we need to drain a request in the middle of a link, drain
6568                  * the head request and the next request/link after the current
6569                  * link. Considering sequential execution of links,
6570                  * REQ_F_IO_DRAIN will be maintained for every request of our
6571                  * link.
6572                  */
6573                 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
6574                 ctx->drain_next = true;
6575         }
6576 }
6577
6578 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6579                        const struct io_uring_sqe *sqe)
6580         __must_hold(&ctx->uring_lock)
6581 {
6582         const struct io_op_def *def;
6583         unsigned int sqe_flags;
6584         int personality;
6585         u8 opcode;
6586
6587         /* req is partially pre-initialised, see io_preinit_req() */
6588         req->opcode = opcode = READ_ONCE(sqe->opcode);
6589         /* same numerical values with corresponding REQ_F_*, safe to copy */
6590         req->flags = sqe_flags = READ_ONCE(sqe->flags);
6591         req->cqe.user_data = READ_ONCE(sqe->user_data);
6592         req->file = NULL;
6593         req->rsrc_node = NULL;
6594         req->task = current;
6595
6596         if (unlikely(opcode >= IORING_OP_LAST)) {
6597                 req->opcode = 0;
6598                 return -EINVAL;
6599         }
6600         def = &io_op_defs[opcode];
6601         if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
6602                 /* enforce forwards compatibility on users */
6603                 if (sqe_flags & ~SQE_VALID_FLAGS)
6604                         return -EINVAL;
6605                 if (sqe_flags & IOSQE_BUFFER_SELECT) {
6606                         if (!def->buffer_select)
6607                                 return -EOPNOTSUPP;
6608                         req->buf_index = READ_ONCE(sqe->buf_group);
6609                 }
6610                 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
6611                         ctx->drain_disabled = true;
6612                 if (sqe_flags & IOSQE_IO_DRAIN) {
6613                         if (ctx->drain_disabled)
6614                                 return -EOPNOTSUPP;
6615                         io_init_req_drain(req);
6616                 }
6617         }
6618         if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
6619                 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
6620                         return -EACCES;
6621                 /* knock it to the slow queue path, will be drained there */
6622                 if (ctx->drain_active)
6623                         req->flags |= REQ_F_FORCE_ASYNC;
6624                 /* if there is no link, we're at "next" request and need to drain */
6625                 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
6626                         ctx->drain_next = false;
6627                         ctx->drain_active = true;
6628                         req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
6629                 }
6630         }
6631
6632         if (!def->ioprio && sqe->ioprio)
6633                 return -EINVAL;
6634         if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
6635                 return -EINVAL;
6636
6637         if (def->needs_file) {
6638                 struct io_submit_state *state = &ctx->submit_state;
6639
6640                 req->cqe.fd = READ_ONCE(sqe->fd);
6641
6642                 /*
6643                  * Plug now if we have more than 2 IO left after this, and the
6644                  * target is potentially a read/write to block based storage.
6645                  */
6646                 if (state->need_plug && def->plug) {
6647                         state->plug_started = true;
6648                         state->need_plug = false;
6649                         blk_start_plug_nr_ios(&state->plug, state->submit_nr);
6650                 }
6651         }
6652
6653         personality = READ_ONCE(sqe->personality);
6654         if (personality) {
6655                 int ret;
6656
6657                 req->creds = xa_load(&ctx->personalities, personality);
6658                 if (!req->creds)
6659                         return -EINVAL;
6660                 get_cred(req->creds);
6661                 ret = security_uring_override_creds(req->creds);
6662                 if (ret) {
6663                         put_cred(req->creds);
6664                         return ret;
6665                 }
6666                 req->flags |= REQ_F_CREDS;
6667         }
6668
6669         return def->prep(req, sqe);
6670 }
6671
6672 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
6673                                       struct io_kiocb *req, int ret)
6674 {
6675         struct io_ring_ctx *ctx = req->ctx;
6676         struct io_submit_link *link = &ctx->submit_state.link;
6677         struct io_kiocb *head = link->head;
6678
6679         trace_io_uring_req_failed(sqe, ctx, req, ret);
6680
6681         /*
6682          * Avoid breaking links in the middle as it renders links with SQPOLL
6683          * unusable. Instead of failing eagerly, continue assembling the link if
6684          * applicable and mark the head with REQ_F_FAIL. The link flushing code
6685          * should find the flag and handle the rest.
6686          */
6687         req_fail_link_node(req, ret);
6688         if (head && !(head->flags & REQ_F_FAIL))
6689                 req_fail_link_node(head, -ECANCELED);
6690
6691         if (!(req->flags & IO_REQ_LINK_FLAGS)) {
6692                 if (head) {
6693                         link->last->link = req;
6694                         link->head = NULL;
6695                         req = head;
6696                 }
6697                 io_queue_sqe_fallback(req);
6698                 return ret;
6699         }
6700
6701         if (head)
6702                 link->last->link = req;
6703         else
6704                 link->head = req;
6705         link->last = req;
6706         return 0;
6707 }
6708
6709 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6710                          const struct io_uring_sqe *sqe)
6711         __must_hold(&ctx->uring_lock)
6712 {
6713         struct io_submit_link *link = &ctx->submit_state.link;
6714         int ret;
6715
6716         ret = io_init_req(ctx, req, sqe);
6717         if (unlikely(ret))
6718                 return io_submit_fail_init(sqe, req, ret);
6719
6720         /* don't need @sqe from now on */
6721         trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
6722                                   req->flags, true,
6723                                   ctx->flags & IORING_SETUP_SQPOLL);
6724
6725         /*
6726          * If we already have a head request, queue this one for async
6727          * submittal once the head completes. If we don't have a head but
6728          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6729          * submitted sync once the chain is complete. If none of those
6730          * conditions are true (normal request), then just queue it.
6731          */
6732         if (unlikely(link->head)) {
6733                 ret = io_req_prep_async(req);
6734                 if (unlikely(ret))
6735                         return io_submit_fail_init(sqe, req, ret);
6736
6737                 trace_io_uring_link(ctx, req, link->head);
6738                 link->last->link = req;
6739                 link->last = req;
6740
6741                 if (req->flags & IO_REQ_LINK_FLAGS)
6742                         return 0;
6743                 /* last request of the link, flush it */
6744                 req = link->head;
6745                 link->head = NULL;
6746                 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
6747                         goto fallback;
6748
6749         } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
6750                                           REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
6751                 if (req->flags & IO_REQ_LINK_FLAGS) {
6752                         link->head = req;
6753                         link->last = req;
6754                 } else {
6755 fallback:
6756                         io_queue_sqe_fallback(req);
6757                 }
6758                 return 0;
6759         }
6760
6761         io_queue_sqe(req);
6762         return 0;
6763 }
6764
6765 /*
6766  * Batched submission is done, ensure local IO is flushed out.
6767  */
6768 static void io_submit_state_end(struct io_ring_ctx *ctx)
6769 {
6770         struct io_submit_state *state = &ctx->submit_state;
6771
6772         if (unlikely(state->link.head))
6773                 io_queue_sqe_fallback(state->link.head);
6774         /* flush only after queuing links as they can generate completions */
6775         io_submit_flush_completions(ctx);
6776         if (state->plug_started)
6777                 blk_finish_plug(&state->plug);
6778 }
6779
6780 /*
6781  * Start submission side cache.
6782  */
6783 static void io_submit_state_start(struct io_submit_state *state,
6784                                   unsigned int max_ios)
6785 {
6786         state->plug_started = false;
6787         state->need_plug = max_ios > 2;
6788         state->submit_nr = max_ios;
6789         /* set only head, no need to init link_last in advance */
6790         state->link.head = NULL;
6791 }
6792
6793 static void io_commit_sqring(struct io_ring_ctx *ctx)
6794 {
6795         struct io_rings *rings = ctx->rings;
6796
6797         /*
6798          * Ensure any loads from the SQEs are done at this point,
6799          * since once we write the new head, the application could
6800          * write new data to them.
6801          */
6802         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6803 }
6804
6805 /*
6806  * Fetch an sqe, if one is available. Note this returns a pointer to memory
6807  * that is mapped by userspace. This means that care needs to be taken to
6808  * ensure that reads are stable, as we cannot rely on userspace always
6809  * being a good citizen. If members of the sqe are validated and then later
6810  * used, it's important that those reads are done through READ_ONCE() to
6811  * prevent a re-load down the line.
6812  */
6813 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6814 {
6815         unsigned head, mask = ctx->sq_entries - 1;
6816         unsigned sq_idx = ctx->cached_sq_head++ & mask;
6817
6818         /*
6819          * The cached sq head (or cq tail) serves two purposes:
6820          *
6821          * 1) allows us to batch the cost of updating the user visible
6822          *    head updates.
6823          * 2) allows the kernel side to track the head on its own, even
6824          *    though the application is the one updating it.
6825          */
6826         head = READ_ONCE(ctx->sq_array[sq_idx]);
6827         if (likely(head < ctx->sq_entries)) {
6828                 /* double index for 128-byte SQEs, twice as long */
6829                 if (ctx->flags & IORING_SETUP_SQE128)
6830                         head <<= 1;
6831                 return &ctx->sq_sqes[head];
6832         }
6833
6834         /* drop invalid entries */
6835         ctx->cq_extra--;
6836         WRITE_ONCE(ctx->rings->sq_dropped,
6837                    READ_ONCE(ctx->rings->sq_dropped) + 1);
6838         return NULL;
6839 }
6840
6841 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6842         __must_hold(&ctx->uring_lock)
6843 {
6844         unsigned int entries = io_sqring_entries(ctx);
6845         unsigned int left;
6846         int ret;
6847
6848         if (unlikely(!entries))
6849                 return 0;
6850         /* make sure SQ entry isn't read before tail */
6851         ret = left = min3(nr, ctx->sq_entries, entries);
6852         io_get_task_refs(left);
6853         io_submit_state_start(&ctx->submit_state, left);
6854
6855         do {
6856                 const struct io_uring_sqe *sqe;
6857                 struct io_kiocb *req;
6858
6859                 if (unlikely(!io_alloc_req_refill(ctx)))
6860                         break;
6861                 req = io_alloc_req(ctx);
6862                 sqe = io_get_sqe(ctx);
6863                 if (unlikely(!sqe)) {
6864                         io_req_add_to_cache(req, ctx);
6865                         break;
6866                 }
6867
6868                 /*
6869                  * Continue submitting even for sqe failure if the
6870                  * ring was setup with IORING_SETUP_SUBMIT_ALL
6871                  */
6872                 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
6873                     !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
6874                         left--;
6875                         break;
6876                 }
6877         } while (--left);
6878
6879         if (unlikely(left)) {
6880                 ret -= left;
6881                 /* try again if it submitted nothing and can't allocate a req */
6882                 if (!ret && io_req_cache_empty(ctx))
6883                         ret = -EAGAIN;
6884                 current->io_uring->cached_refs += left;
6885         }
6886
6887         io_submit_state_end(ctx);
6888          /* Commit SQ ring head once we've consumed and submitted all SQEs */
6889         io_commit_sqring(ctx);
6890         return ret;
6891 }
6892
6893 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6894 {
6895         return READ_ONCE(sqd->state);
6896 }
6897
6898 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6899 {
6900         unsigned int to_submit;
6901         int ret = 0;
6902
6903         to_submit = io_sqring_entries(ctx);
6904         /* if we're handling multiple rings, cap submit size for fairness */
6905         if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6906                 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6907
6908         if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
6909                 const struct cred *creds = NULL;
6910
6911                 if (ctx->sq_creds != current_cred())
6912                         creds = override_creds(ctx->sq_creds);
6913
6914                 mutex_lock(&ctx->uring_lock);
6915                 if (!wq_list_empty(&ctx->iopoll_list))
6916                         io_do_iopoll(ctx, true);
6917
6918                 /*
6919                  * Don't submit if refs are dying, good for io_uring_register(),
6920                  * but also it is relied upon by io_ring_exit_work()
6921                  */
6922                 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6923                     !(ctx->flags & IORING_SETUP_R_DISABLED))
6924                         ret = io_submit_sqes(ctx, to_submit);
6925                 mutex_unlock(&ctx->uring_lock);
6926
6927                 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6928                         wake_up(&ctx->sqo_sq_wait);
6929                 if (creds)
6930                         revert_creds(creds);
6931         }
6932
6933         return ret;
6934 }
6935
6936 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6937 {
6938         struct io_ring_ctx *ctx;
6939         unsigned sq_thread_idle = 0;
6940
6941         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6942                 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6943         sqd->sq_thread_idle = sq_thread_idle;
6944 }
6945
6946 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6947 {
6948         bool did_sig = false;
6949         struct ksignal ksig;
6950
6951         if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6952             signal_pending(current)) {
6953                 mutex_unlock(&sqd->lock);
6954                 if (signal_pending(current))
6955                         did_sig = get_signal(&ksig);
6956                 cond_resched();
6957                 mutex_lock(&sqd->lock);
6958         }
6959         return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6960 }
6961
6962 static int io_sq_thread(void *data)
6963 {
6964         struct io_sq_data *sqd = data;
6965         struct io_ring_ctx *ctx;
6966         unsigned long timeout = 0;
6967         char buf[TASK_COMM_LEN];
6968         DEFINE_WAIT(wait);
6969
6970         snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6971         set_task_comm(current, buf);
6972
6973         if (sqd->sq_cpu != -1)
6974                 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6975         else
6976                 set_cpus_allowed_ptr(current, cpu_online_mask);
6977         current->flags |= PF_NO_SETAFFINITY;
6978
6979         audit_alloc_kernel(current);
6980
6981         mutex_lock(&sqd->lock);
6982         while (1) {
6983                 bool cap_entries, sqt_spin = false;
6984
6985                 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
6986                         if (io_sqd_handle_event(sqd))
6987                                 break;
6988                         timeout = jiffies + sqd->sq_thread_idle;
6989                 }
6990
6991                 cap_entries = !list_is_singular(&sqd->ctx_list);
6992                 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6993                         int ret = __io_sq_thread(ctx, cap_entries);
6994
6995                         if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
6996                                 sqt_spin = true;
6997                 }
6998                 if (io_run_task_work())
6999                         sqt_spin = true;
7000
7001                 if (sqt_spin || !time_after(jiffies, timeout)) {
7002                         cond_resched();
7003                         if (sqt_spin)
7004                                 timeout = jiffies + sqd->sq_thread_idle;
7005                         continue;
7006                 }
7007
7008                 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7009                 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
7010                         bool needs_sched = true;
7011
7012                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7013                                 atomic_or(IORING_SQ_NEED_WAKEUP,
7014                                                 &ctx->rings->sq_flags);
7015                                 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7016                                     !wq_list_empty(&ctx->iopoll_list)) {
7017                                         needs_sched = false;
7018                                         break;
7019                                 }
7020
7021                                 /*
7022                                  * Ensure the store of the wakeup flag is not
7023                                  * reordered with the load of the SQ tail
7024                                  */
7025                                 smp_mb__after_atomic();
7026
7027                                 if (io_sqring_entries(ctx)) {
7028                                         needs_sched = false;
7029                                         break;
7030                                 }
7031                         }
7032
7033                         if (needs_sched) {
7034                                 mutex_unlock(&sqd->lock);
7035                                 schedule();
7036                                 mutex_lock(&sqd->lock);
7037                         }
7038                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7039                                 atomic_andnot(IORING_SQ_NEED_WAKEUP,
7040                                                 &ctx->rings->sq_flags);
7041                 }
7042
7043                 finish_wait(&sqd->wait, &wait);
7044                 timeout = jiffies + sqd->sq_thread_idle;
7045         }
7046
7047         io_uring_cancel_generic(true, sqd);
7048         sqd->thread = NULL;
7049         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7050                 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
7051         io_run_task_work();
7052         mutex_unlock(&sqd->lock);
7053
7054         audit_free(current);
7055
7056         complete(&sqd->exited);
7057         do_exit(0);
7058 }
7059
7060 struct io_wait_queue {
7061         struct wait_queue_entry wq;
7062         struct io_ring_ctx *ctx;
7063         unsigned cq_tail;
7064         unsigned nr_timeouts;
7065 };
7066
7067 static inline bool io_should_wake(struct io_wait_queue *iowq)
7068 {
7069         struct io_ring_ctx *ctx = iowq->ctx;
7070         int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7071
7072         /*
7073          * Wake up if we have enough events, or if a timeout occurred since we
7074          * started waiting. For timeouts, we always want to return to userspace,
7075          * regardless of event count.
7076          */
7077         return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7078 }
7079
7080 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7081                             int wake_flags, void *key)
7082 {
7083         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7084                                                         wq);
7085
7086         /*
7087          * Cannot safely flush overflowed CQEs from here, ensure we wake up
7088          * the task, and the next invocation will do it.
7089          */
7090         if (io_should_wake(iowq) ||
7091             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
7092                 return autoremove_wake_function(curr, mode, wake_flags, key);
7093         return -1;
7094 }
7095
7096 static int io_run_task_work_sig(void)
7097 {
7098         if (io_run_task_work())
7099                 return 1;
7100         if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7101                 return -ERESTARTSYS;
7102         if (task_sigpending(current))
7103                 return -EINTR;
7104         return 0;
7105 }
7106
7107 /* when returns >0, the caller should retry */
7108 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7109                                           struct io_wait_queue *iowq,
7110                                           ktime_t timeout)
7111 {
7112         int ret;
7113         unsigned long check_cq;
7114
7115         /* make sure we run task_work before checking for signals */
7116         ret = io_run_task_work_sig();
7117         if (ret || io_should_wake(iowq))
7118                 return ret;
7119         check_cq = READ_ONCE(ctx->check_cq);
7120         /* let the caller flush overflows, retry */
7121         if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
7122                 return 1;
7123         if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
7124                 return -EBADR;
7125         if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
7126                 return -ETIME;
7127         return 1;
7128 }
7129
7130 /*
7131  * Wait until events become available, if we don't already have some. The
7132  * application must reap them itself, as they reside on the shared cq ring.
7133  */
7134 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7135                           const sigset_t __user *sig, size_t sigsz,
7136                           struct __kernel_timespec __user *uts)
7137 {
7138         struct io_wait_queue iowq;
7139         struct io_rings *rings = ctx->rings;
7140         ktime_t timeout = KTIME_MAX;
7141         int ret;
7142
7143         do {
7144                 io_cqring_overflow_flush(ctx);
7145                 if (io_cqring_events(ctx) >= min_events)
7146                         return 0;
7147                 if (!io_run_task_work())
7148                         break;
7149         } while (1);
7150
7151         if (sig) {
7152 #ifdef CONFIG_COMPAT
7153                 if (in_compat_syscall())
7154                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7155                                                       sigsz);
7156                 else
7157 #endif
7158                         ret = set_user_sigmask(sig, sigsz);
7159
7160                 if (ret)
7161                         return ret;
7162         }
7163
7164         if (uts) {
7165                 struct timespec64 ts;
7166
7167                 if (get_timespec64(&ts, uts))
7168                         return -EFAULT;
7169                 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7170         }
7171
7172         init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7173         iowq.wq.private = current;
7174         INIT_LIST_HEAD(&iowq.wq.entry);
7175         iowq.ctx = ctx;
7176         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7177         iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7178
7179         trace_io_uring_cqring_wait(ctx, min_events);
7180         do {
7181                 /* if we can't even flush overflow, don't wait for more */
7182                 if (!io_cqring_overflow_flush(ctx)) {
7183                         ret = -EBUSY;
7184                         break;
7185                 }
7186                 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7187                                                 TASK_INTERRUPTIBLE);
7188                 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
7189                 cond_resched();
7190         } while (ret > 0);
7191
7192         finish_wait(&ctx->cq_wait, &iowq.wq);
7193         restore_saved_sigmask_unless(ret == -EINTR);
7194
7195         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7196 }
7197
7198 static void io_free_page_table(void **table, size_t size)
7199 {
7200         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7201
7202         for (i = 0; i < nr_tables; i++)
7203                 kfree(table[i]);
7204         kfree(table);
7205 }
7206
7207 static __cold void **io_alloc_page_table(size_t size)
7208 {
7209         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7210         size_t init_size = size;
7211         void **table;
7212
7213         table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7214         if (!table)
7215                 return NULL;
7216
7217         for (i = 0; i < nr_tables; i++) {
7218                 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7219
7220                 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7221                 if (!table[i]) {
7222                         io_free_page_table(table, init_size);
7223                         return NULL;
7224                 }
7225                 size -= this_size;
7226         }
7227         return table;
7228 }
7229
7230 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7231 {
7232         percpu_ref_exit(&ref_node->refs);
7233         kfree(ref_node);
7234 }
7235
7236 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7237 {
7238         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7239         struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7240         unsigned long flags;
7241         bool first_add = false;
7242         unsigned long delay = HZ;
7243
7244         spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7245         node->done = true;
7246
7247         /* if we are mid-quiesce then do not delay */
7248         if (node->rsrc_data->quiesce)
7249                 delay = 0;
7250
7251         while (!list_empty(&ctx->rsrc_ref_list)) {
7252                 node = list_first_entry(&ctx->rsrc_ref_list,
7253                                             struct io_rsrc_node, node);
7254                 /* recycle ref nodes in order */
7255                 if (!node->done)
7256                         break;
7257                 list_del(&node->node);
7258                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7259         }
7260         spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7261
7262         if (first_add)
7263                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7264 }
7265
7266 static struct io_rsrc_node *io_rsrc_node_alloc(void)
7267 {
7268         struct io_rsrc_node *ref_node;
7269
7270         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7271         if (!ref_node)
7272                 return NULL;
7273
7274         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7275                             0, GFP_KERNEL)) {
7276                 kfree(ref_node);
7277                 return NULL;
7278         }
7279         INIT_LIST_HEAD(&ref_node->node);
7280         INIT_LIST_HEAD(&ref_node->rsrc_list);
7281         ref_node->done = false;
7282         return ref_node;
7283 }
7284
7285 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7286                          struct io_rsrc_data *data_to_kill)
7287         __must_hold(&ctx->uring_lock)
7288 {
7289         WARN_ON_ONCE(!ctx->rsrc_backup_node);
7290         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7291
7292         io_rsrc_refs_drop(ctx);
7293
7294         if (data_to_kill) {
7295                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7296
7297                 rsrc_node->rsrc_data = data_to_kill;
7298                 spin_lock_irq(&ctx->rsrc_ref_lock);
7299                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7300                 spin_unlock_irq(&ctx->rsrc_ref_lock);
7301
7302                 atomic_inc(&data_to_kill->refs);
7303                 percpu_ref_kill(&rsrc_node->refs);
7304                 ctx->rsrc_node = NULL;
7305         }
7306
7307         if (!ctx->rsrc_node) {
7308                 ctx->rsrc_node = ctx->rsrc_backup_node;
7309                 ctx->rsrc_backup_node = NULL;
7310         }
7311 }
7312
7313 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7314 {
7315         if (ctx->rsrc_backup_node)
7316                 return 0;
7317         ctx->rsrc_backup_node = io_rsrc_node_alloc();
7318         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7319 }
7320
7321 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7322                                       struct io_ring_ctx *ctx)
7323 {
7324         int ret;
7325
7326         /* As we may drop ->uring_lock, other task may have started quiesce */
7327         if (data->quiesce)
7328                 return -ENXIO;
7329
7330         data->quiesce = true;
7331         do {
7332                 ret = io_rsrc_node_switch_start(ctx);
7333                 if (ret)
7334                         break;
7335                 io_rsrc_node_switch(ctx, data);
7336
7337                 /* kill initial ref, already quiesced if zero */
7338                 if (atomic_dec_and_test(&data->refs))
7339                         break;
7340                 mutex_unlock(&ctx->uring_lock);
7341                 flush_delayed_work(&ctx->rsrc_put_work);
7342                 ret = wait_for_completion_interruptible(&data->done);
7343                 if (!ret) {
7344                         mutex_lock(&ctx->uring_lock);
7345                         if (atomic_read(&data->refs) > 0) {
7346                                 /*
7347                                  * it has been revived by another thread while
7348                                  * we were unlocked
7349                                  */
7350                                 mutex_unlock(&ctx->uring_lock);
7351                         } else {
7352                                 break;
7353                         }
7354                 }
7355
7356                 atomic_inc(&data->refs);
7357                 /* wait for all works potentially completing data->done */
7358                 flush_delayed_work(&ctx->rsrc_put_work);
7359                 reinit_completion(&data->done);
7360
7361                 ret = io_run_task_work_sig();
7362                 mutex_lock(&ctx->uring_lock);
7363         } while (ret >= 0);
7364         data->quiesce = false;
7365
7366         return ret;
7367 }
7368
7369 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7370 {
7371         unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7372         unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7373
7374         return &data->tags[table_idx][off];
7375 }
7376
7377 static void io_rsrc_data_free(struct io_rsrc_data *data)
7378 {
7379         size_t size = data->nr * sizeof(data->tags[0][0]);
7380
7381         if (data->tags)
7382                 io_free_page_table((void **)data->tags, size);
7383         kfree(data);
7384 }
7385
7386 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7387                                      u64 __user *utags, unsigned nr,
7388                                      struct io_rsrc_data **pdata)
7389 {
7390         struct io_rsrc_data *data;
7391         int ret = -ENOMEM;
7392         unsigned i;
7393
7394         data = kzalloc(sizeof(*data), GFP_KERNEL);
7395         if (!data)
7396                 return -ENOMEM;
7397         data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7398         if (!data->tags) {
7399                 kfree(data);
7400                 return -ENOMEM;
7401         }
7402
7403         data->nr = nr;
7404         data->ctx = ctx;
7405         data->do_put = do_put;
7406         if (utags) {
7407                 ret = -EFAULT;
7408                 for (i = 0; i < nr; i++) {
7409                         u64 *tag_slot = io_get_tag_slot(data, i);
7410
7411                         if (copy_from_user(tag_slot, &utags[i],
7412                                            sizeof(*tag_slot)))
7413                                 goto fail;
7414                 }
7415         }
7416
7417         atomic_set(&data->refs, 1);
7418         init_completion(&data->done);
7419         *pdata = data;
7420         return 0;
7421 fail:
7422         io_rsrc_data_free(data);
7423         return ret;
7424 }
7425
7426 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7427 {
7428 #if !defined(IO_URING_SCM_ALL)
7429         int i;
7430
7431         for (i = 0; i < ctx->nr_user_files; i++) {
7432                 struct file *file = io_file_from_index(ctx, i);
7433
7434                 if (!file)
7435                         continue;
7436                 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
7437                         continue;
7438                 io_file_bitmap_clear(&ctx->file_table, i);
7439                 fput(file);
7440         }
7441 #endif
7442
7443 #if defined(CONFIG_UNIX)
7444         if (ctx->ring_sock) {
7445                 struct sock *sock = ctx->ring_sock->sk;
7446                 struct sk_buff *skb;
7447
7448                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7449                         kfree_skb(skb);
7450         }
7451 #endif
7452         io_free_file_tables(&ctx->file_table);
7453         io_rsrc_data_free(ctx->file_data);
7454         ctx->file_data = NULL;
7455         ctx->nr_user_files = 0;
7456 }
7457
7458 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7459 {
7460         unsigned nr = ctx->nr_user_files;
7461         int ret;
7462
7463         if (!ctx->file_data)
7464                 return -ENXIO;
7465
7466         /*
7467          * Quiesce may unlock ->uring_lock, and while it's not held
7468          * prevent new requests using the table.
7469          */
7470         ctx->nr_user_files = 0;
7471         ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7472         ctx->nr_user_files = nr;
7473         if (!ret)
7474                 __io_sqe_files_unregister(ctx);
7475         return ret;
7476 }
7477
7478 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7479         __releases(&sqd->lock)
7480 {
7481         WARN_ON_ONCE(sqd->thread == current);
7482
7483         /*
7484          * Do the dance but not conditional clear_bit() because it'd race with
7485          * other threads incrementing park_pending and setting the bit.
7486          */
7487         clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7488         if (atomic_dec_return(&sqd->park_pending))
7489                 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7490         mutex_unlock(&sqd->lock);
7491 }
7492
7493 static void io_sq_thread_park(struct io_sq_data *sqd)
7494         __acquires(&sqd->lock)
7495 {
7496         WARN_ON_ONCE(sqd->thread == current);
7497
7498         atomic_inc(&sqd->park_pending);
7499         set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7500         mutex_lock(&sqd->lock);
7501         if (sqd->thread)
7502                 wake_up_process(sqd->thread);
7503 }
7504
7505 static void io_sq_thread_stop(struct io_sq_data *sqd)
7506 {
7507         WARN_ON_ONCE(sqd->thread == current);
7508         WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7509
7510         set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7511         mutex_lock(&sqd->lock);
7512         if (sqd->thread)
7513                 wake_up_process(sqd->thread);
7514         mutex_unlock(&sqd->lock);
7515         wait_for_completion(&sqd->exited);
7516 }
7517
7518 static void io_put_sq_data(struct io_sq_data *sqd)
7519 {
7520         if (refcount_dec_and_test(&sqd->refs)) {
7521                 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7522
7523                 io_sq_thread_stop(sqd);
7524                 kfree(sqd);
7525         }
7526 }
7527
7528 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7529 {
7530         struct io_sq_data *sqd = ctx->sq_data;
7531
7532         if (sqd) {
7533                 io_sq_thread_park(sqd);
7534                 list_del_init(&ctx->sqd_list);
7535                 io_sqd_update_thread_idle(sqd);
7536                 io_sq_thread_unpark(sqd);
7537
7538                 io_put_sq_data(sqd);
7539                 ctx->sq_data = NULL;
7540         }
7541 }
7542
7543 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7544 {
7545         struct io_ring_ctx *ctx_attach;
7546         struct io_sq_data *sqd;
7547         struct fd f;
7548
7549         f = fdget(p->wq_fd);
7550         if (!f.file)
7551                 return ERR_PTR(-ENXIO);
7552         if (f.file->f_op != &io_uring_fops) {
7553                 fdput(f);
7554                 return ERR_PTR(-EINVAL);
7555         }
7556
7557         ctx_attach = f.file->private_data;
7558         sqd = ctx_attach->sq_data;
7559         if (!sqd) {
7560                 fdput(f);
7561                 return ERR_PTR(-EINVAL);
7562         }
7563         if (sqd->task_tgid != current->tgid) {
7564                 fdput(f);
7565                 return ERR_PTR(-EPERM);
7566         }
7567
7568         refcount_inc(&sqd->refs);
7569         fdput(f);
7570         return sqd;
7571 }
7572
7573 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7574                                          bool *attached)
7575 {
7576         struct io_sq_data *sqd;
7577
7578         *attached = false;
7579         if (p->flags & IORING_SETUP_ATTACH_WQ) {
7580                 sqd = io_attach_sq_data(p);
7581                 if (!IS_ERR(sqd)) {
7582                         *attached = true;
7583                         return sqd;
7584                 }
7585                 /* fall through for EPERM case, setup new sqd/task */
7586                 if (PTR_ERR(sqd) != -EPERM)
7587                         return sqd;
7588         }
7589
7590         sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7591         if (!sqd)
7592                 return ERR_PTR(-ENOMEM);
7593
7594         atomic_set(&sqd->park_pending, 0);
7595         refcount_set(&sqd->refs, 1);
7596         INIT_LIST_HEAD(&sqd->ctx_list);
7597         mutex_init(&sqd->lock);
7598         init_waitqueue_head(&sqd->wait);
7599         init_completion(&sqd->exited);
7600         return sqd;
7601 }
7602
7603 /*
7604  * Ensure the UNIX gc is aware of our file set, so we are certain that
7605  * the io_uring can be safely unregistered on process exit, even if we have
7606  * loops in the file referencing. We account only files that can hold other
7607  * files because otherwise they can't form a loop and so are not interesting
7608  * for GC.
7609  */
7610 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
7611 {
7612 #if defined(CONFIG_UNIX)
7613         struct sock *sk = ctx->ring_sock->sk;
7614         struct sk_buff_head *head = &sk->sk_receive_queue;
7615         struct scm_fp_list *fpl;
7616         struct sk_buff *skb;
7617
7618         if (likely(!io_file_need_scm(file)))
7619                 return 0;
7620
7621         /*
7622          * See if we can merge this file into an existing skb SCM_RIGHTS
7623          * file set. If there's no room, fall back to allocating a new skb
7624          * and filling it in.
7625          */
7626         spin_lock_irq(&head->lock);
7627         skb = skb_peek(head);
7628         if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
7629                 __skb_unlink(skb, head);
7630         else
7631                 skb = NULL;
7632         spin_unlock_irq(&head->lock);
7633
7634         if (!skb) {
7635                 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7636                 if (!fpl)
7637                         return -ENOMEM;
7638
7639                 skb = alloc_skb(0, GFP_KERNEL);
7640                 if (!skb) {
7641                         kfree(fpl);
7642                         return -ENOMEM;
7643                 }
7644
7645                 fpl->user = get_uid(current_user());
7646                 fpl->max = SCM_MAX_FD;
7647                 fpl->count = 0;
7648
7649                 UNIXCB(skb).fp = fpl;
7650                 skb->sk = sk;
7651                 skb->destructor = unix_destruct_scm;
7652                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7653         }
7654
7655         fpl = UNIXCB(skb).fp;
7656         fpl->fp[fpl->count++] = get_file(file);
7657         unix_inflight(fpl->user, file);
7658         skb_queue_head(head, skb);
7659         fput(file);
7660 #endif
7661         return 0;
7662 }
7663
7664 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7665 {
7666         struct file *file = prsrc->file;
7667 #if defined(CONFIG_UNIX)
7668         struct sock *sock = ctx->ring_sock->sk;
7669         struct sk_buff_head list, *head = &sock->sk_receive_queue;
7670         struct sk_buff *skb;
7671         int i;
7672
7673         if (!io_file_need_scm(file)) {
7674                 fput(file);
7675                 return;
7676         }
7677
7678         __skb_queue_head_init(&list);
7679
7680         /*
7681          * Find the skb that holds this file in its SCM_RIGHTS. When found,
7682          * remove this entry and rearrange the file array.
7683          */
7684         skb = skb_dequeue(head);
7685         while (skb) {
7686                 struct scm_fp_list *fp;
7687
7688                 fp = UNIXCB(skb).fp;
7689                 for (i = 0; i < fp->count; i++) {
7690                         int left;
7691
7692                         if (fp->fp[i] != file)
7693                                 continue;
7694
7695                         unix_notinflight(fp->user, fp->fp[i]);
7696                         left = fp->count - 1 - i;
7697                         if (left) {
7698                                 memmove(&fp->fp[i], &fp->fp[i + 1],
7699                                                 left * sizeof(struct file *));
7700                         }
7701                         fp->count--;
7702                         if (!fp->count) {
7703                                 kfree_skb(skb);
7704                                 skb = NULL;
7705                         } else {
7706                                 __skb_queue_tail(&list, skb);
7707                         }
7708                         fput(file);
7709                         file = NULL;
7710                         break;
7711                 }
7712
7713                 if (!file)
7714                         break;
7715
7716                 __skb_queue_tail(&list, skb);
7717
7718                 skb = skb_dequeue(head);
7719         }
7720
7721         if (skb_peek(&list)) {
7722                 spin_lock_irq(&head->lock);
7723                 while ((skb = __skb_dequeue(&list)) != NULL)
7724                         __skb_queue_tail(head, skb);
7725                 spin_unlock_irq(&head->lock);
7726         }
7727 #else
7728         fput(file);
7729 #endif
7730 }
7731
7732 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7733 {
7734         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7735         struct io_ring_ctx *ctx = rsrc_data->ctx;
7736         struct io_rsrc_put *prsrc, *tmp;
7737
7738         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7739                 list_del(&prsrc->list);
7740
7741                 if (prsrc->tag) {
7742                         if (ctx->flags & IORING_SETUP_IOPOLL)
7743                                 mutex_lock(&ctx->uring_lock);
7744
7745                         spin_lock(&ctx->completion_lock);
7746                         io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
7747                         io_commit_cqring(ctx);
7748                         spin_unlock(&ctx->completion_lock);
7749                         io_cqring_ev_posted(ctx);
7750
7751                         if (ctx->flags & IORING_SETUP_IOPOLL)
7752                                 mutex_unlock(&ctx->uring_lock);
7753                 }
7754
7755                 rsrc_data->do_put(ctx, prsrc);
7756                 kfree(prsrc);
7757         }
7758
7759         io_rsrc_node_destroy(ref_node);
7760         if (atomic_dec_and_test(&rsrc_data->refs))
7761                 complete(&rsrc_data->done);
7762 }
7763
7764 static void io_rsrc_put_work(struct work_struct *work)
7765 {
7766         struct io_ring_ctx *ctx;
7767         struct llist_node *node;
7768
7769         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7770         node = llist_del_all(&ctx->rsrc_put_llist);
7771
7772         while (node) {
7773                 struct io_rsrc_node *ref_node;
7774                 struct llist_node *next = node->next;
7775
7776                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7777                 __io_rsrc_put_work(ref_node);
7778                 node = next;
7779         }
7780 }
7781
7782 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7783                                  unsigned nr_args, u64 __user *tags)
7784 {
7785         __s32 __user *fds = (__s32 __user *) arg;
7786         struct file *file;
7787         int fd, ret;
7788         unsigned i;
7789
7790         if (ctx->file_data)
7791                 return -EBUSY;
7792         if (!nr_args)
7793                 return -EINVAL;
7794         if (nr_args > IORING_MAX_FIXED_FILES)
7795                 return -EMFILE;
7796         if (nr_args > rlimit(RLIMIT_NOFILE))
7797                 return -EMFILE;
7798         ret = io_rsrc_node_switch_start(ctx);
7799         if (ret)
7800                 return ret;
7801         ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7802                                  &ctx->file_data);
7803         if (ret)
7804                 return ret;
7805
7806         if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
7807                 io_rsrc_data_free(ctx->file_data);
7808                 ctx->file_data = NULL;
7809                 return -ENOMEM;
7810         }
7811
7812         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7813                 struct io_fixed_file *file_slot;
7814
7815                 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
7816                         ret = -EFAULT;
7817                         goto fail;
7818                 }
7819                 /* allow sparse sets */
7820                 if (!fds || fd == -1) {
7821                         ret = -EINVAL;
7822                         if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7823                                 goto fail;
7824                         continue;
7825                 }
7826
7827                 file = fget(fd);
7828                 ret = -EBADF;
7829                 if (unlikely(!file))
7830                         goto fail;
7831
7832                 /*
7833                  * Don't allow io_uring instances to be registered. If UNIX
7834                  * isn't enabled, then this causes a reference cycle and this
7835                  * instance can never get freed. If UNIX is enabled we'll
7836                  * handle it just fine, but there's still no point in allowing
7837                  * a ring fd as it doesn't support regular read/write anyway.
7838                  */
7839                 if (file->f_op == &io_uring_fops) {
7840                         fput(file);
7841                         goto fail;
7842                 }
7843                 ret = io_scm_file_account(ctx, file);
7844                 if (ret) {
7845                         fput(file);
7846                         goto fail;
7847                 }
7848                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7849                 io_fixed_file_set(file_slot, file);
7850                 io_file_bitmap_set(&ctx->file_table, i);
7851         }
7852
7853         io_rsrc_node_switch(ctx, NULL);
7854         return 0;
7855 fail:
7856         __io_sqe_files_unregister(ctx);
7857         return ret;
7858 }
7859
7860 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7861                           struct io_rsrc_node *node, void *rsrc)
7862 {
7863         u64 *tag_slot = io_get_tag_slot(data, idx);
7864         struct io_rsrc_put *prsrc;
7865
7866         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7867         if (!prsrc)
7868                 return -ENOMEM;
7869
7870         prsrc->tag = *tag_slot;
7871         *tag_slot = 0;
7872         prsrc->rsrc = rsrc;
7873         list_add(&prsrc->list, &node->rsrc_list);
7874         return 0;
7875 }
7876
7877 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
7878                                  unsigned int issue_flags, u32 slot_index)
7879         __must_hold(&req->ctx->uring_lock)
7880 {
7881         struct io_ring_ctx *ctx = req->ctx;
7882         bool needs_switch = false;
7883         struct io_fixed_file *file_slot;
7884         int ret;
7885
7886         if (file->f_op == &io_uring_fops)
7887                 return -EBADF;
7888         if (!ctx->file_data)
7889                 return -ENXIO;
7890         if (slot_index >= ctx->nr_user_files)
7891                 return -EINVAL;
7892
7893         slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
7894         file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
7895
7896         if (file_slot->file_ptr) {
7897                 struct file *old_file;
7898
7899                 ret = io_rsrc_node_switch_start(ctx);
7900                 if (ret)
7901                         goto err;
7902
7903                 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7904                 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
7905                                             ctx->rsrc_node, old_file);
7906                 if (ret)
7907                         goto err;
7908                 file_slot->file_ptr = 0;
7909                 io_file_bitmap_clear(&ctx->file_table, slot_index);
7910                 needs_switch = true;
7911         }
7912
7913         ret = io_scm_file_account(ctx, file);
7914         if (!ret) {
7915                 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
7916                 io_fixed_file_set(file_slot, file);
7917                 io_file_bitmap_set(&ctx->file_table, slot_index);
7918         }
7919 err:
7920         if (needs_switch)
7921                 io_rsrc_node_switch(ctx, ctx->file_data);
7922         if (ret)
7923                 fput(file);
7924         return ret;
7925 }
7926
7927 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7928                                  struct io_uring_rsrc_update2 *up,
7929                                  unsigned nr_args)
7930 {
7931         u64 __user *tags = u64_to_user_ptr(up->tags);
7932         __s32 __user *fds = u64_to_user_ptr(up->data);
7933         struct io_rsrc_data *data = ctx->file_data;
7934         struct io_fixed_file *file_slot;
7935         struct file *file;
7936         int fd, i, err = 0;
7937         unsigned int done;
7938         bool needs_switch = false;
7939
7940         if (!ctx->file_data)
7941                 return -ENXIO;
7942         if (up->offset + nr_args > ctx->nr_user_files)
7943                 return -EINVAL;
7944
7945         for (done = 0; done < nr_args; done++) {
7946                 u64 tag = 0;
7947
7948                 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7949                     copy_from_user(&fd, &fds[done], sizeof(fd))) {
7950                         err = -EFAULT;
7951                         break;
7952                 }
7953                 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7954                         err = -EINVAL;
7955                         break;
7956                 }
7957                 if (fd == IORING_REGISTER_FILES_SKIP)
7958                         continue;
7959
7960                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7961                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7962
7963                 if (file_slot->file_ptr) {
7964                         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7965                         err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
7966                         if (err)
7967                                 break;
7968                         file_slot->file_ptr = 0;
7969                         io_file_bitmap_clear(&ctx->file_table, i);
7970                         needs_switch = true;
7971                 }
7972                 if (fd != -1) {
7973                         file = fget(fd);
7974                         if (!file) {
7975                                 err = -EBADF;
7976                                 break;
7977                         }
7978                         /*
7979                          * Don't allow io_uring instances to be registered. If
7980                          * UNIX isn't enabled, then this causes a reference
7981                          * cycle and this instance can never get freed. If UNIX
7982                          * is enabled we'll handle it just fine, but there's
7983                          * still no point in allowing a ring fd as it doesn't
7984                          * support regular read/write anyway.
7985                          */
7986                         if (file->f_op == &io_uring_fops) {
7987                                 fput(file);
7988                                 err = -EBADF;
7989                                 break;
7990                         }
7991                         err = io_scm_file_account(ctx, file);
7992                         if (err) {
7993                                 fput(file);
7994                                 break;
7995                         }
7996                         *io_get_tag_slot(data, i) = tag;
7997                         io_fixed_file_set(file_slot, file);
7998                         io_file_bitmap_set(&ctx->file_table, i);
7999                 }
8000         }
8001
8002         if (needs_switch)
8003                 io_rsrc_node_switch(ctx, data);
8004         return done ? done : err;
8005 }
8006
8007 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8008                                         struct task_struct *task)
8009 {
8010         struct io_wq_hash *hash;
8011         struct io_wq_data data;
8012         unsigned int concurrency;
8013
8014         mutex_lock(&ctx->uring_lock);
8015         hash = ctx->hash_map;
8016         if (!hash) {
8017                 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8018                 if (!hash) {
8019                         mutex_unlock(&ctx->uring_lock);
8020                         return ERR_PTR(-ENOMEM);
8021                 }
8022                 refcount_set(&hash->refs, 1);
8023                 init_waitqueue_head(&hash->wait);
8024                 ctx->hash_map = hash;
8025         }
8026         mutex_unlock(&ctx->uring_lock);
8027
8028         data.hash = hash;
8029         data.task = task;
8030         data.free_work = io_wq_free_work;
8031         data.do_work = io_wq_submit_work;
8032
8033         /* Do QD, or 4 * CPUS, whatever is smallest */
8034         concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8035
8036         return io_wq_create(concurrency, &data);
8037 }
8038
8039 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8040                                               struct io_ring_ctx *ctx)
8041 {
8042         struct io_uring_task *tctx;
8043         int ret;
8044
8045         tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8046         if (unlikely(!tctx))
8047                 return -ENOMEM;
8048
8049         tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
8050                                          sizeof(struct file *), GFP_KERNEL);
8051         if (unlikely(!tctx->registered_rings)) {
8052                 kfree(tctx);
8053                 return -ENOMEM;
8054         }
8055
8056         ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8057         if (unlikely(ret)) {
8058                 kfree(tctx->registered_rings);
8059                 kfree(tctx);
8060                 return ret;
8061         }
8062
8063         tctx->io_wq = io_init_wq_offload(ctx, task);
8064         if (IS_ERR(tctx->io_wq)) {
8065                 ret = PTR_ERR(tctx->io_wq);
8066                 percpu_counter_destroy(&tctx->inflight);
8067                 kfree(tctx->registered_rings);
8068                 kfree(tctx);
8069                 return ret;
8070         }
8071
8072         xa_init(&tctx->xa);
8073         init_waitqueue_head(&tctx->wait);
8074         atomic_set(&tctx->in_idle, 0);
8075         atomic_set(&tctx->inflight_tracked, 0);
8076         task->io_uring = tctx;
8077         spin_lock_init(&tctx->task_lock);
8078         INIT_WQ_LIST(&tctx->task_list);
8079         INIT_WQ_LIST(&tctx->prio_task_list);
8080         init_task_work(&tctx->task_work, tctx_task_work);
8081         return 0;
8082 }
8083
8084 void __io_uring_free(struct task_struct *tsk)
8085 {
8086         struct io_uring_task *tctx = tsk->io_uring;
8087
8088         WARN_ON_ONCE(!xa_empty(&tctx->xa));
8089         WARN_ON_ONCE(tctx->io_wq);
8090         WARN_ON_ONCE(tctx->cached_refs);
8091
8092         kfree(tctx->registered_rings);
8093         percpu_counter_destroy(&tctx->inflight);
8094         kfree(tctx);
8095         tsk->io_uring = NULL;
8096 }
8097
8098 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8099                                        struct io_uring_params *p)
8100 {
8101         int ret;
8102
8103         /* Retain compatibility with failing for an invalid attach attempt */
8104         if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8105                                 IORING_SETUP_ATTACH_WQ) {
8106                 struct fd f;
8107
8108                 f = fdget(p->wq_fd);
8109                 if (!f.file)
8110                         return -ENXIO;
8111                 if (f.file->f_op != &io_uring_fops) {
8112                         fdput(f);
8113                         return -EINVAL;
8114                 }
8115                 fdput(f);
8116         }
8117         if (ctx->flags & IORING_SETUP_SQPOLL) {
8118                 struct task_struct *tsk;
8119                 struct io_sq_data *sqd;
8120                 bool attached;
8121
8122                 ret = security_uring_sqpoll();
8123                 if (ret)
8124                         return ret;
8125
8126                 sqd = io_get_sq_data(p, &attached);
8127                 if (IS_ERR(sqd)) {
8128                         ret = PTR_ERR(sqd);
8129                         goto err;
8130                 }
8131
8132                 ctx->sq_creds = get_current_cred();
8133                 ctx->sq_data = sqd;
8134                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8135                 if (!ctx->sq_thread_idle)
8136                         ctx->sq_thread_idle = HZ;
8137
8138                 io_sq_thread_park(sqd);
8139                 list_add(&ctx->sqd_list, &sqd->ctx_list);
8140                 io_sqd_update_thread_idle(sqd);
8141                 /* don't attach to a dying SQPOLL thread, would be racy */
8142                 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8143                 io_sq_thread_unpark(sqd);
8144
8145                 if (ret < 0)
8146                         goto err;
8147                 if (attached)
8148                         return 0;
8149
8150                 if (p->flags & IORING_SETUP_SQ_AFF) {
8151                         int cpu = p->sq_thread_cpu;
8152
8153                         ret = -EINVAL;
8154                         if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8155                                 goto err_sqpoll;
8156                         sqd->sq_cpu = cpu;
8157                 } else {
8158                         sqd->sq_cpu = -1;
8159                 }
8160
8161                 sqd->task_pid = current->pid;
8162                 sqd->task_tgid = current->tgid;
8163                 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8164                 if (IS_ERR(tsk)) {
8165                         ret = PTR_ERR(tsk);
8166                         goto err_sqpoll;
8167                 }
8168
8169                 sqd->thread = tsk;
8170                 ret = io_uring_alloc_task_context(tsk, ctx);
8171                 wake_up_new_task(tsk);
8172                 if (ret)
8173                         goto err;
8174         } else if (p->flags & IORING_SETUP_SQ_AFF) {
8175                 /* Can't have SQ_AFF without SQPOLL */
8176                 ret = -EINVAL;
8177                 goto err;
8178         }
8179
8180         return 0;
8181 err_sqpoll:
8182         complete(&ctx->sq_data->exited);
8183 err:
8184         io_sq_thread_finish(ctx);
8185         return ret;
8186 }
8187
8188 static inline void __io_unaccount_mem(struct user_struct *user,
8189                                       unsigned long nr_pages)
8190 {
8191         atomic_long_sub(nr_pages, &user->locked_vm);
8192 }
8193
8194 static inline int __io_account_mem(struct user_struct *user,
8195                                    unsigned long nr_pages)
8196 {
8197         unsigned long page_limit, cur_pages, new_pages;
8198
8199         /* Don't allow more pages than we can safely lock */
8200         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8201
8202         do {
8203                 cur_pages = atomic_long_read(&user->locked_vm);
8204                 new_pages = cur_pages + nr_pages;
8205                 if (new_pages > page_limit)
8206                         return -ENOMEM;
8207         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8208                                         new_pages) != cur_pages);
8209
8210         return 0;
8211 }
8212
8213 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8214 {
8215         if (ctx->user)
8216                 __io_unaccount_mem(ctx->user, nr_pages);
8217
8218         if (ctx->mm_account)
8219                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8220 }
8221
8222 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8223 {
8224         int ret;
8225
8226         if (ctx->user) {
8227                 ret = __io_account_mem(ctx->user, nr_pages);
8228                 if (ret)
8229                         return ret;
8230         }
8231
8232         if (ctx->mm_account)
8233                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8234
8235         return 0;
8236 }
8237
8238 static void io_mem_free(void *ptr)
8239 {
8240         struct page *page;
8241
8242         if (!ptr)
8243                 return;
8244
8245         page = virt_to_head_page(ptr);
8246         if (put_page_testzero(page))
8247                 free_compound_page(page);
8248 }
8249
8250 static void *io_mem_alloc(size_t size)
8251 {
8252         gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8253
8254         return (void *) __get_free_pages(gfp, get_order(size));
8255 }
8256
8257 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
8258                                 unsigned int cq_entries, size_t *sq_offset)
8259 {
8260         struct io_rings *rings;
8261         size_t off, sq_array_size;
8262
8263         off = struct_size(rings, cqes, cq_entries);
8264         if (off == SIZE_MAX)
8265                 return SIZE_MAX;
8266         if (ctx->flags & IORING_SETUP_CQE32) {
8267                 if (check_shl_overflow(off, 1, &off))
8268                         return SIZE_MAX;
8269         }
8270
8271 #ifdef CONFIG_SMP
8272         off = ALIGN(off, SMP_CACHE_BYTES);
8273         if (off == 0)
8274                 return SIZE_MAX;
8275 #endif
8276
8277         if (sq_offset)
8278                 *sq_offset = off;
8279
8280         sq_array_size = array_size(sizeof(u32), sq_entries);
8281         if (sq_array_size == SIZE_MAX)
8282                 return SIZE_MAX;
8283
8284         if (check_add_overflow(off, sq_array_size, &off))
8285                 return SIZE_MAX;
8286
8287         return off;
8288 }
8289
8290 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8291 {
8292         struct io_mapped_ubuf *imu = *slot;
8293         unsigned int i;
8294
8295         if (imu != ctx->dummy_ubuf) {
8296                 for (i = 0; i < imu->nr_bvecs; i++)
8297                         unpin_user_page(imu->bvec[i].bv_page);
8298                 if (imu->acct_pages)
8299                         io_unaccount_mem(ctx, imu->acct_pages);
8300                 kvfree(imu);
8301         }
8302         *slot = NULL;
8303 }
8304
8305 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8306 {
8307         io_buffer_unmap(ctx, &prsrc->buf);
8308         prsrc->buf = NULL;
8309 }
8310
8311 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8312 {
8313         unsigned int i;
8314
8315         for (i = 0; i < ctx->nr_user_bufs; i++)
8316                 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8317         kfree(ctx->user_bufs);
8318         io_rsrc_data_free(ctx->buf_data);
8319         ctx->user_bufs = NULL;
8320         ctx->buf_data = NULL;
8321         ctx->nr_user_bufs = 0;
8322 }
8323
8324 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8325 {
8326         unsigned nr = ctx->nr_user_bufs;
8327         int ret;
8328
8329         if (!ctx->buf_data)
8330                 return -ENXIO;
8331
8332         /*
8333          * Quiesce may unlock ->uring_lock, and while it's not held
8334          * prevent new requests using the table.
8335          */
8336         ctx->nr_user_bufs = 0;
8337         ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8338         ctx->nr_user_bufs = nr;
8339         if (!ret)
8340                 __io_sqe_buffers_unregister(ctx);
8341         return ret;
8342 }
8343
8344 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8345                        void __user *arg, unsigned index)
8346 {
8347         struct iovec __user *src;
8348
8349 #ifdef CONFIG_COMPAT
8350         if (ctx->compat) {
8351                 struct compat_iovec __user *ciovs;
8352                 struct compat_iovec ciov;
8353
8354                 ciovs = (struct compat_iovec __user *) arg;
8355                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8356                         return -EFAULT;
8357
8358                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8359                 dst->iov_len = ciov.iov_len;
8360                 return 0;
8361         }
8362 #endif
8363         src = (struct iovec __user *) arg;
8364         if (copy_from_user(dst, &src[index], sizeof(*dst)))
8365                 return -EFAULT;
8366         return 0;
8367 }
8368
8369 /*
8370  * Not super efficient, but this is just a registration time. And we do cache
8371  * the last compound head, so generally we'll only do a full search if we don't
8372  * match that one.
8373  *
8374  * We check if the given compound head page has already been accounted, to
8375  * avoid double accounting it. This allows us to account the full size of the
8376  * page, not just the constituent pages of a huge page.
8377  */
8378 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8379                                   int nr_pages, struct page *hpage)
8380 {
8381         int i, j;
8382
8383         /* check current page array */
8384         for (i = 0; i < nr_pages; i++) {
8385                 if (!PageCompound(pages[i]))
8386                         continue;
8387                 if (compound_head(pages[i]) == hpage)
8388                         return true;
8389         }
8390
8391         /* check previously registered pages */
8392         for (i = 0; i < ctx->nr_user_bufs; i++) {
8393                 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8394
8395                 for (j = 0; j < imu->nr_bvecs; j++) {
8396                         if (!PageCompound(imu->bvec[j].bv_page))
8397                                 continue;
8398                         if (compound_head(imu->bvec[j].bv_page) == hpage)
8399                                 return true;
8400                 }
8401         }
8402
8403         return false;
8404 }
8405
8406 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8407                                  int nr_pages, struct io_mapped_ubuf *imu,
8408                                  struct page **last_hpage)
8409 {
8410         int i, ret;
8411
8412         imu->acct_pages = 0;
8413         for (i = 0; i < nr_pages; i++) {
8414                 if (!PageCompound(pages[i])) {
8415                         imu->acct_pages++;
8416                 } else {
8417                         struct page *hpage;
8418
8419                         hpage = compound_head(pages[i]);
8420                         if (hpage == *last_hpage)
8421                                 continue;
8422                         *last_hpage = hpage;
8423                         if (headpage_already_acct(ctx, pages, i, hpage))
8424                                 continue;
8425                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8426                 }
8427         }
8428
8429         if (!imu->acct_pages)
8430                 return 0;
8431
8432         ret = io_account_mem(ctx, imu->acct_pages);
8433         if (ret)
8434                 imu->acct_pages = 0;
8435         return ret;
8436 }
8437
8438 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
8439                                   int *npages)
8440 {
8441         unsigned long start, end, nr_pages;
8442         struct vm_area_struct **vmas = NULL;
8443         struct page **pages = NULL;
8444         int i, pret, ret = -ENOMEM;
8445
8446         end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8447         start = ubuf >> PAGE_SHIFT;
8448         nr_pages = end - start;
8449
8450         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8451         if (!pages)
8452                 goto done;
8453
8454         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8455                               GFP_KERNEL);
8456         if (!vmas)
8457                 goto done;
8458
8459         ret = 0;
8460         mmap_read_lock(current->mm);
8461         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8462                               pages, vmas);
8463         if (pret == nr_pages) {
8464                 /* don't support file backed memory */
8465                 for (i = 0; i < nr_pages; i++) {
8466                         struct vm_area_struct *vma = vmas[i];
8467
8468                         if (vma_is_shmem(vma))
8469                                 continue;
8470                         if (vma->vm_file &&
8471                             !is_file_hugepages(vma->vm_file)) {
8472                                 ret = -EOPNOTSUPP;
8473                                 break;
8474                         }
8475                 }
8476                 *npages = nr_pages;
8477         } else {
8478                 ret = pret < 0 ? pret : -EFAULT;
8479         }
8480         mmap_read_unlock(current->mm);
8481         if (ret) {
8482                 /*
8483                  * if we did partial map, or found file backed vmas,
8484                  * release any pages we did get
8485                  */
8486                 if (pret > 0)
8487                         unpin_user_pages(pages, pret);
8488                 goto done;
8489         }
8490         ret = 0;
8491 done:
8492         kvfree(vmas);
8493         if (ret < 0) {
8494                 kvfree(pages);
8495                 pages = ERR_PTR(ret);
8496         }
8497         return pages;
8498 }
8499
8500 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8501                                   struct io_mapped_ubuf **pimu,
8502                                   struct page **last_hpage)
8503 {
8504         struct io_mapped_ubuf *imu = NULL;
8505         struct page **pages = NULL;
8506         unsigned long off;
8507         size_t size;
8508         int ret, nr_pages, i;
8509
8510         if (!iov->iov_base) {
8511                 *pimu = ctx->dummy_ubuf;
8512                 return 0;
8513         }
8514
8515         *pimu = NULL;
8516         ret = -ENOMEM;
8517
8518         pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
8519                                 &nr_pages);
8520         if (IS_ERR(pages)) {
8521                 ret = PTR_ERR(pages);
8522                 pages = NULL;
8523                 goto done;
8524         }
8525
8526         imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8527         if (!imu)
8528                 goto done;
8529
8530         ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
8531         if (ret) {
8532                 unpin_user_pages(pages, nr_pages);
8533                 goto done;
8534         }
8535
8536         off = (unsigned long) iov->iov_base & ~PAGE_MASK;
8537         size = iov->iov_len;
8538         for (i = 0; i < nr_pages; i++) {
8539                 size_t vec_len;
8540
8541                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8542                 imu->bvec[i].bv_page = pages[i];
8543                 imu->bvec[i].bv_len = vec_len;
8544                 imu->bvec[i].bv_offset = off;
8545                 off = 0;
8546                 size -= vec_len;
8547         }
8548         /* store original address for later verification */
8549         imu->ubuf = (unsigned long) iov->iov_base;
8550         imu->ubuf_end = imu->ubuf + iov->iov_len;
8551         imu->nr_bvecs = nr_pages;
8552         *pimu = imu;
8553         ret = 0;
8554 done:
8555         if (ret)
8556                 kvfree(imu);
8557         kvfree(pages);
8558         return ret;
8559 }
8560
8561 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8562 {
8563         ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8564         return ctx->user_bufs ? 0 : -ENOMEM;
8565 }
8566
8567 static int io_buffer_validate(struct iovec *iov)
8568 {
8569         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8570
8571         /*
8572          * Don't impose further limits on the size and buffer
8573          * constraints here, we'll -EINVAL later when IO is
8574          * submitted if they are wrong.
8575          */
8576         if (!iov->iov_base)
8577                 return iov->iov_len ? -EFAULT : 0;
8578         if (!iov->iov_len)
8579                 return -EFAULT;
8580
8581         /* arbitrary limit, but we need something */
8582         if (iov->iov_len > SZ_1G)
8583                 return -EFAULT;
8584
8585         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8586                 return -EOVERFLOW;
8587
8588         return 0;
8589 }
8590
8591 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8592                                    unsigned int nr_args, u64 __user *tags)
8593 {
8594         struct page *last_hpage = NULL;
8595         struct io_rsrc_data *data;
8596         int i, ret;
8597         struct iovec iov;
8598
8599         if (ctx->user_bufs)
8600                 return -EBUSY;
8601         if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8602                 return -EINVAL;
8603         ret = io_rsrc_node_switch_start(ctx);
8604         if (ret)
8605                 return ret;
8606         ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8607         if (ret)
8608                 return ret;
8609         ret = io_buffers_map_alloc(ctx, nr_args);
8610         if (ret) {
8611                 io_rsrc_data_free(data);
8612                 return ret;
8613         }
8614
8615         for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8616                 if (arg) {
8617                         ret = io_copy_iov(ctx, &iov, arg, i);
8618                         if (ret)
8619                                 break;
8620                         ret = io_buffer_validate(&iov);
8621                         if (ret)
8622                                 break;
8623                 } else {
8624                         memset(&iov, 0, sizeof(iov));
8625                 }
8626
8627                 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8628                         ret = -EINVAL;
8629                         break;
8630                 }
8631
8632                 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8633                                              &last_hpage);
8634                 if (ret)
8635                         break;
8636         }
8637
8638         WARN_ON_ONCE(ctx->buf_data);
8639
8640         ctx->buf_data = data;
8641         if (ret)
8642                 __io_sqe_buffers_unregister(ctx);
8643         else
8644                 io_rsrc_node_switch(ctx, NULL);
8645         return ret;
8646 }
8647
8648 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8649                                    struct io_uring_rsrc_update2 *up,
8650                                    unsigned int nr_args)
8651 {
8652         u64 __user *tags = u64_to_user_ptr(up->tags);
8653         struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8654         struct page *last_hpage = NULL;
8655         bool needs_switch = false;
8656         __u32 done;
8657         int i, err;
8658
8659         if (!ctx->buf_data)
8660                 return -ENXIO;
8661         if (up->offset + nr_args > ctx->nr_user_bufs)
8662                 return -EINVAL;
8663
8664         for (done = 0; done < nr_args; done++) {
8665                 struct io_mapped_ubuf *imu;
8666                 int offset = up->offset + done;
8667                 u64 tag = 0;
8668
8669                 err = io_copy_iov(ctx, &iov, iovs, done);
8670                 if (err)
8671                         break;
8672                 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8673                         err = -EFAULT;
8674                         break;
8675                 }
8676                 err = io_buffer_validate(&iov);
8677                 if (err)
8678                         break;
8679                 if (!iov.iov_base && tag) {
8680                         err = -EINVAL;
8681                         break;
8682                 }
8683                 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8684                 if (err)
8685                         break;
8686
8687                 i = array_index_nospec(offset, ctx->nr_user_bufs);
8688                 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8689                         err = io_queue_rsrc_removal(ctx->buf_data, i,
8690                                                     ctx->rsrc_node, ctx->user_bufs[i]);
8691                         if (unlikely(err)) {
8692                                 io_buffer_unmap(ctx, &imu);
8693                                 break;
8694                         }
8695                         ctx->user_bufs[i] = NULL;
8696                         needs_switch = true;
8697                 }
8698
8699                 ctx->user_bufs[i] = imu;
8700                 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8701         }
8702
8703         if (needs_switch)
8704                 io_rsrc_node_switch(ctx, ctx->buf_data);
8705         return done ? done : err;
8706 }
8707
8708 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
8709                                unsigned int eventfd_async)
8710 {
8711         struct io_ev_fd *ev_fd;
8712         __s32 __user *fds = arg;
8713         int fd;
8714
8715         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
8716                                         lockdep_is_held(&ctx->uring_lock));
8717         if (ev_fd)
8718                 return -EBUSY;
8719
8720         if (copy_from_user(&fd, fds, sizeof(*fds)))
8721                 return -EFAULT;
8722
8723         ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
8724         if (!ev_fd)
8725                 return -ENOMEM;
8726
8727         ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
8728         if (IS_ERR(ev_fd->cq_ev_fd)) {
8729                 int ret = PTR_ERR(ev_fd->cq_ev_fd);
8730                 kfree(ev_fd);
8731                 return ret;
8732         }
8733         ev_fd->eventfd_async = eventfd_async;
8734         ctx->has_evfd = true;
8735         rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
8736         return 0;
8737 }
8738
8739 static void io_eventfd_put(struct rcu_head *rcu)
8740 {
8741         struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
8742
8743         eventfd_ctx_put(ev_fd->cq_ev_fd);
8744         kfree(ev_fd);
8745 }
8746
8747 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8748 {
8749         struct io_ev_fd *ev_fd;
8750
8751         ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
8752                                         lockdep_is_held(&ctx->uring_lock));
8753         if (ev_fd) {
8754                 ctx->has_evfd = false;
8755                 rcu_assign_pointer(ctx->io_ev_fd, NULL);
8756                 call_rcu(&ev_fd->rcu, io_eventfd_put);
8757                 return 0;
8758         }
8759
8760         return -ENXIO;
8761 }
8762
8763 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8764 {
8765         struct io_buffer_list *bl;
8766         unsigned long index;
8767         int i;
8768
8769         for (i = 0; i < BGID_ARRAY; i++) {
8770                 if (!ctx->io_bl)
8771                         break;
8772                 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
8773         }
8774
8775         xa_for_each(&ctx->io_bl_xa, index, bl) {
8776                 xa_erase(&ctx->io_bl_xa, bl->bgid);
8777                 __io_remove_buffers(ctx, bl, -1U);
8778                 kfree(bl);
8779         }
8780
8781         while (!list_empty(&ctx->io_buffers_pages)) {
8782                 struct page *page;
8783
8784                 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
8785                 list_del_init(&page->lru);
8786                 __free_page(page);
8787         }
8788 }
8789
8790 static void io_req_caches_free(struct io_ring_ctx *ctx)
8791 {
8792         struct io_submit_state *state = &ctx->submit_state;
8793         int nr = 0;
8794
8795         mutex_lock(&ctx->uring_lock);
8796         io_flush_cached_locked_reqs(ctx, state);
8797
8798         while (!io_req_cache_empty(ctx)) {
8799                 struct io_wq_work_node *node;
8800                 struct io_kiocb *req;
8801
8802                 node = wq_stack_extract(&state->free_list);
8803                 req = container_of(node, struct io_kiocb, comp_list);
8804                 kmem_cache_free(req_cachep, req);
8805                 nr++;
8806         }
8807         if (nr)
8808                 percpu_ref_put_many(&ctx->refs, nr);
8809         mutex_unlock(&ctx->uring_lock);
8810 }
8811
8812 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8813 {
8814         if (data && !atomic_dec_and_test(&data->refs))
8815                 wait_for_completion(&data->done);
8816 }
8817
8818 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
8819 {
8820         struct async_poll *apoll;
8821
8822         while (!list_empty(&ctx->apoll_cache)) {
8823                 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
8824                                                 poll.wait.entry);
8825                 list_del(&apoll->poll.wait.entry);
8826                 kfree(apoll);
8827         }
8828 }
8829
8830 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
8831 {
8832         io_sq_thread_finish(ctx);
8833
8834         if (ctx->mm_account) {
8835                 mmdrop(ctx->mm_account);
8836                 ctx->mm_account = NULL;
8837         }
8838
8839         io_rsrc_refs_drop(ctx);
8840         /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8841         io_wait_rsrc_data(ctx->buf_data);
8842         io_wait_rsrc_data(ctx->file_data);
8843
8844         mutex_lock(&ctx->uring_lock);
8845         if (ctx->buf_data)
8846                 __io_sqe_buffers_unregister(ctx);
8847         if (ctx->file_data)
8848                 __io_sqe_files_unregister(ctx);
8849         if (ctx->rings)
8850                 __io_cqring_overflow_flush(ctx, true);
8851         io_eventfd_unregister(ctx);
8852         io_flush_apoll_cache(ctx);
8853         mutex_unlock(&ctx->uring_lock);
8854         io_destroy_buffers(ctx);
8855         if (ctx->sq_creds)
8856                 put_cred(ctx->sq_creds);
8857
8858         /* there are no registered resources left, nobody uses it */
8859         if (ctx->rsrc_node)
8860                 io_rsrc_node_destroy(ctx->rsrc_node);
8861         if (ctx->rsrc_backup_node)
8862                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8863         flush_delayed_work(&ctx->rsrc_put_work);
8864         flush_delayed_work(&ctx->fallback_work);
8865
8866         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8867         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8868
8869 #if defined(CONFIG_UNIX)
8870         if (ctx->ring_sock) {
8871                 ctx->ring_sock->file = NULL; /* so that iput() is called */
8872                 sock_release(ctx->ring_sock);
8873         }
8874 #endif
8875         WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8876
8877         io_mem_free(ctx->rings);
8878         io_mem_free(ctx->sq_sqes);
8879
8880         percpu_ref_exit(&ctx->refs);
8881         free_uid(ctx->user);
8882         io_req_caches_free(ctx);
8883         if (ctx->hash_map)
8884                 io_wq_put_hash(ctx->hash_map);
8885         kfree(ctx->cancel_hash);
8886         kfree(ctx->dummy_ubuf);
8887         kfree(ctx->io_bl);
8888         xa_destroy(&ctx->io_bl_xa);
8889         kfree(ctx);
8890 }
8891
8892 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8893 {
8894         struct io_ring_ctx *ctx = file->private_data;
8895         __poll_t mask = 0;
8896
8897         poll_wait(file, &ctx->cq_wait, wait);
8898         /*
8899          * synchronizes with barrier from wq_has_sleeper call in
8900          * io_commit_cqring
8901          */
8902         smp_rmb();
8903         if (!io_sqring_full(ctx))
8904                 mask |= EPOLLOUT | EPOLLWRNORM;
8905
8906         /*
8907          * Don't flush cqring overflow list here, just do a simple check.
8908          * Otherwise there could possible be ABBA deadlock:
8909          *      CPU0                    CPU1
8910          *      ----                    ----
8911          * lock(&ctx->uring_lock);
8912          *                              lock(&ep->mtx);
8913          *                              lock(&ctx->uring_lock);
8914          * lock(&ep->mtx);
8915          *
8916          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8917          * pushs them to do the flush.
8918          */
8919         if (io_cqring_events(ctx) ||
8920             test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
8921                 mask |= EPOLLIN | EPOLLRDNORM;
8922
8923         return mask;
8924 }
8925
8926 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8927 {
8928         const struct cred *creds;
8929
8930         creds = xa_erase(&ctx->personalities, id);
8931         if (creds) {
8932                 put_cred(creds);
8933                 return 0;
8934         }
8935
8936         return -EINVAL;
8937 }
8938
8939 struct io_tctx_exit {
8940         struct callback_head            task_work;
8941         struct completion               completion;
8942         struct io_ring_ctx              *ctx;
8943 };
8944
8945 static __cold void io_tctx_exit_cb(struct callback_head *cb)
8946 {
8947         struct io_uring_task *tctx = current->io_uring;
8948         struct io_tctx_exit *work;
8949
8950         work = container_of(cb, struct io_tctx_exit, task_work);
8951         /*
8952          * When @in_idle, we're in cancellation and it's racy to remove the
8953          * node. It'll be removed by the end of cancellation, just ignore it.
8954          */
8955         if (!atomic_read(&tctx->in_idle))
8956                 io_uring_del_tctx_node((unsigned long)work->ctx);
8957         complete(&work->completion);
8958 }
8959
8960 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8961 {
8962         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8963
8964         return req->ctx == data;
8965 }
8966
8967 static __cold void io_ring_exit_work(struct work_struct *work)
8968 {
8969         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8970         unsigned long timeout = jiffies + HZ * 60 * 5;
8971         unsigned long interval = HZ / 20;
8972         struct io_tctx_exit exit;
8973         struct io_tctx_node *node;
8974         int ret;
8975
8976         /*
8977          * If we're doing polled IO and end up having requests being
8978          * submitted async (out-of-line), then completions can come in while
8979          * we're waiting for refs to drop. We need to reap these manually,
8980          * as nobody else will be looking for them.
8981          */
8982         do {
8983                 io_uring_try_cancel_requests(ctx, NULL, true);
8984                 if (ctx->sq_data) {
8985                         struct io_sq_data *sqd = ctx->sq_data;
8986                         struct task_struct *tsk;
8987
8988                         io_sq_thread_park(sqd);
8989                         tsk = sqd->thread;
8990                         if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8991                                 io_wq_cancel_cb(tsk->io_uring->io_wq,
8992                                                 io_cancel_ctx_cb, ctx, true);
8993                         io_sq_thread_unpark(sqd);
8994                 }
8995
8996                 io_req_caches_free(ctx);
8997
8998                 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
8999                         /* there is little hope left, don't run it too often */
9000                         interval = HZ * 60;
9001                 }
9002         } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9003
9004         init_completion(&exit.completion);
9005         init_task_work(&exit.task_work, io_tctx_exit_cb);
9006         exit.ctx = ctx;
9007         /*
9008          * Some may use context even when all refs and requests have been put,
9009          * and they are free to do so while still holding uring_lock or
9010          * completion_lock, see io_req_task_submit(). Apart from other work,
9011          * this lock/unlock section also waits them to finish.
9012          */
9013         mutex_lock(&ctx->uring_lock);
9014         while (!list_empty(&ctx->tctx_list)) {
9015                 WARN_ON_ONCE(time_after(jiffies, timeout));
9016
9017                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9018                                         ctx_node);
9019                 /* don't spin on a single task if cancellation failed */
9020                 list_rotate_left(&ctx->tctx_list);
9021                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9022                 if (WARN_ON_ONCE(ret))
9023                         continue;
9024
9025                 mutex_unlock(&ctx->uring_lock);
9026                 wait_for_completion(&exit.completion);
9027                 mutex_lock(&ctx->uring_lock);
9028         }
9029         mutex_unlock(&ctx->uring_lock);
9030         spin_lock(&ctx->completion_lock);
9031         spin_unlock(&ctx->completion_lock);
9032
9033         io_ring_ctx_free(ctx);
9034 }
9035
9036 /* Returns true if we found and killed one or more timeouts */
9037 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9038                                     struct task_struct *tsk, bool cancel_all)
9039 {
9040         struct io_timeout *timeout, *tmp;
9041         int canceled = 0;
9042
9043         spin_lock(&ctx->completion_lock);
9044         spin_lock_irq(&ctx->timeout_lock);
9045         list_for_each_entry_safe(timeout, tmp, &ctx->timeout_list, list) {
9046                 struct io_kiocb *req = cmd_to_io_kiocb(timeout);
9047
9048                 if (io_match_task(req, tsk, cancel_all)) {
9049                         io_kill_timeout(req, -ECANCELED);
9050                         canceled++;
9051                 }
9052         }
9053         spin_unlock_irq(&ctx->timeout_lock);
9054         io_commit_cqring(ctx);
9055         spin_unlock(&ctx->completion_lock);
9056         if (canceled != 0)
9057                 io_cqring_ev_posted(ctx);
9058         return canceled != 0;
9059 }
9060
9061 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9062 {
9063         unsigned long index;
9064         struct creds *creds;
9065
9066         mutex_lock(&ctx->uring_lock);
9067         percpu_ref_kill(&ctx->refs);
9068         if (ctx->rings)
9069                 __io_cqring_overflow_flush(ctx, true);
9070         xa_for_each(&ctx->personalities, index, creds)
9071                 io_unregister_personality(ctx, index);
9072         mutex_unlock(&ctx->uring_lock);
9073
9074         /* failed during ring init, it couldn't have issued any requests */
9075         if (ctx->rings) {
9076                 io_kill_timeouts(ctx, NULL, true);
9077                 io_poll_remove_all(ctx, NULL, true);
9078                 /* if we failed setting up the ctx, we might not have any rings */
9079                 io_iopoll_try_reap_events(ctx);
9080         }
9081
9082         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9083         /*
9084          * Use system_unbound_wq to avoid spawning tons of event kworkers
9085          * if we're exiting a ton of rings at the same time. It just adds
9086          * noise and overhead, there's no discernable change in runtime
9087          * over using system_wq.
9088          */
9089         queue_work(system_unbound_wq, &ctx->exit_work);
9090 }
9091
9092 static int io_uring_release(struct inode *inode, struct file *file)
9093 {
9094         struct io_ring_ctx *ctx = file->private_data;
9095
9096         file->private_data = NULL;
9097         io_ring_ctx_wait_and_kill(ctx);
9098         return 0;
9099 }
9100
9101 struct io_task_cancel {
9102         struct task_struct *task;
9103         bool all;
9104 };
9105
9106 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9107 {
9108         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9109         struct io_task_cancel *cancel = data;
9110
9111         return io_match_task_safe(req, cancel->task, cancel->all);
9112 }
9113
9114 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9115                                          struct task_struct *task,
9116                                          bool cancel_all)
9117 {
9118         struct io_defer_entry *de;
9119         LIST_HEAD(list);
9120
9121         spin_lock(&ctx->completion_lock);
9122         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9123                 if (io_match_task_safe(de->req, task, cancel_all)) {
9124                         list_cut_position(&list, &ctx->defer_list, &de->list);
9125                         break;
9126                 }
9127         }
9128         spin_unlock(&ctx->completion_lock);
9129         if (list_empty(&list))
9130                 return false;
9131
9132         while (!list_empty(&list)) {
9133                 de = list_first_entry(&list, struct io_defer_entry, list);
9134                 list_del_init(&de->list);
9135                 io_req_complete_failed(de->req, -ECANCELED);
9136                 kfree(de);
9137         }
9138         return true;
9139 }
9140
9141 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9142 {
9143         struct io_tctx_node *node;
9144         enum io_wq_cancel cret;
9145         bool ret = false;
9146
9147         mutex_lock(&ctx->uring_lock);
9148         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9149                 struct io_uring_task *tctx = node->task->io_uring;
9150
9151                 /*
9152                  * io_wq will stay alive while we hold uring_lock, because it's
9153                  * killed after ctx nodes, which requires to take the lock.
9154                  */
9155                 if (!tctx || !tctx->io_wq)
9156                         continue;
9157                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9158                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9159         }
9160         mutex_unlock(&ctx->uring_lock);
9161
9162         return ret;
9163 }
9164
9165 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9166                                                 struct task_struct *task,
9167                                                 bool cancel_all)
9168 {
9169         struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9170         struct io_uring_task *tctx = task ? task->io_uring : NULL;
9171
9172         /* failed during ring init, it couldn't have issued any requests */
9173         if (!ctx->rings)
9174                 return;
9175
9176         while (1) {
9177                 enum io_wq_cancel cret;
9178                 bool ret = false;
9179
9180                 if (!task) {
9181                         ret |= io_uring_try_cancel_iowq(ctx);
9182                 } else if (tctx && tctx->io_wq) {
9183                         /*
9184                          * Cancels requests of all rings, not only @ctx, but
9185                          * it's fine as the task is in exit/exec.
9186                          */
9187                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9188                                                &cancel, true);
9189                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9190                 }
9191
9192                 /* SQPOLL thread does its own polling */
9193                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9194                     (ctx->sq_data && ctx->sq_data->thread == current)) {
9195                         while (!wq_list_empty(&ctx->iopoll_list)) {
9196                                 io_iopoll_try_reap_events(ctx);
9197                                 ret = true;
9198                         }
9199                 }
9200
9201                 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9202                 ret |= io_poll_remove_all(ctx, task, cancel_all);
9203                 ret |= io_kill_timeouts(ctx, task, cancel_all);
9204                 if (task)
9205                         ret |= io_run_task_work();
9206                 if (!ret)
9207                         break;
9208                 cond_resched();
9209         }
9210 }
9211
9212 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9213 {
9214         struct io_uring_task *tctx = current->io_uring;
9215         struct io_tctx_node *node;
9216         int ret;
9217
9218         if (unlikely(!tctx)) {
9219                 ret = io_uring_alloc_task_context(current, ctx);
9220                 if (unlikely(ret))
9221                         return ret;
9222
9223                 tctx = current->io_uring;
9224                 if (ctx->iowq_limits_set) {
9225                         unsigned int limits[2] = { ctx->iowq_limits[0],
9226                                                    ctx->iowq_limits[1], };
9227
9228                         ret = io_wq_max_workers(tctx->io_wq, limits);
9229                         if (ret)
9230                                 return ret;
9231                 }
9232         }
9233         if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9234                 node = kmalloc(sizeof(*node), GFP_KERNEL);
9235                 if (!node)
9236                         return -ENOMEM;
9237                 node->ctx = ctx;
9238                 node->task = current;
9239
9240                 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9241                                         node, GFP_KERNEL));
9242                 if (ret) {
9243                         kfree(node);
9244                         return ret;
9245                 }
9246
9247                 mutex_lock(&ctx->uring_lock);
9248                 list_add(&node->ctx_node, &ctx->tctx_list);
9249                 mutex_unlock(&ctx->uring_lock);
9250         }
9251         tctx->last = ctx;
9252         return 0;
9253 }
9254
9255 /*
9256  * Note that this task has used io_uring. We use it for cancelation purposes.
9257  */
9258 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9259 {
9260         struct io_uring_task *tctx = current->io_uring;
9261
9262         if (likely(tctx && tctx->last == ctx))
9263                 return 0;
9264         return __io_uring_add_tctx_node(ctx);
9265 }
9266
9267 /*
9268  * Remove this io_uring_file -> task mapping.
9269  */
9270 static __cold void io_uring_del_tctx_node(unsigned long index)
9271 {
9272         struct io_uring_task *tctx = current->io_uring;
9273         struct io_tctx_node *node;
9274
9275         if (!tctx)
9276                 return;
9277         node = xa_erase(&tctx->xa, index);
9278         if (!node)
9279                 return;
9280
9281         WARN_ON_ONCE(current != node->task);
9282         WARN_ON_ONCE(list_empty(&node->ctx_node));
9283
9284         mutex_lock(&node->ctx->uring_lock);
9285         list_del(&node->ctx_node);
9286         mutex_unlock(&node->ctx->uring_lock);
9287
9288         if (tctx->last == node->ctx)
9289                 tctx->last = NULL;
9290         kfree(node);
9291 }
9292
9293 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9294 {
9295         struct io_wq *wq = tctx->io_wq;
9296         struct io_tctx_node *node;
9297         unsigned long index;
9298
9299         xa_for_each(&tctx->xa, index, node) {
9300                 io_uring_del_tctx_node(index);
9301                 cond_resched();
9302         }
9303         if (wq) {
9304                 /*
9305                  * Must be after io_uring_del_tctx_node() (removes nodes under
9306                  * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9307                  */
9308                 io_wq_put_and_exit(wq);
9309                 tctx->io_wq = NULL;
9310         }
9311 }
9312
9313 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9314 {
9315         if (tracked)
9316                 return atomic_read(&tctx->inflight_tracked);
9317         return percpu_counter_sum(&tctx->inflight);
9318 }
9319
9320 /*
9321  * Find any io_uring ctx that this task has registered or done IO on, and cancel
9322  * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9323  */
9324 static __cold void io_uring_cancel_generic(bool cancel_all,
9325                                            struct io_sq_data *sqd)
9326 {
9327         struct io_uring_task *tctx = current->io_uring;
9328         struct io_ring_ctx *ctx;
9329         s64 inflight;
9330         DEFINE_WAIT(wait);
9331
9332         WARN_ON_ONCE(sqd && sqd->thread != current);
9333
9334         if (!current->io_uring)
9335                 return;
9336         if (tctx->io_wq)
9337                 io_wq_exit_start(tctx->io_wq);
9338
9339         atomic_inc(&tctx->in_idle);
9340         do {
9341                 io_uring_drop_tctx_refs(current);
9342                 /* read completions before cancelations */
9343                 inflight = tctx_inflight(tctx, !cancel_all);
9344                 if (!inflight)
9345                         break;
9346
9347                 if (!sqd) {
9348                         struct io_tctx_node *node;
9349                         unsigned long index;
9350
9351                         xa_for_each(&tctx->xa, index, node) {
9352                                 /* sqpoll task will cancel all its requests */
9353                                 if (node->ctx->sq_data)
9354                                         continue;
9355                                 io_uring_try_cancel_requests(node->ctx, current,
9356                                                              cancel_all);
9357                         }
9358                 } else {
9359                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9360                                 io_uring_try_cancel_requests(ctx, current,
9361                                                              cancel_all);
9362                 }
9363
9364                 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9365                 io_run_task_work();
9366                 io_uring_drop_tctx_refs(current);
9367
9368                 /*
9369                  * If we've seen completions, retry without waiting. This
9370                  * avoids a race where a completion comes in before we did
9371                  * prepare_to_wait().
9372                  */
9373                 if (inflight == tctx_inflight(tctx, !cancel_all))
9374                         schedule();
9375                 finish_wait(&tctx->wait, &wait);
9376         } while (1);
9377
9378         io_uring_clean_tctx(tctx);
9379         if (cancel_all) {
9380                 /*
9381                  * We shouldn't run task_works after cancel, so just leave
9382                  * ->in_idle set for normal exit.
9383                  */
9384                 atomic_dec(&tctx->in_idle);
9385                 /* for exec all current's requests should be gone, kill tctx */
9386                 __io_uring_free(current);
9387         }
9388 }
9389
9390 void __io_uring_cancel(bool cancel_all)
9391 {
9392         io_uring_cancel_generic(cancel_all, NULL);
9393 }
9394
9395 void io_uring_unreg_ringfd(void)
9396 {
9397         struct io_uring_task *tctx = current->io_uring;
9398         int i;
9399
9400         for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
9401                 if (tctx->registered_rings[i]) {
9402                         fput(tctx->registered_rings[i]);
9403                         tctx->registered_rings[i] = NULL;
9404                 }
9405         }
9406 }
9407
9408 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
9409                                      int start, int end)
9410 {
9411         struct file *file;
9412         int offset;
9413
9414         for (offset = start; offset < end; offset++) {
9415                 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
9416                 if (tctx->registered_rings[offset])
9417                         continue;
9418
9419                 file = fget(fd);
9420                 if (!file) {
9421                         return -EBADF;
9422                 } else if (file->f_op != &io_uring_fops) {
9423                         fput(file);
9424                         return -EOPNOTSUPP;
9425                 }
9426                 tctx->registered_rings[offset] = file;
9427                 return offset;
9428         }
9429
9430         return -EBUSY;
9431 }
9432
9433 /*
9434  * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
9435  * invocation. User passes in an array of struct io_uring_rsrc_update
9436  * with ->data set to the ring_fd, and ->offset given for the desired
9437  * index. If no index is desired, application may set ->offset == -1U
9438  * and we'll find an available index. Returns number of entries
9439  * successfully processed, or < 0 on error if none were processed.
9440  */
9441 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
9442                               unsigned nr_args)
9443 {
9444         struct io_uring_rsrc_update __user *arg = __arg;
9445         struct io_uring_rsrc_update reg;
9446         struct io_uring_task *tctx;
9447         int ret, i;
9448
9449         if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
9450                 return -EINVAL;
9451
9452         mutex_unlock(&ctx->uring_lock);
9453         ret = io_uring_add_tctx_node(ctx);
9454         mutex_lock(&ctx->uring_lock);
9455         if (ret)
9456                 return ret;
9457
9458         tctx = current->io_uring;
9459         for (i = 0; i < nr_args; i++) {
9460                 int start, end;
9461
9462                 if (copy_from_user(&reg, &arg[i], sizeof(reg))) {
9463                         ret = -EFAULT;
9464                         break;
9465                 }
9466
9467                 if (reg.resv) {
9468                         ret = -EINVAL;
9469                         break;
9470                 }
9471
9472                 if (reg.offset == -1U) {
9473                         start = 0;
9474                         end = IO_RINGFD_REG_MAX;
9475                 } else {
9476                         if (reg.offset >= IO_RINGFD_REG_MAX) {
9477                                 ret = -EINVAL;
9478                                 break;
9479                         }
9480                         start = reg.offset;
9481                         end = start + 1;
9482                 }
9483
9484                 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
9485                 if (ret < 0)
9486                         break;
9487
9488                 reg.offset = ret;
9489                 if (copy_to_user(&arg[i], &reg, sizeof(reg))) {
9490                         fput(tctx->registered_rings[reg.offset]);
9491                         tctx->registered_rings[reg.offset] = NULL;
9492                         ret = -EFAULT;
9493                         break;
9494                 }
9495         }
9496
9497         return i ? i : ret;
9498 }
9499
9500 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
9501                                 unsigned nr_args)
9502 {
9503         struct io_uring_rsrc_update __user *arg = __arg;
9504         struct io_uring_task *tctx = current->io_uring;
9505         struct io_uring_rsrc_update reg;
9506         int ret = 0, i;
9507
9508         if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
9509                 return -EINVAL;
9510         if (!tctx)
9511                 return 0;
9512
9513         for (i = 0; i < nr_args; i++) {
9514                 if (copy_from_user(&reg, &arg[i], sizeof(reg))) {
9515                         ret = -EFAULT;
9516                         break;
9517                 }
9518                 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
9519                         ret = -EINVAL;
9520                         break;
9521                 }
9522
9523                 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
9524                 if (tctx->registered_rings[reg.offset]) {
9525                         fput(tctx->registered_rings[reg.offset]);
9526                         tctx->registered_rings[reg.offset] = NULL;
9527                 }
9528         }
9529
9530         return i ? i : ret;
9531 }
9532
9533 static void *io_uring_validate_mmap_request(struct file *file,
9534                                             loff_t pgoff, size_t sz)
9535 {
9536         struct io_ring_ctx *ctx = file->private_data;
9537         loff_t offset = pgoff << PAGE_SHIFT;
9538         struct page *page;
9539         void *ptr;
9540
9541         switch (offset) {
9542         case IORING_OFF_SQ_RING:
9543         case IORING_OFF_CQ_RING:
9544                 ptr = ctx->rings;
9545                 break;
9546         case IORING_OFF_SQES:
9547                 ptr = ctx->sq_sqes;
9548                 break;
9549         default:
9550                 return ERR_PTR(-EINVAL);
9551         }
9552
9553         page = virt_to_head_page(ptr);
9554         if (sz > page_size(page))
9555                 return ERR_PTR(-EINVAL);
9556
9557         return ptr;
9558 }
9559
9560 #ifdef CONFIG_MMU
9561
9562 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9563 {
9564         size_t sz = vma->vm_end - vma->vm_start;
9565         unsigned long pfn;
9566         void *ptr;
9567
9568         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9569         if (IS_ERR(ptr))
9570                 return PTR_ERR(ptr);
9571
9572         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9573         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9574 }
9575
9576 #else /* !CONFIG_MMU */
9577
9578 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9579 {
9580         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9581 }
9582
9583 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9584 {
9585         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9586 }
9587
9588 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9589         unsigned long addr, unsigned long len,
9590         unsigned long pgoff, unsigned long flags)
9591 {
9592         void *ptr;
9593
9594         ptr = io_uring_validate_mmap_request(file, pgoff, len);
9595         if (IS_ERR(ptr))
9596                 return PTR_ERR(ptr);
9597
9598         return (unsigned long) ptr;
9599 }
9600
9601 #endif /* !CONFIG_MMU */
9602
9603 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9604 {
9605         DEFINE_WAIT(wait);
9606
9607         do {
9608                 if (!io_sqring_full(ctx))
9609                         break;
9610                 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9611
9612                 if (!io_sqring_full(ctx))
9613                         break;
9614                 schedule();
9615         } while (!signal_pending(current));
9616
9617         finish_wait(&ctx->sqo_sq_wait, &wait);
9618         return 0;
9619 }
9620
9621 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
9622 {
9623         if (flags & IORING_ENTER_EXT_ARG) {
9624                 struct io_uring_getevents_arg arg;
9625
9626                 if (argsz != sizeof(arg))
9627                         return -EINVAL;
9628                 if (copy_from_user(&arg, argp, sizeof(arg)))
9629                         return -EFAULT;
9630         }
9631         return 0;
9632 }
9633
9634 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9635                           struct __kernel_timespec __user **ts,
9636                           const sigset_t __user **sig)
9637 {
9638         struct io_uring_getevents_arg arg;
9639
9640         /*
9641          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9642          * is just a pointer to the sigset_t.
9643          */
9644         if (!(flags & IORING_ENTER_EXT_ARG)) {
9645                 *sig = (const sigset_t __user *) argp;
9646                 *ts = NULL;
9647                 return 0;
9648         }
9649
9650         /*
9651          * EXT_ARG is set - ensure we agree on the size of it and copy in our
9652          * timespec and sigset_t pointers if good.
9653          */
9654         if (*argsz != sizeof(arg))
9655                 return -EINVAL;
9656         if (copy_from_user(&arg, argp, sizeof(arg)))
9657                 return -EFAULT;
9658         if (arg.pad)
9659                 return -EINVAL;
9660         *sig = u64_to_user_ptr(arg.sigmask);
9661         *argsz = arg.sigmask_sz;
9662         *ts = u64_to_user_ptr(arg.ts);
9663         return 0;
9664 }
9665
9666 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9667                 u32, min_complete, u32, flags, const void __user *, argp,
9668                 size_t, argsz)
9669 {
9670         struct io_ring_ctx *ctx;
9671         struct fd f;
9672         long ret;
9673
9674         io_run_task_work();
9675
9676         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9677                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
9678                                IORING_ENTER_REGISTERED_RING)))
9679                 return -EINVAL;
9680
9681         /*
9682          * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
9683          * need only dereference our task private array to find it.
9684          */
9685         if (flags & IORING_ENTER_REGISTERED_RING) {
9686                 struct io_uring_task *tctx = current->io_uring;
9687
9688                 if (!tctx || fd >= IO_RINGFD_REG_MAX)
9689                         return -EINVAL;
9690                 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
9691                 f.file = tctx->registered_rings[fd];
9692                 f.flags = 0;
9693         } else {
9694                 f = fdget(fd);
9695         }
9696
9697         if (unlikely(!f.file))
9698                 return -EBADF;
9699
9700         ret = -EOPNOTSUPP;
9701         if (unlikely(f.file->f_op != &io_uring_fops))
9702                 goto out_fput;
9703
9704         ret = -ENXIO;
9705         ctx = f.file->private_data;
9706         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9707                 goto out_fput;
9708
9709         ret = -EBADFD;
9710         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9711                 goto out;
9712
9713         /*
9714          * For SQ polling, the thread will do all submissions and completions.
9715          * Just return the requested submit count, and wake the thread if
9716          * we were asked to.
9717          */
9718         ret = 0;
9719         if (ctx->flags & IORING_SETUP_SQPOLL) {
9720                 io_cqring_overflow_flush(ctx);
9721
9722                 if (unlikely(ctx->sq_data->thread == NULL)) {
9723                         ret = -EOWNERDEAD;
9724                         goto out;
9725                 }
9726                 if (flags & IORING_ENTER_SQ_WAKEUP)
9727                         wake_up(&ctx->sq_data->wait);
9728                 if (flags & IORING_ENTER_SQ_WAIT) {
9729                         ret = io_sqpoll_wait_sq(ctx);
9730                         if (ret)
9731                                 goto out;
9732                 }
9733                 ret = to_submit;
9734         } else if (to_submit) {
9735                 ret = io_uring_add_tctx_node(ctx);
9736                 if (unlikely(ret))
9737                         goto out;
9738
9739                 mutex_lock(&ctx->uring_lock);
9740                 ret = io_submit_sqes(ctx, to_submit);
9741                 if (ret != to_submit) {
9742                         mutex_unlock(&ctx->uring_lock);
9743                         goto out;
9744                 }
9745                 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
9746                         goto iopoll_locked;
9747                 mutex_unlock(&ctx->uring_lock);
9748         }
9749         if (flags & IORING_ENTER_GETEVENTS) {
9750                 int ret2;
9751                 if (ctx->syscall_iopoll) {
9752                         /*
9753                          * We disallow the app entering submit/complete with
9754                          * polling, but we still need to lock the ring to
9755                          * prevent racing with polled issue that got punted to
9756                          * a workqueue.
9757                          */
9758                         mutex_lock(&ctx->uring_lock);
9759 iopoll_locked:
9760                         ret2 = io_validate_ext_arg(flags, argp, argsz);
9761                         if (likely(!ret2)) {
9762                                 min_complete = min(min_complete,
9763                                                    ctx->cq_entries);
9764                                 ret2 = io_iopoll_check(ctx, min_complete);
9765                         }
9766                         mutex_unlock(&ctx->uring_lock);
9767                 } else {
9768                         const sigset_t __user *sig;
9769                         struct __kernel_timespec __user *ts;
9770
9771                         ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9772                         if (likely(!ret2)) {
9773                                 min_complete = min(min_complete,
9774                                                    ctx->cq_entries);
9775                                 ret2 = io_cqring_wait(ctx, min_complete, sig,
9776                                                       argsz, ts);
9777                         }
9778                 }
9779
9780                 if (!ret) {
9781                         ret = ret2;
9782
9783                         /*
9784                          * EBADR indicates that one or more CQE were dropped.
9785                          * Once the user has been informed we can clear the bit
9786                          * as they are obviously ok with those drops.
9787                          */
9788                         if (unlikely(ret2 == -EBADR))
9789                                 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
9790                                           &ctx->check_cq);
9791                 }
9792         }
9793
9794 out:
9795         percpu_ref_put(&ctx->refs);
9796 out_fput:
9797         fdput(f);
9798         return ret;
9799 }
9800
9801 #ifdef CONFIG_PROC_FS
9802 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
9803                 const struct cred *cred)
9804 {
9805         struct user_namespace *uns = seq_user_ns(m);
9806         struct group_info *gi;
9807         kernel_cap_t cap;
9808         unsigned __capi;
9809         int g;
9810
9811         seq_printf(m, "%5d\n", id);
9812         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9813         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9814         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9815         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9816         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9817         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9818         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9819         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9820         seq_puts(m, "\n\tGroups:\t");
9821         gi = cred->group_info;
9822         for (g = 0; g < gi->ngroups; g++) {
9823                 seq_put_decimal_ull(m, g ? " " : "",
9824                                         from_kgid_munged(uns, gi->gid[g]));
9825         }
9826         seq_puts(m, "\n\tCapEff:\t");
9827         cap = cred->cap_effective;
9828         CAP_FOR_EACH_U32(__capi)
9829                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9830         seq_putc(m, '\n');
9831         return 0;
9832 }
9833
9834 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
9835                                           struct seq_file *m)
9836 {
9837         struct io_sq_data *sq = NULL;
9838         struct io_overflow_cqe *ocqe;
9839         struct io_rings *r = ctx->rings;
9840         unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
9841         unsigned int sq_head = READ_ONCE(r->sq.head);
9842         unsigned int sq_tail = READ_ONCE(r->sq.tail);
9843         unsigned int cq_head = READ_ONCE(r->cq.head);
9844         unsigned int cq_tail = READ_ONCE(r->cq.tail);
9845         unsigned int cq_shift = 0;
9846         unsigned int sq_entries, cq_entries;
9847         bool has_lock;
9848         bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
9849         unsigned int i;
9850
9851         if (is_cqe32)
9852                 cq_shift = 1;
9853
9854         /*
9855          * we may get imprecise sqe and cqe info if uring is actively running
9856          * since we get cached_sq_head and cached_cq_tail without uring_lock
9857          * and sq_tail and cq_head are changed by userspace. But it's ok since
9858          * we usually use these info when it is stuck.
9859          */
9860         seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
9861         seq_printf(m, "SqHead:\t%u\n", sq_head);
9862         seq_printf(m, "SqTail:\t%u\n", sq_tail);
9863         seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
9864         seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
9865         seq_printf(m, "CqHead:\t%u\n", cq_head);
9866         seq_printf(m, "CqTail:\t%u\n", cq_tail);
9867         seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
9868         seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
9869         sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
9870         for (i = 0; i < sq_entries; i++) {
9871                 unsigned int entry = i + sq_head;
9872                 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
9873                 struct io_uring_sqe *sqe;
9874
9875                 if (sq_idx > sq_mask)
9876                         continue;
9877                 sqe = &ctx->sq_sqes[sq_idx];
9878                 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
9879                            sq_idx, sqe->opcode, sqe->fd, sqe->flags,
9880                            sqe->user_data);
9881         }
9882         seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
9883         cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
9884         for (i = 0; i < cq_entries; i++) {
9885                 unsigned int entry = i + cq_head;
9886                 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
9887
9888                 if (!is_cqe32) {
9889                         seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
9890                            entry & cq_mask, cqe->user_data, cqe->res,
9891                            cqe->flags);
9892                 } else {
9893                         seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
9894                                 "extra1:%llu, extra2:%llu\n",
9895                                 entry & cq_mask, cqe->user_data, cqe->res,
9896                                 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
9897                 }
9898         }
9899
9900         /*
9901          * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9902          * since fdinfo case grabs it in the opposite direction of normal use
9903          * cases. If we fail to get the lock, we just don't iterate any
9904          * structures that could be going away outside the io_uring mutex.
9905          */
9906         has_lock = mutex_trylock(&ctx->uring_lock);
9907
9908         if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9909                 sq = ctx->sq_data;
9910                 if (!sq->thread)
9911                         sq = NULL;
9912         }
9913
9914         seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9915         seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9916         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9917         for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9918                 struct file *f = io_file_from_index(ctx, i);
9919
9920                 if (f)
9921                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9922                 else
9923                         seq_printf(m, "%5u: <none>\n", i);
9924         }
9925         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9926         for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9927                 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9928                 unsigned int len = buf->ubuf_end - buf->ubuf;
9929
9930                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9931         }
9932         if (has_lock && !xa_empty(&ctx->personalities)) {
9933                 unsigned long index;
9934                 const struct cred *cred;
9935
9936                 seq_printf(m, "Personalities:\n");
9937                 xa_for_each(&ctx->personalities, index, cred)
9938                         io_uring_show_cred(m, index, cred);
9939         }
9940         if (has_lock)
9941                 mutex_unlock(&ctx->uring_lock);
9942
9943         seq_puts(m, "PollList:\n");
9944         spin_lock(&ctx->completion_lock);
9945         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9946                 struct hlist_head *list = &ctx->cancel_hash[i];
9947                 struct io_kiocb *req;
9948
9949                 hlist_for_each_entry(req, list, hash_node)
9950                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
9951                                         task_work_pending(req->task));
9952         }
9953
9954         seq_puts(m, "CqOverflowList:\n");
9955         list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
9956                 struct io_uring_cqe *cqe = &ocqe->cqe;
9957
9958                 seq_printf(m, "  user_data=%llu, res=%d, flags=%x\n",
9959                            cqe->user_data, cqe->res, cqe->flags);
9960
9961         }
9962
9963         spin_unlock(&ctx->completion_lock);
9964 }
9965
9966 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9967 {
9968         struct io_ring_ctx *ctx = f->private_data;
9969
9970         if (percpu_ref_tryget(&ctx->refs)) {
9971                 __io_uring_show_fdinfo(ctx, m);
9972                 percpu_ref_put(&ctx->refs);
9973         }
9974 }
9975 #endif
9976
9977 static const struct file_operations io_uring_fops = {
9978         .release        = io_uring_release,
9979         .mmap           = io_uring_mmap,
9980 #ifndef CONFIG_MMU
9981         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9982         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9983 #endif
9984         .poll           = io_uring_poll,
9985 #ifdef CONFIG_PROC_FS
9986         .show_fdinfo    = io_uring_show_fdinfo,
9987 #endif
9988 };
9989
9990 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9991                                          struct io_uring_params *p)
9992 {
9993         struct io_rings *rings;
9994         size_t size, sq_array_offset;
9995
9996         /* make sure these are sane, as we already accounted them */
9997         ctx->sq_entries = p->sq_entries;
9998         ctx->cq_entries = p->cq_entries;
9999
10000         size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
10001         if (size == SIZE_MAX)
10002                 return -EOVERFLOW;
10003
10004         rings = io_mem_alloc(size);
10005         if (!rings)
10006                 return -ENOMEM;
10007
10008         ctx->rings = rings;
10009         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10010         rings->sq_ring_mask = p->sq_entries - 1;
10011         rings->cq_ring_mask = p->cq_entries - 1;
10012         rings->sq_ring_entries = p->sq_entries;
10013         rings->cq_ring_entries = p->cq_entries;
10014
10015         if (p->flags & IORING_SETUP_SQE128)
10016                 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
10017         else
10018                 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10019         if (size == SIZE_MAX) {
10020                 io_mem_free(ctx->rings);
10021                 ctx->rings = NULL;
10022                 return -EOVERFLOW;
10023         }
10024
10025         ctx->sq_sqes = io_mem_alloc(size);
10026         if (!ctx->sq_sqes) {
10027                 io_mem_free(ctx->rings);
10028                 ctx->rings = NULL;
10029                 return -ENOMEM;
10030         }
10031
10032         return 0;
10033 }
10034
10035 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10036 {
10037         int ret, fd;
10038
10039         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10040         if (fd < 0)
10041                 return fd;
10042
10043         ret = io_uring_add_tctx_node(ctx);
10044         if (ret) {
10045                 put_unused_fd(fd);
10046                 return ret;
10047         }
10048         fd_install(fd, file);
10049         return fd;
10050 }
10051
10052 /*
10053  * Allocate an anonymous fd, this is what constitutes the application
10054  * visible backing of an io_uring instance. The application mmaps this
10055  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10056  * we have to tie this fd to a socket for file garbage collection purposes.
10057  */
10058 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10059 {
10060         struct file *file;
10061 #if defined(CONFIG_UNIX)
10062         int ret;
10063
10064         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10065                                 &ctx->ring_sock);
10066         if (ret)
10067                 return ERR_PTR(ret);
10068 #endif
10069
10070         file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10071                                          O_RDWR | O_CLOEXEC, NULL);
10072 #if defined(CONFIG_UNIX)
10073         if (IS_ERR(file)) {
10074                 sock_release(ctx->ring_sock);
10075                 ctx->ring_sock = NULL;
10076         } else {
10077                 ctx->ring_sock->file = file;
10078         }
10079 #endif
10080         return file;
10081 }
10082
10083 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10084                                   struct io_uring_params __user *params)
10085 {
10086         struct io_ring_ctx *ctx;
10087         struct file *file;
10088         int ret;
10089
10090         if (!entries)
10091                 return -EINVAL;
10092         if (entries > IORING_MAX_ENTRIES) {
10093                 if (!(p->flags & IORING_SETUP_CLAMP))
10094                         return -EINVAL;
10095                 entries = IORING_MAX_ENTRIES;
10096         }
10097
10098         /*
10099          * Use twice as many entries for the CQ ring. It's possible for the
10100          * application to drive a higher depth than the size of the SQ ring,
10101          * since the sqes are only used at submission time. This allows for
10102          * some flexibility in overcommitting a bit. If the application has
10103          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10104          * of CQ ring entries manually.
10105          */
10106         p->sq_entries = roundup_pow_of_two(entries);
10107         if (p->flags & IORING_SETUP_CQSIZE) {
10108                 /*
10109                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
10110                  * to a power-of-two, if it isn't already. We do NOT impose
10111                  * any cq vs sq ring sizing.
10112                  */
10113                 if (!p->cq_entries)
10114                         return -EINVAL;
10115                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10116                         if (!(p->flags & IORING_SETUP_CLAMP))
10117                                 return -EINVAL;
10118                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
10119                 }
10120                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10121                 if (p->cq_entries < p->sq_entries)
10122                         return -EINVAL;
10123         } else {
10124                 p->cq_entries = 2 * p->sq_entries;
10125         }
10126
10127         ctx = io_ring_ctx_alloc(p);
10128         if (!ctx)
10129                 return -ENOMEM;
10130
10131         /*
10132          * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10133          * space applications don't need to do io completion events
10134          * polling again, they can rely on io_sq_thread to do polling
10135          * work, which can reduce cpu usage and uring_lock contention.
10136          */
10137         if (ctx->flags & IORING_SETUP_IOPOLL &&
10138             !(ctx->flags & IORING_SETUP_SQPOLL))
10139                 ctx->syscall_iopoll = 1;
10140
10141         ctx->compat = in_compat_syscall();
10142         if (!capable(CAP_IPC_LOCK))
10143                 ctx->user = get_uid(current_user());
10144
10145         /*
10146          * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
10147          * COOP_TASKRUN is set, then IPIs are never needed by the app.
10148          */
10149         ret = -EINVAL;
10150         if (ctx->flags & IORING_SETUP_SQPOLL) {
10151                 /* IPI related flags don't make sense with SQPOLL */
10152                 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
10153                                   IORING_SETUP_TASKRUN_FLAG))
10154                         goto err;
10155                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
10156         } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
10157                 ctx->notify_method = TWA_SIGNAL_NO_IPI;
10158         } else {
10159                 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
10160                         goto err;
10161                 ctx->notify_method = TWA_SIGNAL;
10162         }
10163
10164         /*
10165          * This is just grabbed for accounting purposes. When a process exits,
10166          * the mm is exited and dropped before the files, hence we need to hang
10167          * on to this mm purely for the purposes of being able to unaccount
10168          * memory (locked/pinned vm). It's not used for anything else.
10169          */
10170         mmgrab(current->mm);
10171         ctx->mm_account = current->mm;
10172
10173         ret = io_allocate_scq_urings(ctx, p);
10174         if (ret)
10175                 goto err;
10176
10177         ret = io_sq_offload_create(ctx, p);
10178         if (ret)
10179                 goto err;
10180         /* always set a rsrc node */
10181         ret = io_rsrc_node_switch_start(ctx);
10182         if (ret)
10183                 goto err;
10184         io_rsrc_node_switch(ctx, NULL);
10185
10186         memset(&p->sq_off, 0, sizeof(p->sq_off));
10187         p->sq_off.head = offsetof(struct io_rings, sq.head);
10188         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10189         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10190         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10191         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10192         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10193         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10194
10195         memset(&p->cq_off, 0, sizeof(p->cq_off));
10196         p->cq_off.head = offsetof(struct io_rings, cq.head);
10197         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10198         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10199         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10200         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10201         p->cq_off.cqes = offsetof(struct io_rings, cqes);
10202         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10203
10204         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10205                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10206                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10207                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10208                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10209                         IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
10210                         IORING_FEAT_LINKED_FILE;
10211
10212         if (copy_to_user(params, p, sizeof(*p))) {
10213                 ret = -EFAULT;
10214                 goto err;
10215         }
10216
10217         file = io_uring_get_file(ctx);
10218         if (IS_ERR(file)) {
10219                 ret = PTR_ERR(file);
10220                 goto err;
10221         }
10222
10223         /*
10224          * Install ring fd as the very last thing, so we don't risk someone
10225          * having closed it before we finish setup
10226          */
10227         ret = io_uring_install_fd(ctx, file);
10228         if (ret < 0) {
10229                 /* fput will clean it up */
10230                 fput(file);
10231                 return ret;
10232         }
10233
10234         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10235         return ret;
10236 err:
10237         io_ring_ctx_wait_and_kill(ctx);
10238         return ret;
10239 }
10240
10241 /*
10242  * Sets up an aio uring context, and returns the fd. Applications asks for a
10243  * ring size, we return the actual sq/cq ring sizes (among other things) in the
10244  * params structure passed in.
10245  */
10246 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10247 {
10248         struct io_uring_params p;
10249         int i;
10250
10251         if (copy_from_user(&p, params, sizeof(p)))
10252                 return -EFAULT;
10253         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10254                 if (p.resv[i])
10255                         return -EINVAL;
10256         }
10257
10258         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10259                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10260                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10261                         IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
10262                         IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
10263                         IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
10264                 return -EINVAL;
10265
10266         return io_uring_create(entries, &p, params);
10267 }
10268
10269 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10270                 struct io_uring_params __user *, params)
10271 {
10272         return io_uring_setup(entries, params);
10273 }
10274
10275 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10276                            unsigned nr_args)
10277 {
10278         struct io_uring_probe *p;
10279         size_t size;
10280         int i, ret;
10281
10282         size = struct_size(p, ops, nr_args);
10283         if (size == SIZE_MAX)
10284                 return -EOVERFLOW;
10285         p = kzalloc(size, GFP_KERNEL);
10286         if (!p)
10287                 return -ENOMEM;
10288
10289         ret = -EFAULT;
10290         if (copy_from_user(p, arg, size))
10291                 goto out;
10292         ret = -EINVAL;
10293         if (memchr_inv(p, 0, size))
10294                 goto out;
10295
10296         p->last_op = IORING_OP_LAST - 1;
10297         if (nr_args > IORING_OP_LAST)
10298                 nr_args = IORING_OP_LAST;
10299
10300         for (i = 0; i < nr_args; i++) {
10301                 p->ops[i].op = i;
10302                 if (!io_op_defs[i].not_supported)
10303                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
10304         }
10305         p->ops_len = i;
10306
10307         ret = 0;
10308         if (copy_to_user(arg, p, size))
10309                 ret = -EFAULT;
10310 out:
10311         kfree(p);
10312         return ret;
10313 }
10314
10315 static int io_register_personality(struct io_ring_ctx *ctx)
10316 {
10317         const struct cred *creds;
10318         u32 id;
10319         int ret;
10320
10321         creds = get_current_cred();
10322
10323         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10324                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10325         if (ret < 0) {
10326                 put_cred(creds);
10327                 return ret;
10328         }
10329         return id;
10330 }
10331
10332 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10333                                            void __user *arg, unsigned int nr_args)
10334 {
10335         struct io_uring_restriction *res;
10336         size_t size;
10337         int i, ret;
10338
10339         /* Restrictions allowed only if rings started disabled */
10340         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10341                 return -EBADFD;
10342
10343         /* We allow only a single restrictions registration */
10344         if (ctx->restrictions.registered)
10345                 return -EBUSY;
10346
10347         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10348                 return -EINVAL;
10349
10350         size = array_size(nr_args, sizeof(*res));
10351         if (size == SIZE_MAX)
10352                 return -EOVERFLOW;
10353
10354         res = memdup_user(arg, size);
10355         if (IS_ERR(res))
10356                 return PTR_ERR(res);
10357
10358         ret = 0;
10359
10360         for (i = 0; i < nr_args; i++) {
10361                 switch (res[i].opcode) {
10362                 case IORING_RESTRICTION_REGISTER_OP:
10363                         if (res[i].register_op >= IORING_REGISTER_LAST) {
10364                                 ret = -EINVAL;
10365                                 goto out;
10366                         }
10367
10368                         __set_bit(res[i].register_op,
10369                                   ctx->restrictions.register_op);
10370                         break;
10371                 case IORING_RESTRICTION_SQE_OP:
10372                         if (res[i].sqe_op >= IORING_OP_LAST) {
10373                                 ret = -EINVAL;
10374                                 goto out;
10375                         }
10376
10377                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10378                         break;
10379                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10380                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10381                         break;
10382                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10383                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10384                         break;
10385                 default:
10386                         ret = -EINVAL;
10387                         goto out;
10388                 }
10389         }
10390
10391 out:
10392         /* Reset all restrictions if an error happened */
10393         if (ret != 0)
10394                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10395         else
10396                 ctx->restrictions.registered = true;
10397
10398         kfree(res);
10399         return ret;
10400 }
10401
10402 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10403 {
10404         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10405                 return -EBADFD;
10406
10407         if (ctx->restrictions.registered)
10408                 ctx->restricted = 1;
10409
10410         ctx->flags &= ~IORING_SETUP_R_DISABLED;
10411         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10412                 wake_up(&ctx->sq_data->wait);
10413         return 0;
10414 }
10415
10416 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10417                                      struct io_uring_rsrc_update2 *up,
10418                                      unsigned nr_args)
10419 {
10420         __u32 tmp;
10421         int err;
10422
10423         if (check_add_overflow(up->offset, nr_args, &tmp))
10424                 return -EOVERFLOW;
10425         err = io_rsrc_node_switch_start(ctx);
10426         if (err)
10427                 return err;
10428
10429         switch (type) {
10430         case IORING_RSRC_FILE:
10431                 return __io_sqe_files_update(ctx, up, nr_args);
10432         case IORING_RSRC_BUFFER:
10433                 return __io_sqe_buffers_update(ctx, up, nr_args);
10434         }
10435         return -EINVAL;
10436 }
10437
10438 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10439                                     unsigned nr_args)
10440 {
10441         struct io_uring_rsrc_update2 up;
10442
10443         if (!nr_args)
10444                 return -EINVAL;
10445         memset(&up, 0, sizeof(up));
10446         if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10447                 return -EFAULT;
10448         if (up.resv || up.resv2)
10449                 return -EINVAL;
10450         return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10451 }
10452
10453 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10454                                    unsigned size, unsigned type)
10455 {
10456         struct io_uring_rsrc_update2 up;
10457
10458         if (size != sizeof(up))
10459                 return -EINVAL;
10460         if (copy_from_user(&up, arg, sizeof(up)))
10461                 return -EFAULT;
10462         if (!up.nr || up.resv || up.resv2)
10463                 return -EINVAL;
10464         return __io_register_rsrc_update(ctx, type, &up, up.nr);
10465 }
10466
10467 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10468                             unsigned int size, unsigned int type)
10469 {
10470         struct io_uring_rsrc_register rr;
10471
10472         /* keep it extendible */
10473         if (size != sizeof(rr))
10474                 return -EINVAL;
10475
10476         memset(&rr, 0, sizeof(rr));
10477         if (copy_from_user(&rr, arg, size))
10478                 return -EFAULT;
10479         if (!rr.nr || rr.resv2)
10480                 return -EINVAL;
10481         if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
10482                 return -EINVAL;
10483
10484         switch (type) {
10485         case IORING_RSRC_FILE:
10486                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
10487                         break;
10488                 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10489                                              rr.nr, u64_to_user_ptr(rr.tags));
10490         case IORING_RSRC_BUFFER:
10491                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
10492                         break;
10493                 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10494                                                rr.nr, u64_to_user_ptr(rr.tags));
10495         }
10496         return -EINVAL;
10497 }
10498
10499 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
10500                                        void __user *arg, unsigned len)
10501 {
10502         struct io_uring_task *tctx = current->io_uring;
10503         cpumask_var_t new_mask;
10504         int ret;
10505
10506         if (!tctx || !tctx->io_wq)
10507                 return -EINVAL;
10508
10509         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10510                 return -ENOMEM;
10511
10512         cpumask_clear(new_mask);
10513         if (len > cpumask_size())
10514                 len = cpumask_size();
10515
10516         if (in_compat_syscall()) {
10517                 ret = compat_get_bitmap(cpumask_bits(new_mask),
10518                                         (const compat_ulong_t __user *)arg,
10519                                         len * 8 /* CHAR_BIT */);
10520         } else {
10521                 ret = copy_from_user(new_mask, arg, len);
10522         }
10523
10524         if (ret) {
10525                 free_cpumask_var(new_mask);
10526                 return -EFAULT;
10527         }
10528
10529         ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10530         free_cpumask_var(new_mask);
10531         return ret;
10532 }
10533
10534 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10535 {
10536         struct io_uring_task *tctx = current->io_uring;
10537
10538         if (!tctx || !tctx->io_wq)
10539                 return -EINVAL;
10540
10541         return io_wq_cpu_affinity(tctx->io_wq, NULL);
10542 }
10543
10544 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10545                                                void __user *arg)
10546         __must_hold(&ctx->uring_lock)
10547 {
10548         struct io_tctx_node *node;
10549         struct io_uring_task *tctx = NULL;
10550         struct io_sq_data *sqd = NULL;
10551         __u32 new_count[2];
10552         int i, ret;
10553
10554         if (copy_from_user(new_count, arg, sizeof(new_count)))
10555                 return -EFAULT;
10556         for (i = 0; i < ARRAY_SIZE(new_count); i++)
10557                 if (new_count[i] > INT_MAX)
10558                         return -EINVAL;
10559
10560         if (ctx->flags & IORING_SETUP_SQPOLL) {
10561                 sqd = ctx->sq_data;
10562                 if (sqd) {
10563                         /*
10564                          * Observe the correct sqd->lock -> ctx->uring_lock
10565                          * ordering. Fine to drop uring_lock here, we hold
10566                          * a ref to the ctx.
10567                          */
10568                         refcount_inc(&sqd->refs);
10569                         mutex_unlock(&ctx->uring_lock);
10570                         mutex_lock(&sqd->lock);
10571                         mutex_lock(&ctx->uring_lock);
10572                         if (sqd->thread)
10573                                 tctx = sqd->thread->io_uring;
10574                 }
10575         } else {
10576                 tctx = current->io_uring;
10577         }
10578
10579         BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10580
10581         for (i = 0; i < ARRAY_SIZE(new_count); i++)
10582                 if (new_count[i])
10583                         ctx->iowq_limits[i] = new_count[i];
10584         ctx->iowq_limits_set = true;
10585
10586         if (tctx && tctx->io_wq) {
10587                 ret = io_wq_max_workers(tctx->io_wq, new_count);
10588                 if (ret)
10589                         goto err;
10590         } else {
10591                 memset(new_count, 0, sizeof(new_count));
10592         }
10593
10594         if (sqd) {
10595                 mutex_unlock(&sqd->lock);
10596                 io_put_sq_data(sqd);
10597         }
10598
10599         if (copy_to_user(arg, new_count, sizeof(new_count)))
10600                 return -EFAULT;
10601
10602         /* that's it for SQPOLL, only the SQPOLL task creates requests */
10603         if (sqd)
10604                 return 0;
10605
10606         /* now propagate the restriction to all registered users */
10607         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10608                 struct io_uring_task *tctx = node->task->io_uring;
10609
10610                 if (WARN_ON_ONCE(!tctx->io_wq))
10611                         continue;
10612
10613                 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10614                         new_count[i] = ctx->iowq_limits[i];
10615                 /* ignore errors, it always returns zero anyway */
10616                 (void)io_wq_max_workers(tctx->io_wq, new_count);
10617         }
10618         return 0;
10619 err:
10620         if (sqd) {
10621                 mutex_unlock(&sqd->lock);
10622                 io_put_sq_data(sqd);
10623         }
10624         return ret;
10625 }
10626
10627 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
10628 {
10629         struct io_uring_buf_ring *br;
10630         struct io_uring_buf_reg reg;
10631         struct io_buffer_list *bl, *free_bl = NULL;
10632         struct page **pages;
10633         int nr_pages;
10634
10635         if (copy_from_user(&reg, arg, sizeof(reg)))
10636                 return -EFAULT;
10637
10638         if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
10639                 return -EINVAL;
10640         if (!reg.ring_addr)
10641                 return -EFAULT;
10642         if (reg.ring_addr & ~PAGE_MASK)
10643                 return -EINVAL;
10644         if (!is_power_of_2(reg.ring_entries))
10645                 return -EINVAL;
10646
10647         /* cannot disambiguate full vs empty due to head/tail size */
10648         if (reg.ring_entries >= 65536)
10649                 return -EINVAL;
10650
10651         if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
10652                 int ret = io_init_bl_list(ctx);
10653                 if (ret)
10654                         return ret;
10655         }
10656
10657         bl = io_buffer_get_list(ctx, reg.bgid);
10658         if (bl) {
10659                 /* if mapped buffer ring OR classic exists, don't allow */
10660                 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
10661                         return -EEXIST;
10662         } else {
10663                 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
10664                 if (!bl)
10665                         return -ENOMEM;
10666         }
10667
10668         pages = io_pin_pages(reg.ring_addr,
10669                              struct_size(br, bufs, reg.ring_entries),
10670                              &nr_pages);
10671         if (IS_ERR(pages)) {
10672                 kfree(free_bl);
10673                 return PTR_ERR(pages);
10674         }
10675
10676         br = page_address(pages[0]);
10677         bl->buf_pages = pages;
10678         bl->buf_nr_pages = nr_pages;
10679         bl->nr_entries = reg.ring_entries;
10680         bl->buf_ring = br;
10681         bl->mask = reg.ring_entries - 1;
10682         io_buffer_add_list(ctx, bl, reg.bgid);
10683         return 0;
10684 }
10685
10686 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
10687 {
10688         struct io_uring_buf_reg reg;
10689         struct io_buffer_list *bl;
10690
10691         if (copy_from_user(&reg, arg, sizeof(reg)))
10692                 return -EFAULT;
10693         if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
10694                 return -EINVAL;
10695
10696         bl = io_buffer_get_list(ctx, reg.bgid);
10697         if (!bl)
10698                 return -ENOENT;
10699         if (!bl->buf_nr_pages)
10700                 return -EINVAL;
10701
10702         __io_remove_buffers(ctx, bl, -1U);
10703         if (bl->bgid >= BGID_ARRAY) {
10704                 xa_erase(&ctx->io_bl_xa, bl->bgid);
10705                 kfree(bl);
10706         }
10707         return 0;
10708 }
10709
10710 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10711                                void __user *arg, unsigned nr_args)
10712         __releases(ctx->uring_lock)
10713         __acquires(ctx->uring_lock)
10714 {
10715         int ret;
10716
10717         /*
10718          * We're inside the ring mutex, if the ref is already dying, then
10719          * someone else killed the ctx or is already going through
10720          * io_uring_register().
10721          */
10722         if (percpu_ref_is_dying(&ctx->refs))
10723                 return -ENXIO;
10724
10725         if (ctx->restricted) {
10726                 if (opcode >= IORING_REGISTER_LAST)
10727                         return -EINVAL;
10728                 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10729                 if (!test_bit(opcode, ctx->restrictions.register_op))
10730                         return -EACCES;
10731         }
10732
10733         switch (opcode) {
10734         case IORING_REGISTER_BUFFERS:
10735                 ret = -EFAULT;
10736                 if (!arg)
10737                         break;
10738                 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10739                 break;
10740         case IORING_UNREGISTER_BUFFERS:
10741                 ret = -EINVAL;
10742                 if (arg || nr_args)
10743                         break;
10744                 ret = io_sqe_buffers_unregister(ctx);
10745                 break;
10746         case IORING_REGISTER_FILES:
10747                 ret = -EFAULT;
10748                 if (!arg)
10749                         break;
10750                 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10751                 break;
10752         case IORING_UNREGISTER_FILES:
10753                 ret = -EINVAL;
10754                 if (arg || nr_args)
10755                         break;
10756                 ret = io_sqe_files_unregister(ctx);
10757                 break;
10758         case IORING_REGISTER_FILES_UPDATE:
10759                 ret = io_register_files_update(ctx, arg, nr_args);
10760                 break;
10761         case IORING_REGISTER_EVENTFD:
10762                 ret = -EINVAL;
10763                 if (nr_args != 1)
10764                         break;
10765                 ret = io_eventfd_register(ctx, arg, 0);
10766                 break;
10767         case IORING_REGISTER_EVENTFD_ASYNC:
10768                 ret = -EINVAL;
10769                 if (nr_args != 1)
10770                         break;
10771                 ret = io_eventfd_register(ctx, arg, 1);
10772                 break;
10773         case IORING_UNREGISTER_EVENTFD:
10774                 ret = -EINVAL;
10775                 if (arg || nr_args)
10776                         break;
10777                 ret = io_eventfd_unregister(ctx);
10778                 break;
10779         case IORING_REGISTER_PROBE:
10780                 ret = -EINVAL;
10781                 if (!arg || nr_args > 256)
10782                         break;
10783                 ret = io_probe(ctx, arg, nr_args);
10784                 break;
10785         case IORING_REGISTER_PERSONALITY:
10786                 ret = -EINVAL;
10787                 if (arg || nr_args)
10788                         break;
10789                 ret = io_register_personality(ctx);
10790                 break;
10791         case IORING_UNREGISTER_PERSONALITY:
10792                 ret = -EINVAL;
10793                 if (arg)
10794                         break;
10795                 ret = io_unregister_personality(ctx, nr_args);
10796                 break;
10797         case IORING_REGISTER_ENABLE_RINGS:
10798                 ret = -EINVAL;
10799                 if (arg || nr_args)
10800                         break;
10801                 ret = io_register_enable_rings(ctx);
10802                 break;
10803         case IORING_REGISTER_RESTRICTIONS:
10804                 ret = io_register_restrictions(ctx, arg, nr_args);
10805                 break;
10806         case IORING_REGISTER_FILES2:
10807                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10808                 break;
10809         case IORING_REGISTER_FILES_UPDATE2:
10810                 ret = io_register_rsrc_update(ctx, arg, nr_args,
10811                                               IORING_RSRC_FILE);
10812                 break;
10813         case IORING_REGISTER_BUFFERS2:
10814                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10815                 break;
10816         case IORING_REGISTER_BUFFERS_UPDATE:
10817                 ret = io_register_rsrc_update(ctx, arg, nr_args,
10818                                               IORING_RSRC_BUFFER);
10819                 break;
10820         case IORING_REGISTER_IOWQ_AFF:
10821                 ret = -EINVAL;
10822                 if (!arg || !nr_args)
10823                         break;
10824                 ret = io_register_iowq_aff(ctx, arg, nr_args);
10825                 break;
10826         case IORING_UNREGISTER_IOWQ_AFF:
10827                 ret = -EINVAL;
10828                 if (arg || nr_args)
10829                         break;
10830                 ret = io_unregister_iowq_aff(ctx);
10831                 break;
10832         case IORING_REGISTER_IOWQ_MAX_WORKERS:
10833                 ret = -EINVAL;
10834                 if (!arg || nr_args != 2)
10835                         break;
10836                 ret = io_register_iowq_max_workers(ctx, arg);
10837                 break;
10838         case IORING_REGISTER_RING_FDS:
10839                 ret = io_ringfd_register(ctx, arg, nr_args);
10840                 break;
10841         case IORING_UNREGISTER_RING_FDS:
10842                 ret = io_ringfd_unregister(ctx, arg, nr_args);
10843                 break;
10844         case IORING_REGISTER_PBUF_RING:
10845                 ret = -EINVAL;
10846                 if (!arg || nr_args != 1)
10847                         break;
10848                 ret = io_register_pbuf_ring(ctx, arg);
10849                 break;
10850         case IORING_UNREGISTER_PBUF_RING:
10851                 ret = -EINVAL;
10852                 if (!arg || nr_args != 1)
10853                         break;
10854                 ret = io_unregister_pbuf_ring(ctx, arg);
10855                 break;
10856         default:
10857                 ret = -EINVAL;
10858                 break;
10859         }
10860
10861         return ret;
10862 }
10863
10864 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10865                 void __user *, arg, unsigned int, nr_args)
10866 {
10867         struct io_ring_ctx *ctx;
10868         long ret = -EBADF;
10869         struct fd f;
10870
10871         f = fdget(fd);
10872         if (!f.file)
10873                 return -EBADF;
10874
10875         ret = -EOPNOTSUPP;
10876         if (f.file->f_op != &io_uring_fops)
10877                 goto out_fput;
10878
10879         ctx = f.file->private_data;
10880
10881         io_run_task_work();
10882
10883         mutex_lock(&ctx->uring_lock);
10884         ret = __io_uring_register(ctx, opcode, arg, nr_args);
10885         mutex_unlock(&ctx->uring_lock);
10886         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
10887 out_fput:
10888         fdput(f);
10889         return ret;
10890 }
10891
10892 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
10893 {
10894         WARN_ON_ONCE(1);
10895         return -ECANCELED;
10896 }
10897
10898 static const struct io_op_def io_op_defs[] = {
10899         [IORING_OP_NOP] = {
10900                 .audit_skip             = 1,
10901                 .iopoll                 = 1,
10902                 .prep                   = io_nop_prep,
10903                 .issue                  = io_nop,
10904         },
10905         [IORING_OP_READV] = {
10906                 .needs_file             = 1,
10907                 .unbound_nonreg_file    = 1,
10908                 .pollin                 = 1,
10909                 .buffer_select          = 1,
10910                 .plug                   = 1,
10911                 .audit_skip             = 1,
10912                 .ioprio                 = 1,
10913                 .iopoll                 = 1,
10914                 .async_size             = sizeof(struct io_async_rw),
10915                 .prep                   = io_prep_rw,
10916                 .issue                  = io_read,
10917                 .prep_async             = io_readv_prep_async,
10918                 .cleanup                = io_readv_writev_cleanup,
10919         },
10920         [IORING_OP_WRITEV] = {
10921                 .needs_file             = 1,
10922                 .hash_reg_file          = 1,
10923                 .unbound_nonreg_file    = 1,
10924                 .pollout                = 1,
10925                 .plug                   = 1,
10926                 .audit_skip             = 1,
10927                 .ioprio                 = 1,
10928                 .iopoll                 = 1,
10929                 .async_size             = sizeof(struct io_async_rw),
10930                 .prep                   = io_prep_rw,
10931                 .issue                  = io_write,
10932                 .prep_async             = io_writev_prep_async,
10933                 .cleanup                = io_readv_writev_cleanup,
10934         },
10935         [IORING_OP_FSYNC] = {
10936                 .needs_file             = 1,
10937                 .audit_skip             = 1,
10938                 .prep                   = io_fsync_prep,
10939                 .issue                  = io_fsync,
10940         },
10941         [IORING_OP_READ_FIXED] = {
10942                 .needs_file             = 1,
10943                 .unbound_nonreg_file    = 1,
10944                 .pollin                 = 1,
10945                 .plug                   = 1,
10946                 .audit_skip             = 1,
10947                 .ioprio                 = 1,
10948                 .iopoll                 = 1,
10949                 .async_size             = sizeof(struct io_async_rw),
10950                 .prep                   = io_prep_rw,
10951                 .issue                  = io_read,
10952         },
10953         [IORING_OP_WRITE_FIXED] = {
10954                 .needs_file             = 1,
10955                 .hash_reg_file          = 1,
10956                 .unbound_nonreg_file    = 1,
10957                 .pollout                = 1,
10958                 .plug                   = 1,
10959                 .audit_skip             = 1,
10960                 .ioprio                 = 1,
10961                 .iopoll                 = 1,
10962                 .async_size             = sizeof(struct io_async_rw),
10963                 .prep                   = io_prep_rw,
10964                 .issue                  = io_write,
10965         },
10966         [IORING_OP_POLL_ADD] = {
10967                 .needs_file             = 1,
10968                 .unbound_nonreg_file    = 1,
10969                 .audit_skip             = 1,
10970                 .prep                   = io_poll_add_prep,
10971                 .issue                  = io_poll_add,
10972         },
10973         [IORING_OP_POLL_REMOVE] = {
10974                 .audit_skip             = 1,
10975                 .prep                   = io_poll_remove_prep,
10976                 .issue                  = io_poll_remove,
10977         },
10978         [IORING_OP_SYNC_FILE_RANGE] = {
10979                 .needs_file             = 1,
10980                 .audit_skip             = 1,
10981                 .prep                   = io_sfr_prep,
10982                 .issue                  = io_sync_file_range,
10983         },
10984         [IORING_OP_SENDMSG] = {
10985                 .needs_file             = 1,
10986                 .unbound_nonreg_file    = 1,
10987                 .pollout                = 1,
10988                 .ioprio                 = 1,
10989                 .async_size             = sizeof(struct io_async_msghdr),
10990                 .prep                   = io_sendmsg_prep,
10991                 .issue                  = io_sendmsg,
10992                 .prep_async             = io_sendmsg_prep_async,
10993 #if defined(CONFIG_NET)
10994                 .cleanup                = io_sendmsg_recvmsg_cleanup,
10995 #endif
10996         },
10997         [IORING_OP_RECVMSG] = {
10998                 .needs_file             = 1,
10999                 .unbound_nonreg_file    = 1,
11000                 .pollin                 = 1,
11001                 .buffer_select          = 1,
11002                 .ioprio                 = 1,
11003                 .async_size             = sizeof(struct io_async_msghdr),
11004                 .prep                   = io_recvmsg_prep,
11005                 .issue                  = io_recvmsg,
11006                 .prep_async             = io_recvmsg_prep_async,
11007 #if defined(CONFIG_NET)
11008                 .cleanup                = io_sendmsg_recvmsg_cleanup,
11009 #endif
11010         },
11011         [IORING_OP_TIMEOUT] = {
11012                 .audit_skip             = 1,
11013                 .async_size             = sizeof(struct io_timeout_data),
11014                 .prep                   = io_timeout_prep,
11015                 .issue                  = io_timeout,
11016         },
11017         [IORING_OP_TIMEOUT_REMOVE] = {
11018                 /* used by timeout updates' prep() */
11019                 .audit_skip             = 1,
11020                 .prep                   = io_timeout_remove_prep,
11021                 .issue                  = io_timeout_remove,
11022         },
11023         [IORING_OP_ACCEPT] = {
11024                 .needs_file             = 1,
11025                 .unbound_nonreg_file    = 1,
11026                 .pollin                 = 1,
11027                 .poll_exclusive         = 1,
11028                 .ioprio                 = 1,    /* used for flags */
11029                 .prep                   = io_accept_prep,
11030                 .issue                  = io_accept,
11031         },
11032         [IORING_OP_ASYNC_CANCEL] = {
11033                 .audit_skip             = 1,
11034                 .prep                   = io_async_cancel_prep,
11035                 .issue                  = io_async_cancel,
11036         },
11037         [IORING_OP_LINK_TIMEOUT] = {
11038                 .audit_skip             = 1,
11039                 .async_size             = sizeof(struct io_timeout_data),
11040                 .prep                   = io_link_timeout_prep,
11041                 .issue                  = io_no_issue,
11042         },
11043         [IORING_OP_CONNECT] = {
11044                 .needs_file             = 1,
11045                 .unbound_nonreg_file    = 1,
11046                 .pollout                = 1,
11047                 .async_size             = sizeof(struct io_async_connect),
11048                 .prep                   = io_connect_prep,
11049                 .issue                  = io_connect,
11050                 .prep_async             = io_connect_prep_async,
11051         },
11052         [IORING_OP_FALLOCATE] = {
11053                 .needs_file             = 1,
11054                 .prep                   = io_fallocate_prep,
11055                 .issue                  = io_fallocate,
11056         },
11057         [IORING_OP_OPENAT] = {
11058                 .prep                   = io_openat_prep,
11059                 .issue                  = io_openat,
11060                 .cleanup                = io_open_cleanup,
11061         },
11062         [IORING_OP_CLOSE] = {
11063                 .prep                   = io_close_prep,
11064                 .issue                  = io_close,
11065         },
11066         [IORING_OP_FILES_UPDATE] = {
11067                 .audit_skip             = 1,
11068                 .iopoll                 = 1,
11069                 .prep                   = io_files_update_prep,
11070                 .issue                  = io_files_update,
11071         },
11072         [IORING_OP_STATX] = {
11073                 .audit_skip             = 1,
11074                 .prep                   = io_statx_prep,
11075                 .issue                  = io_statx,
11076                 .cleanup                = io_statx_cleanup,
11077         },
11078         [IORING_OP_READ] = {
11079                 .needs_file             = 1,
11080                 .unbound_nonreg_file    = 1,
11081                 .pollin                 = 1,
11082                 .buffer_select          = 1,
11083                 .plug                   = 1,
11084                 .audit_skip             = 1,
11085                 .ioprio                 = 1,
11086                 .iopoll                 = 1,
11087                 .async_size             = sizeof(struct io_async_rw),
11088                 .prep                   = io_prep_rw,
11089                 .issue                  = io_read,
11090         },
11091         [IORING_OP_WRITE] = {
11092                 .needs_file             = 1,
11093                 .hash_reg_file          = 1,
11094                 .unbound_nonreg_file    = 1,
11095                 .pollout                = 1,
11096                 .plug                   = 1,
11097                 .audit_skip             = 1,
11098                 .ioprio                 = 1,
11099                 .iopoll                 = 1,
11100                 .async_size             = sizeof(struct io_async_rw),
11101                 .prep                   = io_prep_rw,
11102                 .issue                  = io_write,
11103         },
11104         [IORING_OP_FADVISE] = {
11105                 .needs_file             = 1,
11106                 .audit_skip             = 1,
11107                 .prep                   = io_fadvise_prep,
11108                 .issue                  = io_fadvise,
11109         },
11110         [IORING_OP_MADVISE] = {
11111                 .prep                   = io_madvise_prep,
11112                 .issue                  = io_madvise,
11113         },
11114         [IORING_OP_SEND] = {
11115                 .needs_file             = 1,
11116                 .unbound_nonreg_file    = 1,
11117                 .pollout                = 1,
11118                 .audit_skip             = 1,
11119                 .ioprio                 = 1,
11120                 .prep                   = io_sendmsg_prep,
11121                 .issue                  = io_send,
11122         },
11123         [IORING_OP_RECV] = {
11124                 .needs_file             = 1,
11125                 .unbound_nonreg_file    = 1,
11126                 .pollin                 = 1,
11127                 .buffer_select          = 1,
11128                 .audit_skip             = 1,
11129                 .ioprio                 = 1,
11130                 .prep                   = io_recvmsg_prep,
11131                 .issue                  = io_recv,
11132         },
11133         [IORING_OP_OPENAT2] = {
11134                 .prep                   = io_openat2_prep,
11135                 .issue                  = io_openat2,
11136                 .cleanup                = io_open_cleanup,
11137         },
11138         [IORING_OP_EPOLL_CTL] = {
11139                 .unbound_nonreg_file    = 1,
11140                 .audit_skip             = 1,
11141 #if defined(CONFIG_EPOLL)
11142                 .prep                   = io_epoll_ctl_prep,
11143                 .issue                  = io_epoll_ctl,
11144 #else
11145                 .prep                   = io_eopnotsupp_prep,
11146 #endif
11147         },
11148         [IORING_OP_SPLICE] = {
11149                 .needs_file             = 1,
11150                 .hash_reg_file          = 1,
11151                 .unbound_nonreg_file    = 1,
11152                 .audit_skip             = 1,
11153                 .prep                   = io_splice_prep,
11154                 .issue                  = io_splice,
11155         },
11156         [IORING_OP_PROVIDE_BUFFERS] = {
11157                 .audit_skip             = 1,
11158                 .iopoll                 = 1,
11159                 .prep                   = io_provide_buffers_prep,
11160                 .issue                  = io_provide_buffers,
11161         },
11162         [IORING_OP_REMOVE_BUFFERS] = {
11163                 .audit_skip             = 1,
11164                 .iopoll                 = 1,
11165                 .prep                   = io_remove_buffers_prep,
11166                 .issue                  = io_remove_buffers,
11167         },
11168         [IORING_OP_TEE] = {
11169                 .needs_file             = 1,
11170                 .hash_reg_file          = 1,
11171                 .unbound_nonreg_file    = 1,
11172                 .audit_skip             = 1,
11173                 .prep                   = io_tee_prep,
11174                 .issue                  = io_tee,
11175         },
11176         [IORING_OP_SHUTDOWN] = {
11177                 .needs_file             = 1,
11178                 .prep                   = io_shutdown_prep,
11179                 .issue                  = io_shutdown,
11180         },
11181         [IORING_OP_RENAMEAT] = {
11182                 .prep                   = io_renameat_prep,
11183                 .issue                  = io_renameat,
11184                 .cleanup                = io_renameat_cleanup,
11185         },
11186         [IORING_OP_UNLINKAT] = {
11187                 .prep                   = io_unlinkat_prep,
11188                 .issue                  = io_unlinkat,
11189                 .cleanup                = io_unlinkat_cleanup,
11190         },
11191         [IORING_OP_MKDIRAT] = {
11192                 .prep                   = io_mkdirat_prep,
11193                 .issue                  = io_mkdirat,
11194                 .cleanup                = io_mkdirat_cleanup,
11195         },
11196         [IORING_OP_SYMLINKAT] = {
11197                 .prep                   = io_symlinkat_prep,
11198                 .issue                  = io_symlinkat,
11199                 .cleanup                = io_link_cleanup,
11200         },
11201         [IORING_OP_LINKAT] = {
11202                 .prep                   = io_linkat_prep,
11203                 .issue                  = io_linkat,
11204                 .cleanup                = io_link_cleanup,
11205         },
11206         [IORING_OP_MSG_RING] = {
11207                 .needs_file             = 1,
11208                 .iopoll                 = 1,
11209                 .prep                   = io_msg_ring_prep,
11210                 .issue                  = io_msg_ring,
11211         },
11212         [IORING_OP_FSETXATTR] = {
11213                 .needs_file = 1,
11214                 .prep                   = io_fsetxattr_prep,
11215                 .issue                  = io_fsetxattr,
11216                 .cleanup                = io_xattr_cleanup,
11217         },
11218         [IORING_OP_SETXATTR] = {
11219                 .prep                   = io_setxattr_prep,
11220                 .issue                  = io_setxattr,
11221                 .cleanup                = io_xattr_cleanup,
11222         },
11223         [IORING_OP_FGETXATTR] = {
11224                 .needs_file = 1,
11225                 .prep                   = io_fgetxattr_prep,
11226                 .issue                  = io_fgetxattr,
11227                 .cleanup                = io_xattr_cleanup,
11228         },
11229         [IORING_OP_GETXATTR] = {
11230                 .prep                   = io_getxattr_prep,
11231                 .issue                  = io_getxattr,
11232                 .cleanup                = io_xattr_cleanup,
11233         },
11234         [IORING_OP_SOCKET] = {
11235                 .audit_skip             = 1,
11236                 .prep                   = io_socket_prep,
11237                 .issue                  = io_socket,
11238         },
11239         [IORING_OP_URING_CMD] = {
11240                 .needs_file             = 1,
11241                 .plug                   = 1,
11242                 .async_size             = uring_cmd_pdu_size(1),
11243                 .prep                   = io_uring_cmd_prep,
11244                 .issue                  = io_uring_cmd,
11245                 .prep_async             = io_uring_cmd_prep_async,
11246         },
11247 };
11248
11249 static int __init io_uring_init(void)
11250 {
11251         int i;
11252
11253 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11254         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11255         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11256 } while (0)
11257
11258 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11259         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11260         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11261         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
11262         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
11263         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
11264         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
11265         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
11266         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
11267         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
11268         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
11269         BUILD_BUG_SQE_ELEM(24, __u32,  len);
11270         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
11271         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
11272         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11273         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
11274         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
11275         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
11276         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
11277         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
11278         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
11279         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
11280         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
11281         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
11282         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
11283         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
11284         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
11285         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
11286         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
11287         BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
11288         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
11289         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
11290         BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
11291         BUILD_BUG_SQE_ELEM(48, __u64,  addr3);
11292
11293         BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11294                      sizeof(struct io_uring_rsrc_update));
11295         BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11296                      sizeof(struct io_uring_rsrc_update2));
11297
11298         /* ->buf_index is u16 */
11299         BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11300         BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
11301         BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
11302         BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
11303                      offsetof(struct io_uring_buf_ring, tail));
11304
11305         /* should fit into one byte */
11306         BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11307         BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11308         BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11309
11310         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11311         BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11312
11313         BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
11314
11315         for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
11316                 BUG_ON(!io_op_defs[i].prep);
11317                 if (io_op_defs[i].prep != io_eopnotsupp_prep)
11318                         BUG_ON(!io_op_defs[i].issue);
11319         }
11320
11321         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11322                                 SLAB_ACCOUNT);
11323         return 0;
11324 };
11325 __initcall(io_uring_init);