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