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