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