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