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