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