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