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