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