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