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