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