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