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