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