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