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