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