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