GNU Linux-libre 5.15.131-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         } while (!ret && nr_events < min && !need_resched());
2672 out:
2673         mutex_unlock(&ctx->uring_lock);
2674         return ret;
2675 }
2676
2677 static void kiocb_end_write(struct io_kiocb *req)
2678 {
2679         /*
2680          * Tell lockdep we inherited freeze protection from submission
2681          * thread.
2682          */
2683         if (req->flags & REQ_F_ISREG) {
2684                 struct super_block *sb = file_inode(req->file)->i_sb;
2685
2686                 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2687                 sb_end_write(sb);
2688         }
2689 }
2690
2691 #ifdef CONFIG_BLOCK
2692 static bool io_resubmit_prep(struct io_kiocb *req)
2693 {
2694         struct io_async_rw *rw = req->async_data;
2695
2696         if (!rw)
2697                 return !io_req_prep_async(req);
2698         iov_iter_restore(&rw->iter, &rw->iter_state);
2699         return true;
2700 }
2701
2702 static bool io_rw_should_reissue(struct io_kiocb *req)
2703 {
2704         umode_t mode = file_inode(req->file)->i_mode;
2705         struct io_ring_ctx *ctx = req->ctx;
2706
2707         if (!S_ISBLK(mode) && !S_ISREG(mode))
2708                 return false;
2709         if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2710             !(ctx->flags & IORING_SETUP_IOPOLL)))
2711                 return false;
2712         /*
2713          * If ref is dying, we might be running poll reap from the exit work.
2714          * Don't attempt to reissue from that path, just let it fail with
2715          * -EAGAIN.
2716          */
2717         if (percpu_ref_is_dying(&ctx->refs))
2718                 return false;
2719         /*
2720          * Play it safe and assume not safe to re-import and reissue if we're
2721          * not in the original thread group (or in task context).
2722          */
2723         if (!same_thread_group(req->task, current) || !in_task())
2724                 return false;
2725         return true;
2726 }
2727 #else
2728 static bool io_resubmit_prep(struct io_kiocb *req)
2729 {
2730         return false;
2731 }
2732 static bool io_rw_should_reissue(struct io_kiocb *req)
2733 {
2734         return false;
2735 }
2736 #endif
2737
2738 /*
2739  * Trigger the notifications after having done some IO, and finish the write
2740  * accounting, if any.
2741  */
2742 static void io_req_io_end(struct io_kiocb *req)
2743 {
2744         struct io_rw *rw = &req->rw;
2745
2746         if (rw->kiocb.ki_flags & IOCB_WRITE) {
2747                 kiocb_end_write(req);
2748                 fsnotify_modify(req->file);
2749         } else {
2750                 fsnotify_access(req->file);
2751         }
2752 }
2753
2754 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2755 {
2756         if (res != req->result) {
2757                 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2758                     io_rw_should_reissue(req)) {
2759                         /*
2760                          * Reissue will start accounting again, finish the
2761                          * current cycle.
2762                          */
2763                         io_req_io_end(req);
2764                         req->flags |= REQ_F_REISSUE;
2765                         return true;
2766                 }
2767                 req_set_fail(req);
2768                 req->result = res;
2769         }
2770         return false;
2771 }
2772
2773 static inline int io_fixup_rw_res(struct io_kiocb *req, long res)
2774 {
2775         struct io_async_rw *io = req->async_data;
2776
2777         /* add previously done IO, if any */
2778         if (io && io->bytes_done > 0) {
2779                 if (res < 0)
2780                         res = io->bytes_done;
2781                 else
2782                         res += io->bytes_done;
2783         }
2784         return res;
2785 }
2786
2787 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2788 {
2789         unsigned int cflags = io_put_rw_kbuf(req);
2790         int res = req->result;
2791
2792         if (*locked) {
2793                 struct io_ring_ctx *ctx = req->ctx;
2794                 struct io_submit_state *state = &ctx->submit_state;
2795
2796                 io_req_complete_state(req, res, cflags);
2797                 state->compl_reqs[state->compl_nr++] = req;
2798                 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2799                         io_submit_flush_completions(ctx);
2800         } else {
2801                 io_req_complete_post(req, res, cflags);
2802         }
2803 }
2804
2805 static void io_req_rw_complete(struct io_kiocb *req, bool *locked)
2806 {
2807         io_req_io_end(req);
2808         io_req_task_complete(req, locked);
2809 }
2810
2811 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2812 {
2813         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2814
2815         if (__io_complete_rw_common(req, res))
2816                 return;
2817         req->result = io_fixup_rw_res(req, res);
2818         req->io_task_work.func = io_req_rw_complete;
2819         io_req_task_work_add(req);
2820 }
2821
2822 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2823 {
2824         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2825
2826         if (kiocb->ki_flags & IOCB_WRITE)
2827                 kiocb_end_write(req);
2828         if (unlikely(res != req->result)) {
2829                 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2830                         req->flags |= REQ_F_REISSUE;
2831                         return;
2832                 }
2833         }
2834
2835         WRITE_ONCE(req->result, res);
2836         /* order with io_iopoll_complete() checking ->result */
2837         smp_wmb();
2838         WRITE_ONCE(req->iopoll_completed, 1);
2839 }
2840
2841 /*
2842  * After the iocb has been issued, it's safe to be found on the poll list.
2843  * Adding the kiocb to the list AFTER submission ensures that we don't
2844  * find it from a io_do_iopoll() thread before the issuer is done
2845  * accessing the kiocb cookie.
2846  */
2847 static void io_iopoll_req_issued(struct io_kiocb *req)
2848 {
2849         struct io_ring_ctx *ctx = req->ctx;
2850         const bool in_async = io_wq_current_is_worker();
2851
2852         /* workqueue context doesn't hold uring_lock, grab it now */
2853         if (unlikely(in_async))
2854                 mutex_lock(&ctx->uring_lock);
2855
2856         /*
2857          * Track whether we have multiple files in our lists. This will impact
2858          * how we do polling eventually, not spinning if we're on potentially
2859          * different devices.
2860          */
2861         if (list_empty(&ctx->iopoll_list)) {
2862                 ctx->poll_multi_queue = false;
2863         } else if (!ctx->poll_multi_queue) {
2864                 struct io_kiocb *list_req;
2865                 unsigned int queue_num0, queue_num1;
2866
2867                 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2868                                                 inflight_entry);
2869
2870                 if (list_req->file != req->file) {
2871                         ctx->poll_multi_queue = true;
2872                 } else {
2873                         queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2874                         queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2875                         if (queue_num0 != queue_num1)
2876                                 ctx->poll_multi_queue = true;
2877                 }
2878         }
2879
2880         /*
2881          * For fast devices, IO may have already completed. If it has, add
2882          * it to the front so we find it first.
2883          */
2884         if (READ_ONCE(req->iopoll_completed))
2885                 list_add(&req->inflight_entry, &ctx->iopoll_list);
2886         else
2887                 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2888
2889         if (unlikely(in_async)) {
2890                 /*
2891                  * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2892                  * in sq thread task context or in io worker task context. If
2893                  * current task context is sq thread, we don't need to check
2894                  * whether should wake up sq thread.
2895                  */
2896                 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2897                     wq_has_sleeper(&ctx->sq_data->wait))
2898                         wake_up(&ctx->sq_data->wait);
2899
2900                 mutex_unlock(&ctx->uring_lock);
2901         }
2902 }
2903
2904 static bool io_bdev_nowait(struct block_device *bdev)
2905 {
2906         return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2907 }
2908
2909 /*
2910  * If we tracked the file through the SCM inflight mechanism, we could support
2911  * any file. For now, just ensure that anything potentially problematic is done
2912  * inline.
2913  */
2914 static bool __io_file_supports_nowait(struct file *file, int rw)
2915 {
2916         umode_t mode = file_inode(file)->i_mode;
2917
2918         if (S_ISBLK(mode)) {
2919                 if (IS_ENABLED(CONFIG_BLOCK) &&
2920                     io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2921                         return true;
2922                 return false;
2923         }
2924         if (S_ISSOCK(mode))
2925                 return true;
2926         if (S_ISREG(mode)) {
2927                 if (IS_ENABLED(CONFIG_BLOCK) &&
2928                     io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2929                     file->f_op != &io_uring_fops)
2930                         return true;
2931                 return false;
2932         }
2933
2934         /* any ->read/write should understand O_NONBLOCK */
2935         if (file->f_flags & O_NONBLOCK)
2936                 return true;
2937
2938         if (!(file->f_mode & FMODE_NOWAIT))
2939                 return false;
2940
2941         if (rw == READ)
2942                 return file->f_op->read_iter != NULL;
2943
2944         return file->f_op->write_iter != NULL;
2945 }
2946
2947 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2948 {
2949         if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2950                 return true;
2951         else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2952                 return true;
2953
2954         return __io_file_supports_nowait(req->file, rw);
2955 }
2956
2957 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2958                       int rw)
2959 {
2960         struct io_ring_ctx *ctx = req->ctx;
2961         struct kiocb *kiocb = &req->rw.kiocb;
2962         struct file *file = req->file;
2963         unsigned ioprio;
2964         int ret;
2965
2966         if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2967                 req->flags |= REQ_F_ISREG;
2968
2969         kiocb->ki_pos = READ_ONCE(sqe->off);
2970         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2971         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2972         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2973         if (unlikely(ret))
2974                 return ret;
2975
2976         /*
2977          * If the file is marked O_NONBLOCK, still allow retry for it if it
2978          * supports async. Otherwise it's impossible to use O_NONBLOCK files
2979          * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2980          */
2981         if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2982             ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req, rw)))
2983                 req->flags |= REQ_F_NOWAIT;
2984
2985         ioprio = READ_ONCE(sqe->ioprio);
2986         if (ioprio) {
2987                 ret = ioprio_check_cap(ioprio);
2988                 if (ret)
2989                         return ret;
2990
2991                 kiocb->ki_ioprio = ioprio;
2992         } else
2993                 kiocb->ki_ioprio = get_current_ioprio();
2994
2995         if (ctx->flags & IORING_SETUP_IOPOLL) {
2996                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2997                     !kiocb->ki_filp->f_op->iopoll)
2998                         return -EOPNOTSUPP;
2999
3000                 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3001                 kiocb->ki_complete = io_complete_rw_iopoll;
3002                 req->iopoll_completed = 0;
3003         } else {
3004                 if (kiocb->ki_flags & IOCB_HIPRI)
3005                         return -EINVAL;
3006                 kiocb->ki_complete = io_complete_rw;
3007         }
3008
3009         /* used for fixed read/write too - just read unconditionally */
3010         req->buf_index = READ_ONCE(sqe->buf_index);
3011         req->imu = NULL;
3012
3013         if (req->opcode == IORING_OP_READ_FIXED ||
3014             req->opcode == IORING_OP_WRITE_FIXED) {
3015                 struct io_ring_ctx *ctx = req->ctx;
3016                 u16 index;
3017
3018                 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3019                         return -EFAULT;
3020                 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3021                 req->imu = ctx->user_bufs[index];
3022                 io_req_set_rsrc_node(req);
3023         }
3024
3025         req->rw.addr = READ_ONCE(sqe->addr);
3026         req->rw.len = READ_ONCE(sqe->len);
3027         return 0;
3028 }
3029
3030 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3031 {
3032         switch (ret) {
3033         case -EIOCBQUEUED:
3034                 break;
3035         case -ERESTARTSYS:
3036         case -ERESTARTNOINTR:
3037         case -ERESTARTNOHAND:
3038         case -ERESTART_RESTARTBLOCK:
3039                 /*
3040                  * We can't just restart the syscall, since previously
3041                  * submitted sqes may already be in progress. Just fail this
3042                  * IO with EINTR.
3043                  */
3044                 ret = -EINTR;
3045                 fallthrough;
3046         default:
3047                 kiocb->ki_complete(kiocb, ret, 0);
3048         }
3049 }
3050
3051 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3052 {
3053         struct kiocb *kiocb = &req->rw.kiocb;
3054
3055         if (kiocb->ki_pos != -1)
3056                 return &kiocb->ki_pos;
3057
3058         if (!(req->file->f_mode & FMODE_STREAM)) {
3059                 req->flags |= REQ_F_CUR_POS;
3060                 kiocb->ki_pos = req->file->f_pos;
3061                 return &kiocb->ki_pos;
3062         }
3063
3064         kiocb->ki_pos = 0;
3065         return NULL;
3066 }
3067
3068 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3069                        unsigned int issue_flags)
3070 {
3071         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3072
3073         if (req->flags & REQ_F_CUR_POS)
3074                 req->file->f_pos = kiocb->ki_pos;
3075         if (ret >= 0 && (kiocb->ki_complete == io_complete_rw)) {
3076                 if (!__io_complete_rw_common(req, ret)) {
3077                         /*
3078                          * Safe to call io_end from here as we're inline
3079                          * from the submission path.
3080                          */
3081                         io_req_io_end(req);
3082                         __io_req_complete(req, issue_flags,
3083                                           io_fixup_rw_res(req, ret),
3084                                           io_put_rw_kbuf(req));
3085                 }
3086         } else {
3087                 io_rw_done(kiocb, ret);
3088         }
3089
3090         if (req->flags & REQ_F_REISSUE) {
3091                 req->flags &= ~REQ_F_REISSUE;
3092                 if (io_resubmit_prep(req)) {
3093                         io_req_task_queue_reissue(req);
3094                 } else {
3095                         unsigned int cflags = io_put_rw_kbuf(req);
3096                         struct io_ring_ctx *ctx = req->ctx;
3097
3098                         ret = io_fixup_rw_res(req, ret);
3099                         req_set_fail(req);
3100                         if (!(issue_flags & IO_URING_F_NONBLOCK)) {
3101                                 mutex_lock(&ctx->uring_lock);
3102                                 __io_req_complete(req, issue_flags, ret, cflags);
3103                                 mutex_unlock(&ctx->uring_lock);
3104                         } else {
3105                                 __io_req_complete(req, issue_flags, ret, cflags);
3106                         }
3107                 }
3108         }
3109 }
3110
3111 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3112                              struct io_mapped_ubuf *imu)
3113 {
3114         size_t len = req->rw.len;
3115         u64 buf_end, buf_addr = req->rw.addr;
3116         size_t offset;
3117
3118         if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3119                 return -EFAULT;
3120         /* not inside the mapped region */
3121         if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3122                 return -EFAULT;
3123
3124         /*
3125          * May not be a start of buffer, set size appropriately
3126          * and advance us to the beginning.
3127          */
3128         offset = buf_addr - imu->ubuf;
3129         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3130
3131         if (offset) {
3132                 /*
3133                  * Don't use iov_iter_advance() here, as it's really slow for
3134                  * using the latter parts of a big fixed buffer - it iterates
3135                  * over each segment manually. We can cheat a bit here, because
3136                  * we know that:
3137                  *
3138                  * 1) it's a BVEC iter, we set it up
3139                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
3140                  *    first and last bvec
3141                  *
3142                  * So just find our index, and adjust the iterator afterwards.
3143                  * If the offset is within the first bvec (or the whole first
3144                  * bvec, just use iov_iter_advance(). This makes it easier
3145                  * since we can just skip the first segment, which may not
3146                  * be PAGE_SIZE aligned.
3147                  */
3148                 const struct bio_vec *bvec = imu->bvec;
3149
3150                 if (offset <= bvec->bv_len) {
3151                         iov_iter_advance(iter, offset);
3152                 } else {
3153                         unsigned long seg_skip;
3154
3155                         /* skip first vec */
3156                         offset -= bvec->bv_len;
3157                         seg_skip = 1 + (offset >> PAGE_SHIFT);
3158
3159                         iter->bvec = bvec + seg_skip;
3160                         iter->nr_segs -= seg_skip;
3161                         iter->count -= bvec->bv_len + offset;
3162                         iter->iov_offset = offset & ~PAGE_MASK;
3163                 }
3164         }
3165
3166         return 0;
3167 }
3168
3169 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3170 {
3171         if (WARN_ON_ONCE(!req->imu))
3172                 return -EFAULT;
3173         return __io_import_fixed(req, rw, iter, req->imu);
3174 }
3175
3176 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3177 {
3178         if (needs_lock)
3179                 mutex_unlock(&ctx->uring_lock);
3180 }
3181
3182 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3183 {
3184         /*
3185          * "Normal" inline submissions always hold the uring_lock, since we
3186          * grab it from the system call. Same is true for the SQPOLL offload.
3187          * The only exception is when we've detached the request and issue it
3188          * from an async worker thread, grab the lock for that case.
3189          */
3190         if (needs_lock)
3191                 mutex_lock(&ctx->uring_lock);
3192 }
3193
3194 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3195                                           int bgid, struct io_buffer *kbuf,
3196                                           bool needs_lock)
3197 {
3198         struct io_buffer *head;
3199
3200         if (req->flags & REQ_F_BUFFER_SELECTED)
3201                 return kbuf;
3202
3203         io_ring_submit_lock(req->ctx, needs_lock);
3204
3205         lockdep_assert_held(&req->ctx->uring_lock);
3206
3207         head = xa_load(&req->ctx->io_buffers, bgid);
3208         if (head) {
3209                 if (!list_empty(&head->list)) {
3210                         kbuf = list_last_entry(&head->list, struct io_buffer,
3211                                                         list);
3212                         list_del(&kbuf->list);
3213                 } else {
3214                         kbuf = head;
3215                         xa_erase(&req->ctx->io_buffers, bgid);
3216                 }
3217                 if (*len > kbuf->len)
3218                         *len = kbuf->len;
3219         } else {
3220                 kbuf = ERR_PTR(-ENOBUFS);
3221         }
3222
3223         io_ring_submit_unlock(req->ctx, needs_lock);
3224
3225         return kbuf;
3226 }
3227
3228 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3229                                         bool needs_lock)
3230 {
3231         struct io_buffer *kbuf;
3232         u16 bgid;
3233
3234         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3235         bgid = req->buf_index;
3236         kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3237         if (IS_ERR(kbuf))
3238                 return kbuf;
3239         req->rw.addr = (u64) (unsigned long) kbuf;
3240         req->flags |= REQ_F_BUFFER_SELECTED;
3241         return u64_to_user_ptr(kbuf->addr);
3242 }
3243
3244 #ifdef CONFIG_COMPAT
3245 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3246                                 bool needs_lock)
3247 {
3248         struct compat_iovec __user *uiov;
3249         compat_ssize_t clen;
3250         void __user *buf;
3251         ssize_t len;
3252
3253         uiov = u64_to_user_ptr(req->rw.addr);
3254         if (!access_ok(uiov, sizeof(*uiov)))
3255                 return -EFAULT;
3256         if (__get_user(clen, &uiov->iov_len))
3257                 return -EFAULT;
3258         if (clen < 0)
3259                 return -EINVAL;
3260
3261         len = clen;
3262         buf = io_rw_buffer_select(req, &len, needs_lock);
3263         if (IS_ERR(buf))
3264                 return PTR_ERR(buf);
3265         iov[0].iov_base = buf;
3266         iov[0].iov_len = (compat_size_t) len;
3267         return 0;
3268 }
3269 #endif
3270
3271 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3272                                       bool needs_lock)
3273 {
3274         struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3275         void __user *buf;
3276         ssize_t len;
3277
3278         if (copy_from_user(iov, uiov, sizeof(*uiov)))
3279                 return -EFAULT;
3280
3281         len = iov[0].iov_len;
3282         if (len < 0)
3283                 return -EINVAL;
3284         buf = io_rw_buffer_select(req, &len, needs_lock);
3285         if (IS_ERR(buf))
3286                 return PTR_ERR(buf);
3287         iov[0].iov_base = buf;
3288         iov[0].iov_len = len;
3289         return 0;
3290 }
3291
3292 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3293                                     bool needs_lock)
3294 {
3295         if (req->flags & REQ_F_BUFFER_SELECTED) {
3296                 struct io_buffer *kbuf;
3297
3298                 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3299                 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3300                 iov[0].iov_len = kbuf->len;
3301                 return 0;
3302         }
3303         if (req->rw.len != 1)
3304                 return -EINVAL;
3305
3306 #ifdef CONFIG_COMPAT
3307         if (req->ctx->compat)
3308                 return io_compat_import(req, iov, needs_lock);
3309 #endif
3310
3311         return __io_iov_buffer_select(req, iov, needs_lock);
3312 }
3313
3314 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3315                            struct iov_iter *iter, bool needs_lock)
3316 {
3317         void __user *buf = u64_to_user_ptr(req->rw.addr);
3318         size_t sqe_len = req->rw.len;
3319         u8 opcode = req->opcode;
3320         ssize_t ret;
3321
3322         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3323                 *iovec = NULL;
3324                 return io_import_fixed(req, rw, iter);
3325         }
3326
3327         /* buffer index only valid with fixed read/write, or buffer select  */
3328         if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3329                 return -EINVAL;
3330
3331         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3332                 if (req->flags & REQ_F_BUFFER_SELECT) {
3333                         buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3334                         if (IS_ERR(buf))
3335                                 return PTR_ERR(buf);
3336                         req->rw.len = sqe_len;
3337                 }
3338
3339                 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3340                 *iovec = NULL;
3341                 return ret;
3342         }
3343
3344         if (req->flags & REQ_F_BUFFER_SELECT) {
3345                 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3346                 if (!ret)
3347                         iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3348                 *iovec = NULL;
3349                 return ret;
3350         }
3351
3352         return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3353                               req->ctx->compat);
3354 }
3355
3356 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3357 {
3358         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3359 }
3360
3361 /*
3362  * For files that don't have ->read_iter() and ->write_iter(), handle them
3363  * by looping over ->read() or ->write() manually.
3364  */
3365 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3366 {
3367         struct kiocb *kiocb = &req->rw.kiocb;
3368         struct file *file = req->file;
3369         ssize_t ret = 0;
3370         loff_t *ppos;
3371
3372         /*
3373          * Don't support polled IO through this interface, and we can't
3374          * support non-blocking either. For the latter, this just causes
3375          * the kiocb to be handled from an async context.
3376          */
3377         if (kiocb->ki_flags & IOCB_HIPRI)
3378                 return -EOPNOTSUPP;
3379         if (kiocb->ki_flags & IOCB_NOWAIT)
3380                 return -EAGAIN;
3381
3382         ppos = io_kiocb_ppos(kiocb);
3383
3384         while (iov_iter_count(iter)) {
3385                 struct iovec iovec;
3386                 ssize_t nr;
3387
3388                 if (!iov_iter_is_bvec(iter)) {
3389                         iovec = iov_iter_iovec(iter);
3390                 } else {
3391                         iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3392                         iovec.iov_len = req->rw.len;
3393                 }
3394
3395                 if (rw == READ) {
3396                         nr = file->f_op->read(file, iovec.iov_base,
3397                                               iovec.iov_len, ppos);
3398                 } else {
3399                         nr = file->f_op->write(file, iovec.iov_base,
3400                                                iovec.iov_len, ppos);
3401                 }
3402
3403                 if (nr < 0) {
3404                         if (!ret)
3405                                 ret = nr;
3406                         break;
3407                 }
3408                 ret += nr;
3409                 if (!iov_iter_is_bvec(iter)) {
3410                         iov_iter_advance(iter, nr);
3411                 } else {
3412                         req->rw.addr += nr;
3413                         req->rw.len -= nr;
3414                         if (!req->rw.len)
3415                                 break;
3416                 }
3417                 if (nr != iovec.iov_len)
3418                         break;
3419         }
3420
3421         return ret;
3422 }
3423
3424 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3425                           const struct iovec *fast_iov, struct iov_iter *iter)
3426 {
3427         struct io_async_rw *rw = req->async_data;
3428
3429         memcpy(&rw->iter, iter, sizeof(*iter));
3430         rw->free_iovec = iovec;
3431         rw->bytes_done = 0;
3432         /* can only be fixed buffers, no need to do anything */
3433         if (iov_iter_is_bvec(iter))
3434                 return;
3435         if (!iovec) {
3436                 unsigned iov_off = 0;
3437
3438                 rw->iter.iov = rw->fast_iov;
3439                 if (iter->iov != fast_iov) {
3440                         iov_off = iter->iov - fast_iov;
3441                         rw->iter.iov += iov_off;
3442                 }
3443                 if (rw->fast_iov != fast_iov)
3444                         memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3445                                sizeof(struct iovec) * iter->nr_segs);
3446         } else {
3447                 req->flags |= REQ_F_NEED_CLEANUP;
3448         }
3449 }
3450
3451 static inline int io_alloc_async_data(struct io_kiocb *req)
3452 {
3453         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3454         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3455         return req->async_data == NULL;
3456 }
3457
3458 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3459                              const struct iovec *fast_iov,
3460                              struct iov_iter *iter, bool force)
3461 {
3462         if (!force && !io_op_defs[req->opcode].needs_async_setup)
3463                 return 0;
3464         if (!req->async_data) {
3465                 struct io_async_rw *iorw;
3466
3467                 if (io_alloc_async_data(req)) {
3468                         kfree(iovec);
3469                         return -ENOMEM;
3470                 }
3471
3472                 io_req_map_rw(req, iovec, fast_iov, iter);
3473                 iorw = req->async_data;
3474                 /* we've copied and mapped the iter, ensure state is saved */
3475                 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3476         }
3477         return 0;
3478 }
3479
3480 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3481 {
3482         struct io_async_rw *iorw = req->async_data;
3483         struct iovec *iov = iorw->fast_iov;
3484         int ret;
3485
3486         ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3487         if (unlikely(ret < 0))
3488                 return ret;
3489
3490         iorw->bytes_done = 0;
3491         iorw->free_iovec = iov;
3492         if (iov)
3493                 req->flags |= REQ_F_NEED_CLEANUP;
3494         iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3495         return 0;
3496 }
3497
3498 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3499 {
3500         if (unlikely(!(req->file->f_mode & FMODE_READ)))
3501                 return -EBADF;
3502         return io_prep_rw(req, sqe, READ);
3503 }
3504
3505 /*
3506  * This is our waitqueue callback handler, registered through lock_page_async()
3507  * when we initially tried to do the IO with the iocb armed our waitqueue.
3508  * This gets called when the page is unlocked, and we generally expect that to
3509  * happen when the page IO is completed and the page is now uptodate. This will
3510  * queue a task_work based retry of the operation, attempting to copy the data
3511  * again. If the latter fails because the page was NOT uptodate, then we will
3512  * do a thread based blocking retry of the operation. That's the unexpected
3513  * slow path.
3514  */
3515 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3516                              int sync, void *arg)
3517 {
3518         struct wait_page_queue *wpq;
3519         struct io_kiocb *req = wait->private;
3520         struct wait_page_key *key = arg;
3521
3522         wpq = container_of(wait, struct wait_page_queue, wait);
3523
3524         if (!wake_page_match(wpq, key))
3525                 return 0;
3526
3527         req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3528         list_del_init(&wait->entry);
3529         io_req_task_queue(req);
3530         return 1;
3531 }
3532
3533 /*
3534  * This controls whether a given IO request should be armed for async page
3535  * based retry. If we return false here, the request is handed to the async
3536  * worker threads for retry. If we're doing buffered reads on a regular file,
3537  * we prepare a private wait_page_queue entry and retry the operation. This
3538  * will either succeed because the page is now uptodate and unlocked, or it
3539  * will register a callback when the page is unlocked at IO completion. Through
3540  * that callback, io_uring uses task_work to setup a retry of the operation.
3541  * That retry will attempt the buffered read again. The retry will generally
3542  * succeed, or in rare cases where it fails, we then fall back to using the
3543  * async worker threads for a blocking retry.
3544  */
3545 static bool io_rw_should_retry(struct io_kiocb *req)
3546 {
3547         struct io_async_rw *rw = req->async_data;
3548         struct wait_page_queue *wait = &rw->wpq;
3549         struct kiocb *kiocb = &req->rw.kiocb;
3550
3551         /* never retry for NOWAIT, we just complete with -EAGAIN */
3552         if (req->flags & REQ_F_NOWAIT)
3553                 return false;
3554
3555         /* Only for buffered IO */
3556         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3557                 return false;
3558
3559         /*
3560          * just use poll if we can, and don't attempt if the fs doesn't
3561          * support callback based unlocks
3562          */
3563         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3564                 return false;
3565
3566         wait->wait.func = io_async_buf_func;
3567         wait->wait.private = req;
3568         wait->wait.flags = 0;
3569         INIT_LIST_HEAD(&wait->wait.entry);
3570         kiocb->ki_flags |= IOCB_WAITQ;
3571         kiocb->ki_flags &= ~IOCB_NOWAIT;
3572         kiocb->ki_waitq = wait;
3573         return true;
3574 }
3575
3576 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3577 {
3578         if (req->file->f_op->read_iter)
3579                 return call_read_iter(req->file, &req->rw.kiocb, iter);
3580         else if (req->file->f_op->read)
3581                 return loop_rw_iter(READ, req, iter);
3582         else
3583                 return -EINVAL;
3584 }
3585
3586 static bool need_read_all(struct io_kiocb *req)
3587 {
3588         return req->flags & REQ_F_ISREG ||
3589                 S_ISBLK(file_inode(req->file)->i_mode);
3590 }
3591
3592 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3593 {
3594         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3595         struct kiocb *kiocb = &req->rw.kiocb;
3596         struct iov_iter __iter, *iter = &__iter;
3597         struct io_async_rw *rw = req->async_data;
3598         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3599         struct iov_iter_state __state, *state;
3600         ssize_t ret, ret2;
3601         loff_t *ppos;
3602
3603         if (rw) {
3604                 iter = &rw->iter;
3605                 state = &rw->iter_state;
3606                 /*
3607                  * We come here from an earlier attempt, restore our state to
3608                  * match in case it doesn't. It's cheap enough that we don't
3609                  * need to make this conditional.
3610                  */
3611                 iov_iter_restore(iter, state);
3612                 iovec = NULL;
3613         } else {
3614                 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3615                 if (ret < 0)
3616                         return ret;
3617                 state = &__state;
3618                 iov_iter_save_state(iter, state);
3619         }
3620         req->result = iov_iter_count(iter);
3621
3622         /* Ensure we clear previously set non-block flag */
3623         if (!force_nonblock)
3624                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3625         else
3626                 kiocb->ki_flags |= IOCB_NOWAIT;
3627
3628         /* If the file doesn't support async, just async punt */
3629         if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3630                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3631                 return ret ?: -EAGAIN;
3632         }
3633
3634         ppos = io_kiocb_update_pos(req);
3635
3636         ret = rw_verify_area(READ, req->file, ppos, req->result);
3637         if (unlikely(ret)) {
3638                 kfree(iovec);
3639                 return ret;
3640         }
3641
3642         ret = io_iter_do_read(req, iter);
3643
3644         if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3645                 req->flags &= ~REQ_F_REISSUE;
3646                 /* IOPOLL retry should happen for io-wq threads */
3647                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3648                         goto done;
3649                 /* no retry on NONBLOCK nor RWF_NOWAIT */
3650                 if (req->flags & REQ_F_NOWAIT)
3651                         goto done;
3652                 ret = 0;
3653         } else if (ret == -EIOCBQUEUED) {
3654                 goto out_free;
3655         } else if (ret <= 0 || ret == req->result || !force_nonblock ||
3656                    (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3657                 /* read all, failed, already did sync or don't want to retry */
3658                 goto done;
3659         }
3660
3661         /*
3662          * Don't depend on the iter state matching what was consumed, or being
3663          * untouched in case of error. Restore it and we'll advance it
3664          * manually if we need to.
3665          */
3666         iov_iter_restore(iter, state);
3667
3668         ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3669         if (ret2)
3670                 return ret2;
3671
3672         iovec = NULL;
3673         rw = req->async_data;
3674         /*
3675          * Now use our persistent iterator and state, if we aren't already.
3676          * We've restored and mapped the iter to match.
3677          */
3678         if (iter != &rw->iter) {
3679                 iter = &rw->iter;
3680                 state = &rw->iter_state;
3681         }
3682
3683         do {
3684                 /*
3685                  * We end up here because of a partial read, either from
3686                  * above or inside this loop. Advance the iter by the bytes
3687                  * that were consumed.
3688                  */
3689                 iov_iter_advance(iter, ret);
3690                 if (!iov_iter_count(iter))
3691                         break;
3692                 rw->bytes_done += ret;
3693                 iov_iter_save_state(iter, state);
3694
3695                 /* if we can retry, do so with the callbacks armed */
3696                 if (!io_rw_should_retry(req)) {
3697                         kiocb->ki_flags &= ~IOCB_WAITQ;
3698                         return -EAGAIN;
3699                 }
3700
3701                 req->result = iov_iter_count(iter);
3702                 /*
3703                  * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3704                  * we get -EIOCBQUEUED, then we'll get a notification when the
3705                  * desired page gets unlocked. We can also get a partial read
3706                  * here, and if we do, then just retry at the new offset.
3707                  */
3708                 ret = io_iter_do_read(req, iter);
3709                 if (ret == -EIOCBQUEUED)
3710                         return 0;
3711                 /* we got some bytes, but not all. retry. */
3712                 kiocb->ki_flags &= ~IOCB_WAITQ;
3713                 iov_iter_restore(iter, state);
3714         } while (ret > 0);
3715 done:
3716         kiocb_done(kiocb, ret, issue_flags);
3717 out_free:
3718         /* it's faster to check here then delegate to kfree */
3719         if (iovec)
3720                 kfree(iovec);
3721         return 0;
3722 }
3723
3724 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3725 {
3726         if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3727                 return -EBADF;
3728         return io_prep_rw(req, sqe, WRITE);
3729 }
3730
3731 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3732 {
3733         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3734         struct kiocb *kiocb = &req->rw.kiocb;
3735         struct iov_iter __iter, *iter = &__iter;
3736         struct io_async_rw *rw = req->async_data;
3737         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3738         struct iov_iter_state __state, *state;
3739         ssize_t ret, ret2;
3740         loff_t *ppos;
3741
3742         if (rw) {
3743                 iter = &rw->iter;
3744                 state = &rw->iter_state;
3745                 iov_iter_restore(iter, state);
3746                 iovec = NULL;
3747         } else {
3748                 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3749                 if (ret < 0)
3750                         return ret;
3751                 state = &__state;
3752                 iov_iter_save_state(iter, state);
3753         }
3754         req->result = iov_iter_count(iter);
3755
3756         /* Ensure we clear previously set non-block flag */
3757         if (!force_nonblock)
3758                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3759         else
3760                 kiocb->ki_flags |= IOCB_NOWAIT;
3761
3762         /* If the file doesn't support async, just async punt */
3763         if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3764                 goto copy_iov;
3765
3766         /* file path doesn't support NOWAIT for non-direct_IO */
3767         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3768             (req->flags & REQ_F_ISREG))
3769                 goto copy_iov;
3770
3771         ppos = io_kiocb_update_pos(req);
3772
3773         ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3774         if (unlikely(ret))
3775                 goto out_free;
3776
3777         /*
3778          * Open-code file_start_write here to grab freeze protection,
3779          * which will be released by another thread in
3780          * io_complete_rw().  Fool lockdep by telling it the lock got
3781          * released so that it doesn't complain about the held lock when
3782          * we return to userspace.
3783          */
3784         if (req->flags & REQ_F_ISREG) {
3785                 sb_start_write(file_inode(req->file)->i_sb);
3786                 __sb_writers_release(file_inode(req->file)->i_sb,
3787                                         SB_FREEZE_WRITE);
3788         }
3789         kiocb->ki_flags |= IOCB_WRITE;
3790
3791         if (req->file->f_op->write_iter)
3792                 ret2 = call_write_iter(req->file, kiocb, iter);
3793         else if (req->file->f_op->write)
3794                 ret2 = loop_rw_iter(WRITE, req, iter);
3795         else
3796                 ret2 = -EINVAL;
3797
3798         if (req->flags & REQ_F_REISSUE) {
3799                 req->flags &= ~REQ_F_REISSUE;
3800                 ret2 = -EAGAIN;
3801         }
3802
3803         /*
3804          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3805          * retry them without IOCB_NOWAIT.
3806          */
3807         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3808                 ret2 = -EAGAIN;
3809         /* no retry on NONBLOCK nor RWF_NOWAIT */
3810         if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3811                 goto done;
3812         if (!force_nonblock || ret2 != -EAGAIN) {
3813                 /* IOPOLL retry should happen for io-wq threads */
3814                 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3815                         goto copy_iov;
3816 done:
3817                 kiocb_done(kiocb, ret2, issue_flags);
3818         } else {
3819 copy_iov:
3820                 iov_iter_restore(iter, state);
3821                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3822                 if (!ret) {
3823                         if (kiocb->ki_flags & IOCB_WRITE)
3824                                 kiocb_end_write(req);
3825                         return -EAGAIN;
3826                 }
3827                 return ret;
3828         }
3829 out_free:
3830         /* it's reportedly faster than delegating the null check to kfree() */
3831         if (iovec)
3832                 kfree(iovec);
3833         return ret;
3834 }
3835
3836 static int io_renameat_prep(struct io_kiocb *req,
3837                             const struct io_uring_sqe *sqe)
3838 {
3839         struct io_rename *ren = &req->rename;
3840         const char __user *oldf, *newf;
3841
3842         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3843                 return -EINVAL;
3844         if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3845                 return -EINVAL;
3846         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3847                 return -EBADF;
3848
3849         ren->old_dfd = READ_ONCE(sqe->fd);
3850         oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3851         newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3852         ren->new_dfd = READ_ONCE(sqe->len);
3853         ren->flags = READ_ONCE(sqe->rename_flags);
3854
3855         ren->oldpath = getname(oldf);
3856         if (IS_ERR(ren->oldpath))
3857                 return PTR_ERR(ren->oldpath);
3858
3859         ren->newpath = getname(newf);
3860         if (IS_ERR(ren->newpath)) {
3861                 putname(ren->oldpath);
3862                 return PTR_ERR(ren->newpath);
3863         }
3864
3865         req->flags |= REQ_F_NEED_CLEANUP;
3866         return 0;
3867 }
3868
3869 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3870 {
3871         struct io_rename *ren = &req->rename;
3872         int ret;
3873
3874         if (issue_flags & IO_URING_F_NONBLOCK)
3875                 return -EAGAIN;
3876
3877         ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3878                                 ren->newpath, ren->flags);
3879
3880         req->flags &= ~REQ_F_NEED_CLEANUP;
3881         if (ret < 0)
3882                 req_set_fail(req);
3883         io_req_complete(req, ret);
3884         return 0;
3885 }
3886
3887 static int io_unlinkat_prep(struct io_kiocb *req,
3888                             const struct io_uring_sqe *sqe)
3889 {
3890         struct io_unlink *un = &req->unlink;
3891         const char __user *fname;
3892
3893         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3894                 return -EINVAL;
3895         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3896             sqe->splice_fd_in)
3897                 return -EINVAL;
3898         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3899                 return -EBADF;
3900
3901         un->dfd = READ_ONCE(sqe->fd);
3902
3903         un->flags = READ_ONCE(sqe->unlink_flags);
3904         if (un->flags & ~AT_REMOVEDIR)
3905                 return -EINVAL;
3906
3907         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3908         un->filename = getname(fname);
3909         if (IS_ERR(un->filename))
3910                 return PTR_ERR(un->filename);
3911
3912         req->flags |= REQ_F_NEED_CLEANUP;
3913         return 0;
3914 }
3915
3916 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3917 {
3918         struct io_unlink *un = &req->unlink;
3919         int ret;
3920
3921         if (issue_flags & IO_URING_F_NONBLOCK)
3922                 return -EAGAIN;
3923
3924         if (un->flags & AT_REMOVEDIR)
3925                 ret = do_rmdir(un->dfd, un->filename);
3926         else
3927                 ret = do_unlinkat(un->dfd, un->filename);
3928
3929         req->flags &= ~REQ_F_NEED_CLEANUP;
3930         if (ret < 0)
3931                 req_set_fail(req);
3932         io_req_complete(req, ret);
3933         return 0;
3934 }
3935
3936 static int io_mkdirat_prep(struct io_kiocb *req,
3937                             const struct io_uring_sqe *sqe)
3938 {
3939         struct io_mkdir *mkd = &req->mkdir;
3940         const char __user *fname;
3941
3942         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3943                 return -EINVAL;
3944         if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3945             sqe->splice_fd_in)
3946                 return -EINVAL;
3947         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3948                 return -EBADF;
3949
3950         mkd->dfd = READ_ONCE(sqe->fd);
3951         mkd->mode = READ_ONCE(sqe->len);
3952
3953         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3954         mkd->filename = getname(fname);
3955         if (IS_ERR(mkd->filename))
3956                 return PTR_ERR(mkd->filename);
3957
3958         req->flags |= REQ_F_NEED_CLEANUP;
3959         return 0;
3960 }
3961
3962 static int io_mkdirat(struct io_kiocb *req, int issue_flags)
3963 {
3964         struct io_mkdir *mkd = &req->mkdir;
3965         int ret;
3966
3967         if (issue_flags & IO_URING_F_NONBLOCK)
3968                 return -EAGAIN;
3969
3970         ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3971
3972         req->flags &= ~REQ_F_NEED_CLEANUP;
3973         if (ret < 0)
3974                 req_set_fail(req);
3975         io_req_complete(req, ret);
3976         return 0;
3977 }
3978
3979 static int io_symlinkat_prep(struct io_kiocb *req,
3980                             const struct io_uring_sqe *sqe)
3981 {
3982         struct io_symlink *sl = &req->symlink;
3983         const char __user *oldpath, *newpath;
3984
3985         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3986                 return -EINVAL;
3987         if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3988             sqe->splice_fd_in)
3989                 return -EINVAL;
3990         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3991                 return -EBADF;
3992
3993         sl->new_dfd = READ_ONCE(sqe->fd);
3994         oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3995         newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3996
3997         sl->oldpath = getname(oldpath);
3998         if (IS_ERR(sl->oldpath))
3999                 return PTR_ERR(sl->oldpath);
4000
4001         sl->newpath = getname(newpath);
4002         if (IS_ERR(sl->newpath)) {
4003                 putname(sl->oldpath);
4004                 return PTR_ERR(sl->newpath);
4005         }
4006
4007         req->flags |= REQ_F_NEED_CLEANUP;
4008         return 0;
4009 }
4010
4011 static int io_symlinkat(struct io_kiocb *req, int issue_flags)
4012 {
4013         struct io_symlink *sl = &req->symlink;
4014         int ret;
4015
4016         if (issue_flags & IO_URING_F_NONBLOCK)
4017                 return -EAGAIN;
4018
4019         ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4020
4021         req->flags &= ~REQ_F_NEED_CLEANUP;
4022         if (ret < 0)
4023                 req_set_fail(req);
4024         io_req_complete(req, ret);
4025         return 0;
4026 }
4027
4028 static int io_linkat_prep(struct io_kiocb *req,
4029                             const struct io_uring_sqe *sqe)
4030 {
4031         struct io_hardlink *lnk = &req->hardlink;
4032         const char __user *oldf, *newf;
4033
4034         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4035                 return -EINVAL;
4036         if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4037                 return -EINVAL;
4038         if (unlikely(req->flags & REQ_F_FIXED_FILE))
4039                 return -EBADF;
4040
4041         lnk->old_dfd = READ_ONCE(sqe->fd);
4042         lnk->new_dfd = READ_ONCE(sqe->len);
4043         oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4044         newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4045         lnk->flags = READ_ONCE(sqe->hardlink_flags);
4046
4047         lnk->oldpath = getname(oldf);
4048         if (IS_ERR(lnk->oldpath))
4049                 return PTR_ERR(lnk->oldpath);
4050
4051         lnk->newpath = getname(newf);
4052         if (IS_ERR(lnk->newpath)) {
4053                 putname(lnk->oldpath);
4054                 return PTR_ERR(lnk->newpath);
4055         }
4056
4057         req->flags |= REQ_F_NEED_CLEANUP;
4058         return 0;
4059 }
4060
4061 static int io_linkat(struct io_kiocb *req, int issue_flags)
4062 {
4063         struct io_hardlink *lnk = &req->hardlink;
4064         int ret;
4065
4066         if (issue_flags & IO_URING_F_NONBLOCK)
4067                 return -EAGAIN;
4068
4069         ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4070                                 lnk->newpath, lnk->flags);
4071
4072         req->flags &= ~REQ_F_NEED_CLEANUP;
4073         if (ret < 0)
4074                 req_set_fail(req);
4075         io_req_complete(req, ret);
4076         return 0;
4077 }
4078
4079 static int io_shutdown_prep(struct io_kiocb *req,
4080                             const struct io_uring_sqe *sqe)
4081 {
4082 #if defined(CONFIG_NET)
4083         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4084                 return -EINVAL;
4085         if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4086                      sqe->buf_index || sqe->splice_fd_in))
4087                 return -EINVAL;
4088
4089         req->shutdown.how = READ_ONCE(sqe->len);
4090         return 0;
4091 #else
4092         return -EOPNOTSUPP;
4093 #endif
4094 }
4095
4096 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4097 {
4098 #if defined(CONFIG_NET)
4099         struct socket *sock;
4100         int ret;
4101
4102         if (issue_flags & IO_URING_F_NONBLOCK)
4103                 return -EAGAIN;
4104
4105         sock = sock_from_file(req->file);
4106         if (unlikely(!sock))
4107                 return -ENOTSOCK;
4108
4109         ret = __sys_shutdown_sock(sock, req->shutdown.how);
4110         if (ret < 0)
4111                 req_set_fail(req);
4112         io_req_complete(req, ret);
4113         return 0;
4114 #else
4115         return -EOPNOTSUPP;
4116 #endif
4117 }
4118
4119 static int __io_splice_prep(struct io_kiocb *req,
4120                             const struct io_uring_sqe *sqe)
4121 {
4122         struct io_splice *sp = &req->splice;
4123         unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4124
4125         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4126                 return -EINVAL;
4127
4128         sp->len = READ_ONCE(sqe->len);
4129         sp->flags = READ_ONCE(sqe->splice_flags);
4130         if (unlikely(sp->flags & ~valid_flags))
4131                 return -EINVAL;
4132         sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4133         return 0;
4134 }
4135
4136 static int io_tee_prep(struct io_kiocb *req,
4137                        const struct io_uring_sqe *sqe)
4138 {
4139         if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4140                 return -EINVAL;
4141         return __io_splice_prep(req, sqe);
4142 }
4143
4144 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4145 {
4146         struct io_splice *sp = &req->splice;
4147         struct file *out = sp->file_out;
4148         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4149         struct file *in;
4150         long ret = 0;
4151
4152         if (issue_flags & IO_URING_F_NONBLOCK)
4153                 return -EAGAIN;
4154
4155         in = io_file_get(req->ctx, req, sp->splice_fd_in,
4156                          (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4157         if (!in) {
4158                 ret = -EBADF;
4159                 goto done;
4160         }
4161
4162         if (sp->len)
4163                 ret = do_tee(in, out, sp->len, flags);
4164
4165         if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4166                 io_put_file(in);
4167 done:
4168         if (ret != sp->len)
4169                 req_set_fail(req);
4170         io_req_complete(req, ret);
4171         return 0;
4172 }
4173
4174 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4175 {
4176         struct io_splice *sp = &req->splice;
4177
4178         sp->off_in = READ_ONCE(sqe->splice_off_in);
4179         sp->off_out = READ_ONCE(sqe->off);
4180         return __io_splice_prep(req, sqe);
4181 }
4182
4183 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4184 {
4185         struct io_splice *sp = &req->splice;
4186         struct file *out = sp->file_out;
4187         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4188         loff_t *poff_in, *poff_out;
4189         struct file *in;
4190         long ret = 0;
4191
4192         if (issue_flags & IO_URING_F_NONBLOCK)
4193                 return -EAGAIN;
4194
4195         in = io_file_get(req->ctx, req, sp->splice_fd_in,
4196                          (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4197         if (!in) {
4198                 ret = -EBADF;
4199                 goto done;
4200         }
4201
4202         poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4203         poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4204
4205         if (sp->len)
4206                 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4207
4208         if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4209                 io_put_file(in);
4210 done:
4211         if (ret != sp->len)
4212                 req_set_fail(req);
4213         io_req_complete(req, ret);
4214         return 0;
4215 }
4216
4217 /*
4218  * IORING_OP_NOP just posts a completion event, nothing else.
4219  */
4220 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4221 {
4222         struct io_ring_ctx *ctx = req->ctx;
4223
4224         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4225                 return -EINVAL;
4226
4227         __io_req_complete(req, issue_flags, 0, 0);
4228         return 0;
4229 }
4230
4231 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4232 {
4233         struct io_ring_ctx *ctx = req->ctx;
4234
4235         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4236                 return -EINVAL;
4237         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4238                      sqe->splice_fd_in))
4239                 return -EINVAL;
4240
4241         req->sync.flags = READ_ONCE(sqe->fsync_flags);
4242         if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4243                 return -EINVAL;
4244
4245         req->sync.off = READ_ONCE(sqe->off);
4246         req->sync.len = READ_ONCE(sqe->len);
4247         return 0;
4248 }
4249
4250 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4251 {
4252         loff_t end = req->sync.off + req->sync.len;
4253         int ret;
4254
4255         /* fsync always requires a blocking context */
4256         if (issue_flags & IO_URING_F_NONBLOCK)
4257                 return -EAGAIN;
4258
4259         ret = vfs_fsync_range(req->file, req->sync.off,
4260                                 end > 0 ? end : LLONG_MAX,
4261                                 req->sync.flags & IORING_FSYNC_DATASYNC);
4262         if (ret < 0)
4263                 req_set_fail(req);
4264         io_req_complete(req, ret);
4265         return 0;
4266 }
4267
4268 static int io_fallocate_prep(struct io_kiocb *req,
4269                              const struct io_uring_sqe *sqe)
4270 {
4271         if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4272             sqe->splice_fd_in)
4273                 return -EINVAL;
4274         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4275                 return -EINVAL;
4276
4277         req->sync.off = READ_ONCE(sqe->off);
4278         req->sync.len = READ_ONCE(sqe->addr);
4279         req->sync.mode = READ_ONCE(sqe->len);
4280         return 0;
4281 }
4282
4283 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4284 {
4285         int ret;
4286
4287         /* fallocate always requiring blocking context */
4288         if (issue_flags & IO_URING_F_NONBLOCK)
4289                 return -EAGAIN;
4290         ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4291                                 req->sync.len);
4292         if (ret < 0)
4293                 req_set_fail(req);
4294         else
4295                 fsnotify_modify(req->file);
4296         io_req_complete(req, ret);
4297         return 0;
4298 }
4299
4300 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4301 {
4302         const char __user *fname;
4303         int ret;
4304
4305         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4306                 return -EINVAL;
4307         if (unlikely(sqe->ioprio || sqe->buf_index))
4308                 return -EINVAL;
4309         if (unlikely(req->flags & REQ_F_FIXED_FILE))
4310                 return -EBADF;
4311
4312         /* open.how should be already initialised */
4313         if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4314                 req->open.how.flags |= O_LARGEFILE;
4315
4316         req->open.dfd = READ_ONCE(sqe->fd);
4317         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4318         req->open.filename = getname(fname);
4319         if (IS_ERR(req->open.filename)) {
4320                 ret = PTR_ERR(req->open.filename);
4321                 req->open.filename = NULL;
4322                 return ret;
4323         }
4324
4325         req->open.file_slot = READ_ONCE(sqe->file_index);
4326         if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4327                 return -EINVAL;
4328
4329         req->open.nofile = rlimit(RLIMIT_NOFILE);
4330         req->flags |= REQ_F_NEED_CLEANUP;
4331         return 0;
4332 }
4333
4334 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4335 {
4336         u64 mode = READ_ONCE(sqe->len);
4337         u64 flags = READ_ONCE(sqe->open_flags);
4338
4339         req->open.how = build_open_how(flags, mode);
4340         return __io_openat_prep(req, sqe);
4341 }
4342
4343 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4344 {
4345         struct open_how __user *how;
4346         size_t len;
4347         int ret;
4348
4349         how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4350         len = READ_ONCE(sqe->len);
4351         if (len < OPEN_HOW_SIZE_VER0)
4352                 return -EINVAL;
4353
4354         ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4355                                         len);
4356         if (ret)
4357                 return ret;
4358
4359         return __io_openat_prep(req, sqe);
4360 }
4361
4362 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4363 {
4364         struct open_flags op;
4365         struct file *file;
4366         bool resolve_nonblock, nonblock_set;
4367         bool fixed = !!req->open.file_slot;
4368         int ret;
4369
4370         ret = build_open_flags(&req->open.how, &op);
4371         if (ret)
4372                 goto err;
4373         nonblock_set = op.open_flag & O_NONBLOCK;
4374         resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4375         if (issue_flags & IO_URING_F_NONBLOCK) {
4376                 /*
4377                  * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4378                  * it'll always -EAGAIN. Note that we test for __O_TMPFILE
4379                  * because O_TMPFILE includes O_DIRECTORY, which isn't a flag
4380                  * we need to force async for.
4381                  */
4382                 if (req->open.how.flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
4383                         return -EAGAIN;
4384                 op.lookup_flags |= LOOKUP_CACHED;
4385                 op.open_flag |= O_NONBLOCK;
4386         }
4387
4388         if (!fixed) {
4389                 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4390                 if (ret < 0)
4391                         goto err;
4392         }
4393
4394         file = do_filp_open(req->open.dfd, req->open.filename, &op);
4395         if (IS_ERR(file)) {
4396                 /*
4397                  * We could hang on to this 'fd' on retrying, but seems like
4398                  * marginal gain for something that is now known to be a slower
4399                  * path. So just put it, and we'll get a new one when we retry.
4400                  */
4401                 if (!fixed)
4402                         put_unused_fd(ret);
4403
4404                 ret = PTR_ERR(file);
4405                 /* only retry if RESOLVE_CACHED wasn't already set by application */
4406                 if (ret == -EAGAIN &&
4407                     (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4408                         return -EAGAIN;
4409                 goto err;
4410         }
4411
4412         if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4413                 file->f_flags &= ~O_NONBLOCK;
4414         fsnotify_open(file);
4415
4416         if (!fixed)
4417                 fd_install(ret, file);
4418         else
4419                 ret = io_install_fixed_file(req, file, issue_flags,
4420                                             req->open.file_slot - 1);
4421 err:
4422         putname(req->open.filename);
4423         req->flags &= ~REQ_F_NEED_CLEANUP;
4424         if (ret < 0)
4425                 req_set_fail(req);
4426         __io_req_complete(req, issue_flags, ret, 0);
4427         return 0;
4428 }
4429
4430 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4431 {
4432         return io_openat2(req, issue_flags);
4433 }
4434
4435 static int io_remove_buffers_prep(struct io_kiocb *req,
4436                                   const struct io_uring_sqe *sqe)
4437 {
4438         struct io_provide_buf *p = &req->pbuf;
4439         u64 tmp;
4440
4441         if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4442             sqe->splice_fd_in)
4443                 return -EINVAL;
4444
4445         tmp = READ_ONCE(sqe->fd);
4446         if (!tmp || tmp > USHRT_MAX)
4447                 return -EINVAL;
4448
4449         memset(p, 0, sizeof(*p));
4450         p->nbufs = tmp;
4451         p->bgid = READ_ONCE(sqe->buf_group);
4452         return 0;
4453 }
4454
4455 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4456                                int bgid, unsigned nbufs)
4457 {
4458         unsigned i = 0;
4459
4460         /* shouldn't happen */
4461         if (!nbufs)
4462                 return 0;
4463
4464         /* the head kbuf is the list itself */
4465         while (!list_empty(&buf->list)) {
4466                 struct io_buffer *nxt;
4467
4468                 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4469                 list_del(&nxt->list);
4470                 kfree(nxt);
4471                 if (++i == nbufs)
4472                         return i;
4473                 cond_resched();
4474         }
4475         i++;
4476         kfree(buf);
4477         xa_erase(&ctx->io_buffers, bgid);
4478
4479         return i;
4480 }
4481
4482 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4483 {
4484         struct io_provide_buf *p = &req->pbuf;
4485         struct io_ring_ctx *ctx = req->ctx;
4486         struct io_buffer *head;
4487         int ret = 0;
4488         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4489
4490         io_ring_submit_lock(ctx, !force_nonblock);
4491
4492         lockdep_assert_held(&ctx->uring_lock);
4493
4494         ret = -ENOENT;
4495         head = xa_load(&ctx->io_buffers, p->bgid);
4496         if (head)
4497                 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4498         if (ret < 0)
4499                 req_set_fail(req);
4500
4501         /* complete before unlock, IOPOLL may need the lock */
4502         __io_req_complete(req, issue_flags, ret, 0);
4503         io_ring_submit_unlock(ctx, !force_nonblock);
4504         return 0;
4505 }
4506
4507 static int io_provide_buffers_prep(struct io_kiocb *req,
4508                                    const struct io_uring_sqe *sqe)
4509 {
4510         unsigned long size, tmp_check;
4511         struct io_provide_buf *p = &req->pbuf;
4512         u64 tmp;
4513
4514         if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4515                 return -EINVAL;
4516
4517         tmp = READ_ONCE(sqe->fd);
4518         if (!tmp || tmp > USHRT_MAX)
4519                 return -E2BIG;
4520         p->nbufs = tmp;
4521         p->addr = READ_ONCE(sqe->addr);
4522         p->len = READ_ONCE(sqe->len);
4523
4524         if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4525                                 &size))
4526                 return -EOVERFLOW;
4527         if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4528                 return -EOVERFLOW;
4529
4530         size = (unsigned long)p->len * p->nbufs;
4531         if (!access_ok(u64_to_user_ptr(p->addr), size))
4532                 return -EFAULT;
4533
4534         p->bgid = READ_ONCE(sqe->buf_group);
4535         tmp = READ_ONCE(sqe->off);
4536         if (tmp > USHRT_MAX)
4537                 return -E2BIG;
4538         p->bid = tmp;
4539         return 0;
4540 }
4541
4542 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4543 {
4544         struct io_buffer *buf;
4545         u64 addr = pbuf->addr;
4546         int i, bid = pbuf->bid;
4547
4548         for (i = 0; i < pbuf->nbufs; i++) {
4549                 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4550                 if (!buf)
4551                         break;
4552
4553                 buf->addr = addr;
4554                 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4555                 buf->bid = bid;
4556                 addr += pbuf->len;
4557                 bid++;
4558                 if (!*head) {
4559                         INIT_LIST_HEAD(&buf->list);
4560                         *head = buf;
4561                 } else {
4562                         list_add_tail(&buf->list, &(*head)->list);
4563                 }
4564                 cond_resched();
4565         }
4566
4567         return i ? i : -ENOMEM;
4568 }
4569
4570 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4571 {
4572         struct io_provide_buf *p = &req->pbuf;
4573         struct io_ring_ctx *ctx = req->ctx;
4574         struct io_buffer *head, *list;
4575         int ret = 0;
4576         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4577
4578         io_ring_submit_lock(ctx, !force_nonblock);
4579
4580         lockdep_assert_held(&ctx->uring_lock);
4581
4582         list = head = xa_load(&ctx->io_buffers, p->bgid);
4583
4584         ret = io_add_buffers(p, &head);
4585         if (ret >= 0 && !list) {
4586                 ret = xa_insert(&ctx->io_buffers, p->bgid, head,
4587                                 GFP_KERNEL_ACCOUNT);
4588                 if (ret < 0)
4589                         __io_remove_buffers(ctx, head, p->bgid, -1U);
4590         }
4591         if (ret < 0)
4592                 req_set_fail(req);
4593         /* complete before unlock, IOPOLL may need the lock */
4594         __io_req_complete(req, issue_flags, ret, 0);
4595         io_ring_submit_unlock(ctx, !force_nonblock);
4596         return 0;
4597 }
4598
4599 static int io_epoll_ctl_prep(struct io_kiocb *req,
4600                              const struct io_uring_sqe *sqe)
4601 {
4602 #if defined(CONFIG_EPOLL)
4603         if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4604                 return -EINVAL;
4605         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4606                 return -EINVAL;
4607
4608         req->epoll.epfd = READ_ONCE(sqe->fd);
4609         req->epoll.op = READ_ONCE(sqe->len);
4610         req->epoll.fd = READ_ONCE(sqe->off);
4611
4612         if (ep_op_has_event(req->epoll.op)) {
4613                 struct epoll_event __user *ev;
4614
4615                 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4616                 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4617                         return -EFAULT;
4618         }
4619
4620         return 0;
4621 #else
4622         return -EOPNOTSUPP;
4623 #endif
4624 }
4625
4626 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4627 {
4628 #if defined(CONFIG_EPOLL)
4629         struct io_epoll *ie = &req->epoll;
4630         int ret;
4631         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4632
4633         ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4634         if (force_nonblock && ret == -EAGAIN)
4635                 return -EAGAIN;
4636
4637         if (ret < 0)
4638                 req_set_fail(req);
4639         __io_req_complete(req, issue_flags, ret, 0);
4640         return 0;
4641 #else
4642         return -EOPNOTSUPP;
4643 #endif
4644 }
4645
4646 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4647 {
4648 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4649         if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4650                 return -EINVAL;
4651         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4652                 return -EINVAL;
4653
4654         req->madvise.addr = READ_ONCE(sqe->addr);
4655         req->madvise.len = READ_ONCE(sqe->len);
4656         req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4657         return 0;
4658 #else
4659         return -EOPNOTSUPP;
4660 #endif
4661 }
4662
4663 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4664 {
4665 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4666         struct io_madvise *ma = &req->madvise;
4667         int ret;
4668
4669         if (issue_flags & IO_URING_F_NONBLOCK)
4670                 return -EAGAIN;
4671
4672         ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4673         if (ret < 0)
4674                 req_set_fail(req);
4675         io_req_complete(req, ret);
4676         return 0;
4677 #else
4678         return -EOPNOTSUPP;
4679 #endif
4680 }
4681
4682 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4683 {
4684         if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4685                 return -EINVAL;
4686         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4687                 return -EINVAL;
4688
4689         req->fadvise.offset = READ_ONCE(sqe->off);
4690         req->fadvise.len = READ_ONCE(sqe->len);
4691         req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4692         return 0;
4693 }
4694
4695 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4696 {
4697         struct io_fadvise *fa = &req->fadvise;
4698         int ret;
4699
4700         if (issue_flags & IO_URING_F_NONBLOCK) {
4701                 switch (fa->advice) {
4702                 case POSIX_FADV_NORMAL:
4703                 case POSIX_FADV_RANDOM:
4704                 case POSIX_FADV_SEQUENTIAL:
4705                         break;
4706                 default:
4707                         return -EAGAIN;
4708                 }
4709         }
4710
4711         ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4712         if (ret < 0)
4713                 req_set_fail(req);
4714         __io_req_complete(req, issue_flags, ret, 0);
4715         return 0;
4716 }
4717
4718 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4719 {
4720         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4721                 return -EINVAL;
4722         if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4723                 return -EINVAL;
4724         if (req->flags & REQ_F_FIXED_FILE)
4725                 return -EBADF;
4726
4727         req->statx.dfd = READ_ONCE(sqe->fd);
4728         req->statx.mask = READ_ONCE(sqe->len);
4729         req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4730         req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4731         req->statx.flags = READ_ONCE(sqe->statx_flags);
4732
4733         return 0;
4734 }
4735
4736 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4737 {
4738         struct io_statx *ctx = &req->statx;
4739         int ret;
4740
4741         if (issue_flags & IO_URING_F_NONBLOCK)
4742                 return -EAGAIN;
4743
4744         ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4745                        ctx->buffer);
4746
4747         if (ret < 0)
4748                 req_set_fail(req);
4749         io_req_complete(req, ret);
4750         return 0;
4751 }
4752
4753 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4754 {
4755         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4756                 return -EINVAL;
4757         if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4758             sqe->rw_flags || sqe->buf_index)
4759                 return -EINVAL;
4760         if (req->flags & REQ_F_FIXED_FILE)
4761                 return -EBADF;
4762
4763         req->close.fd = READ_ONCE(sqe->fd);
4764         req->close.file_slot = READ_ONCE(sqe->file_index);
4765         if (req->close.file_slot && req->close.fd)
4766                 return -EINVAL;
4767
4768         return 0;
4769 }
4770
4771 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4772 {
4773         struct files_struct *files = current->files;
4774         struct io_close *close = &req->close;
4775         struct fdtable *fdt;
4776         struct file *file = NULL;
4777         int ret = -EBADF;
4778
4779         if (req->close.file_slot) {
4780                 ret = io_close_fixed(req, issue_flags);
4781                 goto err;
4782         }
4783
4784         spin_lock(&files->file_lock);
4785         fdt = files_fdtable(files);
4786         if (close->fd >= fdt->max_fds) {
4787                 spin_unlock(&files->file_lock);
4788                 goto err;
4789         }
4790         file = fdt->fd[close->fd];
4791         if (!file || file->f_op == &io_uring_fops) {
4792                 spin_unlock(&files->file_lock);
4793                 file = NULL;
4794                 goto err;
4795         }
4796
4797         /* if the file has a flush method, be safe and punt to async */
4798         if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4799                 spin_unlock(&files->file_lock);
4800                 return -EAGAIN;
4801         }
4802
4803         ret = __close_fd_get_file(close->fd, &file);
4804         spin_unlock(&files->file_lock);
4805         if (ret < 0) {
4806                 if (ret == -ENOENT)
4807                         ret = -EBADF;
4808                 goto err;
4809         }
4810
4811         /* No ->flush() or already async, safely close from here */
4812         ret = filp_close(file, current->files);
4813 err:
4814         if (ret < 0)
4815                 req_set_fail(req);
4816         if (file)
4817                 fput(file);
4818         __io_req_complete(req, issue_flags, ret, 0);
4819         return 0;
4820 }
4821
4822 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4823 {
4824         struct io_ring_ctx *ctx = req->ctx;
4825
4826         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4827                 return -EINVAL;
4828         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4829                      sqe->splice_fd_in))
4830                 return -EINVAL;
4831
4832         req->sync.off = READ_ONCE(sqe->off);
4833         req->sync.len = READ_ONCE(sqe->len);
4834         req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4835         return 0;
4836 }
4837
4838 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4839 {
4840         int ret;
4841
4842         /* sync_file_range always requires a blocking context */
4843         if (issue_flags & IO_URING_F_NONBLOCK)
4844                 return -EAGAIN;
4845
4846         ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4847                                 req->sync.flags);
4848         if (ret < 0)
4849                 req_set_fail(req);
4850         io_req_complete(req, ret);
4851         return 0;
4852 }
4853
4854 #if defined(CONFIG_NET)
4855 static bool io_net_retry(struct socket *sock, int flags)
4856 {
4857         if (!(flags & MSG_WAITALL))
4858                 return false;
4859         return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4860 }
4861
4862 static int io_setup_async_msg(struct io_kiocb *req,
4863                               struct io_async_msghdr *kmsg)
4864 {
4865         struct io_async_msghdr *async_msg = req->async_data;
4866
4867         if (async_msg)
4868                 return -EAGAIN;
4869         if (io_alloc_async_data(req)) {
4870                 kfree(kmsg->free_iov);
4871                 return -ENOMEM;
4872         }
4873         async_msg = req->async_data;
4874         req->flags |= REQ_F_NEED_CLEANUP;
4875         memcpy(async_msg, kmsg, sizeof(*kmsg));
4876         if (async_msg->msg.msg_name)
4877                 async_msg->msg.msg_name = &async_msg->addr;
4878         /* if were using fast_iov, set it to the new one */
4879         if (!kmsg->free_iov) {
4880                 size_t fast_idx = kmsg->msg.msg_iter.iov - kmsg->fast_iov;
4881                 async_msg->msg.msg_iter.iov = &async_msg->fast_iov[fast_idx];
4882         }
4883
4884         return -EAGAIN;
4885 }
4886
4887 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4888                                struct io_async_msghdr *iomsg)
4889 {
4890         struct io_sr_msg *sr = &req->sr_msg;
4891         int ret;
4892
4893         iomsg->msg.msg_name = &iomsg->addr;
4894         iomsg->free_iov = iomsg->fast_iov;
4895         ret = sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4896                                    req->sr_msg.msg_flags, &iomsg->free_iov);
4897         /* save msg_control as sys_sendmsg() overwrites it */
4898         sr->msg_control = iomsg->msg.msg_control;
4899         return ret;
4900 }
4901
4902 static int io_sendmsg_prep_async(struct io_kiocb *req)
4903 {
4904         int ret;
4905
4906         ret = io_sendmsg_copy_hdr(req, req->async_data);
4907         if (!ret)
4908                 req->flags |= REQ_F_NEED_CLEANUP;
4909         return ret;
4910 }
4911
4912 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4913 {
4914         struct io_sr_msg *sr = &req->sr_msg;
4915
4916         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4917                 return -EINVAL;
4918         if (unlikely(sqe->addr2 || sqe->file_index))
4919                 return -EINVAL;
4920         if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
4921                 return -EINVAL;
4922
4923         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4924         sr->len = READ_ONCE(sqe->len);
4925         sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4926         if (sr->msg_flags & MSG_DONTWAIT)
4927                 req->flags |= REQ_F_NOWAIT;
4928
4929 #ifdef CONFIG_COMPAT
4930         if (req->ctx->compat)
4931                 sr->msg_flags |= MSG_CMSG_COMPAT;
4932 #endif
4933         sr->done_io = 0;
4934         return 0;
4935 }
4936
4937 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4938 {
4939         struct io_async_msghdr iomsg, *kmsg;
4940         struct io_sr_msg *sr = &req->sr_msg;
4941         struct socket *sock;
4942         unsigned flags;
4943         int min_ret = 0;
4944         int ret;
4945
4946         sock = sock_from_file(req->file);
4947         if (unlikely(!sock))
4948                 return -ENOTSOCK;
4949
4950         kmsg = req->async_data;
4951         if (!kmsg) {
4952                 ret = io_sendmsg_copy_hdr(req, &iomsg);
4953                 if (ret)
4954                         return ret;
4955                 kmsg = &iomsg;
4956         } else {
4957                 kmsg->msg.msg_control = sr->msg_control;
4958         }
4959
4960         flags = req->sr_msg.msg_flags;
4961         if (issue_flags & IO_URING_F_NONBLOCK)
4962                 flags |= MSG_DONTWAIT;
4963         if (flags & MSG_WAITALL)
4964                 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4965
4966         ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4967
4968         if (ret < min_ret) {
4969                 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4970                         return io_setup_async_msg(req, kmsg);
4971                 if (ret == -ERESTARTSYS)
4972                         ret = -EINTR;
4973                 if (ret > 0 && io_net_retry(sock, flags)) {
4974                         kmsg->msg.msg_controllen = 0;
4975                         kmsg->msg.msg_control = NULL;
4976                         sr->done_io += ret;
4977                         req->flags |= REQ_F_PARTIAL_IO;
4978                         return io_setup_async_msg(req, kmsg);
4979                 }
4980                 req_set_fail(req);
4981         }
4982         /* fast path, check for non-NULL to avoid function call */
4983         if (kmsg->free_iov)
4984                 kfree(kmsg->free_iov);
4985         req->flags &= ~REQ_F_NEED_CLEANUP;
4986         if (ret >= 0)
4987                 ret += sr->done_io;
4988         else if (sr->done_io)
4989                 ret = sr->done_io;
4990         __io_req_complete(req, issue_flags, ret, 0);
4991         return 0;
4992 }
4993
4994 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4995 {
4996         struct io_sr_msg *sr = &req->sr_msg;
4997         struct msghdr msg;
4998         struct iovec iov;
4999         struct socket *sock;
5000         unsigned flags;
5001         int min_ret = 0;
5002         int ret;
5003
5004         sock = sock_from_file(req->file);
5005         if (unlikely(!sock))
5006                 return -ENOTSOCK;
5007
5008         ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5009         if (unlikely(ret))
5010                 return ret;
5011
5012         msg.msg_name = NULL;
5013         msg.msg_control = NULL;
5014         msg.msg_controllen = 0;
5015         msg.msg_namelen = 0;
5016
5017         flags = req->sr_msg.msg_flags;
5018         if (issue_flags & IO_URING_F_NONBLOCK)
5019                 flags |= MSG_DONTWAIT;
5020         if (flags & MSG_WAITALL)
5021                 min_ret = iov_iter_count(&msg.msg_iter);
5022
5023         msg.msg_flags = flags;
5024         ret = sock_sendmsg(sock, &msg);
5025         if (ret < min_ret) {
5026                 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5027                         return -EAGAIN;
5028                 if (ret == -ERESTARTSYS)
5029                         ret = -EINTR;
5030                 if (ret > 0 && io_net_retry(sock, flags)) {
5031                         sr->len -= ret;
5032                         sr->buf += ret;
5033                         sr->done_io += ret;
5034                         req->flags |= REQ_F_PARTIAL_IO;
5035                         return -EAGAIN;
5036                 }
5037                 req_set_fail(req);
5038         }
5039         if (ret >= 0)
5040                 ret += sr->done_io;
5041         else if (sr->done_io)
5042                 ret = sr->done_io;
5043         __io_req_complete(req, issue_flags, ret, 0);
5044         return 0;
5045 }
5046
5047 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5048                                  struct io_async_msghdr *iomsg)
5049 {
5050         struct io_sr_msg *sr = &req->sr_msg;
5051         struct iovec __user *uiov;
5052         size_t iov_len;
5053         int ret;
5054
5055         ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5056                                         &iomsg->uaddr, &uiov, &iov_len);
5057         if (ret)
5058                 return ret;
5059
5060         if (req->flags & REQ_F_BUFFER_SELECT) {
5061                 if (iov_len > 1)
5062                         return -EINVAL;
5063                 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5064                         return -EFAULT;
5065                 sr->len = iomsg->fast_iov[0].iov_len;
5066                 iomsg->free_iov = NULL;
5067         } else {
5068                 iomsg->free_iov = iomsg->fast_iov;
5069                 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5070                                      &iomsg->free_iov, &iomsg->msg.msg_iter,
5071                                      false);
5072                 if (ret > 0)
5073                         ret = 0;
5074         }
5075
5076         return ret;
5077 }
5078
5079 #ifdef CONFIG_COMPAT
5080 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5081                                         struct io_async_msghdr *iomsg)
5082 {
5083         struct io_sr_msg *sr = &req->sr_msg;
5084         struct compat_iovec __user *uiov;
5085         compat_uptr_t ptr;
5086         compat_size_t len;
5087         int ret;
5088
5089         ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5090                                   &ptr, &len);
5091         if (ret)
5092                 return ret;
5093
5094         uiov = compat_ptr(ptr);
5095         if (req->flags & REQ_F_BUFFER_SELECT) {
5096                 compat_ssize_t clen;
5097
5098                 if (len > 1)
5099                         return -EINVAL;
5100                 if (!access_ok(uiov, sizeof(*uiov)))
5101                         return -EFAULT;
5102                 if (__get_user(clen, &uiov->iov_len))
5103                         return -EFAULT;
5104                 if (clen < 0)
5105                         return -EINVAL;
5106                 sr->len = clen;
5107                 iomsg->free_iov = NULL;
5108         } else {
5109                 iomsg->free_iov = iomsg->fast_iov;
5110                 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5111                                    UIO_FASTIOV, &iomsg->free_iov,
5112                                    &iomsg->msg.msg_iter, true);
5113                 if (ret < 0)
5114                         return ret;
5115         }
5116
5117         return 0;
5118 }
5119 #endif
5120
5121 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5122                                struct io_async_msghdr *iomsg)
5123 {
5124         iomsg->msg.msg_name = &iomsg->addr;
5125
5126 #ifdef CONFIG_COMPAT
5127         if (req->ctx->compat)
5128                 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5129 #endif
5130
5131         return __io_recvmsg_copy_hdr(req, iomsg);
5132 }
5133
5134 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5135                                                bool needs_lock)
5136 {
5137         struct io_sr_msg *sr = &req->sr_msg;
5138         struct io_buffer *kbuf;
5139
5140         kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
5141         if (IS_ERR(kbuf))
5142                 return kbuf;
5143
5144         sr->kbuf = kbuf;
5145         req->flags |= REQ_F_BUFFER_SELECTED;
5146         return kbuf;
5147 }
5148
5149 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
5150 {
5151         return io_put_kbuf(req, req->sr_msg.kbuf);
5152 }
5153
5154 static int io_recvmsg_prep_async(struct io_kiocb *req)
5155 {
5156         int ret;
5157
5158         ret = io_recvmsg_copy_hdr(req, req->async_data);
5159         if (!ret)
5160                 req->flags |= REQ_F_NEED_CLEANUP;
5161         return ret;
5162 }
5163
5164 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5165 {
5166         struct io_sr_msg *sr = &req->sr_msg;
5167
5168         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5169                 return -EINVAL;
5170         if (unlikely(sqe->addr2 || sqe->file_index))
5171                 return -EINVAL;
5172         if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
5173                 return -EINVAL;
5174
5175         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5176         sr->len = READ_ONCE(sqe->len);
5177         sr->bgid = READ_ONCE(sqe->buf_group);
5178         sr->msg_flags = READ_ONCE(sqe->msg_flags);
5179         if (sr->msg_flags & MSG_DONTWAIT)
5180                 req->flags |= REQ_F_NOWAIT;
5181
5182 #ifdef CONFIG_COMPAT
5183         if (req->ctx->compat)
5184                 sr->msg_flags |= MSG_CMSG_COMPAT;
5185 #endif
5186         sr->done_io = 0;
5187         return 0;
5188 }
5189
5190 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5191 {
5192         struct io_async_msghdr iomsg, *kmsg;
5193         struct io_sr_msg *sr = &req->sr_msg;
5194         struct socket *sock;
5195         struct io_buffer *kbuf;
5196         unsigned flags;
5197         int min_ret = 0;
5198         int ret, cflags = 0;
5199         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5200
5201         sock = sock_from_file(req->file);
5202         if (unlikely(!sock))
5203                 return -ENOTSOCK;
5204
5205         kmsg = req->async_data;
5206         if (!kmsg) {
5207                 ret = io_recvmsg_copy_hdr(req, &iomsg);
5208                 if (ret)
5209                         return ret;
5210                 kmsg = &iomsg;
5211         }
5212
5213         if (req->flags & REQ_F_BUFFER_SELECT) {
5214                 kbuf = io_recv_buffer_select(req, !force_nonblock);
5215                 if (IS_ERR(kbuf))
5216                         return PTR_ERR(kbuf);
5217                 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5218                 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5219                 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5220                                 1, req->sr_msg.len);
5221         }
5222
5223         flags = req->sr_msg.msg_flags;
5224         if (force_nonblock)
5225                 flags |= MSG_DONTWAIT;
5226         if (flags & MSG_WAITALL && !kmsg->msg.msg_controllen)
5227                 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5228
5229         ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5230                                         kmsg->uaddr, flags);
5231         if (ret < min_ret) {
5232                 if (ret == -EAGAIN && force_nonblock)
5233                         return io_setup_async_msg(req, kmsg);
5234                 if (ret == -ERESTARTSYS)
5235                         ret = -EINTR;
5236                 if (ret > 0 && io_net_retry(sock, flags)) {
5237                         sr->done_io += ret;
5238                         req->flags |= REQ_F_PARTIAL_IO;
5239                         return io_setup_async_msg(req, kmsg);
5240                 }
5241                 req_set_fail(req);
5242         } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5243                 req_set_fail(req);
5244         }
5245
5246         if (req->flags & REQ_F_BUFFER_SELECTED)
5247                 cflags = io_put_recv_kbuf(req);
5248         /* fast path, check for non-NULL to avoid function call */
5249         if (kmsg->free_iov)
5250                 kfree(kmsg->free_iov);
5251         req->flags &= ~REQ_F_NEED_CLEANUP;
5252         if (ret >= 0)
5253                 ret += sr->done_io;
5254         else if (sr->done_io)
5255                 ret = sr->done_io;
5256         __io_req_complete(req, issue_flags, ret, cflags);
5257         return 0;
5258 }
5259
5260 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5261 {
5262         struct io_buffer *kbuf;
5263         struct io_sr_msg *sr = &req->sr_msg;
5264         struct msghdr msg;
5265         void __user *buf = sr->buf;
5266         struct socket *sock;
5267         struct iovec iov;
5268         unsigned flags;
5269         int min_ret = 0;
5270         int ret, cflags = 0;
5271         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5272
5273         sock = sock_from_file(req->file);
5274         if (unlikely(!sock))
5275                 return -ENOTSOCK;
5276
5277         if (req->flags & REQ_F_BUFFER_SELECT) {
5278                 kbuf = io_recv_buffer_select(req, !force_nonblock);
5279                 if (IS_ERR(kbuf))
5280                         return PTR_ERR(kbuf);
5281                 buf = u64_to_user_ptr(kbuf->addr);
5282         }
5283
5284         ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5285         if (unlikely(ret))
5286                 goto out_free;
5287
5288         msg.msg_name = NULL;
5289         msg.msg_control = NULL;
5290         msg.msg_controllen = 0;
5291         msg.msg_namelen = 0;
5292         msg.msg_iocb = NULL;
5293         msg.msg_flags = 0;
5294
5295         flags = req->sr_msg.msg_flags;
5296         if (force_nonblock)
5297                 flags |= MSG_DONTWAIT;
5298         if (flags & MSG_WAITALL)
5299                 min_ret = iov_iter_count(&msg.msg_iter);
5300
5301         ret = sock_recvmsg(sock, &msg, flags);
5302         if (ret < min_ret) {
5303                 if (ret == -EAGAIN && force_nonblock)
5304                         return -EAGAIN;
5305                 if (ret == -ERESTARTSYS)
5306                         ret = -EINTR;
5307                 if (ret > 0 && io_net_retry(sock, flags)) {
5308                         sr->len -= ret;
5309                         sr->buf += ret;
5310                         sr->done_io += ret;
5311                         req->flags |= REQ_F_PARTIAL_IO;
5312                         return -EAGAIN;
5313                 }
5314                 req_set_fail(req);
5315         } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5316 out_free:
5317                 req_set_fail(req);
5318         }
5319         if (req->flags & REQ_F_BUFFER_SELECTED)
5320                 cflags = io_put_recv_kbuf(req);
5321         if (ret >= 0)
5322                 ret += sr->done_io;
5323         else if (sr->done_io)
5324                 ret = sr->done_io;
5325         __io_req_complete(req, issue_flags, ret, cflags);
5326         return 0;
5327 }
5328
5329 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5330 {
5331         struct io_accept *accept = &req->accept;
5332
5333         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5334                 return -EINVAL;
5335         if (sqe->ioprio || sqe->len || sqe->buf_index)
5336                 return -EINVAL;
5337
5338         accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5339         accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5340         accept->flags = READ_ONCE(sqe->accept_flags);
5341         accept->nofile = rlimit(RLIMIT_NOFILE);
5342
5343         accept->file_slot = READ_ONCE(sqe->file_index);
5344         if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5345                 return -EINVAL;
5346         if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5347                 return -EINVAL;
5348         if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5349                 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5350         return 0;
5351 }
5352
5353 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5354 {
5355         struct io_accept *accept = &req->accept;
5356         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5357         unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5358         bool fixed = !!accept->file_slot;
5359         struct file *file;
5360         int ret, fd;
5361
5362         if (!fixed) {
5363                 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5364                 if (unlikely(fd < 0))
5365                         return fd;
5366         }
5367         file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5368                          accept->flags);
5369         if (IS_ERR(file)) {
5370                 if (!fixed)
5371                         put_unused_fd(fd);
5372                 ret = PTR_ERR(file);
5373                 /* safe to retry */
5374                 req->flags |= REQ_F_PARTIAL_IO;
5375                 if (ret == -EAGAIN && force_nonblock)
5376                         return -EAGAIN;
5377                 if (ret == -ERESTARTSYS)
5378                         ret = -EINTR;
5379                 req_set_fail(req);
5380         } else if (!fixed) {
5381                 fd_install(fd, file);
5382                 ret = fd;
5383         } else {
5384                 ret = io_install_fixed_file(req, file, issue_flags,
5385                                             accept->file_slot - 1);
5386         }
5387         __io_req_complete(req, issue_flags, ret, 0);
5388         return 0;
5389 }
5390
5391 static int io_connect_prep_async(struct io_kiocb *req)
5392 {
5393         struct io_async_connect *io = req->async_data;
5394         struct io_connect *conn = &req->connect;
5395
5396         return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5397 }
5398
5399 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5400 {
5401         struct io_connect *conn = &req->connect;
5402
5403         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5404                 return -EINVAL;
5405         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5406             sqe->splice_fd_in)
5407                 return -EINVAL;
5408
5409         conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5410         conn->addr_len =  READ_ONCE(sqe->addr2);
5411         return 0;
5412 }
5413
5414 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5415 {
5416         struct io_async_connect __io, *io;
5417         unsigned file_flags;
5418         int ret;
5419         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5420
5421         if (req->async_data) {
5422                 io = req->async_data;
5423         } else {
5424                 ret = move_addr_to_kernel(req->connect.addr,
5425                                                 req->connect.addr_len,
5426                                                 &__io.address);
5427                 if (ret)
5428                         goto out;
5429                 io = &__io;
5430         }
5431
5432         file_flags = force_nonblock ? O_NONBLOCK : 0;
5433
5434         ret = __sys_connect_file(req->file, &io->address,
5435                                         req->connect.addr_len, file_flags);
5436         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5437                 if (req->async_data)
5438                         return -EAGAIN;
5439                 if (io_alloc_async_data(req)) {
5440                         ret = -ENOMEM;
5441                         goto out;
5442                 }
5443                 memcpy(req->async_data, &__io, sizeof(__io));
5444                 return -EAGAIN;
5445         }
5446         if (ret == -ERESTARTSYS)
5447                 ret = -EINTR;
5448 out:
5449         if (ret < 0)
5450                 req_set_fail(req);
5451         __io_req_complete(req, issue_flags, ret, 0);
5452         return 0;
5453 }
5454 #else /* !CONFIG_NET */
5455 #define IO_NETOP_FN(op)                                                 \
5456 static int io_##op(struct io_kiocb *req, unsigned int issue_flags)      \
5457 {                                                                       \
5458         return -EOPNOTSUPP;                                             \
5459 }
5460
5461 #define IO_NETOP_PREP(op)                                               \
5462 IO_NETOP_FN(op)                                                         \
5463 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5464 {                                                                       \
5465         return -EOPNOTSUPP;                                             \
5466 }                                                                       \
5467
5468 #define IO_NETOP_PREP_ASYNC(op)                                         \
5469 IO_NETOP_PREP(op)                                                       \
5470 static int io_##op##_prep_async(struct io_kiocb *req)                   \
5471 {                                                                       \
5472         return -EOPNOTSUPP;                                             \
5473 }
5474
5475 IO_NETOP_PREP_ASYNC(sendmsg);
5476 IO_NETOP_PREP_ASYNC(recvmsg);
5477 IO_NETOP_PREP_ASYNC(connect);
5478 IO_NETOP_PREP(accept);
5479 IO_NETOP_FN(send);
5480 IO_NETOP_FN(recv);
5481 #endif /* CONFIG_NET */
5482
5483 struct io_poll_table {
5484         struct poll_table_struct pt;
5485         struct io_kiocb *req;
5486         int nr_entries;
5487         int error;
5488 };
5489
5490 #define IO_POLL_CANCEL_FLAG     BIT(31)
5491 #define IO_POLL_RETRY_FLAG      BIT(30)
5492 #define IO_POLL_REF_MASK        GENMASK(29, 0)
5493
5494 /*
5495  * We usually have 1-2 refs taken, 128 is more than enough and we want to
5496  * maximise the margin between this amount and the moment when it overflows.
5497  */
5498 #define IO_POLL_REF_BIAS       128
5499
5500 static bool io_poll_get_ownership_slowpath(struct io_kiocb *req)
5501 {
5502         int v;
5503
5504         /*
5505          * poll_refs are already elevated and we don't have much hope for
5506          * grabbing the ownership. Instead of incrementing set a retry flag
5507          * to notify the loop that there might have been some change.
5508          */
5509         v = atomic_fetch_or(IO_POLL_RETRY_FLAG, &req->poll_refs);
5510         if (v & IO_POLL_REF_MASK)
5511                 return false;
5512         return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5513 }
5514
5515 /*
5516  * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5517  * bump it and acquire ownership. It's disallowed to modify requests while not
5518  * owning it, that prevents from races for enqueueing task_work's and b/w
5519  * arming poll and wakeups.
5520  */
5521 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5522 {
5523         if (unlikely(atomic_read(&req->poll_refs) >= IO_POLL_REF_BIAS))
5524                 return io_poll_get_ownership_slowpath(req);
5525         return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5526 }
5527
5528 static void io_poll_mark_cancelled(struct io_kiocb *req)
5529 {
5530         atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5531 }
5532
5533 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5534 {
5535         /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5536         if (req->opcode == IORING_OP_POLL_ADD)
5537                 return req->async_data;
5538         return req->apoll->double_poll;
5539 }
5540
5541 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5542 {
5543         if (req->opcode == IORING_OP_POLL_ADD)
5544                 return &req->poll;
5545         return &req->apoll->poll;
5546 }
5547
5548 static void io_poll_req_insert(struct io_kiocb *req)
5549 {
5550         struct io_ring_ctx *ctx = req->ctx;
5551         struct hlist_head *list;
5552
5553         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5554         hlist_add_head(&req->hash_node, list);
5555 }
5556
5557 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5558                               wait_queue_func_t wake_func)
5559 {
5560         poll->head = NULL;
5561 #define IO_POLL_UNMASK  (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5562         /* mask in events that we always want/need */
5563         poll->events = events | IO_POLL_UNMASK;
5564         INIT_LIST_HEAD(&poll->wait.entry);
5565         init_waitqueue_func_entry(&poll->wait, wake_func);
5566 }
5567
5568 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5569 {
5570         struct wait_queue_head *head = smp_load_acquire(&poll->head);
5571
5572         if (head) {
5573                 spin_lock_irq(&head->lock);
5574                 list_del_init(&poll->wait.entry);
5575                 poll->head = NULL;
5576                 spin_unlock_irq(&head->lock);
5577         }
5578 }
5579
5580 static void io_poll_remove_entries(struct io_kiocb *req)
5581 {
5582         struct io_poll_iocb *poll = io_poll_get_single(req);
5583         struct io_poll_iocb *poll_double = io_poll_get_double(req);
5584
5585         /*
5586          * While we hold the waitqueue lock and the waitqueue is nonempty,
5587          * wake_up_pollfree() will wait for us.  However, taking the waitqueue
5588          * lock in the first place can race with the waitqueue being freed.
5589          *
5590          * We solve this as eventpoll does: by taking advantage of the fact that
5591          * all users of wake_up_pollfree() will RCU-delay the actual free.  If
5592          * we enter rcu_read_lock() and see that the pointer to the queue is
5593          * non-NULL, we can then lock it without the memory being freed out from
5594          * under us.
5595          *
5596          * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5597          * case the caller deletes the entry from the queue, leaving it empty.
5598          * In that case, only RCU prevents the queue memory from being freed.
5599          */
5600         rcu_read_lock();
5601         io_poll_remove_entry(poll);
5602         if (poll_double)
5603                 io_poll_remove_entry(poll_double);
5604         rcu_read_unlock();
5605 }
5606
5607 /*
5608  * All poll tw should go through this. Checks for poll events, manages
5609  * references, does rewait, etc.
5610  *
5611  * Returns a negative error on failure. >0 when no action require, which is
5612  * either spurious wakeup or multishot CQE is served. 0 when it's done with
5613  * the request, then the mask is stored in req->result.
5614  */
5615 static int io_poll_check_events(struct io_kiocb *req)
5616 {
5617         struct io_ring_ctx *ctx = req->ctx;
5618         struct io_poll_iocb *poll = io_poll_get_single(req);
5619         int v;
5620
5621         /* req->task == current here, checking PF_EXITING is safe */
5622         if (unlikely(req->task->flags & PF_EXITING))
5623                 io_poll_mark_cancelled(req);
5624
5625         do {
5626                 v = atomic_read(&req->poll_refs);
5627
5628                 /* tw handler should be the owner, and so have some references */
5629                 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5630                         return 0;
5631                 if (v & IO_POLL_CANCEL_FLAG)
5632                         return -ECANCELED;
5633                 /*
5634                  * cqe.res contains only events of the first wake up
5635                  * and all others are be lost. Redo vfs_poll() to get
5636                  * up to date state.
5637                  */
5638                 if ((v & IO_POLL_REF_MASK) != 1)
5639                         req->result = 0;
5640                 if (v & IO_POLL_RETRY_FLAG) {
5641                         req->result = 0;
5642                         /*
5643                          * We won't find new events that came in between
5644                          * vfs_poll and the ref put unless we clear the
5645                          * flag in advance.
5646                          */
5647                         atomic_andnot(IO_POLL_RETRY_FLAG, &req->poll_refs);
5648                         v &= ~IO_POLL_RETRY_FLAG;
5649                 }
5650
5651                 if (!req->result) {
5652                         struct poll_table_struct pt = { ._key = poll->events };
5653
5654                         req->result = vfs_poll(req->file, &pt) & poll->events;
5655                 }
5656
5657                 /* multishot, just fill an CQE and proceed */
5658                 if (req->result && !(poll->events & EPOLLONESHOT)) {
5659                         __poll_t mask = mangle_poll(req->result & poll->events);
5660                         bool filled;
5661
5662                         spin_lock(&ctx->completion_lock);
5663                         filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5664                                                  IORING_CQE_F_MORE);
5665                         io_commit_cqring(ctx);
5666                         spin_unlock(&ctx->completion_lock);
5667                         if (unlikely(!filled))
5668                                 return -ECANCELED;
5669                         io_cqring_ev_posted(ctx);
5670                 } else if (req->result) {
5671                         return 0;
5672                 }
5673
5674                 /* force the next iteration to vfs_poll() */
5675                 req->result = 0;
5676
5677                 /*
5678                  * Release all references, retry if someone tried to restart
5679                  * task_work while we were executing it.
5680                  */
5681         } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs) &
5682                                         IO_POLL_REF_MASK);
5683
5684         return 1;
5685 }
5686
5687 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5688 {
5689         struct io_ring_ctx *ctx = req->ctx;
5690         int ret;
5691
5692         ret = io_poll_check_events(req);
5693         if (ret > 0)
5694                 return;
5695
5696         if (!ret) {
5697                 req->result = mangle_poll(req->result & req->poll.events);
5698         } else {
5699                 req->result = ret;
5700                 req_set_fail(req);
5701         }
5702
5703         io_poll_remove_entries(req);
5704         spin_lock(&ctx->completion_lock);
5705         hash_del(&req->hash_node);
5706         spin_unlock(&ctx->completion_lock);
5707         io_req_complete_post(req, req->result, 0);
5708 }
5709
5710 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5711 {
5712         struct io_ring_ctx *ctx = req->ctx;
5713         int ret;
5714
5715         ret = io_poll_check_events(req);
5716         if (ret > 0)
5717                 return;
5718
5719         io_poll_remove_entries(req);
5720         spin_lock(&ctx->completion_lock);
5721         hash_del(&req->hash_node);
5722         spin_unlock(&ctx->completion_lock);
5723
5724         if (!ret)
5725                 io_req_task_submit(req, locked);
5726         else
5727                 io_req_complete_failed(req, ret);
5728 }
5729
5730 static void __io_poll_execute(struct io_kiocb *req, int mask)
5731 {
5732         req->result = mask;
5733         if (req->opcode == IORING_OP_POLL_ADD)
5734                 req->io_task_work.func = io_poll_task_func;
5735         else
5736                 req->io_task_work.func = io_apoll_task_func;
5737
5738         trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5739         io_req_task_work_add(req);
5740 }
5741
5742 static inline void io_poll_execute(struct io_kiocb *req, int res)
5743 {
5744         if (io_poll_get_ownership(req))
5745                 __io_poll_execute(req, res);
5746 }
5747
5748 static void io_poll_cancel_req(struct io_kiocb *req)
5749 {
5750         io_poll_mark_cancelled(req);
5751         /* kick tw, which should complete the request */
5752         io_poll_execute(req, 0);
5753 }
5754
5755 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5756                         void *key)
5757 {
5758         struct io_kiocb *req = wait->private;
5759         struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5760                                                  wait);
5761         __poll_t mask = key_to_poll(key);
5762
5763         if (unlikely(mask & POLLFREE)) {
5764                 io_poll_mark_cancelled(req);
5765                 /* we have to kick tw in case it's not already */
5766                 io_poll_execute(req, 0);
5767
5768                 /*
5769                  * If the waitqueue is being freed early but someone is already
5770                  * holds ownership over it, we have to tear down the request as
5771                  * best we can. That means immediately removing the request from
5772                  * its waitqueue and preventing all further accesses to the
5773                  * waitqueue via the request.
5774                  */
5775                 list_del_init(&poll->wait.entry);
5776
5777                 /*
5778                  * Careful: this *must* be the last step, since as soon
5779                  * as req->head is NULL'ed out, the request can be
5780                  * completed and freed, since aio_poll_complete_work()
5781                  * will no longer need to take the waitqueue lock.
5782                  */
5783                 smp_store_release(&poll->head, NULL);
5784                 return 1;
5785         }
5786
5787         /* for instances that support it check for an event match first */
5788         if (mask && !(mask & poll->events))
5789                 return 0;
5790
5791         if (io_poll_get_ownership(req)) {
5792                 /*
5793                  * If we trigger a multishot poll off our own wakeup path,
5794                  * disable multishot as there is a circular dependency between
5795                  * CQ posting and triggering the event.
5796                  */
5797                 if (mask & EPOLL_URING_WAKE)
5798                         poll->events |= EPOLLONESHOT;
5799
5800                 __io_poll_execute(req, mask);
5801         }
5802         return 1;
5803 }
5804
5805 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5806                             struct wait_queue_head *head,
5807                             struct io_poll_iocb **poll_ptr)
5808 {
5809         struct io_kiocb *req = pt->req;
5810
5811         /*
5812          * The file being polled uses multiple waitqueues for poll handling
5813          * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5814          * if this happens.
5815          */
5816         if (unlikely(pt->nr_entries)) {
5817                 struct io_poll_iocb *first = poll;
5818
5819                 /* double add on the same waitqueue head, ignore */
5820                 if (first->head == head)
5821                         return;
5822                 /* already have a 2nd entry, fail a third attempt */
5823                 if (*poll_ptr) {
5824                         if ((*poll_ptr)->head == head)
5825                                 return;
5826                         pt->error = -EINVAL;
5827                         return;
5828                 }
5829
5830                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5831                 if (!poll) {
5832                         pt->error = -ENOMEM;
5833                         return;
5834                 }
5835                 io_init_poll_iocb(poll, first->events, first->wait.func);
5836                 *poll_ptr = poll;
5837         }
5838
5839         pt->nr_entries++;
5840         poll->head = head;
5841         poll->wait.private = req;
5842
5843         if (poll->events & EPOLLEXCLUSIVE)
5844                 add_wait_queue_exclusive(head, &poll->wait);
5845         else
5846                 add_wait_queue(head, &poll->wait);
5847 }
5848
5849 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5850                                struct poll_table_struct *p)
5851 {
5852         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5853
5854         __io_queue_proc(&pt->req->poll, pt, head,
5855                         (struct io_poll_iocb **) &pt->req->async_data);
5856 }
5857
5858 static int __io_arm_poll_handler(struct io_kiocb *req,
5859                                  struct io_poll_iocb *poll,
5860                                  struct io_poll_table *ipt, __poll_t mask)
5861 {
5862         struct io_ring_ctx *ctx = req->ctx;
5863
5864         INIT_HLIST_NODE(&req->hash_node);
5865         io_init_poll_iocb(poll, mask, io_poll_wake);
5866         poll->file = req->file;
5867         poll->wait.private = req;
5868
5869         ipt->pt._key = mask;
5870         ipt->req = req;
5871         ipt->error = 0;
5872         ipt->nr_entries = 0;
5873
5874         /*
5875          * Take the ownership to delay any tw execution up until we're done
5876          * with poll arming. see io_poll_get_ownership().
5877          */
5878         atomic_set(&req->poll_refs, 1);
5879         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5880
5881         if (mask && (poll->events & EPOLLONESHOT)) {
5882                 io_poll_remove_entries(req);
5883                 /* no one else has access to the req, forget about the ref */
5884                 return mask;
5885         }
5886         if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5887                 io_poll_remove_entries(req);
5888                 if (!ipt->error)
5889                         ipt->error = -EINVAL;
5890                 return 0;
5891         }
5892
5893         spin_lock(&ctx->completion_lock);
5894         io_poll_req_insert(req);
5895         spin_unlock(&ctx->completion_lock);
5896
5897         if (mask) {
5898                 /* can't multishot if failed, just queue the event we've got */
5899                 if (unlikely(ipt->error || !ipt->nr_entries)) {
5900                         poll->events |= EPOLLONESHOT;
5901                         ipt->error = 0;
5902                 }
5903                 __io_poll_execute(req, mask);
5904                 return 0;
5905         }
5906
5907         /*
5908          * Try to release ownership. If we see a change of state, e.g.
5909          * poll was waken up, queue up a tw, it'll deal with it.
5910          */
5911         if (atomic_cmpxchg(&req->poll_refs, 1, 0) != 1)
5912                 __io_poll_execute(req, 0);
5913         return 0;
5914 }
5915
5916 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5917                                struct poll_table_struct *p)
5918 {
5919         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5920         struct async_poll *apoll = pt->req->apoll;
5921
5922         __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5923 }
5924
5925 enum {
5926         IO_APOLL_OK,
5927         IO_APOLL_ABORTED,
5928         IO_APOLL_READY
5929 };
5930
5931 /*
5932  * We can't reliably detect loops in repeated poll triggers and issue
5933  * subsequently failing. But rather than fail these immediately, allow a
5934  * certain amount of retries before we give up. Given that this condition
5935  * should _rarely_ trigger even once, we should be fine with a larger value.
5936  */
5937 #define APOLL_MAX_RETRY         128
5938
5939 static int io_arm_poll_handler(struct io_kiocb *req)
5940 {
5941         const struct io_op_def *def = &io_op_defs[req->opcode];
5942         struct io_ring_ctx *ctx = req->ctx;
5943         struct async_poll *apoll;
5944         struct io_poll_table ipt;
5945         __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5946         int ret;
5947
5948         if (!req->file || !file_can_poll(req->file))
5949                 return IO_APOLL_ABORTED;
5950         if (!def->pollin && !def->pollout)
5951                 return IO_APOLL_ABORTED;
5952
5953         if (def->pollin) {
5954                 mask |= POLLIN | POLLRDNORM;
5955
5956                 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5957                 if ((req->opcode == IORING_OP_RECVMSG) &&
5958                     (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5959                         mask &= ~POLLIN;
5960         } else {
5961                 mask |= POLLOUT | POLLWRNORM;
5962         }
5963
5964         if (req->flags & REQ_F_POLLED) {
5965                 apoll = req->apoll;
5966                 kfree(apoll->double_poll);
5967                 if (unlikely(!--apoll->poll.retries)) {
5968                         apoll->double_poll = NULL;
5969                         return IO_APOLL_ABORTED;
5970                 }
5971         } else {
5972                 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5973                 if (unlikely(!apoll))
5974                         return IO_APOLL_ABORTED;
5975                 apoll->poll.retries = APOLL_MAX_RETRY;
5976         }
5977         apoll->double_poll = NULL;
5978         req->apoll = apoll;
5979         req->flags |= REQ_F_POLLED;
5980         ipt.pt._qproc = io_async_queue_proc;
5981
5982         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5983         if (ret || ipt.error)
5984                 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5985
5986         trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5987                                 mask, apoll->poll.events);
5988         return IO_APOLL_OK;
5989 }
5990
5991 /*
5992  * Returns true if we found and killed one or more poll requests
5993  */
5994 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5995                                bool cancel_all)
5996 {
5997         struct hlist_node *tmp;
5998         struct io_kiocb *req;
5999         bool found = false;
6000         int i;
6001
6002         spin_lock(&ctx->completion_lock);
6003         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6004                 struct hlist_head *list;
6005
6006                 list = &ctx->cancel_hash[i];
6007                 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6008                         if (io_match_task_safe(req, tsk, cancel_all)) {
6009                                 hlist_del_init(&req->hash_node);
6010                                 io_poll_cancel_req(req);
6011                                 found = true;
6012                         }
6013                 }
6014         }
6015         spin_unlock(&ctx->completion_lock);
6016         return found;
6017 }
6018
6019 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6020                                      bool poll_only)
6021         __must_hold(&ctx->completion_lock)
6022 {
6023         struct hlist_head *list;
6024         struct io_kiocb *req;
6025
6026         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6027         hlist_for_each_entry(req, list, hash_node) {
6028                 if (sqe_addr != req->user_data)
6029                         continue;
6030                 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6031                         continue;
6032                 return req;
6033         }
6034         return NULL;
6035 }
6036
6037 static bool io_poll_disarm(struct io_kiocb *req)
6038         __must_hold(&ctx->completion_lock)
6039 {
6040         if (!io_poll_get_ownership(req))
6041                 return false;
6042         io_poll_remove_entries(req);
6043         hash_del(&req->hash_node);
6044         return true;
6045 }
6046
6047 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6048                           bool poll_only)
6049         __must_hold(&ctx->completion_lock)
6050 {
6051         struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6052
6053         if (!req)
6054                 return -ENOENT;
6055         io_poll_cancel_req(req);
6056         return 0;
6057 }
6058
6059 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6060                                      unsigned int flags)
6061 {
6062         u32 events;
6063
6064         events = READ_ONCE(sqe->poll32_events);
6065 #ifdef __BIG_ENDIAN
6066         events = swahw32(events);
6067 #endif
6068         if (!(flags & IORING_POLL_ADD_MULTI))
6069                 events |= EPOLLONESHOT;
6070         return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6071 }
6072
6073 static int io_poll_update_prep(struct io_kiocb *req,
6074                                const struct io_uring_sqe *sqe)
6075 {
6076         struct io_poll_update *upd = &req->poll_update;
6077         u32 flags;
6078
6079         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6080                 return -EINVAL;
6081         if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6082                 return -EINVAL;
6083         flags = READ_ONCE(sqe->len);
6084         if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6085                       IORING_POLL_ADD_MULTI))
6086                 return -EINVAL;
6087         /* meaningless without update */
6088         if (flags == IORING_POLL_ADD_MULTI)
6089                 return -EINVAL;
6090
6091         upd->old_user_data = READ_ONCE(sqe->addr);
6092         upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6093         upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6094
6095         upd->new_user_data = READ_ONCE(sqe->off);
6096         if (!upd->update_user_data && upd->new_user_data)
6097                 return -EINVAL;
6098         if (upd->update_events)
6099                 upd->events = io_poll_parse_events(sqe, flags);
6100         else if (sqe->poll32_events)
6101                 return -EINVAL;
6102
6103         return 0;
6104 }
6105
6106 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6107 {
6108         struct io_poll_iocb *poll = &req->poll;
6109         u32 flags;
6110
6111         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6112                 return -EINVAL;
6113         if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6114                 return -EINVAL;
6115         flags = READ_ONCE(sqe->len);
6116         if (flags & ~IORING_POLL_ADD_MULTI)
6117                 return -EINVAL;
6118
6119         io_req_set_refcount(req);
6120         poll->events = io_poll_parse_events(sqe, flags);
6121         return 0;
6122 }
6123
6124 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6125 {
6126         struct io_poll_iocb *poll = &req->poll;
6127         struct io_poll_table ipt;
6128         int ret;
6129
6130         ipt.pt._qproc = io_poll_queue_proc;
6131
6132         ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6133         if (!ret && ipt.error)
6134                 req_set_fail(req);
6135         ret = ret ?: ipt.error;
6136         if (ret)
6137                 __io_req_complete(req, issue_flags, ret, 0);
6138         return 0;
6139 }
6140
6141 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6142 {
6143         struct io_ring_ctx *ctx = req->ctx;
6144         struct io_kiocb *preq;
6145         int ret2, ret = 0;
6146
6147         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6148
6149         spin_lock(&ctx->completion_lock);
6150         preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6151         if (!preq || !io_poll_disarm(preq)) {
6152                 spin_unlock(&ctx->completion_lock);
6153                 ret = preq ? -EALREADY : -ENOENT;
6154                 goto out;
6155         }
6156         spin_unlock(&ctx->completion_lock);
6157
6158         if (req->poll_update.update_events || req->poll_update.update_user_data) {
6159                 /* only mask one event flags, keep behavior flags */
6160                 if (req->poll_update.update_events) {
6161                         preq->poll.events &= ~0xffff;
6162                         preq->poll.events |= req->poll_update.events & 0xffff;
6163                         preq->poll.events |= IO_POLL_UNMASK;
6164                 }
6165                 if (req->poll_update.update_user_data)
6166                         preq->user_data = req->poll_update.new_user_data;
6167
6168                 ret2 = io_poll_add(preq, issue_flags);
6169                 /* successfully updated, don't complete poll request */
6170                 if (!ret2)
6171                         goto out;
6172         }
6173         req_set_fail(preq);
6174         io_req_complete(preq, -ECANCELED);
6175 out:
6176         if (ret < 0)
6177                 req_set_fail(req);
6178         /* complete update request, we're done with it */
6179         io_req_complete(req, ret);
6180         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6181         return 0;
6182 }
6183
6184 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
6185 {
6186         req_set_fail(req);
6187         io_req_complete_post(req, -ETIME, 0);
6188 }
6189
6190 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6191 {
6192         struct io_timeout_data *data = container_of(timer,
6193                                                 struct io_timeout_data, timer);
6194         struct io_kiocb *req = data->req;
6195         struct io_ring_ctx *ctx = req->ctx;
6196         unsigned long flags;
6197
6198         spin_lock_irqsave(&ctx->timeout_lock, flags);
6199         list_del_init(&req->timeout.list);
6200         atomic_set(&req->ctx->cq_timeouts,
6201                 atomic_read(&req->ctx->cq_timeouts) + 1);
6202         spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6203
6204         req->io_task_work.func = io_req_task_timeout;
6205         io_req_task_work_add(req);
6206         return HRTIMER_NORESTART;
6207 }
6208
6209 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6210                                            __u64 user_data)
6211         __must_hold(&ctx->timeout_lock)
6212 {
6213         struct io_timeout_data *io;
6214         struct io_kiocb *req;
6215         bool found = false;
6216
6217         list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6218                 found = user_data == req->user_data;
6219                 if (found)
6220                         break;
6221         }
6222         if (!found)
6223                 return ERR_PTR(-ENOENT);
6224
6225         io = req->async_data;
6226         if (hrtimer_try_to_cancel(&io->timer) == -1)
6227                 return ERR_PTR(-EALREADY);
6228         list_del_init(&req->timeout.list);
6229         return req;
6230 }
6231
6232 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6233         __must_hold(&ctx->completion_lock)
6234         __must_hold(&ctx->timeout_lock)
6235 {
6236         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6237
6238         if (IS_ERR(req))
6239                 return PTR_ERR(req);
6240
6241         req_set_fail(req);
6242         io_fill_cqe_req(req, -ECANCELED, 0);
6243         io_put_req_deferred(req);
6244         return 0;
6245 }
6246
6247 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6248 {
6249         switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6250         case IORING_TIMEOUT_BOOTTIME:
6251                 return CLOCK_BOOTTIME;
6252         case IORING_TIMEOUT_REALTIME:
6253                 return CLOCK_REALTIME;
6254         default:
6255                 /* can't happen, vetted at prep time */
6256                 WARN_ON_ONCE(1);
6257                 fallthrough;
6258         case 0:
6259                 return CLOCK_MONOTONIC;
6260         }
6261 }
6262
6263 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6264                                     struct timespec64 *ts, enum hrtimer_mode mode)
6265         __must_hold(&ctx->timeout_lock)
6266 {
6267         struct io_timeout_data *io;
6268         struct io_kiocb *req;
6269         bool found = false;
6270
6271         list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6272                 found = user_data == req->user_data;
6273                 if (found)
6274                         break;
6275         }
6276         if (!found)
6277                 return -ENOENT;
6278
6279         io = req->async_data;
6280         if (hrtimer_try_to_cancel(&io->timer) == -1)
6281                 return -EALREADY;
6282         hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6283         io->timer.function = io_link_timeout_fn;
6284         hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6285         return 0;
6286 }
6287
6288 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6289                              struct timespec64 *ts, enum hrtimer_mode mode)
6290         __must_hold(&ctx->timeout_lock)
6291 {
6292         struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6293         struct io_timeout_data *data;
6294
6295         if (IS_ERR(req))
6296                 return PTR_ERR(req);
6297
6298         req->timeout.off = 0; /* noseq */
6299         data = req->async_data;
6300         list_add_tail(&req->timeout.list, &ctx->timeout_list);
6301         hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6302         data->timer.function = io_timeout_fn;
6303         hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6304         return 0;
6305 }
6306
6307 static int io_timeout_remove_prep(struct io_kiocb *req,
6308                                   const struct io_uring_sqe *sqe)
6309 {
6310         struct io_timeout_rem *tr = &req->timeout_rem;
6311
6312         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6313                 return -EINVAL;
6314         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6315                 return -EINVAL;
6316         if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6317                 return -EINVAL;
6318
6319         tr->ltimeout = false;
6320         tr->addr = READ_ONCE(sqe->addr);
6321         tr->flags = READ_ONCE(sqe->timeout_flags);
6322         if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6323                 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6324                         return -EINVAL;
6325                 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6326                         tr->ltimeout = true;
6327                 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6328                         return -EINVAL;
6329                 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6330                         return -EFAULT;
6331         } else if (tr->flags) {
6332                 /* timeout removal doesn't support flags */
6333                 return -EINVAL;
6334         }
6335
6336         return 0;
6337 }
6338
6339 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6340 {
6341         return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6342                                             : HRTIMER_MODE_REL;
6343 }
6344
6345 /*
6346  * Remove or update an existing timeout command
6347  */
6348 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6349 {
6350         struct io_timeout_rem *tr = &req->timeout_rem;
6351         struct io_ring_ctx *ctx = req->ctx;
6352         int ret;
6353
6354         if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6355                 spin_lock(&ctx->completion_lock);
6356                 spin_lock_irq(&ctx->timeout_lock);
6357                 ret = io_timeout_cancel(ctx, tr->addr);
6358                 spin_unlock_irq(&ctx->timeout_lock);
6359                 spin_unlock(&ctx->completion_lock);
6360         } else {
6361                 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6362
6363                 spin_lock_irq(&ctx->timeout_lock);
6364                 if (tr->ltimeout)
6365                         ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6366                 else
6367                         ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6368                 spin_unlock_irq(&ctx->timeout_lock);
6369         }
6370
6371         if (ret < 0)
6372                 req_set_fail(req);
6373         io_req_complete_post(req, ret, 0);
6374         return 0;
6375 }
6376
6377 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6378                            bool is_timeout_link)
6379 {
6380         struct io_timeout_data *data;
6381         unsigned flags;
6382         u32 off = READ_ONCE(sqe->off);
6383
6384         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6385                 return -EINVAL;
6386         if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6387             sqe->splice_fd_in)
6388                 return -EINVAL;
6389         if (off && is_timeout_link)
6390                 return -EINVAL;
6391         flags = READ_ONCE(sqe->timeout_flags);
6392         if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6393                 return -EINVAL;
6394         /* more than one clock specified is invalid, obviously */
6395         if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6396                 return -EINVAL;
6397
6398         INIT_LIST_HEAD(&req->timeout.list);
6399         req->timeout.off = off;
6400         if (unlikely(off && !req->ctx->off_timeout_used))
6401                 req->ctx->off_timeout_used = true;
6402
6403         if (!req->async_data && io_alloc_async_data(req))
6404                 return -ENOMEM;
6405
6406         data = req->async_data;
6407         data->req = req;
6408         data->flags = flags;
6409
6410         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6411                 return -EFAULT;
6412
6413         INIT_LIST_HEAD(&req->timeout.list);
6414         data->mode = io_translate_timeout_mode(flags);
6415         hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6416
6417         if (is_timeout_link) {
6418                 struct io_submit_link *link = &req->ctx->submit_state.link;
6419
6420                 if (!link->head)
6421                         return -EINVAL;
6422                 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6423                         return -EINVAL;
6424                 req->timeout.head = link->last;
6425                 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6426         }
6427         return 0;
6428 }
6429
6430 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6431 {
6432         struct io_ring_ctx *ctx = req->ctx;
6433         struct io_timeout_data *data = req->async_data;
6434         struct list_head *entry;
6435         u32 tail, off = req->timeout.off;
6436
6437         spin_lock_irq(&ctx->timeout_lock);
6438
6439         /*
6440          * sqe->off holds how many events that need to occur for this
6441          * timeout event to be satisfied. If it isn't set, then this is
6442          * a pure timeout request, sequence isn't used.
6443          */
6444         if (io_is_timeout_noseq(req)) {
6445                 entry = ctx->timeout_list.prev;
6446                 goto add;
6447         }
6448
6449         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6450         req->timeout.target_seq = tail + off;
6451
6452         /* Update the last seq here in case io_flush_timeouts() hasn't.
6453          * This is safe because ->completion_lock is held, and submissions
6454          * and completions are never mixed in the same ->completion_lock section.
6455          */
6456         ctx->cq_last_tm_flush = tail;
6457
6458         /*
6459          * Insertion sort, ensuring the first entry in the list is always
6460          * the one we need first.
6461          */
6462         list_for_each_prev(entry, &ctx->timeout_list) {
6463                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6464                                                   timeout.list);
6465
6466                 if (io_is_timeout_noseq(nxt))
6467                         continue;
6468                 /* nxt.seq is behind @tail, otherwise would've been completed */
6469                 if (off >= nxt->timeout.target_seq - tail)
6470                         break;
6471         }
6472 add:
6473         list_add(&req->timeout.list, entry);
6474         data->timer.function = io_timeout_fn;
6475         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6476         spin_unlock_irq(&ctx->timeout_lock);
6477         return 0;
6478 }
6479
6480 struct io_cancel_data {
6481         struct io_ring_ctx *ctx;
6482         u64 user_data;
6483 };
6484
6485 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6486 {
6487         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6488         struct io_cancel_data *cd = data;
6489
6490         return req->ctx == cd->ctx && req->user_data == cd->user_data;
6491 }
6492
6493 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6494                                struct io_ring_ctx *ctx)
6495 {
6496         struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6497         enum io_wq_cancel cancel_ret;
6498         int ret = 0;
6499
6500         if (!tctx || !tctx->io_wq)
6501                 return -ENOENT;
6502
6503         cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6504         switch (cancel_ret) {
6505         case IO_WQ_CANCEL_OK:
6506                 ret = 0;
6507                 break;
6508         case IO_WQ_CANCEL_RUNNING:
6509                 ret = -EALREADY;
6510                 break;
6511         case IO_WQ_CANCEL_NOTFOUND:
6512                 ret = -ENOENT;
6513                 break;
6514         }
6515
6516         return ret;
6517 }
6518
6519 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6520 {
6521         struct io_ring_ctx *ctx = req->ctx;
6522         int ret;
6523
6524         WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6525
6526         ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6527         if (ret != -ENOENT)
6528                 return ret;
6529
6530         spin_lock(&ctx->completion_lock);
6531         spin_lock_irq(&ctx->timeout_lock);
6532         ret = io_timeout_cancel(ctx, sqe_addr);
6533         spin_unlock_irq(&ctx->timeout_lock);
6534         if (ret != -ENOENT)
6535                 goto out;
6536         ret = io_poll_cancel(ctx, sqe_addr, false);
6537 out:
6538         spin_unlock(&ctx->completion_lock);
6539         return ret;
6540 }
6541
6542 static int io_async_cancel_prep(struct io_kiocb *req,
6543                                 const struct io_uring_sqe *sqe)
6544 {
6545         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6546                 return -EINVAL;
6547         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6548                 return -EINVAL;
6549         if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6550             sqe->splice_fd_in)
6551                 return -EINVAL;
6552
6553         req->cancel.addr = READ_ONCE(sqe->addr);
6554         return 0;
6555 }
6556
6557 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6558 {
6559         struct io_ring_ctx *ctx = req->ctx;
6560         u64 sqe_addr = req->cancel.addr;
6561         struct io_tctx_node *node;
6562         int ret;
6563
6564         ret = io_try_cancel_userdata(req, sqe_addr);
6565         if (ret != -ENOENT)
6566                 goto done;
6567
6568         /* slow path, try all io-wq's */
6569         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6570         ret = -ENOENT;
6571         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6572                 struct io_uring_task *tctx = node->task->io_uring;
6573
6574                 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6575                 if (ret != -ENOENT)
6576                         break;
6577         }
6578         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6579 done:
6580         if (ret < 0)
6581                 req_set_fail(req);
6582         io_req_complete_post(req, ret, 0);
6583         return 0;
6584 }
6585
6586 static int io_rsrc_update_prep(struct io_kiocb *req,
6587                                 const struct io_uring_sqe *sqe)
6588 {
6589         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6590                 return -EINVAL;
6591         if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6592                 return -EINVAL;
6593
6594         req->rsrc_update.offset = READ_ONCE(sqe->off);
6595         req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6596         if (!req->rsrc_update.nr_args)
6597                 return -EINVAL;
6598         req->rsrc_update.arg = READ_ONCE(sqe->addr);
6599         return 0;
6600 }
6601
6602 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6603 {
6604         struct io_ring_ctx *ctx = req->ctx;
6605         struct io_uring_rsrc_update2 up;
6606         int ret;
6607
6608         up.offset = req->rsrc_update.offset;
6609         up.data = req->rsrc_update.arg;
6610         up.nr = 0;
6611         up.tags = 0;
6612         up.resv = 0;
6613         up.resv2 = 0;
6614
6615         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6616         ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6617                                         &up, req->rsrc_update.nr_args);
6618         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6619
6620         if (ret < 0)
6621                 req_set_fail(req);
6622         __io_req_complete(req, issue_flags, ret, 0);
6623         return 0;
6624 }
6625
6626 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6627 {
6628         switch (req->opcode) {
6629         case IORING_OP_NOP:
6630                 return 0;
6631         case IORING_OP_READV:
6632         case IORING_OP_READ_FIXED:
6633         case IORING_OP_READ:
6634                 return io_read_prep(req, sqe);
6635         case IORING_OP_WRITEV:
6636         case IORING_OP_WRITE_FIXED:
6637         case IORING_OP_WRITE:
6638                 return io_write_prep(req, sqe);
6639         case IORING_OP_POLL_ADD:
6640                 return io_poll_add_prep(req, sqe);
6641         case IORING_OP_POLL_REMOVE:
6642                 return io_poll_update_prep(req, sqe);
6643         case IORING_OP_FSYNC:
6644                 return io_fsync_prep(req, sqe);
6645         case IORING_OP_SYNC_FILE_RANGE:
6646                 return io_sfr_prep(req, sqe);
6647         case IORING_OP_SENDMSG:
6648         case IORING_OP_SEND:
6649                 return io_sendmsg_prep(req, sqe);
6650         case IORING_OP_RECVMSG:
6651         case IORING_OP_RECV:
6652                 return io_recvmsg_prep(req, sqe);
6653         case IORING_OP_CONNECT:
6654                 return io_connect_prep(req, sqe);
6655         case IORING_OP_TIMEOUT:
6656                 return io_timeout_prep(req, sqe, false);
6657         case IORING_OP_TIMEOUT_REMOVE:
6658                 return io_timeout_remove_prep(req, sqe);
6659         case IORING_OP_ASYNC_CANCEL:
6660                 return io_async_cancel_prep(req, sqe);
6661         case IORING_OP_LINK_TIMEOUT:
6662                 return io_timeout_prep(req, sqe, true);
6663         case IORING_OP_ACCEPT:
6664                 return io_accept_prep(req, sqe);
6665         case IORING_OP_FALLOCATE:
6666                 return io_fallocate_prep(req, sqe);
6667         case IORING_OP_OPENAT:
6668                 return io_openat_prep(req, sqe);
6669         case IORING_OP_CLOSE:
6670                 return io_close_prep(req, sqe);
6671         case IORING_OP_FILES_UPDATE:
6672                 return io_rsrc_update_prep(req, sqe);
6673         case IORING_OP_STATX:
6674                 return io_statx_prep(req, sqe);
6675         case IORING_OP_FADVISE:
6676                 return io_fadvise_prep(req, sqe);
6677         case IORING_OP_MADVISE:
6678                 return io_madvise_prep(req, sqe);
6679         case IORING_OP_OPENAT2:
6680                 return io_openat2_prep(req, sqe);
6681         case IORING_OP_EPOLL_CTL:
6682                 return io_epoll_ctl_prep(req, sqe);
6683         case IORING_OP_SPLICE:
6684                 return io_splice_prep(req, sqe);
6685         case IORING_OP_PROVIDE_BUFFERS:
6686                 return io_provide_buffers_prep(req, sqe);
6687         case IORING_OP_REMOVE_BUFFERS:
6688                 return io_remove_buffers_prep(req, sqe);
6689         case IORING_OP_TEE:
6690                 return io_tee_prep(req, sqe);
6691         case IORING_OP_SHUTDOWN:
6692                 return io_shutdown_prep(req, sqe);
6693         case IORING_OP_RENAMEAT:
6694                 return io_renameat_prep(req, sqe);
6695         case IORING_OP_UNLINKAT:
6696                 return io_unlinkat_prep(req, sqe);
6697         case IORING_OP_MKDIRAT:
6698                 return io_mkdirat_prep(req, sqe);
6699         case IORING_OP_SYMLINKAT:
6700                 return io_symlinkat_prep(req, sqe);
6701         case IORING_OP_LINKAT:
6702                 return io_linkat_prep(req, sqe);
6703         }
6704
6705         printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6706                         req->opcode);
6707         return -EINVAL;
6708 }
6709
6710 static int io_req_prep_async(struct io_kiocb *req)
6711 {
6712         if (!io_op_defs[req->opcode].needs_async_setup)
6713                 return 0;
6714         if (WARN_ON_ONCE(req->async_data))
6715                 return -EFAULT;
6716         if (io_alloc_async_data(req))
6717                 return -EAGAIN;
6718
6719         switch (req->opcode) {
6720         case IORING_OP_READV:
6721                 return io_rw_prep_async(req, READ);
6722         case IORING_OP_WRITEV:
6723                 return io_rw_prep_async(req, WRITE);
6724         case IORING_OP_SENDMSG:
6725                 return io_sendmsg_prep_async(req);
6726         case IORING_OP_RECVMSG:
6727                 return io_recvmsg_prep_async(req);
6728         case IORING_OP_CONNECT:
6729                 return io_connect_prep_async(req);
6730         }
6731         printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6732                     req->opcode);
6733         return -EFAULT;
6734 }
6735
6736 static u32 io_get_sequence(struct io_kiocb *req)
6737 {
6738         u32 seq = req->ctx->cached_sq_head;
6739
6740         /* need original cached_sq_head, but it was increased for each req */
6741         io_for_each_link(req, req)
6742                 seq--;
6743         return seq;
6744 }
6745
6746 static bool io_drain_req(struct io_kiocb *req)
6747 {
6748         struct io_kiocb *pos;
6749         struct io_ring_ctx *ctx = req->ctx;
6750         struct io_defer_entry *de;
6751         int ret;
6752         u32 seq;
6753
6754         if (req->flags & REQ_F_FAIL) {
6755                 io_req_complete_fail_submit(req);
6756                 return true;
6757         }
6758
6759         /*
6760          * If we need to drain a request in the middle of a link, drain the
6761          * head request and the next request/link after the current link.
6762          * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6763          * maintained for every request of our link.
6764          */
6765         if (ctx->drain_next) {
6766                 req->flags |= REQ_F_IO_DRAIN;
6767                 ctx->drain_next = false;
6768         }
6769         /* not interested in head, start from the first linked */
6770         io_for_each_link(pos, req->link) {
6771                 if (pos->flags & REQ_F_IO_DRAIN) {
6772                         ctx->drain_next = true;
6773                         req->flags |= REQ_F_IO_DRAIN;
6774                         break;
6775                 }
6776         }
6777
6778         /* Still need defer if there is pending req in defer list. */
6779         spin_lock(&ctx->completion_lock);
6780         if (likely(list_empty_careful(&ctx->defer_list) &&
6781                 !(req->flags & REQ_F_IO_DRAIN))) {
6782                 spin_unlock(&ctx->completion_lock);
6783                 ctx->drain_active = false;
6784                 return false;
6785         }
6786         spin_unlock(&ctx->completion_lock);
6787
6788         seq = io_get_sequence(req);
6789         /* Still a chance to pass the sequence check */
6790         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6791                 return false;
6792
6793         ret = io_req_prep_async(req);
6794         if (ret)
6795                 goto fail;
6796         io_prep_async_link(req);
6797         de = kmalloc(sizeof(*de), GFP_KERNEL);
6798         if (!de) {
6799                 ret = -ENOMEM;
6800 fail:
6801                 io_req_complete_failed(req, ret);
6802                 return true;
6803         }
6804
6805         spin_lock(&ctx->completion_lock);
6806         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6807                 spin_unlock(&ctx->completion_lock);
6808                 kfree(de);
6809                 io_queue_async_work(req, NULL);
6810                 return true;
6811         }
6812
6813         trace_io_uring_defer(ctx, req, req->user_data);
6814         de->req = req;
6815         de->seq = seq;
6816         list_add_tail(&de->list, &ctx->defer_list);
6817         spin_unlock(&ctx->completion_lock);
6818         return true;
6819 }
6820
6821 static void io_clean_op(struct io_kiocb *req)
6822 {
6823         if (req->flags & REQ_F_BUFFER_SELECTED) {
6824                 switch (req->opcode) {
6825                 case IORING_OP_READV:
6826                 case IORING_OP_READ_FIXED:
6827                 case IORING_OP_READ:
6828                         kfree((void *)(unsigned long)req->rw.addr);
6829                         break;
6830                 case IORING_OP_RECVMSG:
6831                 case IORING_OP_RECV:
6832                         kfree(req->sr_msg.kbuf);
6833                         break;
6834                 }
6835         }
6836
6837         if (req->flags & REQ_F_NEED_CLEANUP) {
6838                 switch (req->opcode) {
6839                 case IORING_OP_READV:
6840                 case IORING_OP_READ_FIXED:
6841                 case IORING_OP_READ:
6842                 case IORING_OP_WRITEV:
6843                 case IORING_OP_WRITE_FIXED:
6844                 case IORING_OP_WRITE: {
6845                         struct io_async_rw *io = req->async_data;
6846
6847                         kfree(io->free_iovec);
6848                         break;
6849                         }
6850                 case IORING_OP_RECVMSG:
6851                 case IORING_OP_SENDMSG: {
6852                         struct io_async_msghdr *io = req->async_data;
6853
6854                         kfree(io->free_iov);
6855                         break;
6856                         }
6857                 case IORING_OP_OPENAT:
6858                 case IORING_OP_OPENAT2:
6859                         if (req->open.filename)
6860                                 putname(req->open.filename);
6861                         break;
6862                 case IORING_OP_RENAMEAT:
6863                         putname(req->rename.oldpath);
6864                         putname(req->rename.newpath);
6865                         break;
6866                 case IORING_OP_UNLINKAT:
6867                         putname(req->unlink.filename);
6868                         break;
6869                 case IORING_OP_MKDIRAT:
6870                         putname(req->mkdir.filename);
6871                         break;
6872                 case IORING_OP_SYMLINKAT:
6873                         putname(req->symlink.oldpath);
6874                         putname(req->symlink.newpath);
6875                         break;
6876                 case IORING_OP_LINKAT:
6877                         putname(req->hardlink.oldpath);
6878                         putname(req->hardlink.newpath);
6879                         break;
6880                 }
6881         }
6882         if ((req->flags & REQ_F_POLLED) && req->apoll) {
6883                 kfree(req->apoll->double_poll);
6884                 kfree(req->apoll);
6885                 req->apoll = NULL;
6886         }
6887         if (req->flags & REQ_F_INFLIGHT) {
6888                 struct io_uring_task *tctx = req->task->io_uring;
6889
6890                 atomic_dec(&tctx->inflight_tracked);
6891         }
6892         if (req->flags & REQ_F_CREDS)
6893                 put_cred(req->creds);
6894
6895         req->flags &= ~IO_REQ_CLEAN_FLAGS;
6896 }
6897
6898 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6899 {
6900         struct io_ring_ctx *ctx = req->ctx;
6901         const struct cred *creds = NULL;
6902         int ret;
6903
6904         if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6905                 creds = override_creds(req->creds);
6906
6907         switch (req->opcode) {
6908         case IORING_OP_NOP:
6909                 ret = io_nop(req, issue_flags);
6910                 break;
6911         case IORING_OP_READV:
6912         case IORING_OP_READ_FIXED:
6913         case IORING_OP_READ:
6914                 ret = io_read(req, issue_flags);
6915                 break;
6916         case IORING_OP_WRITEV:
6917         case IORING_OP_WRITE_FIXED:
6918         case IORING_OP_WRITE:
6919                 ret = io_write(req, issue_flags);
6920                 break;
6921         case IORING_OP_FSYNC:
6922                 ret = io_fsync(req, issue_flags);
6923                 break;
6924         case IORING_OP_POLL_ADD:
6925                 ret = io_poll_add(req, issue_flags);
6926                 break;
6927         case IORING_OP_POLL_REMOVE:
6928                 ret = io_poll_update(req, issue_flags);
6929                 break;
6930         case IORING_OP_SYNC_FILE_RANGE:
6931                 ret = io_sync_file_range(req, issue_flags);
6932                 break;
6933         case IORING_OP_SENDMSG:
6934                 ret = io_sendmsg(req, issue_flags);
6935                 break;
6936         case IORING_OP_SEND:
6937                 ret = io_send(req, issue_flags);
6938                 break;
6939         case IORING_OP_RECVMSG:
6940                 ret = io_recvmsg(req, issue_flags);
6941                 break;
6942         case IORING_OP_RECV:
6943                 ret = io_recv(req, issue_flags);
6944                 break;
6945         case IORING_OP_TIMEOUT:
6946                 ret = io_timeout(req, issue_flags);
6947                 break;
6948         case IORING_OP_TIMEOUT_REMOVE:
6949                 ret = io_timeout_remove(req, issue_flags);
6950                 break;
6951         case IORING_OP_ACCEPT:
6952                 ret = io_accept(req, issue_flags);
6953                 break;
6954         case IORING_OP_CONNECT:
6955                 ret = io_connect(req, issue_flags);
6956                 break;
6957         case IORING_OP_ASYNC_CANCEL:
6958                 ret = io_async_cancel(req, issue_flags);
6959                 break;
6960         case IORING_OP_FALLOCATE:
6961                 ret = io_fallocate(req, issue_flags);
6962                 break;
6963         case IORING_OP_OPENAT:
6964                 ret = io_openat(req, issue_flags);
6965                 break;
6966         case IORING_OP_CLOSE:
6967                 ret = io_close(req, issue_flags);
6968                 break;
6969         case IORING_OP_FILES_UPDATE:
6970                 ret = io_files_update(req, issue_flags);
6971                 break;
6972         case IORING_OP_STATX:
6973                 ret = io_statx(req, issue_flags);
6974                 break;
6975         case IORING_OP_FADVISE:
6976                 ret = io_fadvise(req, issue_flags);
6977                 break;
6978         case IORING_OP_MADVISE:
6979                 ret = io_madvise(req, issue_flags);
6980                 break;
6981         case IORING_OP_OPENAT2:
6982                 ret = io_openat2(req, issue_flags);
6983                 break;
6984         case IORING_OP_EPOLL_CTL:
6985                 ret = io_epoll_ctl(req, issue_flags);
6986                 break;
6987         case IORING_OP_SPLICE:
6988                 ret = io_splice(req, issue_flags);
6989                 break;
6990         case IORING_OP_PROVIDE_BUFFERS:
6991                 ret = io_provide_buffers(req, issue_flags);
6992                 break;
6993         case IORING_OP_REMOVE_BUFFERS:
6994                 ret = io_remove_buffers(req, issue_flags);
6995                 break;
6996         case IORING_OP_TEE:
6997                 ret = io_tee(req, issue_flags);
6998                 break;
6999         case IORING_OP_SHUTDOWN:
7000                 ret = io_shutdown(req, issue_flags);
7001                 break;
7002         case IORING_OP_RENAMEAT:
7003                 ret = io_renameat(req, issue_flags);
7004                 break;
7005         case IORING_OP_UNLINKAT:
7006                 ret = io_unlinkat(req, issue_flags);
7007                 break;
7008         case IORING_OP_MKDIRAT:
7009                 ret = io_mkdirat(req, issue_flags);
7010                 break;
7011         case IORING_OP_SYMLINKAT:
7012                 ret = io_symlinkat(req, issue_flags);
7013                 break;
7014         case IORING_OP_LINKAT:
7015                 ret = io_linkat(req, issue_flags);
7016                 break;
7017         default:
7018                 ret = -EINVAL;
7019                 break;
7020         }
7021
7022         if (creds)
7023                 revert_creds(creds);
7024         if (ret)
7025                 return ret;
7026         /* If the op doesn't have a file, we're not polling for it */
7027         if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7028                 io_iopoll_req_issued(req);
7029
7030         return 0;
7031 }
7032
7033 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7034 {
7035         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7036
7037         req = io_put_req_find_next(req);
7038         return req ? &req->work : NULL;
7039 }
7040
7041 static void io_wq_submit_work(struct io_wq_work *work)
7042 {
7043         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7044         struct io_kiocb *timeout;
7045         int ret = 0;
7046
7047         /* one will be dropped by ->io_free_work() after returning to io-wq */
7048         if (!(req->flags & REQ_F_REFCOUNT))
7049                 __io_req_set_refcount(req, 2);
7050         else
7051                 req_ref_get(req);
7052
7053         timeout = io_prep_linked_timeout(req);
7054         if (timeout)
7055                 io_queue_linked_timeout(timeout);
7056
7057         /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7058         if (work->flags & IO_WQ_WORK_CANCEL)
7059                 ret = -ECANCELED;
7060
7061         if (!ret) {
7062                 do {
7063                         ret = io_issue_sqe(req, 0);
7064                         /*
7065                          * We can get EAGAIN for polled IO even though we're
7066                          * forcing a sync submission from here, since we can't
7067                          * wait for request slots on the block side.
7068                          */
7069                         if (ret != -EAGAIN || !(req->ctx->flags & IORING_SETUP_IOPOLL))
7070                                 break;
7071
7072                         /*
7073                          * If REQ_F_NOWAIT is set, then don't wait or retry with
7074                          * poll. -EAGAIN is final for that case.
7075                          */
7076                         if (req->flags & REQ_F_NOWAIT)
7077                                 break;
7078
7079                         cond_resched();
7080                 } while (1);
7081         }
7082
7083         /* avoid locking problems by failing it from a clean context */
7084         if (ret)
7085                 io_req_task_queue_fail(req, ret);
7086 }
7087
7088 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7089                                                        unsigned i)
7090 {
7091         return &table->files[i];
7092 }
7093
7094 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7095                                               int index)
7096 {
7097         struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7098
7099         return (struct file *) (slot->file_ptr & FFS_MASK);
7100 }
7101
7102 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7103 {
7104         unsigned long file_ptr = (unsigned long) file;
7105
7106         if (__io_file_supports_nowait(file, READ))
7107                 file_ptr |= FFS_ASYNC_READ;
7108         if (__io_file_supports_nowait(file, WRITE))
7109                 file_ptr |= FFS_ASYNC_WRITE;
7110         if (S_ISREG(file_inode(file)->i_mode))
7111                 file_ptr |= FFS_ISREG;
7112         file_slot->file_ptr = file_ptr;
7113 }
7114
7115 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7116                                              struct io_kiocb *req, int fd,
7117                                              unsigned int issue_flags)
7118 {
7119         struct file *file = NULL;
7120         unsigned long file_ptr;
7121
7122         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
7123
7124         if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7125                 goto out;
7126         fd = array_index_nospec(fd, ctx->nr_user_files);
7127         file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7128         file = (struct file *) (file_ptr & FFS_MASK);
7129         file_ptr &= ~FFS_MASK;
7130         /* mask in overlapping REQ_F and FFS bits */
7131         req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
7132         io_req_set_rsrc_node(req);
7133 out:
7134         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
7135         return file;
7136 }
7137
7138 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7139                                        struct io_kiocb *req, int fd)
7140 {
7141         struct file *file = fget(fd);
7142
7143         trace_io_uring_file_get(ctx, fd);
7144
7145         /* we don't allow fixed io_uring files */
7146         if (file && unlikely(file->f_op == &io_uring_fops))
7147                 io_req_track_inflight(req);
7148         return file;
7149 }
7150
7151 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7152                                        struct io_kiocb *req, int fd, bool fixed,
7153                                        unsigned int issue_flags)
7154 {
7155         if (fixed)
7156                 return io_file_get_fixed(ctx, req, fd, issue_flags);
7157         else
7158                 return io_file_get_normal(ctx, req, fd);
7159 }
7160
7161 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7162 {
7163         struct io_kiocb *prev = req->timeout.prev;
7164         int ret = -ENOENT;
7165
7166         if (prev) {
7167                 if (!(req->task->flags & PF_EXITING))
7168                         ret = io_try_cancel_userdata(req, prev->user_data);
7169                 io_req_complete_post(req, ret ?: -ETIME, 0);
7170                 io_put_req(prev);
7171         } else {
7172                 io_req_complete_post(req, -ETIME, 0);
7173         }
7174 }
7175
7176 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7177 {
7178         struct io_timeout_data *data = container_of(timer,
7179                                                 struct io_timeout_data, timer);
7180         struct io_kiocb *prev, *req = data->req;
7181         struct io_ring_ctx *ctx = req->ctx;
7182         unsigned long flags;
7183
7184         spin_lock_irqsave(&ctx->timeout_lock, flags);
7185         prev = req->timeout.head;
7186         req->timeout.head = NULL;
7187
7188         /*
7189          * We don't expect the list to be empty, that will only happen if we
7190          * race with the completion of the linked work.
7191          */
7192         if (prev) {
7193                 io_remove_next_linked(prev);
7194                 if (!req_ref_inc_not_zero(prev))
7195                         prev = NULL;
7196         }
7197         list_del(&req->timeout.list);
7198         req->timeout.prev = prev;
7199         spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7200
7201         req->io_task_work.func = io_req_task_link_timeout;
7202         io_req_task_work_add(req);
7203         return HRTIMER_NORESTART;
7204 }
7205
7206 static void io_queue_linked_timeout(struct io_kiocb *req)
7207 {
7208         struct io_ring_ctx *ctx = req->ctx;
7209
7210         spin_lock_irq(&ctx->timeout_lock);
7211         /*
7212          * If the back reference is NULL, then our linked request finished
7213          * before we got a chance to setup the timer
7214          */
7215         if (req->timeout.head) {
7216                 struct io_timeout_data *data = req->async_data;
7217
7218                 data->timer.function = io_link_timeout_fn;
7219                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7220                                 data->mode);
7221                 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7222         }
7223         spin_unlock_irq(&ctx->timeout_lock);
7224         /* drop submission reference */
7225         io_put_req(req);
7226 }
7227
7228 static void __io_queue_sqe(struct io_kiocb *req)
7229         __must_hold(&req->ctx->uring_lock)
7230 {
7231         struct io_kiocb *linked_timeout;
7232         int ret;
7233
7234 issue_sqe:
7235         ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7236
7237         /*
7238          * We async punt it if the file wasn't marked NOWAIT, or if the file
7239          * doesn't support non-blocking read/write attempts
7240          */
7241         if (likely(!ret)) {
7242                 if (req->flags & REQ_F_COMPLETE_INLINE) {
7243                         struct io_ring_ctx *ctx = req->ctx;
7244                         struct io_submit_state *state = &ctx->submit_state;
7245
7246                         state->compl_reqs[state->compl_nr++] = req;
7247                         if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
7248                                 io_submit_flush_completions(ctx);
7249                         return;
7250                 }
7251
7252                 linked_timeout = io_prep_linked_timeout(req);
7253                 if (linked_timeout)
7254                         io_queue_linked_timeout(linked_timeout);
7255         } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7256                 linked_timeout = io_prep_linked_timeout(req);
7257
7258                 switch (io_arm_poll_handler(req)) {
7259                 case IO_APOLL_READY:
7260                         if (linked_timeout)
7261                                 io_queue_linked_timeout(linked_timeout);
7262                         goto issue_sqe;
7263                 case IO_APOLL_ABORTED:
7264                         /*
7265                          * Queued up for async execution, worker will release
7266                          * submit reference when the iocb is actually submitted.
7267                          */
7268                         io_queue_async_work(req, NULL);
7269                         break;
7270                 }
7271
7272                 if (linked_timeout)
7273                         io_queue_linked_timeout(linked_timeout);
7274         } else {
7275                 io_req_complete_failed(req, ret);
7276         }
7277 }
7278
7279 static inline void io_queue_sqe(struct io_kiocb *req)
7280         __must_hold(&req->ctx->uring_lock)
7281 {
7282         if (unlikely(req->ctx->drain_active) && io_drain_req(req))
7283                 return;
7284
7285         if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
7286                 __io_queue_sqe(req);
7287         } else if (req->flags & REQ_F_FAIL) {
7288                 io_req_complete_fail_submit(req);
7289         } else {
7290                 int ret = io_req_prep_async(req);
7291
7292                 if (unlikely(ret))
7293                         io_req_complete_failed(req, ret);
7294                 else
7295                         io_queue_async_work(req, NULL);
7296         }
7297 }
7298
7299 /*
7300  * Check SQE restrictions (opcode and flags).
7301  *
7302  * Returns 'true' if SQE is allowed, 'false' otherwise.
7303  */
7304 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7305                                         struct io_kiocb *req,
7306                                         unsigned int sqe_flags)
7307 {
7308         if (likely(!ctx->restricted))
7309                 return true;
7310
7311         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7312                 return false;
7313
7314         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7315             ctx->restrictions.sqe_flags_required)
7316                 return false;
7317
7318         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7319                           ctx->restrictions.sqe_flags_required))
7320                 return false;
7321
7322         return true;
7323 }
7324
7325 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7326                        const struct io_uring_sqe *sqe)
7327         __must_hold(&ctx->uring_lock)
7328 {
7329         struct io_submit_state *state;
7330         unsigned int sqe_flags;
7331         int personality, ret = 0;
7332
7333         /* req is partially pre-initialised, see io_preinit_req() */
7334         req->opcode = READ_ONCE(sqe->opcode);
7335         /* same numerical values with corresponding REQ_F_*, safe to copy */
7336         req->flags = sqe_flags = READ_ONCE(sqe->flags);
7337         req->user_data = READ_ONCE(sqe->user_data);
7338         req->file = NULL;
7339         req->fixed_rsrc_refs = NULL;
7340         req->task = current;
7341
7342         /* enforce forwards compatibility on users */
7343         if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
7344                 return -EINVAL;
7345         if (unlikely(req->opcode >= IORING_OP_LAST))
7346                 return -EINVAL;
7347         if (!io_check_restriction(ctx, req, sqe_flags))
7348                 return -EACCES;
7349
7350         if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7351             !io_op_defs[req->opcode].buffer_select)
7352                 return -EOPNOTSUPP;
7353         if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
7354                 ctx->drain_active = true;
7355
7356         personality = READ_ONCE(sqe->personality);
7357         if (personality) {
7358                 req->creds = xa_load(&ctx->personalities, personality);
7359                 if (!req->creds)
7360                         return -EINVAL;
7361                 get_cred(req->creds);
7362                 req->flags |= REQ_F_CREDS;
7363         }
7364         state = &ctx->submit_state;
7365
7366         /*
7367          * Plug now if we have more than 1 IO left after this, and the target
7368          * is potentially a read/write to block based storage.
7369          */
7370         if (!state->plug_started && state->ios_left > 1 &&
7371             io_op_defs[req->opcode].plug) {
7372                 blk_start_plug(&state->plug);
7373                 state->plug_started = true;
7374         }
7375
7376         if (io_op_defs[req->opcode].needs_file) {
7377                 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7378                                         (sqe_flags & IOSQE_FIXED_FILE),
7379                                         IO_URING_F_NONBLOCK);
7380                 if (unlikely(!req->file))
7381                         ret = -EBADF;
7382         }
7383
7384         state->ios_left--;
7385         return ret;
7386 }
7387
7388 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7389                          const struct io_uring_sqe *sqe)
7390         __must_hold(&ctx->uring_lock)
7391 {
7392         struct io_submit_link *link = &ctx->submit_state.link;
7393         int ret;
7394
7395         ret = io_init_req(ctx, req, sqe);
7396         if (unlikely(ret)) {
7397 fail_req:
7398                 /* fail even hard links since we don't submit */
7399                 if (link->head) {
7400                         /*
7401                          * we can judge a link req is failed or cancelled by if
7402                          * REQ_F_FAIL is set, but the head is an exception since
7403                          * it may be set REQ_F_FAIL because of other req's failure
7404                          * so let's leverage req->result to distinguish if a head
7405                          * is set REQ_F_FAIL because of its failure or other req's
7406                          * failure so that we can set the correct ret code for it.
7407                          * init result here to avoid affecting the normal path.
7408                          */
7409                         if (!(link->head->flags & REQ_F_FAIL))
7410                                 req_fail_link_node(link->head, -ECANCELED);
7411                 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7412                         /*
7413                          * the current req is a normal req, we should return
7414                          * error and thus break the submittion loop.
7415                          */
7416                         io_req_complete_failed(req, ret);
7417                         return ret;
7418                 }
7419                 req_fail_link_node(req, ret);
7420         } else {
7421                 ret = io_req_prep(req, sqe);
7422                 if (unlikely(ret))
7423                         goto fail_req;
7424         }
7425
7426         /* don't need @sqe from now on */
7427         trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7428                                   req->flags, true,
7429                                   ctx->flags & IORING_SETUP_SQPOLL);
7430
7431         /*
7432          * If we already have a head request, queue this one for async
7433          * submittal once the head completes. If we don't have a head but
7434          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7435          * submitted sync once the chain is complete. If none of those
7436          * conditions are true (normal request), then just queue it.
7437          */
7438         if (link->head) {
7439                 struct io_kiocb *head = link->head;
7440
7441                 if (!(req->flags & REQ_F_FAIL)) {
7442                         ret = io_req_prep_async(req);
7443                         if (unlikely(ret)) {
7444                                 req_fail_link_node(req, ret);
7445                                 if (!(head->flags & REQ_F_FAIL))
7446                                         req_fail_link_node(head, -ECANCELED);
7447                         }
7448                 }
7449                 trace_io_uring_link(ctx, req, head);
7450                 link->last->link = req;
7451                 link->last = req;
7452
7453                 /* last request of a link, enqueue the link */
7454                 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7455                         link->head = NULL;
7456                         io_queue_sqe(head);
7457                 }
7458         } else {
7459                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7460                         link->head = req;
7461                         link->last = req;
7462                 } else {
7463                         io_queue_sqe(req);
7464                 }
7465         }
7466
7467         return 0;
7468 }
7469
7470 /*
7471  * Batched submission is done, ensure local IO is flushed out.
7472  */
7473 static void io_submit_state_end(struct io_submit_state *state,
7474                                 struct io_ring_ctx *ctx)
7475 {
7476         if (state->link.head)
7477                 io_queue_sqe(state->link.head);
7478         if (state->compl_nr)
7479                 io_submit_flush_completions(ctx);
7480         if (state->plug_started)
7481                 blk_finish_plug(&state->plug);
7482 }
7483
7484 /*
7485  * Start submission side cache.
7486  */
7487 static void io_submit_state_start(struct io_submit_state *state,
7488                                   unsigned int max_ios)
7489 {
7490         state->plug_started = false;
7491         state->ios_left = max_ios;
7492         /* set only head, no need to init link_last in advance */
7493         state->link.head = NULL;
7494 }
7495
7496 static void io_commit_sqring(struct io_ring_ctx *ctx)
7497 {
7498         struct io_rings *rings = ctx->rings;
7499
7500         /*
7501          * Ensure any loads from the SQEs are done at this point,
7502          * since once we write the new head, the application could
7503          * write new data to them.
7504          */
7505         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7506 }
7507
7508 /*
7509  * Fetch an sqe, if one is available. Note this returns a pointer to memory
7510  * that is mapped by userspace. This means that care needs to be taken to
7511  * ensure that reads are stable, as we cannot rely on userspace always
7512  * being a good citizen. If members of the sqe are validated and then later
7513  * used, it's important that those reads are done through READ_ONCE() to
7514  * prevent a re-load down the line.
7515  */
7516 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7517 {
7518         unsigned head, mask = ctx->sq_entries - 1;
7519         unsigned sq_idx = ctx->cached_sq_head++ & mask;
7520
7521         /*
7522          * The cached sq head (or cq tail) serves two purposes:
7523          *
7524          * 1) allows us to batch the cost of updating the user visible
7525          *    head updates.
7526          * 2) allows the kernel side to track the head on its own, even
7527          *    though the application is the one updating it.
7528          */
7529         head = READ_ONCE(ctx->sq_array[sq_idx]);
7530         if (likely(head < ctx->sq_entries))
7531                 return &ctx->sq_sqes[head];
7532
7533         /* drop invalid entries */
7534         ctx->cq_extra--;
7535         WRITE_ONCE(ctx->rings->sq_dropped,
7536                    READ_ONCE(ctx->rings->sq_dropped) + 1);
7537         return NULL;
7538 }
7539
7540 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7541         __must_hold(&ctx->uring_lock)
7542 {
7543         int submitted = 0;
7544
7545         /* make sure SQ entry isn't read before tail */
7546         nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7547         if (!percpu_ref_tryget_many(&ctx->refs, nr))
7548                 return -EAGAIN;
7549         io_get_task_refs(nr);
7550
7551         io_submit_state_start(&ctx->submit_state, nr);
7552         while (submitted < nr) {
7553                 const struct io_uring_sqe *sqe;
7554                 struct io_kiocb *req;
7555
7556                 req = io_alloc_req(ctx);
7557                 if (unlikely(!req)) {
7558                         if (!submitted)
7559                                 submitted = -EAGAIN;
7560                         break;
7561                 }
7562                 sqe = io_get_sqe(ctx);
7563                 if (unlikely(!sqe)) {
7564                         list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7565                         break;
7566                 }
7567                 /* will complete beyond this point, count as submitted */
7568                 submitted++;
7569                 if (io_submit_sqe(ctx, req, sqe))
7570                         break;
7571         }
7572
7573         if (unlikely(submitted != nr)) {
7574                 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7575                 int unused = nr - ref_used;
7576
7577                 current->io_uring->cached_refs += unused;
7578                 percpu_ref_put_many(&ctx->refs, unused);
7579         }
7580
7581         io_submit_state_end(&ctx->submit_state, ctx);
7582          /* Commit SQ ring head once we've consumed and submitted all SQEs */
7583         io_commit_sqring(ctx);
7584
7585         return submitted;
7586 }
7587
7588 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7589 {
7590         return READ_ONCE(sqd->state);
7591 }
7592
7593 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7594 {
7595         /* Tell userspace we may need a wakeup call */
7596         spin_lock(&ctx->completion_lock);
7597         WRITE_ONCE(ctx->rings->sq_flags,
7598                    ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7599         spin_unlock(&ctx->completion_lock);
7600 }
7601
7602 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7603 {
7604         spin_lock(&ctx->completion_lock);
7605         WRITE_ONCE(ctx->rings->sq_flags,
7606                    ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7607         spin_unlock(&ctx->completion_lock);
7608 }
7609
7610 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7611 {
7612         unsigned int to_submit;
7613         int ret = 0;
7614
7615         to_submit = io_sqring_entries(ctx);
7616         /* if we're handling multiple rings, cap submit size for fairness */
7617         if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7618                 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7619
7620         if (!list_empty(&ctx->iopoll_list) || to_submit) {
7621                 unsigned nr_events = 0;
7622                 const struct cred *creds = NULL;
7623
7624                 if (ctx->sq_creds != current_cred())
7625                         creds = override_creds(ctx->sq_creds);
7626
7627                 mutex_lock(&ctx->uring_lock);
7628                 if (!list_empty(&ctx->iopoll_list))
7629                         io_do_iopoll(ctx, &nr_events, 0);
7630
7631                 /*
7632                  * Don't submit if refs are dying, good for io_uring_register(),
7633                  * but also it is relied upon by io_ring_exit_work()
7634                  */
7635                 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7636                     !(ctx->flags & IORING_SETUP_R_DISABLED))
7637                         ret = io_submit_sqes(ctx, to_submit);
7638                 mutex_unlock(&ctx->uring_lock);
7639
7640                 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7641                         wake_up(&ctx->sqo_sq_wait);
7642                 if (creds)
7643                         revert_creds(creds);
7644         }
7645
7646         return ret;
7647 }
7648
7649 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7650 {
7651         struct io_ring_ctx *ctx;
7652         unsigned sq_thread_idle = 0;
7653
7654         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7655                 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7656         sqd->sq_thread_idle = sq_thread_idle;
7657 }
7658
7659 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7660 {
7661         bool did_sig = false;
7662         struct ksignal ksig;
7663
7664         if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7665             signal_pending(current)) {
7666                 mutex_unlock(&sqd->lock);
7667                 if (signal_pending(current))
7668                         did_sig = get_signal(&ksig);
7669                 cond_resched();
7670                 mutex_lock(&sqd->lock);
7671         }
7672         return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7673 }
7674
7675 static int io_sq_thread(void *data)
7676 {
7677         struct io_sq_data *sqd = data;
7678         struct io_ring_ctx *ctx;
7679         unsigned long timeout = 0;
7680         char buf[TASK_COMM_LEN];
7681         DEFINE_WAIT(wait);
7682
7683         snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7684         set_task_comm(current, buf);
7685
7686         if (sqd->sq_cpu != -1)
7687                 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7688         else
7689                 set_cpus_allowed_ptr(current, cpu_online_mask);
7690         current->flags |= PF_NO_SETAFFINITY;
7691
7692         mutex_lock(&sqd->lock);
7693         while (1) {
7694                 bool cap_entries, sqt_spin = false;
7695
7696                 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7697                         if (io_sqd_handle_event(sqd))
7698                                 break;
7699                         timeout = jiffies + sqd->sq_thread_idle;
7700                 }
7701
7702                 cap_entries = !list_is_singular(&sqd->ctx_list);
7703                 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7704                         int ret = __io_sq_thread(ctx, cap_entries);
7705
7706                         if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7707                                 sqt_spin = true;
7708                 }
7709                 if (io_run_task_work())
7710                         sqt_spin = true;
7711
7712                 if (sqt_spin || !time_after(jiffies, timeout)) {
7713                         cond_resched();
7714                         if (sqt_spin)
7715                                 timeout = jiffies + sqd->sq_thread_idle;
7716                         continue;
7717                 }
7718
7719                 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7720                 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7721                         bool needs_sched = true;
7722
7723                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7724                                 io_ring_set_wakeup_flag(ctx);
7725
7726                                 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7727                                     !list_empty_careful(&ctx->iopoll_list)) {
7728                                         needs_sched = false;
7729                                         break;
7730                                 }
7731                                 if (io_sqring_entries(ctx)) {
7732                                         needs_sched = false;
7733                                         break;
7734                                 }
7735                         }
7736
7737                         if (needs_sched) {
7738                                 mutex_unlock(&sqd->lock);
7739                                 schedule();
7740                                 mutex_lock(&sqd->lock);
7741                         }
7742                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7743                                 io_ring_clear_wakeup_flag(ctx);
7744                 }
7745
7746                 finish_wait(&sqd->wait, &wait);
7747                 timeout = jiffies + sqd->sq_thread_idle;
7748         }
7749
7750         io_uring_cancel_generic(true, sqd);
7751         sqd->thread = NULL;
7752         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7753                 io_ring_set_wakeup_flag(ctx);
7754         io_run_task_work();
7755         mutex_unlock(&sqd->lock);
7756
7757         complete(&sqd->exited);
7758         do_exit(0);
7759 }
7760
7761 struct io_wait_queue {
7762         struct wait_queue_entry wq;
7763         struct io_ring_ctx *ctx;
7764         unsigned cq_tail;
7765         unsigned nr_timeouts;
7766 };
7767
7768 static inline bool io_should_wake(struct io_wait_queue *iowq)
7769 {
7770         struct io_ring_ctx *ctx = iowq->ctx;
7771         int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7772
7773         /*
7774          * Wake up if we have enough events, or if a timeout occurred since we
7775          * started waiting. For timeouts, we always want to return to userspace,
7776          * regardless of event count.
7777          */
7778         return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7779 }
7780
7781 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7782                             int wake_flags, void *key)
7783 {
7784         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7785                                                         wq);
7786
7787         /*
7788          * Cannot safely flush overflowed CQEs from here, ensure we wake up
7789          * the task, and the next invocation will do it.
7790          */
7791         if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7792                 return autoremove_wake_function(curr, mode, wake_flags, key);
7793         return -1;
7794 }
7795
7796 static int io_run_task_work_sig(void)
7797 {
7798         if (io_run_task_work())
7799                 return 1;
7800         if (!signal_pending(current))
7801                 return 0;
7802         if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7803                 return -ERESTARTSYS;
7804         return -EINTR;
7805 }
7806
7807 static bool current_pending_io(void)
7808 {
7809         struct io_uring_task *tctx = current->io_uring;
7810
7811         if (!tctx)
7812                 return false;
7813         return percpu_counter_read_positive(&tctx->inflight);
7814 }
7815
7816 /* when returns >0, the caller should retry */
7817 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7818                                           struct io_wait_queue *iowq,
7819                                           ktime_t *timeout)
7820 {
7821         int io_wait, ret;
7822
7823         /* make sure we run task_work before checking for signals */
7824         ret = io_run_task_work_sig();
7825         if (ret || io_should_wake(iowq))
7826                 return ret;
7827         /* let the caller flush overflows, retry */
7828         if (test_bit(0, &ctx->check_cq_overflow))
7829                 return 1;
7830
7831         /*
7832          * Mark us as being in io_wait if we have pending requests, so cpufreq
7833          * can take into account that the task is waiting for IO - turns out
7834          * to be important for low QD IO.
7835          */
7836         io_wait = current->in_iowait;
7837         if (current_pending_io())
7838                 current->in_iowait = 1;
7839         ret = 1;
7840         if (!schedule_hrtimeout(timeout, HRTIMER_MODE_ABS))
7841                 ret = -ETIME;
7842         current->in_iowait = io_wait;
7843         return ret;
7844 }
7845
7846 /*
7847  * Wait until events become available, if we don't already have some. The
7848  * application must reap them itself, as they reside on the shared cq ring.
7849  */
7850 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7851                           const sigset_t __user *sig, size_t sigsz,
7852                           struct __kernel_timespec __user *uts)
7853 {
7854         struct io_wait_queue iowq;
7855         struct io_rings *rings = ctx->rings;
7856         ktime_t timeout = KTIME_MAX;
7857         int ret;
7858
7859         do {
7860                 io_cqring_overflow_flush(ctx);
7861                 if (io_cqring_events(ctx) >= min_events)
7862                         return 0;
7863                 if (!io_run_task_work())
7864                         break;
7865         } while (1);
7866
7867         if (uts) {
7868                 struct timespec64 ts;
7869
7870                 if (get_timespec64(&ts, uts))
7871                         return -EFAULT;
7872                 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7873         }
7874
7875         if (sig) {
7876 #ifdef CONFIG_COMPAT
7877                 if (in_compat_syscall())
7878                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7879                                                       sigsz);
7880                 else
7881 #endif
7882                         ret = set_user_sigmask(sig, sigsz);
7883
7884                 if (ret)
7885                         return ret;
7886         }
7887
7888         init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7889         iowq.wq.private = current;
7890         INIT_LIST_HEAD(&iowq.wq.entry);
7891         iowq.ctx = ctx;
7892         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7893         iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7894
7895         trace_io_uring_cqring_wait(ctx, min_events);
7896         do {
7897                 /* if we can't even flush overflow, don't wait for more */
7898                 if (!io_cqring_overflow_flush(ctx)) {
7899                         ret = -EBUSY;
7900                         break;
7901                 }
7902                 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7903                                                 TASK_INTERRUPTIBLE);
7904                 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7905                 finish_wait(&ctx->cq_wait, &iowq.wq);
7906                 cond_resched();
7907         } while (ret > 0);
7908
7909         restore_saved_sigmask_unless(ret == -EINTR);
7910
7911         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7912 }
7913
7914 static void io_free_page_table(void **table, size_t size)
7915 {
7916         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7917
7918         for (i = 0; i < nr_tables; i++)
7919                 kfree(table[i]);
7920         kfree(table);
7921 }
7922
7923 static void **io_alloc_page_table(size_t size)
7924 {
7925         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7926         size_t init_size = size;
7927         void **table;
7928
7929         table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7930         if (!table)
7931                 return NULL;
7932
7933         for (i = 0; i < nr_tables; i++) {
7934                 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7935
7936                 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7937                 if (!table[i]) {
7938                         io_free_page_table(table, init_size);
7939                         return NULL;
7940                 }
7941                 size -= this_size;
7942         }
7943         return table;
7944 }
7945
7946 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7947 {
7948         percpu_ref_exit(&ref_node->refs);
7949         kfree(ref_node);
7950 }
7951
7952 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7953 {
7954         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7955         struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7956         unsigned long flags;
7957         bool first_add = false;
7958         unsigned long delay = HZ;
7959
7960         spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7961         node->done = true;
7962
7963         /* if we are mid-quiesce then do not delay */
7964         if (node->rsrc_data->quiesce)
7965                 delay = 0;
7966
7967         while (!list_empty(&ctx->rsrc_ref_list)) {
7968                 node = list_first_entry(&ctx->rsrc_ref_list,
7969                                             struct io_rsrc_node, node);
7970                 /* recycle ref nodes in order */
7971                 if (!node->done)
7972                         break;
7973                 list_del(&node->node);
7974                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7975         }
7976         spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7977
7978         if (first_add)
7979                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7980 }
7981
7982 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7983 {
7984         struct io_rsrc_node *ref_node;
7985
7986         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7987         if (!ref_node)
7988                 return NULL;
7989
7990         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7991                             0, GFP_KERNEL)) {
7992                 kfree(ref_node);
7993                 return NULL;
7994         }
7995         INIT_LIST_HEAD(&ref_node->node);
7996         INIT_LIST_HEAD(&ref_node->rsrc_list);
7997         ref_node->done = false;
7998         return ref_node;
7999 }
8000
8001 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8002                                 struct io_rsrc_data *data_to_kill)
8003 {
8004         WARN_ON_ONCE(!ctx->rsrc_backup_node);
8005         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8006
8007         if (data_to_kill) {
8008                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8009
8010                 rsrc_node->rsrc_data = data_to_kill;
8011                 spin_lock_irq(&ctx->rsrc_ref_lock);
8012                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8013                 spin_unlock_irq(&ctx->rsrc_ref_lock);
8014
8015                 atomic_inc(&data_to_kill->refs);
8016                 percpu_ref_kill(&rsrc_node->refs);
8017                 ctx->rsrc_node = NULL;
8018         }
8019
8020         if (!ctx->rsrc_node) {
8021                 ctx->rsrc_node = ctx->rsrc_backup_node;
8022                 ctx->rsrc_backup_node = NULL;
8023         }
8024 }
8025
8026 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8027 {
8028         if (ctx->rsrc_backup_node)
8029                 return 0;
8030         ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
8031         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8032 }
8033
8034 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
8035 {
8036         int ret;
8037
8038         /* As we may drop ->uring_lock, other task may have started quiesce */
8039         if (data->quiesce)
8040                 return -ENXIO;
8041
8042         data->quiesce = true;
8043         do {
8044                 ret = io_rsrc_node_switch_start(ctx);
8045                 if (ret)
8046                         break;
8047                 io_rsrc_node_switch(ctx, data);
8048
8049                 /* kill initial ref, already quiesced if zero */
8050                 if (atomic_dec_and_test(&data->refs))
8051                         break;
8052                 mutex_unlock(&ctx->uring_lock);
8053                 flush_delayed_work(&ctx->rsrc_put_work);
8054                 ret = wait_for_completion_interruptible(&data->done);
8055                 if (!ret) {
8056                         mutex_lock(&ctx->uring_lock);
8057                         if (atomic_read(&data->refs) > 0) {
8058                                 /*
8059                                  * it has been revived by another thread while
8060                                  * we were unlocked
8061                                  */
8062                                 mutex_unlock(&ctx->uring_lock);
8063                         } else {
8064                                 break;
8065                         }
8066                 }
8067
8068                 atomic_inc(&data->refs);
8069                 /* wait for all works potentially completing data->done */
8070                 flush_delayed_work(&ctx->rsrc_put_work);
8071                 reinit_completion(&data->done);
8072
8073                 ret = io_run_task_work_sig();
8074                 mutex_lock(&ctx->uring_lock);
8075         } while (ret >= 0);
8076         data->quiesce = false;
8077
8078         return ret;
8079 }
8080
8081 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8082 {
8083         unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8084         unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8085
8086         return &data->tags[table_idx][off];
8087 }
8088
8089 static void io_rsrc_data_free(struct io_rsrc_data *data)
8090 {
8091         size_t size = data->nr * sizeof(data->tags[0][0]);
8092
8093         if (data->tags)
8094                 io_free_page_table((void **)data->tags, size);
8095         kfree(data);
8096 }
8097
8098 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8099                               u64 __user *utags, unsigned nr,
8100                               struct io_rsrc_data **pdata)
8101 {
8102         struct io_rsrc_data *data;
8103         int ret = -ENOMEM;
8104         unsigned i;
8105
8106         data = kzalloc(sizeof(*data), GFP_KERNEL);
8107         if (!data)
8108                 return -ENOMEM;
8109         data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8110         if (!data->tags) {
8111                 kfree(data);
8112                 return -ENOMEM;
8113         }
8114
8115         data->nr = nr;
8116         data->ctx = ctx;
8117         data->do_put = do_put;
8118         if (utags) {
8119                 ret = -EFAULT;
8120                 for (i = 0; i < nr; i++) {
8121                         u64 *tag_slot = io_get_tag_slot(data, i);
8122
8123                         if (copy_from_user(tag_slot, &utags[i],
8124                                            sizeof(*tag_slot)))
8125                                 goto fail;
8126                 }
8127         }
8128
8129         atomic_set(&data->refs, 1);
8130         init_completion(&data->done);
8131         *pdata = data;
8132         return 0;
8133 fail:
8134         io_rsrc_data_free(data);
8135         return ret;
8136 }
8137
8138 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8139 {
8140         table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8141                                 GFP_KERNEL_ACCOUNT);
8142         return !!table->files;
8143 }
8144
8145 static void io_free_file_tables(struct io_file_table *table)
8146 {
8147         kvfree(table->files);
8148         table->files = NULL;
8149 }
8150
8151 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8152 {
8153 #if defined(CONFIG_UNIX)
8154         if (ctx->ring_sock) {
8155                 struct sock *sock = ctx->ring_sock->sk;
8156                 struct sk_buff *skb;
8157
8158                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8159                         kfree_skb(skb);
8160         }
8161 #else
8162         int i;
8163
8164         for (i = 0; i < ctx->nr_user_files; i++) {
8165                 struct file *file;
8166
8167                 file = io_file_from_index(ctx, i);
8168                 if (file)
8169                         fput(file);
8170         }
8171 #endif
8172         io_free_file_tables(&ctx->file_table);
8173         io_rsrc_data_free(ctx->file_data);
8174         ctx->file_data = NULL;
8175         ctx->nr_user_files = 0;
8176 }
8177
8178 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8179 {
8180         unsigned nr = ctx->nr_user_files;
8181         int ret;
8182
8183         if (!ctx->file_data)
8184                 return -ENXIO;
8185
8186         /*
8187          * Quiesce may unlock ->uring_lock, and while it's not held
8188          * prevent new requests using the table.
8189          */
8190         ctx->nr_user_files = 0;
8191         ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8192         ctx->nr_user_files = nr;
8193         if (!ret)
8194                 __io_sqe_files_unregister(ctx);
8195         return ret;
8196 }
8197
8198 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8199         __releases(&sqd->lock)
8200 {
8201         WARN_ON_ONCE(sqd->thread == current);
8202
8203         /*
8204          * Do the dance but not conditional clear_bit() because it'd race with
8205          * other threads incrementing park_pending and setting the bit.
8206          */
8207         clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8208         if (atomic_dec_return(&sqd->park_pending))
8209                 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8210         mutex_unlock(&sqd->lock);
8211 }
8212
8213 static void io_sq_thread_park(struct io_sq_data *sqd)
8214         __acquires(&sqd->lock)
8215 {
8216         WARN_ON_ONCE(sqd->thread == current);
8217
8218         atomic_inc(&sqd->park_pending);
8219         set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8220         mutex_lock(&sqd->lock);
8221         if (sqd->thread)
8222                 wake_up_process(sqd->thread);
8223 }
8224
8225 static void io_sq_thread_stop(struct io_sq_data *sqd)
8226 {
8227         WARN_ON_ONCE(sqd->thread == current);
8228         WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8229
8230         set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8231         mutex_lock(&sqd->lock);
8232         if (sqd->thread)
8233                 wake_up_process(sqd->thread);
8234         mutex_unlock(&sqd->lock);
8235         wait_for_completion(&sqd->exited);
8236 }
8237
8238 static void io_put_sq_data(struct io_sq_data *sqd)
8239 {
8240         if (refcount_dec_and_test(&sqd->refs)) {
8241                 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8242
8243                 io_sq_thread_stop(sqd);
8244                 kfree(sqd);
8245         }
8246 }
8247
8248 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8249 {
8250         struct io_sq_data *sqd = ctx->sq_data;
8251
8252         if (sqd) {
8253                 io_sq_thread_park(sqd);
8254                 list_del_init(&ctx->sqd_list);
8255                 io_sqd_update_thread_idle(sqd);
8256                 io_sq_thread_unpark(sqd);
8257
8258                 io_put_sq_data(sqd);
8259                 ctx->sq_data = NULL;
8260         }
8261 }
8262
8263 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8264 {
8265         struct io_ring_ctx *ctx_attach;
8266         struct io_sq_data *sqd;
8267         struct fd f;
8268
8269         f = fdget(p->wq_fd);
8270         if (!f.file)
8271                 return ERR_PTR(-ENXIO);
8272         if (f.file->f_op != &io_uring_fops) {
8273                 fdput(f);
8274                 return ERR_PTR(-EINVAL);
8275         }
8276
8277         ctx_attach = f.file->private_data;
8278         sqd = ctx_attach->sq_data;
8279         if (!sqd) {
8280                 fdput(f);
8281                 return ERR_PTR(-EINVAL);
8282         }
8283         if (sqd->task_tgid != current->tgid) {
8284                 fdput(f);
8285                 return ERR_PTR(-EPERM);
8286         }
8287
8288         refcount_inc(&sqd->refs);
8289         fdput(f);
8290         return sqd;
8291 }
8292
8293 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8294                                          bool *attached)
8295 {
8296         struct io_sq_data *sqd;
8297
8298         *attached = false;
8299         if (p->flags & IORING_SETUP_ATTACH_WQ) {
8300                 sqd = io_attach_sq_data(p);
8301                 if (!IS_ERR(sqd)) {
8302                         *attached = true;
8303                         return sqd;
8304                 }
8305                 /* fall through for EPERM case, setup new sqd/task */
8306                 if (PTR_ERR(sqd) != -EPERM)
8307                         return sqd;
8308         }
8309
8310         sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8311         if (!sqd)
8312                 return ERR_PTR(-ENOMEM);
8313
8314         atomic_set(&sqd->park_pending, 0);
8315         refcount_set(&sqd->refs, 1);
8316         INIT_LIST_HEAD(&sqd->ctx_list);
8317         mutex_init(&sqd->lock);
8318         init_waitqueue_head(&sqd->wait);
8319         init_completion(&sqd->exited);
8320         return sqd;
8321 }
8322
8323 #if defined(CONFIG_UNIX)
8324 /*
8325  * Ensure the UNIX gc is aware of our file set, so we are certain that
8326  * the io_uring can be safely unregistered on process exit, even if we have
8327  * loops in the file referencing.
8328  */
8329 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8330 {
8331         struct sock *sk = ctx->ring_sock->sk;
8332         struct scm_fp_list *fpl;
8333         struct sk_buff *skb;
8334         int i, nr_files;
8335
8336         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8337         if (!fpl)
8338                 return -ENOMEM;
8339
8340         skb = alloc_skb(0, GFP_KERNEL);
8341         if (!skb) {
8342                 kfree(fpl);
8343                 return -ENOMEM;
8344         }
8345
8346         skb->sk = sk;
8347         skb->scm_io_uring = 1;
8348
8349         nr_files = 0;
8350         fpl->user = get_uid(current_user());
8351         for (i = 0; i < nr; i++) {
8352                 struct file *file = io_file_from_index(ctx, i + offset);
8353
8354                 if (!file)
8355                         continue;
8356                 fpl->fp[nr_files] = get_file(file);
8357                 unix_inflight(fpl->user, fpl->fp[nr_files]);
8358                 nr_files++;
8359         }
8360
8361         if (nr_files) {
8362                 fpl->max = SCM_MAX_FD;
8363                 fpl->count = nr_files;
8364                 UNIXCB(skb).fp = fpl;
8365                 skb->destructor = unix_destruct_scm;
8366                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8367                 skb_queue_head(&sk->sk_receive_queue, skb);
8368
8369                 for (i = 0; i < nr; i++) {
8370                         struct file *file = io_file_from_index(ctx, i + offset);
8371
8372                         if (file)
8373                                 fput(file);
8374                 }
8375         } else {
8376                 kfree_skb(skb);
8377                 free_uid(fpl->user);
8378                 kfree(fpl);
8379         }
8380
8381         return 0;
8382 }
8383
8384 /*
8385  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8386  * causes regular reference counting to break down. We rely on the UNIX
8387  * garbage collection to take care of this problem for us.
8388  */
8389 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8390 {
8391         unsigned left, total;
8392         int ret = 0;
8393
8394         total = 0;
8395         left = ctx->nr_user_files;
8396         while (left) {
8397                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8398
8399                 ret = __io_sqe_files_scm(ctx, this_files, total);
8400                 if (ret)
8401                         break;
8402                 left -= this_files;
8403                 total += this_files;
8404         }
8405
8406         if (!ret)
8407                 return 0;
8408
8409         while (total < ctx->nr_user_files) {
8410                 struct file *file = io_file_from_index(ctx, total);
8411
8412                 if (file)
8413                         fput(file);
8414                 total++;
8415         }
8416
8417         return ret;
8418 }
8419 #else
8420 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8421 {
8422         return 0;
8423 }
8424 #endif
8425
8426 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8427 {
8428         struct file *file = prsrc->file;
8429 #if defined(CONFIG_UNIX)
8430         struct sock *sock = ctx->ring_sock->sk;
8431         struct sk_buff_head list, *head = &sock->sk_receive_queue;
8432         struct sk_buff *skb;
8433         int i;
8434
8435         __skb_queue_head_init(&list);
8436
8437         /*
8438          * Find the skb that holds this file in its SCM_RIGHTS. When found,
8439          * remove this entry and rearrange the file array.
8440          */
8441         skb = skb_dequeue(head);
8442         while (skb) {
8443                 struct scm_fp_list *fp;
8444
8445                 fp = UNIXCB(skb).fp;
8446                 for (i = 0; i < fp->count; i++) {
8447                         int left;
8448
8449                         if (fp->fp[i] != file)
8450                                 continue;
8451
8452                         unix_notinflight(fp->user, fp->fp[i]);
8453                         left = fp->count - 1 - i;
8454                         if (left) {
8455                                 memmove(&fp->fp[i], &fp->fp[i + 1],
8456                                                 left * sizeof(struct file *));
8457                         }
8458                         fp->count--;
8459                         if (!fp->count) {
8460                                 kfree_skb(skb);
8461                                 skb = NULL;
8462                         } else {
8463                                 __skb_queue_tail(&list, skb);
8464                         }
8465                         fput(file);
8466                         file = NULL;
8467                         break;
8468                 }
8469
8470                 if (!file)
8471                         break;
8472
8473                 __skb_queue_tail(&list, skb);
8474
8475                 skb = skb_dequeue(head);
8476         }
8477
8478         if (skb_peek(&list)) {
8479                 spin_lock_irq(&head->lock);
8480                 while ((skb = __skb_dequeue(&list)) != NULL)
8481                         __skb_queue_tail(head, skb);
8482                 spin_unlock_irq(&head->lock);
8483         }
8484 #else
8485         fput(file);
8486 #endif
8487 }
8488
8489 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8490 {
8491         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8492         struct io_ring_ctx *ctx = rsrc_data->ctx;
8493         struct io_rsrc_put *prsrc, *tmp;
8494
8495         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8496                 list_del(&prsrc->list);
8497
8498                 if (prsrc->tag) {
8499                         bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8500
8501                         io_ring_submit_lock(ctx, lock_ring);
8502                         spin_lock(&ctx->completion_lock);
8503                         io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8504                         io_commit_cqring(ctx);
8505                         spin_unlock(&ctx->completion_lock);
8506                         io_cqring_ev_posted(ctx);
8507                         io_ring_submit_unlock(ctx, lock_ring);
8508                 }
8509
8510                 rsrc_data->do_put(ctx, prsrc);
8511                 kfree(prsrc);
8512         }
8513
8514         io_rsrc_node_destroy(ref_node);
8515         if (atomic_dec_and_test(&rsrc_data->refs))
8516                 complete(&rsrc_data->done);
8517 }
8518
8519 static void io_rsrc_put_work(struct work_struct *work)
8520 {
8521         struct io_ring_ctx *ctx;
8522         struct llist_node *node;
8523
8524         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8525         node = llist_del_all(&ctx->rsrc_put_llist);
8526
8527         while (node) {
8528                 struct io_rsrc_node *ref_node;
8529                 struct llist_node *next = node->next;
8530
8531                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8532                 __io_rsrc_put_work(ref_node);
8533                 node = next;
8534         }
8535 }
8536
8537 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8538                                  unsigned nr_args, u64 __user *tags)
8539 {
8540         __s32 __user *fds = (__s32 __user *) arg;
8541         struct file *file;
8542         int fd, ret;
8543         unsigned i;
8544
8545         if (ctx->file_data)
8546                 return -EBUSY;
8547         if (!nr_args)
8548                 return -EINVAL;
8549         if (nr_args > IORING_MAX_FIXED_FILES)
8550                 return -EMFILE;
8551         if (nr_args > rlimit(RLIMIT_NOFILE))
8552                 return -EMFILE;
8553         ret = io_rsrc_node_switch_start(ctx);
8554         if (ret)
8555                 return ret;
8556         ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8557                                  &ctx->file_data);
8558         if (ret)
8559                 return ret;
8560
8561         ret = -ENOMEM;
8562         if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8563                 goto out_free;
8564
8565         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8566                 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8567                         ret = -EFAULT;
8568                         goto out_fput;
8569                 }
8570                 /* allow sparse sets */
8571                 if (fd == -1) {
8572                         ret = -EINVAL;
8573                         if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8574                                 goto out_fput;
8575                         continue;
8576                 }
8577
8578                 file = fget(fd);
8579                 ret = -EBADF;
8580                 if (unlikely(!file))
8581                         goto out_fput;
8582
8583                 /*
8584                  * Don't allow io_uring instances to be registered. If UNIX
8585                  * isn't enabled, then this causes a reference cycle and this
8586                  * instance can never get freed. If UNIX is enabled we'll
8587                  * handle it just fine, but there's still no point in allowing
8588                  * a ring fd as it doesn't support regular read/write anyway.
8589                  */
8590                 if (file->f_op == &io_uring_fops) {
8591                         fput(file);
8592                         goto out_fput;
8593                 }
8594                 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8595         }
8596
8597         ret = io_sqe_files_scm(ctx);
8598         if (ret) {
8599                 __io_sqe_files_unregister(ctx);
8600                 return ret;
8601         }
8602
8603         io_rsrc_node_switch(ctx, NULL);
8604         return ret;
8605 out_fput:
8606         for (i = 0; i < ctx->nr_user_files; i++) {
8607                 file = io_file_from_index(ctx, i);
8608                 if (file)
8609                         fput(file);
8610         }
8611         io_free_file_tables(&ctx->file_table);
8612         ctx->nr_user_files = 0;
8613 out_free:
8614         io_rsrc_data_free(ctx->file_data);
8615         ctx->file_data = NULL;
8616         return ret;
8617 }
8618
8619 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8620                                 int index)
8621 {
8622 #if defined(CONFIG_UNIX)
8623         struct sock *sock = ctx->ring_sock->sk;
8624         struct sk_buff_head *head = &sock->sk_receive_queue;
8625         struct sk_buff *skb;
8626
8627         /*
8628          * See if we can merge this file into an existing skb SCM_RIGHTS
8629          * file set. If there's no room, fall back to allocating a new skb
8630          * and filling it in.
8631          */
8632         spin_lock_irq(&head->lock);
8633         skb = skb_peek(head);
8634         if (skb) {
8635                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8636
8637                 if (fpl->count < SCM_MAX_FD) {
8638                         __skb_unlink(skb, head);
8639                         spin_unlock_irq(&head->lock);
8640                         fpl->fp[fpl->count] = get_file(file);
8641                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
8642                         fpl->count++;
8643                         spin_lock_irq(&head->lock);
8644                         __skb_queue_head(head, skb);
8645                 } else {
8646                         skb = NULL;
8647                 }
8648         }
8649         spin_unlock_irq(&head->lock);
8650
8651         if (skb) {
8652                 fput(file);
8653                 return 0;
8654         }
8655
8656         return __io_sqe_files_scm(ctx, 1, index);
8657 #else
8658         return 0;
8659 #endif
8660 }
8661
8662 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8663                                  struct io_rsrc_node *node, void *rsrc)
8664 {
8665         u64 *tag_slot = io_get_tag_slot(data, idx);
8666         struct io_rsrc_put *prsrc;
8667
8668         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8669         if (!prsrc)
8670                 return -ENOMEM;
8671
8672         prsrc->tag = *tag_slot;
8673         *tag_slot = 0;
8674         prsrc->rsrc = rsrc;
8675         list_add(&prsrc->list, &node->rsrc_list);
8676         return 0;
8677 }
8678
8679 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8680                                  unsigned int issue_flags, u32 slot_index)
8681 {
8682         struct io_ring_ctx *ctx = req->ctx;
8683         bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8684         bool needs_switch = false;
8685         struct io_fixed_file *file_slot;
8686         int ret = -EBADF;
8687
8688         io_ring_submit_lock(ctx, !force_nonblock);
8689         if (file->f_op == &io_uring_fops)
8690                 goto err;
8691         ret = -ENXIO;
8692         if (!ctx->file_data)
8693                 goto err;
8694         ret = -EINVAL;
8695         if (slot_index >= ctx->nr_user_files)
8696                 goto err;
8697
8698         slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8699         file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8700
8701         if (file_slot->file_ptr) {
8702                 struct file *old_file;
8703
8704                 ret = io_rsrc_node_switch_start(ctx);
8705                 if (ret)
8706                         goto err;
8707
8708                 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8709                 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8710                                             ctx->rsrc_node, old_file);
8711                 if (ret)
8712                         goto err;
8713                 file_slot->file_ptr = 0;
8714                 needs_switch = true;
8715         }
8716
8717         *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8718         io_fixed_file_set(file_slot, file);
8719         ret = io_sqe_file_register(ctx, file, slot_index);
8720         if (ret) {
8721                 file_slot->file_ptr = 0;
8722                 goto err;
8723         }
8724
8725         ret = 0;
8726 err:
8727         if (needs_switch)
8728                 io_rsrc_node_switch(ctx, ctx->file_data);
8729         io_ring_submit_unlock(ctx, !force_nonblock);
8730         if (ret)
8731                 fput(file);
8732         return ret;
8733 }
8734
8735 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8736 {
8737         unsigned int offset = req->close.file_slot - 1;
8738         struct io_ring_ctx *ctx = req->ctx;
8739         struct io_fixed_file *file_slot;
8740         struct file *file;
8741         int ret;
8742
8743         io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8744         ret = -ENXIO;
8745         if (unlikely(!ctx->file_data))
8746                 goto out;
8747         ret = -EINVAL;
8748         if (offset >= ctx->nr_user_files)
8749                 goto out;
8750         ret = io_rsrc_node_switch_start(ctx);
8751         if (ret)
8752                 goto out;
8753
8754         offset = array_index_nospec(offset, ctx->nr_user_files);
8755         file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8756         ret = -EBADF;
8757         if (!file_slot->file_ptr)
8758                 goto out;
8759
8760         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8761         ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8762         if (ret)
8763                 goto out;
8764
8765         file_slot->file_ptr = 0;
8766         io_rsrc_node_switch(ctx, ctx->file_data);
8767         ret = 0;
8768 out:
8769         io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8770         return ret;
8771 }
8772
8773 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8774                                  struct io_uring_rsrc_update2 *up,
8775                                  unsigned nr_args)
8776 {
8777         u64 __user *tags = u64_to_user_ptr(up->tags);
8778         __s32 __user *fds = u64_to_user_ptr(up->data);
8779         struct io_rsrc_data *data = ctx->file_data;
8780         struct io_fixed_file *file_slot;
8781         struct file *file;
8782         int fd, i, err = 0;
8783         unsigned int done;
8784         bool needs_switch = false;
8785
8786         if (!ctx->file_data)
8787                 return -ENXIO;
8788         if (up->offset + nr_args > ctx->nr_user_files)
8789                 return -EINVAL;
8790
8791         for (done = 0; done < nr_args; done++) {
8792                 u64 tag = 0;
8793
8794                 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8795                     copy_from_user(&fd, &fds[done], sizeof(fd))) {
8796                         err = -EFAULT;
8797                         break;
8798                 }
8799                 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8800                         err = -EINVAL;
8801                         break;
8802                 }
8803                 if (fd == IORING_REGISTER_FILES_SKIP)
8804                         continue;
8805
8806                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8807                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8808
8809                 if (file_slot->file_ptr) {
8810                         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8811                         err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8812                         if (err)
8813                                 break;
8814                         file_slot->file_ptr = 0;
8815                         needs_switch = true;
8816                 }
8817                 if (fd != -1) {
8818                         file = fget(fd);
8819                         if (!file) {
8820                                 err = -EBADF;
8821                                 break;
8822                         }
8823                         /*
8824                          * Don't allow io_uring instances to be registered. If
8825                          * UNIX isn't enabled, then this causes a reference
8826                          * cycle and this instance can never get freed. If UNIX
8827                          * is enabled we'll handle it just fine, but there's
8828                          * still no point in allowing a ring fd as it doesn't
8829                          * support regular read/write anyway.
8830                          */
8831                         if (file->f_op == &io_uring_fops) {
8832                                 fput(file);
8833                                 err = -EBADF;
8834                                 break;
8835                         }
8836                         *io_get_tag_slot(data, i) = tag;
8837                         io_fixed_file_set(file_slot, file);
8838                         err = io_sqe_file_register(ctx, file, i);
8839                         if (err) {
8840                                 file_slot->file_ptr = 0;
8841                                 fput(file);
8842                                 break;
8843                         }
8844                 }
8845         }
8846
8847         if (needs_switch)
8848                 io_rsrc_node_switch(ctx, data);
8849         return done ? done : err;
8850 }
8851
8852 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8853                                         struct task_struct *task)
8854 {
8855         struct io_wq_hash *hash;
8856         struct io_wq_data data;
8857         unsigned int concurrency;
8858
8859         mutex_lock(&ctx->uring_lock);
8860         hash = ctx->hash_map;
8861         if (!hash) {
8862                 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8863                 if (!hash) {
8864                         mutex_unlock(&ctx->uring_lock);
8865                         return ERR_PTR(-ENOMEM);
8866                 }
8867                 refcount_set(&hash->refs, 1);
8868                 init_waitqueue_head(&hash->wait);
8869                 ctx->hash_map = hash;
8870         }
8871         mutex_unlock(&ctx->uring_lock);
8872
8873         data.hash = hash;
8874         data.task = task;
8875         data.free_work = io_wq_free_work;
8876         data.do_work = io_wq_submit_work;
8877
8878         /* Do QD, or 4 * CPUS, whatever is smallest */
8879         concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8880
8881         return io_wq_create(concurrency, &data);
8882 }
8883
8884 static int io_uring_alloc_task_context(struct task_struct *task,
8885                                        struct io_ring_ctx *ctx)
8886 {
8887         struct io_uring_task *tctx;
8888         int ret;
8889
8890         tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8891         if (unlikely(!tctx))
8892                 return -ENOMEM;
8893
8894         ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8895         if (unlikely(ret)) {
8896                 kfree(tctx);
8897                 return ret;
8898         }
8899
8900         tctx->io_wq = io_init_wq_offload(ctx, task);
8901         if (IS_ERR(tctx->io_wq)) {
8902                 ret = PTR_ERR(tctx->io_wq);
8903                 percpu_counter_destroy(&tctx->inflight);
8904                 kfree(tctx);
8905                 return ret;
8906         }
8907
8908         xa_init(&tctx->xa);
8909         init_waitqueue_head(&tctx->wait);
8910         atomic_set(&tctx->in_idle, 0);
8911         atomic_set(&tctx->inflight_tracked, 0);
8912         task->io_uring = tctx;
8913         spin_lock_init(&tctx->task_lock);
8914         INIT_WQ_LIST(&tctx->task_list);
8915         init_task_work(&tctx->task_work, tctx_task_work);
8916         return 0;
8917 }
8918
8919 void __io_uring_free(struct task_struct *tsk)
8920 {
8921         struct io_uring_task *tctx = tsk->io_uring;
8922
8923         WARN_ON_ONCE(!xa_empty(&tctx->xa));
8924         WARN_ON_ONCE(tctx->io_wq);
8925         WARN_ON_ONCE(tctx->cached_refs);
8926
8927         percpu_counter_destroy(&tctx->inflight);
8928         kfree(tctx);
8929         tsk->io_uring = NULL;
8930 }
8931
8932 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8933                                 struct io_uring_params *p)
8934 {
8935         int ret;
8936
8937         /* Retain compatibility with failing for an invalid attach attempt */
8938         if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8939                                 IORING_SETUP_ATTACH_WQ) {
8940                 struct fd f;
8941
8942                 f = fdget(p->wq_fd);
8943                 if (!f.file)
8944                         return -ENXIO;
8945                 if (f.file->f_op != &io_uring_fops) {
8946                         fdput(f);
8947                         return -EINVAL;
8948                 }
8949                 fdput(f);
8950         }
8951         if (ctx->flags & IORING_SETUP_SQPOLL) {
8952                 struct task_struct *tsk;
8953                 struct io_sq_data *sqd;
8954                 bool attached;
8955
8956                 sqd = io_get_sq_data(p, &attached);
8957                 if (IS_ERR(sqd)) {
8958                         ret = PTR_ERR(sqd);
8959                         goto err;
8960                 }
8961
8962                 ctx->sq_creds = get_current_cred();
8963                 ctx->sq_data = sqd;
8964                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8965                 if (!ctx->sq_thread_idle)
8966                         ctx->sq_thread_idle = HZ;
8967
8968                 io_sq_thread_park(sqd);
8969                 list_add(&ctx->sqd_list, &sqd->ctx_list);
8970                 io_sqd_update_thread_idle(sqd);
8971                 /* don't attach to a dying SQPOLL thread, would be racy */
8972                 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8973                 io_sq_thread_unpark(sqd);
8974
8975                 if (ret < 0)
8976                         goto err;
8977                 if (attached)
8978                         return 0;
8979
8980                 if (p->flags & IORING_SETUP_SQ_AFF) {
8981                         int cpu = p->sq_thread_cpu;
8982
8983                         ret = -EINVAL;
8984                         if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8985                                 goto err_sqpoll;
8986                         sqd->sq_cpu = cpu;
8987                 } else {
8988                         sqd->sq_cpu = -1;
8989                 }
8990
8991                 sqd->task_pid = current->pid;
8992                 sqd->task_tgid = current->tgid;
8993                 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8994                 if (IS_ERR(tsk)) {
8995                         ret = PTR_ERR(tsk);
8996                         goto err_sqpoll;
8997                 }
8998
8999                 sqd->thread = tsk;
9000                 ret = io_uring_alloc_task_context(tsk, ctx);
9001                 wake_up_new_task(tsk);
9002                 if (ret)
9003                         goto err;
9004         } else if (p->flags & IORING_SETUP_SQ_AFF) {
9005                 /* Can't have SQ_AFF without SQPOLL */
9006                 ret = -EINVAL;
9007                 goto err;
9008         }
9009
9010         return 0;
9011 err_sqpoll:
9012         complete(&ctx->sq_data->exited);
9013 err:
9014         io_sq_thread_finish(ctx);
9015         return ret;
9016 }
9017
9018 static inline void __io_unaccount_mem(struct user_struct *user,
9019                                       unsigned long nr_pages)
9020 {
9021         atomic_long_sub(nr_pages, &user->locked_vm);
9022 }
9023
9024 static inline int __io_account_mem(struct user_struct *user,
9025                                    unsigned long nr_pages)
9026 {
9027         unsigned long page_limit, cur_pages, new_pages;
9028
9029         /* Don't allow more pages than we can safely lock */
9030         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9031
9032         do {
9033                 cur_pages = atomic_long_read(&user->locked_vm);
9034                 new_pages = cur_pages + nr_pages;
9035                 if (new_pages > page_limit)
9036                         return -ENOMEM;
9037         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9038                                         new_pages) != cur_pages);
9039
9040         return 0;
9041 }
9042
9043 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9044 {
9045         if (ctx->user)
9046                 __io_unaccount_mem(ctx->user, nr_pages);
9047
9048         if (ctx->mm_account)
9049                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9050 }
9051
9052 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9053 {
9054         int ret;
9055
9056         if (ctx->user) {
9057                 ret = __io_account_mem(ctx->user, nr_pages);
9058                 if (ret)
9059                         return ret;
9060         }
9061
9062         if (ctx->mm_account)
9063                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9064
9065         return 0;
9066 }
9067
9068 static void io_mem_free(void *ptr)
9069 {
9070         struct page *page;
9071
9072         if (!ptr)
9073                 return;
9074
9075         page = virt_to_head_page(ptr);
9076         if (put_page_testzero(page))
9077                 free_compound_page(page);
9078 }
9079
9080 static void *io_mem_alloc(size_t size)
9081 {
9082         gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9083
9084         return (void *) __get_free_pages(gfp, get_order(size));
9085 }
9086
9087 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9088                                 size_t *sq_offset)
9089 {
9090         struct io_rings *rings;
9091         size_t off, sq_array_size;
9092
9093         off = struct_size(rings, cqes, cq_entries);
9094         if (off == SIZE_MAX)
9095                 return SIZE_MAX;
9096
9097 #ifdef CONFIG_SMP
9098         off = ALIGN(off, SMP_CACHE_BYTES);
9099         if (off == 0)
9100                 return SIZE_MAX;
9101 #endif
9102
9103         if (sq_offset)
9104                 *sq_offset = off;
9105
9106         sq_array_size = array_size(sizeof(u32), sq_entries);
9107         if (sq_array_size == SIZE_MAX)
9108                 return SIZE_MAX;
9109
9110         if (check_add_overflow(off, sq_array_size, &off))
9111                 return SIZE_MAX;
9112
9113         return off;
9114 }
9115
9116 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9117 {
9118         struct io_mapped_ubuf *imu = *slot;
9119         unsigned int i;
9120
9121         if (imu != ctx->dummy_ubuf) {
9122                 for (i = 0; i < imu->nr_bvecs; i++)
9123                         unpin_user_page(imu->bvec[i].bv_page);
9124                 if (imu->acct_pages)
9125                         io_unaccount_mem(ctx, imu->acct_pages);
9126                 kvfree(imu);
9127         }
9128         *slot = NULL;
9129 }
9130
9131 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9132 {
9133         io_buffer_unmap(ctx, &prsrc->buf);
9134         prsrc->buf = NULL;
9135 }
9136
9137 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9138 {
9139         unsigned int i;
9140
9141         for (i = 0; i < ctx->nr_user_bufs; i++)
9142                 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9143         kfree(ctx->user_bufs);
9144         io_rsrc_data_free(ctx->buf_data);
9145         ctx->user_bufs = NULL;
9146         ctx->buf_data = NULL;
9147         ctx->nr_user_bufs = 0;
9148 }
9149
9150 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9151 {
9152         unsigned nr = ctx->nr_user_bufs;
9153         int ret;
9154
9155         if (!ctx->buf_data)
9156                 return -ENXIO;
9157
9158         /*
9159          * Quiesce may unlock ->uring_lock, and while it's not held
9160          * prevent new requests using the table.
9161          */
9162         ctx->nr_user_bufs = 0;
9163         ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9164         ctx->nr_user_bufs = nr;
9165         if (!ret)
9166                 __io_sqe_buffers_unregister(ctx);
9167         return ret;
9168 }
9169
9170 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9171                        void __user *arg, unsigned index)
9172 {
9173         struct iovec __user *src;
9174
9175 #ifdef CONFIG_COMPAT
9176         if (ctx->compat) {
9177                 struct compat_iovec __user *ciovs;
9178                 struct compat_iovec ciov;
9179
9180                 ciovs = (struct compat_iovec __user *) arg;
9181                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9182                         return -EFAULT;
9183
9184                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9185                 dst->iov_len = ciov.iov_len;
9186                 return 0;
9187         }
9188 #endif
9189         src = (struct iovec __user *) arg;
9190         if (copy_from_user(dst, &src[index], sizeof(*dst)))
9191                 return -EFAULT;
9192         return 0;
9193 }
9194
9195 /*
9196  * Not super efficient, but this is just a registration time. And we do cache
9197  * the last compound head, so generally we'll only do a full search if we don't
9198  * match that one.
9199  *
9200  * We check if the given compound head page has already been accounted, to
9201  * avoid double accounting it. This allows us to account the full size of the
9202  * page, not just the constituent pages of a huge page.
9203  */
9204 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9205                                   int nr_pages, struct page *hpage)
9206 {
9207         int i, j;
9208
9209         /* check current page array */
9210         for (i = 0; i < nr_pages; i++) {
9211                 if (!PageCompound(pages[i]))
9212                         continue;
9213                 if (compound_head(pages[i]) == hpage)
9214                         return true;
9215         }
9216
9217         /* check previously registered pages */
9218         for (i = 0; i < ctx->nr_user_bufs; i++) {
9219                 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9220
9221                 for (j = 0; j < imu->nr_bvecs; j++) {
9222                         if (!PageCompound(imu->bvec[j].bv_page))
9223                                 continue;
9224                         if (compound_head(imu->bvec[j].bv_page) == hpage)
9225                                 return true;
9226                 }
9227         }
9228
9229         return false;
9230 }
9231
9232 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9233                                  int nr_pages, struct io_mapped_ubuf *imu,
9234                                  struct page **last_hpage)
9235 {
9236         int i, ret;
9237
9238         imu->acct_pages = 0;
9239         for (i = 0; i < nr_pages; i++) {
9240                 if (!PageCompound(pages[i])) {
9241                         imu->acct_pages++;
9242                 } else {
9243                         struct page *hpage;
9244
9245                         hpage = compound_head(pages[i]);
9246                         if (hpage == *last_hpage)
9247                                 continue;
9248                         *last_hpage = hpage;
9249                         if (headpage_already_acct(ctx, pages, i, hpage))
9250                                 continue;
9251                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9252                 }
9253         }
9254
9255         if (!imu->acct_pages)
9256                 return 0;
9257
9258         ret = io_account_mem(ctx, imu->acct_pages);
9259         if (ret)
9260                 imu->acct_pages = 0;
9261         return ret;
9262 }
9263
9264 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9265                                   struct io_mapped_ubuf **pimu,
9266                                   struct page **last_hpage)
9267 {
9268         struct io_mapped_ubuf *imu = NULL;
9269         struct vm_area_struct **vmas = NULL;
9270         struct page **pages = NULL;
9271         unsigned long off, start, end, ubuf;
9272         size_t size;
9273         int ret, pret, nr_pages, i;
9274
9275         if (!iov->iov_base) {
9276                 *pimu = ctx->dummy_ubuf;
9277                 return 0;
9278         }
9279
9280         ubuf = (unsigned long) iov->iov_base;
9281         end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9282         start = ubuf >> PAGE_SHIFT;
9283         nr_pages = end - start;
9284
9285         *pimu = NULL;
9286         ret = -ENOMEM;
9287
9288         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9289         if (!pages)
9290                 goto done;
9291
9292         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9293                               GFP_KERNEL);
9294         if (!vmas)
9295                 goto done;
9296
9297         imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9298         if (!imu)
9299                 goto done;
9300
9301         ret = 0;
9302         mmap_read_lock(current->mm);
9303         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9304                               pages, vmas);
9305         if (pret == nr_pages) {
9306                 struct file *file = vmas[0]->vm_file;
9307
9308                 /* don't support file backed memory */
9309                 for (i = 0; i < nr_pages; i++) {
9310                         if (vmas[i]->vm_file != file) {
9311                                 ret = -EINVAL;
9312                                 break;
9313                         }
9314                         if (!file)
9315                                 continue;
9316                         if (!vma_is_shmem(vmas[i]) && !is_file_hugepages(file)) {
9317                                 ret = -EOPNOTSUPP;
9318                                 break;
9319                         }
9320                 }
9321         } else {
9322                 ret = pret < 0 ? pret : -EFAULT;
9323         }
9324         mmap_read_unlock(current->mm);
9325         if (ret) {
9326                 /*
9327                  * if we did partial map, or found file backed vmas,
9328                  * release any pages we did get
9329                  */
9330                 if (pret > 0)
9331                         unpin_user_pages(pages, pret);
9332                 goto done;
9333         }
9334
9335         ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9336         if (ret) {
9337                 unpin_user_pages(pages, pret);
9338                 goto done;
9339         }
9340
9341         off = ubuf & ~PAGE_MASK;
9342         size = iov->iov_len;
9343         for (i = 0; i < nr_pages; i++) {
9344                 size_t vec_len;
9345
9346                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9347                 imu->bvec[i].bv_page = pages[i];
9348                 imu->bvec[i].bv_len = vec_len;
9349                 imu->bvec[i].bv_offset = off;
9350                 off = 0;
9351                 size -= vec_len;
9352         }
9353         /* store original address for later verification */
9354         imu->ubuf = ubuf;
9355         imu->ubuf_end = ubuf + iov->iov_len;
9356         imu->nr_bvecs = nr_pages;
9357         *pimu = imu;
9358         ret = 0;
9359 done:
9360         if (ret)
9361                 kvfree(imu);
9362         kvfree(pages);
9363         kvfree(vmas);
9364         return ret;
9365 }
9366
9367 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9368 {
9369         ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9370         return ctx->user_bufs ? 0 : -ENOMEM;
9371 }
9372
9373 static int io_buffer_validate(struct iovec *iov)
9374 {
9375         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9376
9377         /*
9378          * Don't impose further limits on the size and buffer
9379          * constraints here, we'll -EINVAL later when IO is
9380          * submitted if they are wrong.
9381          */
9382         if (!iov->iov_base)
9383                 return iov->iov_len ? -EFAULT : 0;
9384         if (!iov->iov_len)
9385                 return -EFAULT;
9386
9387         /* arbitrary limit, but we need something */
9388         if (iov->iov_len > SZ_1G)
9389                 return -EFAULT;
9390
9391         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9392                 return -EOVERFLOW;
9393
9394         return 0;
9395 }
9396
9397 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9398                                    unsigned int nr_args, u64 __user *tags)
9399 {
9400         struct page *last_hpage = NULL;
9401         struct io_rsrc_data *data;
9402         int i, ret;
9403         struct iovec iov;
9404
9405         if (ctx->user_bufs)
9406                 return -EBUSY;
9407         if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9408                 return -EINVAL;
9409         ret = io_rsrc_node_switch_start(ctx);
9410         if (ret)
9411                 return ret;
9412         ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9413         if (ret)
9414                 return ret;
9415         ret = io_buffers_map_alloc(ctx, nr_args);
9416         if (ret) {
9417                 io_rsrc_data_free(data);
9418                 return ret;
9419         }
9420
9421         for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9422                 ret = io_copy_iov(ctx, &iov, arg, i);
9423                 if (ret)
9424                         break;
9425                 ret = io_buffer_validate(&iov);
9426                 if (ret)
9427                         break;
9428                 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9429                         ret = -EINVAL;
9430                         break;
9431                 }
9432
9433                 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9434                                              &last_hpage);
9435                 if (ret)
9436                         break;
9437         }
9438
9439         WARN_ON_ONCE(ctx->buf_data);
9440
9441         ctx->buf_data = data;
9442         if (ret)
9443                 __io_sqe_buffers_unregister(ctx);
9444         else
9445                 io_rsrc_node_switch(ctx, NULL);
9446         return ret;
9447 }
9448
9449 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9450                                    struct io_uring_rsrc_update2 *up,
9451                                    unsigned int nr_args)
9452 {
9453         u64 __user *tags = u64_to_user_ptr(up->tags);
9454         struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9455         struct page *last_hpage = NULL;
9456         bool needs_switch = false;
9457         __u32 done;
9458         int i, err;
9459
9460         if (!ctx->buf_data)
9461                 return -ENXIO;
9462         if (up->offset + nr_args > ctx->nr_user_bufs)
9463                 return -EINVAL;
9464
9465         for (done = 0; done < nr_args; done++) {
9466                 struct io_mapped_ubuf *imu;
9467                 int offset = up->offset + done;
9468                 u64 tag = 0;
9469
9470                 err = io_copy_iov(ctx, &iov, iovs, done);
9471                 if (err)
9472                         break;
9473                 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9474                         err = -EFAULT;
9475                         break;
9476                 }
9477                 err = io_buffer_validate(&iov);
9478                 if (err)
9479                         break;
9480                 if (!iov.iov_base && tag) {
9481                         err = -EINVAL;
9482                         break;
9483                 }
9484                 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9485                 if (err)
9486                         break;
9487
9488                 i = array_index_nospec(offset, ctx->nr_user_bufs);
9489                 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9490                         err = io_queue_rsrc_removal(ctx->buf_data, i,
9491                                                     ctx->rsrc_node, ctx->user_bufs[i]);
9492                         if (unlikely(err)) {
9493                                 io_buffer_unmap(ctx, &imu);
9494                                 break;
9495                         }
9496                         ctx->user_bufs[i] = NULL;
9497                         needs_switch = true;
9498                 }
9499
9500                 ctx->user_bufs[i] = imu;
9501                 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9502         }
9503
9504         if (needs_switch)
9505                 io_rsrc_node_switch(ctx, ctx->buf_data);
9506         return done ? done : err;
9507 }
9508
9509 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9510 {
9511         __s32 __user *fds = arg;
9512         int fd;
9513
9514         if (ctx->cq_ev_fd)
9515                 return -EBUSY;
9516
9517         if (copy_from_user(&fd, fds, sizeof(*fds)))
9518                 return -EFAULT;
9519
9520         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9521         if (IS_ERR(ctx->cq_ev_fd)) {
9522                 int ret = PTR_ERR(ctx->cq_ev_fd);
9523
9524                 ctx->cq_ev_fd = NULL;
9525                 return ret;
9526         }
9527
9528         return 0;
9529 }
9530
9531 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9532 {
9533         if (ctx->cq_ev_fd) {
9534                 eventfd_ctx_put(ctx->cq_ev_fd);
9535                 ctx->cq_ev_fd = NULL;
9536                 return 0;
9537         }
9538
9539         return -ENXIO;
9540 }
9541
9542 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9543 {
9544         struct io_buffer *buf;
9545         unsigned long index;
9546
9547         xa_for_each(&ctx->io_buffers, index, buf)
9548                 __io_remove_buffers(ctx, buf, index, -1U);
9549 }
9550
9551 static void io_req_cache_free(struct list_head *list)
9552 {
9553         struct io_kiocb *req, *nxt;
9554
9555         list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9556                 list_del(&req->inflight_entry);
9557                 kmem_cache_free(req_cachep, req);
9558         }
9559 }
9560
9561 static void io_req_caches_free(struct io_ring_ctx *ctx)
9562 {
9563         struct io_submit_state *state = &ctx->submit_state;
9564
9565         mutex_lock(&ctx->uring_lock);
9566
9567         if (state->free_reqs) {
9568                 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9569                 state->free_reqs = 0;
9570         }
9571
9572         io_flush_cached_locked_reqs(ctx, state);
9573         io_req_cache_free(&state->free_list);
9574         mutex_unlock(&ctx->uring_lock);
9575 }
9576
9577 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9578 {
9579         if (data && !atomic_dec_and_test(&data->refs))
9580                 wait_for_completion(&data->done);
9581 }
9582
9583 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9584 {
9585         io_sq_thread_finish(ctx);
9586
9587         /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9588         io_wait_rsrc_data(ctx->buf_data);
9589         io_wait_rsrc_data(ctx->file_data);
9590
9591         mutex_lock(&ctx->uring_lock);
9592         if (ctx->buf_data)
9593                 __io_sqe_buffers_unregister(ctx);
9594         if (ctx->file_data)
9595                 __io_sqe_files_unregister(ctx);
9596         if (ctx->rings)
9597                 __io_cqring_overflow_flush(ctx, true);
9598         mutex_unlock(&ctx->uring_lock);
9599         io_eventfd_unregister(ctx);
9600         io_destroy_buffers(ctx);
9601         if (ctx->sq_creds)
9602                 put_cred(ctx->sq_creds);
9603
9604         /* there are no registered resources left, nobody uses it */
9605         if (ctx->rsrc_node)
9606                 io_rsrc_node_destroy(ctx->rsrc_node);
9607         if (ctx->rsrc_backup_node)
9608                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9609         flush_delayed_work(&ctx->rsrc_put_work);
9610
9611         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9612         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9613
9614 #if defined(CONFIG_UNIX)
9615         if (ctx->ring_sock) {
9616                 ctx->ring_sock->file = NULL; /* so that iput() is called */
9617                 sock_release(ctx->ring_sock);
9618         }
9619 #endif
9620         WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9621
9622         if (ctx->mm_account) {
9623                 mmdrop(ctx->mm_account);
9624                 ctx->mm_account = NULL;
9625         }
9626
9627         io_mem_free(ctx->rings);
9628         io_mem_free(ctx->sq_sqes);
9629
9630         percpu_ref_exit(&ctx->refs);
9631         free_uid(ctx->user);
9632         io_req_caches_free(ctx);
9633         if (ctx->hash_map)
9634                 io_wq_put_hash(ctx->hash_map);
9635         kfree(ctx->cancel_hash);
9636         kfree(ctx->dummy_ubuf);
9637         kfree(ctx);
9638 }
9639
9640 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9641 {
9642         struct io_ring_ctx *ctx = file->private_data;
9643         __poll_t mask = 0;
9644
9645         poll_wait(file, &ctx->poll_wait, wait);
9646         /*
9647          * synchronizes with barrier from wq_has_sleeper call in
9648          * io_commit_cqring
9649          */
9650         smp_rmb();
9651         if (!io_sqring_full(ctx))
9652                 mask |= EPOLLOUT | EPOLLWRNORM;
9653
9654         /*
9655          * Don't flush cqring overflow list here, just do a simple check.
9656          * Otherwise there could possible be ABBA deadlock:
9657          *      CPU0                    CPU1
9658          *      ----                    ----
9659          * lock(&ctx->uring_lock);
9660          *                              lock(&ep->mtx);
9661          *                              lock(&ctx->uring_lock);
9662          * lock(&ep->mtx);
9663          *
9664          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9665          * pushs them to do the flush.
9666          */
9667         if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9668                 mask |= EPOLLIN | EPOLLRDNORM;
9669
9670         return mask;
9671 }
9672
9673 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9674 {
9675         const struct cred *creds;
9676
9677         creds = xa_erase(&ctx->personalities, id);
9678         if (creds) {
9679                 put_cred(creds);
9680                 return 0;
9681         }
9682
9683         return -EINVAL;
9684 }
9685
9686 struct io_tctx_exit {
9687         struct callback_head            task_work;
9688         struct completion               completion;
9689         struct io_ring_ctx              *ctx;
9690 };
9691
9692 static void io_tctx_exit_cb(struct callback_head *cb)
9693 {
9694         struct io_uring_task *tctx = current->io_uring;
9695         struct io_tctx_exit *work;
9696
9697         work = container_of(cb, struct io_tctx_exit, task_work);
9698         /*
9699          * When @in_idle, we're in cancellation and it's racy to remove the
9700          * node. It'll be removed by the end of cancellation, just ignore it.
9701          * tctx can be NULL if the queueing of this task_work raced with
9702          * work cancelation off the exec path.
9703          */
9704         if (tctx && !atomic_read(&tctx->in_idle))
9705                 io_uring_del_tctx_node((unsigned long)work->ctx);
9706         complete(&work->completion);
9707 }
9708
9709 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9710 {
9711         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9712
9713         return req->ctx == data;
9714 }
9715
9716 static void io_ring_exit_work(struct work_struct *work)
9717 {
9718         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9719         unsigned long timeout = jiffies + HZ * 60 * 5;
9720         unsigned long interval = HZ / 20;
9721         struct io_tctx_exit exit;
9722         struct io_tctx_node *node;
9723         int ret;
9724
9725         /*
9726          * If we're doing polled IO and end up having requests being
9727          * submitted async (out-of-line), then completions can come in while
9728          * we're waiting for refs to drop. We need to reap these manually,
9729          * as nobody else will be looking for them.
9730          */
9731         do {
9732                 io_uring_try_cancel_requests(ctx, NULL, true);
9733                 if (ctx->sq_data) {
9734                         struct io_sq_data *sqd = ctx->sq_data;
9735                         struct task_struct *tsk;
9736
9737                         io_sq_thread_park(sqd);
9738                         tsk = sqd->thread;
9739                         if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9740                                 io_wq_cancel_cb(tsk->io_uring->io_wq,
9741                                                 io_cancel_ctx_cb, ctx, true);
9742                         io_sq_thread_unpark(sqd);
9743                 }
9744
9745                 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9746                         /* there is little hope left, don't run it too often */
9747                         interval = HZ * 60;
9748                 }
9749                 /*
9750                  * This is really an uninterruptible wait, as it has to be
9751                  * complete. But it's also run from a kworker, which doesn't
9752                  * take signals, so it's fine to make it interruptible. This
9753                  * avoids scenarios where we knowingly can wait much longer
9754                  * on completions, for example if someone does a SIGSTOP on
9755                  * a task that needs to finish task_work to make this loop
9756                  * complete. That's a synthetic situation that should not
9757                  * cause a stuck task backtrace, and hence a potential panic
9758                  * on stuck tasks if that is enabled.
9759                  */
9760         } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
9761
9762         init_completion(&exit.completion);
9763         init_task_work(&exit.task_work, io_tctx_exit_cb);
9764         exit.ctx = ctx;
9765         /*
9766          * Some may use context even when all refs and requests have been put,
9767          * and they are free to do so while still holding uring_lock or
9768          * completion_lock, see io_req_task_submit(). Apart from other work,
9769          * this lock/unlock section also waits them to finish.
9770          */
9771         mutex_lock(&ctx->uring_lock);
9772         while (!list_empty(&ctx->tctx_list)) {
9773                 WARN_ON_ONCE(time_after(jiffies, timeout));
9774
9775                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9776                                         ctx_node);
9777                 /* don't spin on a single task if cancellation failed */
9778                 list_rotate_left(&ctx->tctx_list);
9779                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9780                 if (WARN_ON_ONCE(ret))
9781                         continue;
9782                 wake_up_process(node->task);
9783
9784                 mutex_unlock(&ctx->uring_lock);
9785                 /*
9786                  * See comment above for
9787                  * wait_for_completion_interruptible_timeout() on why this
9788                  * wait is marked as interruptible.
9789                  */
9790                 wait_for_completion_interruptible(&exit.completion);
9791                 mutex_lock(&ctx->uring_lock);
9792         }
9793         mutex_unlock(&ctx->uring_lock);
9794         spin_lock(&ctx->completion_lock);
9795         spin_unlock(&ctx->completion_lock);
9796
9797         io_ring_ctx_free(ctx);
9798 }
9799
9800 /* Returns true if we found and killed one or more timeouts */
9801 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9802                              bool cancel_all)
9803 {
9804         struct io_kiocb *req, *tmp;
9805         int canceled = 0;
9806
9807         spin_lock(&ctx->completion_lock);
9808         spin_lock_irq(&ctx->timeout_lock);
9809         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9810                 if (io_match_task(req, tsk, cancel_all)) {
9811                         io_kill_timeout(req, -ECANCELED);
9812                         canceled++;
9813                 }
9814         }
9815         spin_unlock_irq(&ctx->timeout_lock);
9816         if (canceled != 0)
9817                 io_commit_cqring(ctx);
9818         spin_unlock(&ctx->completion_lock);
9819         if (canceled != 0)
9820                 io_cqring_ev_posted(ctx);
9821         return canceled != 0;
9822 }
9823
9824 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9825 {
9826         unsigned long index;
9827         struct creds *creds;
9828
9829         mutex_lock(&ctx->uring_lock);
9830         percpu_ref_kill(&ctx->refs);
9831         if (ctx->rings)
9832                 __io_cqring_overflow_flush(ctx, true);
9833         xa_for_each(&ctx->personalities, index, creds)
9834                 io_unregister_personality(ctx, index);
9835         mutex_unlock(&ctx->uring_lock);
9836
9837         io_kill_timeouts(ctx, NULL, true);
9838         io_poll_remove_all(ctx, NULL, true);
9839
9840         /* if we failed setting up the ctx, we might not have any rings */
9841         io_iopoll_try_reap_events(ctx);
9842
9843         /* drop cached put refs after potentially doing completions */
9844         if (current->io_uring)
9845                 io_uring_drop_tctx_refs(current);
9846
9847         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9848         /*
9849          * Use system_unbound_wq to avoid spawning tons of event kworkers
9850          * if we're exiting a ton of rings at the same time. It just adds
9851          * noise and overhead, there's no discernable change in runtime
9852          * over using system_wq.
9853          */
9854         queue_work(system_unbound_wq, &ctx->exit_work);
9855 }
9856
9857 static int io_uring_release(struct inode *inode, struct file *file)
9858 {
9859         struct io_ring_ctx *ctx = file->private_data;
9860
9861         file->private_data = NULL;
9862         io_ring_ctx_wait_and_kill(ctx);
9863         return 0;
9864 }
9865
9866 struct io_task_cancel {
9867         struct task_struct *task;
9868         bool all;
9869 };
9870
9871 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9872 {
9873         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9874         struct io_task_cancel *cancel = data;
9875
9876         return io_match_task_safe(req, cancel->task, cancel->all);
9877 }
9878
9879 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9880                                   struct task_struct *task, bool cancel_all)
9881 {
9882         struct io_defer_entry *de;
9883         LIST_HEAD(list);
9884
9885         spin_lock(&ctx->completion_lock);
9886         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9887                 if (io_match_task_safe(de->req, task, cancel_all)) {
9888                         list_cut_position(&list, &ctx->defer_list, &de->list);
9889                         break;
9890                 }
9891         }
9892         spin_unlock(&ctx->completion_lock);
9893         if (list_empty(&list))
9894                 return false;
9895
9896         while (!list_empty(&list)) {
9897                 de = list_first_entry(&list, struct io_defer_entry, list);
9898                 list_del_init(&de->list);
9899                 io_req_complete_failed(de->req, -ECANCELED);
9900                 kfree(de);
9901         }
9902         return true;
9903 }
9904
9905 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9906 {
9907         struct io_tctx_node *node;
9908         enum io_wq_cancel cret;
9909         bool ret = false;
9910
9911         mutex_lock(&ctx->uring_lock);
9912         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9913                 struct io_uring_task *tctx = node->task->io_uring;
9914
9915                 /*
9916                  * io_wq will stay alive while we hold uring_lock, because it's
9917                  * killed after ctx nodes, which requires to take the lock.
9918                  */
9919                 if (!tctx || !tctx->io_wq)
9920                         continue;
9921                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9922                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9923         }
9924         mutex_unlock(&ctx->uring_lock);
9925
9926         return ret;
9927 }
9928
9929 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9930                                          struct task_struct *task,
9931                                          bool cancel_all)
9932 {
9933         struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9934         struct io_uring_task *tctx = task ? task->io_uring : NULL;
9935
9936         while (1) {
9937                 enum io_wq_cancel cret;
9938                 bool ret = false;
9939
9940                 if (!task) {
9941                         ret |= io_uring_try_cancel_iowq(ctx);
9942                 } else if (tctx && tctx->io_wq) {
9943                         /*
9944                          * Cancels requests of all rings, not only @ctx, but
9945                          * it's fine as the task is in exit/exec.
9946                          */
9947                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9948                                                &cancel, true);
9949                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9950                 }
9951
9952                 /* SQPOLL thread does its own polling */
9953                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9954                     (ctx->sq_data && ctx->sq_data->thread == current)) {
9955                         while (!list_empty_careful(&ctx->iopoll_list)) {
9956                                 io_iopoll_try_reap_events(ctx);
9957                                 ret = true;
9958                                 cond_resched();
9959                         }
9960                 }
9961
9962                 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9963                 ret |= io_poll_remove_all(ctx, task, cancel_all);
9964                 ret |= io_kill_timeouts(ctx, task, cancel_all);
9965                 if (task)
9966                         ret |= io_run_task_work();
9967                 if (!ret)
9968                         break;
9969                 cond_resched();
9970         }
9971 }
9972
9973 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9974 {
9975         struct io_uring_task *tctx = current->io_uring;
9976         struct io_tctx_node *node;
9977         int ret;
9978
9979         if (unlikely(!tctx)) {
9980                 ret = io_uring_alloc_task_context(current, ctx);
9981                 if (unlikely(ret))
9982                         return ret;
9983
9984                 tctx = current->io_uring;
9985                 if (ctx->iowq_limits_set) {
9986                         unsigned int limits[2] = { ctx->iowq_limits[0],
9987                                                    ctx->iowq_limits[1], };
9988
9989                         ret = io_wq_max_workers(tctx->io_wq, limits);
9990                         if (ret)
9991                                 return ret;
9992                 }
9993         }
9994         if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9995                 node = kmalloc(sizeof(*node), GFP_KERNEL);
9996                 if (!node)
9997                         return -ENOMEM;
9998                 node->ctx = ctx;
9999                 node->task = current;
10000
10001                 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10002                                         node, GFP_KERNEL));
10003                 if (ret) {
10004                         kfree(node);
10005                         return ret;
10006                 }
10007
10008                 mutex_lock(&ctx->uring_lock);
10009                 list_add(&node->ctx_node, &ctx->tctx_list);
10010                 mutex_unlock(&ctx->uring_lock);
10011         }
10012         tctx->last = ctx;
10013         return 0;
10014 }
10015
10016 /*
10017  * Note that this task has used io_uring. We use it for cancelation purposes.
10018  */
10019 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10020 {
10021         struct io_uring_task *tctx = current->io_uring;
10022
10023         if (likely(tctx && tctx->last == ctx))
10024                 return 0;
10025         return __io_uring_add_tctx_node(ctx);
10026 }
10027
10028 /*
10029  * Remove this io_uring_file -> task mapping.
10030  */
10031 static void io_uring_del_tctx_node(unsigned long index)
10032 {
10033         struct io_uring_task *tctx = current->io_uring;
10034         struct io_tctx_node *node;
10035
10036         if (!tctx)
10037                 return;
10038         node = xa_erase(&tctx->xa, index);
10039         if (!node)
10040                 return;
10041
10042         WARN_ON_ONCE(current != node->task);
10043         WARN_ON_ONCE(list_empty(&node->ctx_node));
10044
10045         mutex_lock(&node->ctx->uring_lock);
10046         list_del(&node->ctx_node);
10047         mutex_unlock(&node->ctx->uring_lock);
10048
10049         if (tctx->last == node->ctx)
10050                 tctx->last = NULL;
10051         kfree(node);
10052 }
10053
10054 static void io_uring_clean_tctx(struct io_uring_task *tctx)
10055 {
10056         struct io_wq *wq = tctx->io_wq;
10057         struct io_tctx_node *node;
10058         unsigned long index;
10059
10060         xa_for_each(&tctx->xa, index, node) {
10061                 io_uring_del_tctx_node(index);
10062                 cond_resched();
10063         }
10064         if (wq) {
10065                 /*
10066                  * Must be after io_uring_del_task_file() (removes nodes under
10067                  * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10068                  */
10069                 io_wq_put_and_exit(wq);
10070                 tctx->io_wq = NULL;
10071         }
10072 }
10073
10074 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10075 {
10076         if (tracked)
10077                 return atomic_read(&tctx->inflight_tracked);
10078         return percpu_counter_sum(&tctx->inflight);
10079 }
10080
10081 /*
10082  * Find any io_uring ctx that this task has registered or done IO on, and cancel
10083  * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10084  */
10085 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
10086 {
10087         struct io_uring_task *tctx = current->io_uring;
10088         struct io_ring_ctx *ctx;
10089         s64 inflight;
10090         DEFINE_WAIT(wait);
10091
10092         WARN_ON_ONCE(sqd && sqd->thread != current);
10093
10094         if (!current->io_uring)
10095                 return;
10096         if (tctx->io_wq)
10097                 io_wq_exit_start(tctx->io_wq);
10098
10099         atomic_inc(&tctx->in_idle);
10100         do {
10101                 io_uring_drop_tctx_refs(current);
10102                 /* read completions before cancelations */
10103                 inflight = tctx_inflight(tctx, !cancel_all);
10104                 if (!inflight)
10105                         break;
10106
10107                 if (!sqd) {
10108                         struct io_tctx_node *node;
10109                         unsigned long index;
10110
10111                         xa_for_each(&tctx->xa, index, node) {
10112                                 /* sqpoll task will cancel all its requests */
10113                                 if (node->ctx->sq_data)
10114                                         continue;
10115                                 io_uring_try_cancel_requests(node->ctx, current,
10116                                                              cancel_all);
10117                         }
10118                 } else {
10119                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10120                                 io_uring_try_cancel_requests(ctx, current,
10121                                                              cancel_all);
10122                 }
10123
10124                 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10125                 io_run_task_work();
10126                 io_uring_drop_tctx_refs(current);
10127
10128                 /*
10129                  * If we've seen completions, retry without waiting. This
10130                  * avoids a race where a completion comes in before we did
10131                  * prepare_to_wait().
10132                  */
10133                 if (inflight == tctx_inflight(tctx, !cancel_all))
10134                         schedule();
10135                 finish_wait(&tctx->wait, &wait);
10136         } while (1);
10137
10138         io_uring_clean_tctx(tctx);
10139         if (cancel_all) {
10140                 /*
10141                  * We shouldn't run task_works after cancel, so just leave
10142                  * ->in_idle set for normal exit.
10143                  */
10144                 atomic_dec(&tctx->in_idle);
10145                 /* for exec all current's requests should be gone, kill tctx */
10146                 __io_uring_free(current);
10147         }
10148 }
10149
10150 void __io_uring_cancel(bool cancel_all)
10151 {
10152         io_uring_cancel_generic(cancel_all, NULL);
10153 }
10154
10155 static void *io_uring_validate_mmap_request(struct file *file,
10156                                             loff_t pgoff, size_t sz)
10157 {
10158         struct io_ring_ctx *ctx = file->private_data;
10159         loff_t offset = pgoff << PAGE_SHIFT;
10160         struct page *page;
10161         void *ptr;
10162
10163         switch (offset) {
10164         case IORING_OFF_SQ_RING:
10165         case IORING_OFF_CQ_RING:
10166                 ptr = ctx->rings;
10167                 break;
10168         case IORING_OFF_SQES:
10169                 ptr = ctx->sq_sqes;
10170                 break;
10171         default:
10172                 return ERR_PTR(-EINVAL);
10173         }
10174
10175         page = virt_to_head_page(ptr);
10176         if (sz > page_size(page))
10177                 return ERR_PTR(-EINVAL);
10178
10179         return ptr;
10180 }
10181
10182 #ifdef CONFIG_MMU
10183
10184 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10185 {
10186         size_t sz = vma->vm_end - vma->vm_start;
10187         unsigned long pfn;
10188         void *ptr;
10189
10190         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10191         if (IS_ERR(ptr))
10192                 return PTR_ERR(ptr);
10193
10194         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10195         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10196 }
10197
10198 #else /* !CONFIG_MMU */
10199
10200 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10201 {
10202         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10203 }
10204
10205 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10206 {
10207         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10208 }
10209
10210 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10211         unsigned long addr, unsigned long len,
10212         unsigned long pgoff, unsigned long flags)
10213 {
10214         void *ptr;
10215
10216         ptr = io_uring_validate_mmap_request(file, pgoff, len);
10217         if (IS_ERR(ptr))
10218                 return PTR_ERR(ptr);
10219
10220         return (unsigned long) ptr;
10221 }
10222
10223 #endif /* !CONFIG_MMU */
10224
10225 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10226 {
10227         DEFINE_WAIT(wait);
10228
10229         do {
10230                 if (!io_sqring_full(ctx))
10231                         break;
10232                 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10233
10234                 if (!io_sqring_full(ctx))
10235                         break;
10236                 schedule();
10237         } while (!signal_pending(current));
10238
10239         finish_wait(&ctx->sqo_sq_wait, &wait);
10240         return 0;
10241 }
10242
10243 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10244                           struct __kernel_timespec __user **ts,
10245                           const sigset_t __user **sig)
10246 {
10247         struct io_uring_getevents_arg arg;
10248
10249         /*
10250          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10251          * is just a pointer to the sigset_t.
10252          */
10253         if (!(flags & IORING_ENTER_EXT_ARG)) {
10254                 *sig = (const sigset_t __user *) argp;
10255                 *ts = NULL;
10256                 return 0;
10257         }
10258
10259         /*
10260          * EXT_ARG is set - ensure we agree on the size of it and copy in our
10261          * timespec and sigset_t pointers if good.
10262          */
10263         if (*argsz != sizeof(arg))
10264                 return -EINVAL;
10265         if (copy_from_user(&arg, argp, sizeof(arg)))
10266                 return -EFAULT;
10267         if (arg.pad)
10268                 return -EINVAL;
10269         *sig = u64_to_user_ptr(arg.sigmask);
10270         *argsz = arg.sigmask_sz;
10271         *ts = u64_to_user_ptr(arg.ts);
10272         return 0;
10273 }
10274
10275 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10276                 u32, min_complete, u32, flags, const void __user *, argp,
10277                 size_t, argsz)
10278 {
10279         struct io_ring_ctx *ctx;
10280         int submitted = 0;
10281         struct fd f;
10282         long ret;
10283
10284         io_run_task_work();
10285
10286         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10287                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10288                 return -EINVAL;
10289
10290         f = fdget(fd);
10291         if (unlikely(!f.file))
10292                 return -EBADF;
10293
10294         ret = -EOPNOTSUPP;
10295         if (unlikely(f.file->f_op != &io_uring_fops))
10296                 goto out_fput;
10297
10298         ret = -ENXIO;
10299         ctx = f.file->private_data;
10300         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10301                 goto out_fput;
10302
10303         ret = -EBADFD;
10304         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10305                 goto out;
10306
10307         /*
10308          * For SQ polling, the thread will do all submissions and completions.
10309          * Just return the requested submit count, and wake the thread if
10310          * we were asked to.
10311          */
10312         ret = 0;
10313         if (ctx->flags & IORING_SETUP_SQPOLL) {
10314                 io_cqring_overflow_flush(ctx);
10315
10316                 if (unlikely(ctx->sq_data->thread == NULL)) {
10317                         ret = -EOWNERDEAD;
10318                         goto out;
10319                 }
10320                 if (flags & IORING_ENTER_SQ_WAKEUP)
10321                         wake_up(&ctx->sq_data->wait);
10322                 if (flags & IORING_ENTER_SQ_WAIT) {
10323                         ret = io_sqpoll_wait_sq(ctx);
10324                         if (ret)
10325                                 goto out;
10326                 }
10327                 submitted = to_submit;
10328         } else if (to_submit) {
10329                 ret = io_uring_add_tctx_node(ctx);
10330                 if (unlikely(ret))
10331                         goto out;
10332                 mutex_lock(&ctx->uring_lock);
10333                 submitted = io_submit_sqes(ctx, to_submit);
10334                 mutex_unlock(&ctx->uring_lock);
10335
10336                 if (submitted != to_submit)
10337                         goto out;
10338         }
10339         if (flags & IORING_ENTER_GETEVENTS) {
10340                 const sigset_t __user *sig;
10341                 struct __kernel_timespec __user *ts;
10342
10343                 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10344                 if (unlikely(ret))
10345                         goto out;
10346
10347                 min_complete = min(min_complete, ctx->cq_entries);
10348
10349                 /*
10350                  * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10351                  * space applications don't need to do io completion events
10352                  * polling again, they can rely on io_sq_thread to do polling
10353                  * work, which can reduce cpu usage and uring_lock contention.
10354                  */
10355                 if (ctx->flags & IORING_SETUP_IOPOLL &&
10356                     !(ctx->flags & IORING_SETUP_SQPOLL)) {
10357                         ret = io_iopoll_check(ctx, min_complete);
10358                 } else {
10359                         ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10360                 }
10361         }
10362
10363 out:
10364         percpu_ref_put(&ctx->refs);
10365 out_fput:
10366         fdput(f);
10367         return submitted ? submitted : ret;
10368 }
10369
10370 #ifdef CONFIG_PROC_FS
10371 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
10372                 const struct cred *cred)
10373 {
10374         struct user_namespace *uns = seq_user_ns(m);
10375         struct group_info *gi;
10376         kernel_cap_t cap;
10377         unsigned __capi;
10378         int g;
10379
10380         seq_printf(m, "%5d\n", id);
10381         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10382         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10383         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10384         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10385         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10386         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10387         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10388         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10389         seq_puts(m, "\n\tGroups:\t");
10390         gi = cred->group_info;
10391         for (g = 0; g < gi->ngroups; g++) {
10392                 seq_put_decimal_ull(m, g ? " " : "",
10393                                         from_kgid_munged(uns, gi->gid[g]));
10394         }
10395         seq_puts(m, "\n\tCapEff:\t");
10396         cap = cred->cap_effective;
10397         CAP_FOR_EACH_U32(__capi)
10398                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10399         seq_putc(m, '\n');
10400         return 0;
10401 }
10402
10403 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
10404 {
10405         struct io_sq_data *sq = NULL;
10406         bool has_lock;
10407         int i;
10408
10409         /*
10410          * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10411          * since fdinfo case grabs it in the opposite direction of normal use
10412          * cases. If we fail to get the lock, we just don't iterate any
10413          * structures that could be going away outside the io_uring mutex.
10414          */
10415         has_lock = mutex_trylock(&ctx->uring_lock);
10416
10417         if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10418                 sq = ctx->sq_data;
10419                 if (!sq->thread)
10420                         sq = NULL;
10421         }
10422
10423         seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10424         seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10425         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10426         for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10427                 struct file *f = io_file_from_index(ctx, i);
10428
10429                 if (f)
10430                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10431                 else
10432                         seq_printf(m, "%5u: <none>\n", i);
10433         }
10434         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10435         for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10436                 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10437                 unsigned int len = buf->ubuf_end - buf->ubuf;
10438
10439                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10440         }
10441         if (has_lock && !xa_empty(&ctx->personalities)) {
10442                 unsigned long index;
10443                 const struct cred *cred;
10444
10445                 seq_printf(m, "Personalities:\n");
10446                 xa_for_each(&ctx->personalities, index, cred)
10447                         io_uring_show_cred(m, index, cred);
10448         }
10449         seq_printf(m, "PollList:\n");
10450         spin_lock(&ctx->completion_lock);
10451         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10452                 struct hlist_head *list = &ctx->cancel_hash[i];
10453                 struct io_kiocb *req;
10454
10455                 hlist_for_each_entry(req, list, hash_node)
10456                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
10457                                         req->task->task_works != NULL);
10458         }
10459         spin_unlock(&ctx->completion_lock);
10460         if (has_lock)
10461                 mutex_unlock(&ctx->uring_lock);
10462 }
10463
10464 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10465 {
10466         struct io_ring_ctx *ctx = f->private_data;
10467
10468         if (percpu_ref_tryget(&ctx->refs)) {
10469                 __io_uring_show_fdinfo(ctx, m);
10470                 percpu_ref_put(&ctx->refs);
10471         }
10472 }
10473 #endif
10474
10475 static const struct file_operations io_uring_fops = {
10476         .release        = io_uring_release,
10477         .mmap           = io_uring_mmap,
10478 #ifndef CONFIG_MMU
10479         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10480         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10481 #endif
10482         .poll           = io_uring_poll,
10483 #ifdef CONFIG_PROC_FS
10484         .show_fdinfo    = io_uring_show_fdinfo,
10485 #endif
10486 };
10487
10488 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10489                                   struct io_uring_params *p)
10490 {
10491         struct io_rings *rings;
10492         size_t size, sq_array_offset;
10493
10494         /* make sure these are sane, as we already accounted them */
10495         ctx->sq_entries = p->sq_entries;
10496         ctx->cq_entries = p->cq_entries;
10497
10498         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10499         if (size == SIZE_MAX)
10500                 return -EOVERFLOW;
10501
10502         rings = io_mem_alloc(size);
10503         if (!rings)
10504                 return -ENOMEM;
10505
10506         ctx->rings = rings;
10507         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10508         rings->sq_ring_mask = p->sq_entries - 1;
10509         rings->cq_ring_mask = p->cq_entries - 1;
10510         rings->sq_ring_entries = p->sq_entries;
10511         rings->cq_ring_entries = p->cq_entries;
10512
10513         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10514         if (size == SIZE_MAX) {
10515                 io_mem_free(ctx->rings);
10516                 ctx->rings = NULL;
10517                 return -EOVERFLOW;
10518         }
10519
10520         ctx->sq_sqes = io_mem_alloc(size);
10521         if (!ctx->sq_sqes) {
10522                 io_mem_free(ctx->rings);
10523                 ctx->rings = NULL;
10524                 return -ENOMEM;
10525         }
10526
10527         return 0;
10528 }
10529
10530 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10531 {
10532         int ret, fd;
10533
10534         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10535         if (fd < 0)
10536                 return fd;
10537
10538         ret = io_uring_add_tctx_node(ctx);
10539         if (ret) {
10540                 put_unused_fd(fd);
10541                 return ret;
10542         }
10543         fd_install(fd, file);
10544         return fd;
10545 }
10546
10547 /*
10548  * Allocate an anonymous fd, this is what constitutes the application
10549  * visible backing of an io_uring instance. The application mmaps this
10550  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10551  * we have to tie this fd to a socket for file garbage collection purposes.
10552  */
10553 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10554 {
10555         struct file *file;
10556 #if defined(CONFIG_UNIX)
10557         int ret;
10558
10559         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10560                                 &ctx->ring_sock);
10561         if (ret)
10562                 return ERR_PTR(ret);
10563 #endif
10564
10565         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10566                                         O_RDWR | O_CLOEXEC);
10567 #if defined(CONFIG_UNIX)
10568         if (IS_ERR(file)) {
10569                 sock_release(ctx->ring_sock);
10570                 ctx->ring_sock = NULL;
10571         } else {
10572                 ctx->ring_sock->file = file;
10573         }
10574 #endif
10575         return file;
10576 }
10577
10578 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10579                            struct io_uring_params __user *params)
10580 {
10581         struct io_ring_ctx *ctx;
10582         struct file *file;
10583         int ret;
10584
10585         if (!entries)
10586                 return -EINVAL;
10587         if (entries > IORING_MAX_ENTRIES) {
10588                 if (!(p->flags & IORING_SETUP_CLAMP))
10589                         return -EINVAL;
10590                 entries = IORING_MAX_ENTRIES;
10591         }
10592
10593         /*
10594          * Use twice as many entries for the CQ ring. It's possible for the
10595          * application to drive a higher depth than the size of the SQ ring,
10596          * since the sqes are only used at submission time. This allows for
10597          * some flexibility in overcommitting a bit. If the application has
10598          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10599          * of CQ ring entries manually.
10600          */
10601         p->sq_entries = roundup_pow_of_two(entries);
10602         if (p->flags & IORING_SETUP_CQSIZE) {
10603                 /*
10604                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
10605                  * to a power-of-two, if it isn't already. We do NOT impose
10606                  * any cq vs sq ring sizing.
10607                  */
10608                 if (!p->cq_entries)
10609                         return -EINVAL;
10610                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10611                         if (!(p->flags & IORING_SETUP_CLAMP))
10612                                 return -EINVAL;
10613                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
10614                 }
10615                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10616                 if (p->cq_entries < p->sq_entries)
10617                         return -EINVAL;
10618         } else {
10619                 p->cq_entries = 2 * p->sq_entries;
10620         }
10621
10622         ctx = io_ring_ctx_alloc(p);
10623         if (!ctx)
10624                 return -ENOMEM;
10625         ctx->compat = in_compat_syscall();
10626         if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
10627                 ctx->user = get_uid(current_user());
10628
10629         /*
10630          * This is just grabbed for accounting purposes. When a process exits,
10631          * the mm is exited and dropped before the files, hence we need to hang
10632          * on to this mm purely for the purposes of being able to unaccount
10633          * memory (locked/pinned vm). It's not used for anything else.
10634          */
10635         mmgrab(current->mm);
10636         ctx->mm_account = current->mm;
10637
10638         ret = io_allocate_scq_urings(ctx, p);
10639         if (ret)
10640                 goto err;
10641
10642         ret = io_sq_offload_create(ctx, p);
10643         if (ret)
10644                 goto err;
10645         /* always set a rsrc node */
10646         ret = io_rsrc_node_switch_start(ctx);
10647         if (ret)
10648                 goto err;
10649         io_rsrc_node_switch(ctx, NULL);
10650
10651         memset(&p->sq_off, 0, sizeof(p->sq_off));
10652         p->sq_off.head = offsetof(struct io_rings, sq.head);
10653         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10654         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10655         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10656         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10657         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10658         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10659
10660         memset(&p->cq_off, 0, sizeof(p->cq_off));
10661         p->cq_off.head = offsetof(struct io_rings, cq.head);
10662         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10663         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10664         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10665         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10666         p->cq_off.cqes = offsetof(struct io_rings, cqes);
10667         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10668
10669         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10670                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10671                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10672                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10673                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10674                         IORING_FEAT_RSRC_TAGS;
10675
10676         if (copy_to_user(params, p, sizeof(*p))) {
10677                 ret = -EFAULT;
10678                 goto err;
10679         }
10680
10681         file = io_uring_get_file(ctx);
10682         if (IS_ERR(file)) {
10683                 ret = PTR_ERR(file);
10684                 goto err;
10685         }
10686
10687         /*
10688          * Install ring fd as the very last thing, so we don't risk someone
10689          * having closed it before we finish setup
10690          */
10691         ret = io_uring_install_fd(ctx, file);
10692         if (ret < 0) {
10693                 /* fput will clean it up */
10694                 fput(file);
10695                 return ret;
10696         }
10697
10698         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10699         return ret;
10700 err:
10701         io_ring_ctx_wait_and_kill(ctx);
10702         return ret;
10703 }
10704
10705 /*
10706  * Sets up an aio uring context, and returns the fd. Applications asks for a
10707  * ring size, we return the actual sq/cq ring sizes (among other things) in the
10708  * params structure passed in.
10709  */
10710 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10711 {
10712         struct io_uring_params p;
10713         int i;
10714
10715         if (copy_from_user(&p, params, sizeof(p)))
10716                 return -EFAULT;
10717         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10718                 if (p.resv[i])
10719                         return -EINVAL;
10720         }
10721
10722         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10723                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10724                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10725                         IORING_SETUP_R_DISABLED))
10726                 return -EINVAL;
10727
10728         return  io_uring_create(entries, &p, params);
10729 }
10730
10731 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10732                 struct io_uring_params __user *, params)
10733 {
10734         return io_uring_setup(entries, params);
10735 }
10736
10737 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10738 {
10739         struct io_uring_probe *p;
10740         size_t size;
10741         int i, ret;
10742
10743         size = struct_size(p, ops, nr_args);
10744         if (size == SIZE_MAX)
10745                 return -EOVERFLOW;
10746         p = kzalloc(size, GFP_KERNEL);
10747         if (!p)
10748                 return -ENOMEM;
10749
10750         ret = -EFAULT;
10751         if (copy_from_user(p, arg, size))
10752                 goto out;
10753         ret = -EINVAL;
10754         if (memchr_inv(p, 0, size))
10755                 goto out;
10756
10757         p->last_op = IORING_OP_LAST - 1;
10758         if (nr_args > IORING_OP_LAST)
10759                 nr_args = IORING_OP_LAST;
10760
10761         for (i = 0; i < nr_args; i++) {
10762                 p->ops[i].op = i;
10763                 if (!io_op_defs[i].not_supported)
10764                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
10765         }
10766         p->ops_len = i;
10767
10768         ret = 0;
10769         if (copy_to_user(arg, p, size))
10770                 ret = -EFAULT;
10771 out:
10772         kfree(p);
10773         return ret;
10774 }
10775
10776 static int io_register_personality(struct io_ring_ctx *ctx)
10777 {
10778         const struct cred *creds;
10779         u32 id;
10780         int ret;
10781
10782         creds = get_current_cred();
10783
10784         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10785                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10786         if (ret < 0) {
10787                 put_cred(creds);
10788                 return ret;
10789         }
10790         return id;
10791 }
10792
10793 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10794                                     unsigned int nr_args)
10795 {
10796         struct io_uring_restriction *res;
10797         size_t size;
10798         int i, ret;
10799
10800         /* Restrictions allowed only if rings started disabled */
10801         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10802                 return -EBADFD;
10803
10804         /* We allow only a single restrictions registration */
10805         if (ctx->restrictions.registered)
10806                 return -EBUSY;
10807
10808         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10809                 return -EINVAL;
10810
10811         size = array_size(nr_args, sizeof(*res));
10812         if (size == SIZE_MAX)
10813                 return -EOVERFLOW;
10814
10815         res = memdup_user(arg, size);
10816         if (IS_ERR(res))
10817                 return PTR_ERR(res);
10818
10819         ret = 0;
10820
10821         for (i = 0; i < nr_args; i++) {
10822                 switch (res[i].opcode) {
10823                 case IORING_RESTRICTION_REGISTER_OP:
10824                         if (res[i].register_op >= IORING_REGISTER_LAST) {
10825                                 ret = -EINVAL;
10826                                 goto out;
10827                         }
10828
10829                         __set_bit(res[i].register_op,
10830                                   ctx->restrictions.register_op);
10831                         break;
10832                 case IORING_RESTRICTION_SQE_OP:
10833                         if (res[i].sqe_op >= IORING_OP_LAST) {
10834                                 ret = -EINVAL;
10835                                 goto out;
10836                         }
10837
10838                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10839                         break;
10840                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10841                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10842                         break;
10843                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10844                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10845                         break;
10846                 default:
10847                         ret = -EINVAL;
10848                         goto out;
10849                 }
10850         }
10851
10852 out:
10853         /* Reset all restrictions if an error happened */
10854         if (ret != 0)
10855                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10856         else
10857                 ctx->restrictions.registered = true;
10858
10859         kfree(res);
10860         return ret;
10861 }
10862
10863 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10864 {
10865         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10866                 return -EBADFD;
10867
10868         if (ctx->restrictions.registered)
10869                 ctx->restricted = 1;
10870
10871         ctx->flags &= ~IORING_SETUP_R_DISABLED;
10872         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10873                 wake_up(&ctx->sq_data->wait);
10874         return 0;
10875 }
10876
10877 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10878                                      struct io_uring_rsrc_update2 *up,
10879                                      unsigned nr_args)
10880 {
10881         __u32 tmp;
10882         int err;
10883
10884         if (check_add_overflow(up->offset, nr_args, &tmp))
10885                 return -EOVERFLOW;
10886         err = io_rsrc_node_switch_start(ctx);
10887         if (err)
10888                 return err;
10889
10890         switch (type) {
10891         case IORING_RSRC_FILE:
10892                 return __io_sqe_files_update(ctx, up, nr_args);
10893         case IORING_RSRC_BUFFER:
10894                 return __io_sqe_buffers_update(ctx, up, nr_args);
10895         }
10896         return -EINVAL;
10897 }
10898
10899 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10900                                     unsigned nr_args)
10901 {
10902         struct io_uring_rsrc_update2 up;
10903
10904         if (!nr_args)
10905                 return -EINVAL;
10906         memset(&up, 0, sizeof(up));
10907         if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10908                 return -EFAULT;
10909         if (up.resv || up.resv2)
10910                 return -EINVAL;
10911         return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10912 }
10913
10914 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10915                                    unsigned size, unsigned type)
10916 {
10917         struct io_uring_rsrc_update2 up;
10918
10919         if (size != sizeof(up))
10920                 return -EINVAL;
10921         if (copy_from_user(&up, arg, sizeof(up)))
10922                 return -EFAULT;
10923         if (!up.nr || up.resv || up.resv2)
10924                 return -EINVAL;
10925         return __io_register_rsrc_update(ctx, type, &up, up.nr);
10926 }
10927
10928 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10929                             unsigned int size, unsigned int type)
10930 {
10931         struct io_uring_rsrc_register rr;
10932
10933         /* keep it extendible */
10934         if (size != sizeof(rr))
10935                 return -EINVAL;
10936
10937         memset(&rr, 0, sizeof(rr));
10938         if (copy_from_user(&rr, arg, size))
10939                 return -EFAULT;
10940         if (!rr.nr || rr.resv || rr.resv2)
10941                 return -EINVAL;
10942
10943         switch (type) {
10944         case IORING_RSRC_FILE:
10945                 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10946                                              rr.nr, u64_to_user_ptr(rr.tags));
10947         case IORING_RSRC_BUFFER:
10948                 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10949                                                rr.nr, u64_to_user_ptr(rr.tags));
10950         }
10951         return -EINVAL;
10952 }
10953
10954 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10955                                 unsigned len)
10956 {
10957         struct io_uring_task *tctx = current->io_uring;
10958         cpumask_var_t new_mask;
10959         int ret;
10960
10961         if (!tctx || !tctx->io_wq)
10962                 return -EINVAL;
10963
10964         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10965                 return -ENOMEM;
10966
10967         cpumask_clear(new_mask);
10968         if (len > cpumask_size())
10969                 len = cpumask_size();
10970
10971         if (in_compat_syscall()) {
10972                 ret = compat_get_bitmap(cpumask_bits(new_mask),
10973                                         (const compat_ulong_t __user *)arg,
10974                                         len * 8 /* CHAR_BIT */);
10975         } else {
10976                 ret = copy_from_user(new_mask, arg, len);
10977         }
10978
10979         if (ret) {
10980                 free_cpumask_var(new_mask);
10981                 return -EFAULT;
10982         }
10983
10984         ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10985         free_cpumask_var(new_mask);
10986         return ret;
10987 }
10988
10989 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10990 {
10991         struct io_uring_task *tctx = current->io_uring;
10992
10993         if (!tctx || !tctx->io_wq)
10994                 return -EINVAL;
10995
10996         return io_wq_cpu_affinity(tctx->io_wq, NULL);
10997 }
10998
10999 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11000                                         void __user *arg)
11001         __must_hold(&ctx->uring_lock)
11002 {
11003         struct io_tctx_node *node;
11004         struct io_uring_task *tctx = NULL;
11005         struct io_sq_data *sqd = NULL;
11006         __u32 new_count[2];
11007         int i, ret;
11008
11009         if (copy_from_user(new_count, arg, sizeof(new_count)))
11010                 return -EFAULT;
11011         for (i = 0; i < ARRAY_SIZE(new_count); i++)
11012                 if (new_count[i] > INT_MAX)
11013                         return -EINVAL;
11014
11015         if (ctx->flags & IORING_SETUP_SQPOLL) {
11016                 sqd = ctx->sq_data;
11017                 if (sqd) {
11018                         /*
11019                          * Observe the correct sqd->lock -> ctx->uring_lock
11020                          * ordering. Fine to drop uring_lock here, we hold
11021                          * a ref to the ctx.
11022                          */
11023                         refcount_inc(&sqd->refs);
11024                         mutex_unlock(&ctx->uring_lock);
11025                         mutex_lock(&sqd->lock);
11026                         mutex_lock(&ctx->uring_lock);
11027                         if (sqd->thread)
11028                                 tctx = sqd->thread->io_uring;
11029                 }
11030         } else {
11031                 tctx = current->io_uring;
11032         }
11033
11034         BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11035
11036         for (i = 0; i < ARRAY_SIZE(new_count); i++)
11037                 if (new_count[i])
11038                         ctx->iowq_limits[i] = new_count[i];
11039         ctx->iowq_limits_set = true;
11040
11041         ret = -EINVAL;
11042         if (tctx && tctx->io_wq) {
11043                 ret = io_wq_max_workers(tctx->io_wq, new_count);
11044                 if (ret)
11045                         goto err;
11046         } else {
11047                 memset(new_count, 0, sizeof(new_count));
11048         }
11049
11050         if (sqd) {
11051                 mutex_unlock(&sqd->lock);
11052                 io_put_sq_data(sqd);
11053         }
11054
11055         if (copy_to_user(arg, new_count, sizeof(new_count)))
11056                 return -EFAULT;
11057
11058         /* that's it for SQPOLL, only the SQPOLL task creates requests */
11059         if (sqd)
11060                 return 0;
11061
11062         /* now propagate the restriction to all registered users */
11063         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11064                 struct io_uring_task *tctx = node->task->io_uring;
11065
11066                 if (WARN_ON_ONCE(!tctx->io_wq))
11067                         continue;
11068
11069                 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11070                         new_count[i] = ctx->iowq_limits[i];
11071                 /* ignore errors, it always returns zero anyway */
11072                 (void)io_wq_max_workers(tctx->io_wq, new_count);
11073         }
11074         return 0;
11075 err:
11076         if (sqd) {
11077                 mutex_unlock(&sqd->lock);
11078                 io_put_sq_data(sqd);
11079         }
11080         return ret;
11081 }
11082
11083 static bool io_register_op_must_quiesce(int op)
11084 {
11085         switch (op) {
11086         case IORING_REGISTER_BUFFERS:
11087         case IORING_UNREGISTER_BUFFERS:
11088         case IORING_REGISTER_FILES:
11089         case IORING_UNREGISTER_FILES:
11090         case IORING_REGISTER_FILES_UPDATE:
11091         case IORING_REGISTER_PROBE:
11092         case IORING_REGISTER_PERSONALITY:
11093         case IORING_UNREGISTER_PERSONALITY:
11094         case IORING_REGISTER_FILES2:
11095         case IORING_REGISTER_FILES_UPDATE2:
11096         case IORING_REGISTER_BUFFERS2:
11097         case IORING_REGISTER_BUFFERS_UPDATE:
11098         case IORING_REGISTER_IOWQ_AFF:
11099         case IORING_UNREGISTER_IOWQ_AFF:
11100         case IORING_REGISTER_IOWQ_MAX_WORKERS:
11101                 return false;
11102         default:
11103                 return true;
11104         }
11105 }
11106
11107 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
11108 {
11109         long ret;
11110
11111         percpu_ref_kill(&ctx->refs);
11112
11113         /*
11114          * Drop uring mutex before waiting for references to exit. If another
11115          * thread is currently inside io_uring_enter() it might need to grab the
11116          * uring_lock to make progress. If we hold it here across the drain
11117          * wait, then we can deadlock. It's safe to drop the mutex here, since
11118          * no new references will come in after we've killed the percpu ref.
11119          */
11120         mutex_unlock(&ctx->uring_lock);
11121         do {
11122                 ret = wait_for_completion_interruptible(&ctx->ref_comp);
11123                 if (!ret)
11124                         break;
11125                 ret = io_run_task_work_sig();
11126         } while (ret >= 0);
11127         mutex_lock(&ctx->uring_lock);
11128
11129         if (ret)
11130                 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
11131         return ret;
11132 }
11133
11134 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11135                                void __user *arg, unsigned nr_args)
11136         __releases(ctx->uring_lock)
11137         __acquires(ctx->uring_lock)
11138 {
11139         int ret;
11140
11141         /*
11142          * We're inside the ring mutex, if the ref is already dying, then
11143          * someone else killed the ctx or is already going through
11144          * io_uring_register().
11145          */
11146         if (percpu_ref_is_dying(&ctx->refs))
11147                 return -ENXIO;
11148
11149         if (ctx->restricted) {
11150                 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11151                 if (!test_bit(opcode, ctx->restrictions.register_op))
11152                         return -EACCES;
11153         }
11154
11155         if (io_register_op_must_quiesce(opcode)) {
11156                 ret = io_ctx_quiesce(ctx);
11157                 if (ret)
11158                         return ret;
11159         }
11160
11161         switch (opcode) {
11162         case IORING_REGISTER_BUFFERS:
11163                 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11164                 break;
11165         case IORING_UNREGISTER_BUFFERS:
11166                 ret = -EINVAL;
11167                 if (arg || nr_args)
11168                         break;
11169                 ret = io_sqe_buffers_unregister(ctx);
11170                 break;
11171         case IORING_REGISTER_FILES:
11172                 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11173                 break;
11174         case IORING_UNREGISTER_FILES:
11175                 ret = -EINVAL;
11176                 if (arg || nr_args)
11177                         break;
11178                 ret = io_sqe_files_unregister(ctx);
11179                 break;
11180         case IORING_REGISTER_FILES_UPDATE:
11181                 ret = io_register_files_update(ctx, arg, nr_args);
11182                 break;
11183         case IORING_REGISTER_EVENTFD:
11184         case IORING_REGISTER_EVENTFD_ASYNC:
11185                 ret = -EINVAL;
11186                 if (nr_args != 1)
11187                         break;
11188                 ret = io_eventfd_register(ctx, arg);
11189                 if (ret)
11190                         break;
11191                 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
11192                         ctx->eventfd_async = 1;
11193                 else
11194                         ctx->eventfd_async = 0;
11195                 break;
11196         case IORING_UNREGISTER_EVENTFD:
11197                 ret = -EINVAL;
11198                 if (arg || nr_args)
11199                         break;
11200                 ret = io_eventfd_unregister(ctx);
11201                 break;
11202         case IORING_REGISTER_PROBE:
11203                 ret = -EINVAL;
11204                 if (!arg || nr_args > 256)
11205                         break;
11206                 ret = io_probe(ctx, arg, nr_args);
11207                 break;
11208         case IORING_REGISTER_PERSONALITY:
11209                 ret = -EINVAL;
11210                 if (arg || nr_args)
11211                         break;
11212                 ret = io_register_personality(ctx);
11213                 break;
11214         case IORING_UNREGISTER_PERSONALITY:
11215                 ret = -EINVAL;
11216                 if (arg)
11217                         break;
11218                 ret = io_unregister_personality(ctx, nr_args);
11219                 break;
11220         case IORING_REGISTER_ENABLE_RINGS:
11221                 ret = -EINVAL;
11222                 if (arg || nr_args)
11223                         break;
11224                 ret = io_register_enable_rings(ctx);
11225                 break;
11226         case IORING_REGISTER_RESTRICTIONS:
11227                 ret = io_register_restrictions(ctx, arg, nr_args);
11228                 break;
11229         case IORING_REGISTER_FILES2:
11230                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11231                 break;
11232         case IORING_REGISTER_FILES_UPDATE2:
11233                 ret = io_register_rsrc_update(ctx, arg, nr_args,
11234                                               IORING_RSRC_FILE);
11235                 break;
11236         case IORING_REGISTER_BUFFERS2:
11237                 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11238                 break;
11239         case IORING_REGISTER_BUFFERS_UPDATE:
11240                 ret = io_register_rsrc_update(ctx, arg, nr_args,
11241                                               IORING_RSRC_BUFFER);
11242                 break;
11243         case IORING_REGISTER_IOWQ_AFF:
11244                 ret = -EINVAL;
11245                 if (!arg || !nr_args)
11246                         break;
11247                 ret = io_register_iowq_aff(ctx, arg, nr_args);
11248                 break;
11249         case IORING_UNREGISTER_IOWQ_AFF:
11250                 ret = -EINVAL;
11251                 if (arg || nr_args)
11252                         break;
11253                 ret = io_unregister_iowq_aff(ctx);
11254                 break;
11255         case IORING_REGISTER_IOWQ_MAX_WORKERS:
11256                 ret = -EINVAL;
11257                 if (!arg || nr_args != 2)
11258                         break;
11259                 ret = io_register_iowq_max_workers(ctx, arg);
11260                 break;
11261         default:
11262                 ret = -EINVAL;
11263                 break;
11264         }
11265
11266         if (io_register_op_must_quiesce(opcode)) {
11267                 /* bring the ctx back to life */
11268                 percpu_ref_reinit(&ctx->refs);
11269                 reinit_completion(&ctx->ref_comp);
11270         }
11271         return ret;
11272 }
11273
11274 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11275                 void __user *, arg, unsigned int, nr_args)
11276 {
11277         struct io_ring_ctx *ctx;
11278         long ret = -EBADF;
11279         struct fd f;
11280
11281         if (opcode >= IORING_REGISTER_LAST)
11282                 return -EINVAL;
11283
11284         f = fdget(fd);
11285         if (!f.file)
11286                 return -EBADF;
11287
11288         ret = -EOPNOTSUPP;
11289         if (f.file->f_op != &io_uring_fops)
11290                 goto out_fput;
11291
11292         ctx = f.file->private_data;
11293
11294         io_run_task_work();
11295
11296         mutex_lock(&ctx->uring_lock);
11297         ret = __io_uring_register(ctx, opcode, arg, nr_args);
11298         mutex_unlock(&ctx->uring_lock);
11299         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11300                                                         ctx->cq_ev_fd != NULL, ret);
11301 out_fput:
11302         fdput(f);
11303         return ret;
11304 }
11305
11306 static int __init io_uring_init(void)
11307 {
11308 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11309         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11310         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11311 } while (0)
11312
11313 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11314         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11315         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11316         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
11317         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
11318         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
11319         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
11320         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
11321         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
11322         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
11323         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
11324         BUILD_BUG_SQE_ELEM(24, __u32,  len);
11325         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
11326         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
11327         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11328         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
11329         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
11330         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
11331         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
11332         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
11333         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
11334         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
11335         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
11336         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
11337         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
11338         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
11339         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
11340         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
11341         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
11342         BUILD_BUG_SQE_ELEM(40, __u16,  buf_group);
11343         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
11344         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
11345         BUILD_BUG_SQE_ELEM(44, __u32,  file_index);
11346
11347         BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11348                      sizeof(struct io_uring_rsrc_update));
11349         BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11350                      sizeof(struct io_uring_rsrc_update2));
11351
11352         /* ->buf_index is u16 */
11353         BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11354
11355         /* should fit into one byte */
11356         BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11357
11358         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11359         BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11360
11361         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11362                                 SLAB_ACCOUNT);
11363         return 0;
11364 };
11365 __initcall(io_uring_init);