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