io_uring: remove useless is_dying check on quiesce
[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         struct llist_node               llist;
228         bool                            done;
229 };
230
231 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
232
233 struct io_rsrc_data {
234         struct fixed_rsrc_table         *table;
235         struct io_ring_ctx              *ctx;
236
237         rsrc_put_fn                     *do_put;
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_node;
451         struct io_rsrc_node             *rsrc_backup_node;
452
453         struct io_restriction           restrictions;
454
455         /* exit task_work */
456         struct callback_head            *exit_task_work;
457
458         struct wait_queue_head          hash_wait;
459
460         /* Keep this last, we don't need it for the fast path */
461         struct work_struct              exit_work;
462         struct list_head                tctx_list;
463 };
464
465 struct io_uring_task {
466         /* submission side */
467         struct xarray           xa;
468         struct wait_queue_head  wait;
469         const struct io_ring_ctx *last;
470         struct io_wq            *io_wq;
471         struct percpu_counter   inflight;
472         atomic_t                in_idle;
473
474         spinlock_t              task_lock;
475         struct io_wq_work_list  task_list;
476         unsigned long           task_state;
477         struct callback_head    task_work;
478 };
479
480 /*
481  * First field must be the file pointer in all the
482  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
483  */
484 struct io_poll_iocb {
485         struct file                     *file;
486         struct wait_queue_head          *head;
487         __poll_t                        events;
488         bool                            done;
489         bool                            canceled;
490         bool                            update_events;
491         bool                            update_user_data;
492         union {
493                 struct wait_queue_entry wait;
494                 struct {
495                         u64             old_user_data;
496                         u64             new_user_data;
497                 };
498         };
499 };
500
501 struct io_poll_remove {
502         struct file                     *file;
503         u64                             addr;
504 };
505
506 struct io_close {
507         struct file                     *file;
508         int                             fd;
509 };
510
511 struct io_timeout_data {
512         struct io_kiocb                 *req;
513         struct hrtimer                  timer;
514         struct timespec64               ts;
515         enum hrtimer_mode               mode;
516 };
517
518 struct io_accept {
519         struct file                     *file;
520         struct sockaddr __user          *addr;
521         int __user                      *addr_len;
522         int                             flags;
523         unsigned long                   nofile;
524 };
525
526 struct io_sync {
527         struct file                     *file;
528         loff_t                          len;
529         loff_t                          off;
530         int                             flags;
531         int                             mode;
532 };
533
534 struct io_cancel {
535         struct file                     *file;
536         u64                             addr;
537 };
538
539 struct io_timeout {
540         struct file                     *file;
541         u32                             off;
542         u32                             target_seq;
543         struct list_head                list;
544         /* head of the link, used by linked timeouts only */
545         struct io_kiocb                 *head;
546 };
547
548 struct io_timeout_rem {
549         struct file                     *file;
550         u64                             addr;
551
552         /* timeout update */
553         struct timespec64               ts;
554         u32                             flags;
555 };
556
557 struct io_rw {
558         /* NOTE: kiocb has the file as the first member, so don't do it here */
559         struct kiocb                    kiocb;
560         u64                             addr;
561         u64                             len;
562 };
563
564 struct io_connect {
565         struct file                     *file;
566         struct sockaddr __user          *addr;
567         int                             addr_len;
568 };
569
570 struct io_sr_msg {
571         struct file                     *file;
572         union {
573                 struct user_msghdr __user *umsg;
574                 void __user             *buf;
575         };
576         int                             msg_flags;
577         int                             bgid;
578         size_t                          len;
579         struct io_buffer                *kbuf;
580 };
581
582 struct io_open {
583         struct file                     *file;
584         int                             dfd;
585         struct filename                 *filename;
586         struct open_how                 how;
587         unsigned long                   nofile;
588 };
589
590 struct io_rsrc_update {
591         struct file                     *file;
592         u64                             arg;
593         u32                             nr_args;
594         u32                             offset;
595 };
596
597 struct io_fadvise {
598         struct file                     *file;
599         u64                             offset;
600         u32                             len;
601         u32                             advice;
602 };
603
604 struct io_madvise {
605         struct file                     *file;
606         u64                             addr;
607         u32                             len;
608         u32                             advice;
609 };
610
611 struct io_epoll {
612         struct file                     *file;
613         int                             epfd;
614         int                             op;
615         int                             fd;
616         struct epoll_event              event;
617 };
618
619 struct io_splice {
620         struct file                     *file_out;
621         struct file                     *file_in;
622         loff_t                          off_out;
623         loff_t                          off_in;
624         u64                             len;
625         unsigned int                    flags;
626 };
627
628 struct io_provide_buf {
629         struct file                     *file;
630         __u64                           addr;
631         __s32                           len;
632         __u32                           bgid;
633         __u16                           nbufs;
634         __u16                           bid;
635 };
636
637 struct io_statx {
638         struct file                     *file;
639         int                             dfd;
640         unsigned int                    mask;
641         unsigned int                    flags;
642         const char __user               *filename;
643         struct statx __user             *buffer;
644 };
645
646 struct io_shutdown {
647         struct file                     *file;
648         int                             how;
649 };
650
651 struct io_rename {
652         struct file                     *file;
653         int                             old_dfd;
654         int                             new_dfd;
655         struct filename                 *oldpath;
656         struct filename                 *newpath;
657         int                             flags;
658 };
659
660 struct io_unlink {
661         struct file                     *file;
662         int                             dfd;
663         int                             flags;
664         struct filename                 *filename;
665 };
666
667 struct io_completion {
668         struct file                     *file;
669         struct list_head                list;
670         u32                             cflags;
671 };
672
673 struct io_async_connect {
674         struct sockaddr_storage         address;
675 };
676
677 struct io_async_msghdr {
678         struct iovec                    fast_iov[UIO_FASTIOV];
679         /* points to an allocated iov, if NULL we use fast_iov instead */
680         struct iovec                    *free_iov;
681         struct sockaddr __user          *uaddr;
682         struct msghdr                   msg;
683         struct sockaddr_storage         addr;
684 };
685
686 struct io_async_rw {
687         struct iovec                    fast_iov[UIO_FASTIOV];
688         const struct iovec              *free_iovec;
689         struct iov_iter                 iter;
690         size_t                          bytes_done;
691         struct wait_page_queue          wpq;
692 };
693
694 enum {
695         REQ_F_FIXED_FILE_BIT    = IOSQE_FIXED_FILE_BIT,
696         REQ_F_IO_DRAIN_BIT      = IOSQE_IO_DRAIN_BIT,
697         REQ_F_LINK_BIT          = IOSQE_IO_LINK_BIT,
698         REQ_F_HARDLINK_BIT      = IOSQE_IO_HARDLINK_BIT,
699         REQ_F_FORCE_ASYNC_BIT   = IOSQE_ASYNC_BIT,
700         REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
701
702         REQ_F_FAIL_LINK_BIT,
703         REQ_F_INFLIGHT_BIT,
704         REQ_F_CUR_POS_BIT,
705         REQ_F_NOWAIT_BIT,
706         REQ_F_LINK_TIMEOUT_BIT,
707         REQ_F_NEED_CLEANUP_BIT,
708         REQ_F_POLLED_BIT,
709         REQ_F_BUFFER_SELECTED_BIT,
710         REQ_F_LTIMEOUT_ACTIVE_BIT,
711         REQ_F_COMPLETE_INLINE_BIT,
712         REQ_F_REISSUE_BIT,
713         REQ_F_DONT_REISSUE_BIT,
714         /* keep async read/write and isreg together and in order */
715         REQ_F_ASYNC_READ_BIT,
716         REQ_F_ASYNC_WRITE_BIT,
717         REQ_F_ISREG_BIT,
718
719         /* not a real bit, just to check we're not overflowing the space */
720         __REQ_F_LAST_BIT,
721 };
722
723 enum {
724         /* ctx owns file */
725         REQ_F_FIXED_FILE        = BIT(REQ_F_FIXED_FILE_BIT),
726         /* drain existing IO first */
727         REQ_F_IO_DRAIN          = BIT(REQ_F_IO_DRAIN_BIT),
728         /* linked sqes */
729         REQ_F_LINK              = BIT(REQ_F_LINK_BIT),
730         /* doesn't sever on completion < 0 */
731         REQ_F_HARDLINK          = BIT(REQ_F_HARDLINK_BIT),
732         /* IOSQE_ASYNC */
733         REQ_F_FORCE_ASYNC       = BIT(REQ_F_FORCE_ASYNC_BIT),
734         /* IOSQE_BUFFER_SELECT */
735         REQ_F_BUFFER_SELECT     = BIT(REQ_F_BUFFER_SELECT_BIT),
736
737         /* fail rest of links */
738         REQ_F_FAIL_LINK         = BIT(REQ_F_FAIL_LINK_BIT),
739         /* on inflight list, should be cancelled and waited on exit reliably */
740         REQ_F_INFLIGHT          = BIT(REQ_F_INFLIGHT_BIT),
741         /* read/write uses file position */
742         REQ_F_CUR_POS           = BIT(REQ_F_CUR_POS_BIT),
743         /* must not punt to workers */
744         REQ_F_NOWAIT            = BIT(REQ_F_NOWAIT_BIT),
745         /* has or had linked timeout */
746         REQ_F_LINK_TIMEOUT      = BIT(REQ_F_LINK_TIMEOUT_BIT),
747         /* needs cleanup */
748         REQ_F_NEED_CLEANUP      = BIT(REQ_F_NEED_CLEANUP_BIT),
749         /* already went through poll handler */
750         REQ_F_POLLED            = BIT(REQ_F_POLLED_BIT),
751         /* buffer already selected */
752         REQ_F_BUFFER_SELECTED   = BIT(REQ_F_BUFFER_SELECTED_BIT),
753         /* linked timeout is active, i.e. prepared by link's head */
754         REQ_F_LTIMEOUT_ACTIVE   = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
755         /* completion is deferred through io_comp_state */
756         REQ_F_COMPLETE_INLINE   = BIT(REQ_F_COMPLETE_INLINE_BIT),
757         /* caller should reissue async */
758         REQ_F_REISSUE           = BIT(REQ_F_REISSUE_BIT),
759         /* don't attempt request reissue, see io_rw_reissue() */
760         REQ_F_DONT_REISSUE      = BIT(REQ_F_DONT_REISSUE_BIT),
761         /* supports async reads */
762         REQ_F_ASYNC_READ        = BIT(REQ_F_ASYNC_READ_BIT),
763         /* supports async writes */
764         REQ_F_ASYNC_WRITE       = BIT(REQ_F_ASYNC_WRITE_BIT),
765         /* regular file */
766         REQ_F_ISREG             = BIT(REQ_F_ISREG_BIT),
767 };
768
769 struct async_poll {
770         struct io_poll_iocb     poll;
771         struct io_poll_iocb     *double_poll;
772 };
773
774 struct io_task_work {
775         struct io_wq_work_node  node;
776         task_work_func_t        func;
777 };
778
779 /*
780  * NOTE! Each of the iocb union members has the file pointer
781  * as the first entry in their struct definition. So you can
782  * access the file pointer through any of the sub-structs,
783  * or directly as just 'ki_filp' in this struct.
784  */
785 struct io_kiocb {
786         union {
787                 struct file             *file;
788                 struct io_rw            rw;
789                 struct io_poll_iocb     poll;
790                 struct io_poll_remove   poll_remove;
791                 struct io_accept        accept;
792                 struct io_sync          sync;
793                 struct io_cancel        cancel;
794                 struct io_timeout       timeout;
795                 struct io_timeout_rem   timeout_rem;
796                 struct io_connect       connect;
797                 struct io_sr_msg        sr_msg;
798                 struct io_open          open;
799                 struct io_close         close;
800                 struct io_rsrc_update   rsrc_update;
801                 struct io_fadvise       fadvise;
802                 struct io_madvise       madvise;
803                 struct io_epoll         epoll;
804                 struct io_splice        splice;
805                 struct io_provide_buf   pbuf;
806                 struct io_statx         statx;
807                 struct io_shutdown      shutdown;
808                 struct io_rename        rename;
809                 struct io_unlink        unlink;
810                 /* use only after cleaning per-op data, see io_clean_op() */
811                 struct io_completion    compl;
812         };
813
814         /* opcode allocated if it needs to store data for async defer */
815         void                            *async_data;
816         u8                              opcode;
817         /* polled IO has completed */
818         u8                              iopoll_completed;
819
820         u16                             buf_index;
821         u32                             result;
822
823         struct io_ring_ctx              *ctx;
824         unsigned int                    flags;
825         atomic_t                        refs;
826         struct task_struct              *task;
827         u64                             user_data;
828
829         struct io_kiocb                 *link;
830         struct percpu_ref               *fixed_rsrc_refs;
831
832         /*
833          * 1. used with ctx->iopoll_list with reads/writes
834          * 2. to track reqs with ->files (see io_op_def::file_table)
835          */
836         struct list_head                inflight_entry;
837         union {
838                 struct io_task_work     io_task_work;
839                 struct callback_head    task_work;
840         };
841         /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
842         struct hlist_node               hash_node;
843         struct async_poll               *apoll;
844         struct io_wq_work               work;
845 };
846
847 struct io_tctx_node {
848         struct list_head        ctx_node;
849         struct task_struct      *task;
850         struct io_ring_ctx      *ctx;
851 };
852
853 struct io_defer_entry {
854         struct list_head        list;
855         struct io_kiocb         *req;
856         u32                     seq;
857 };
858
859 struct io_op_def {
860         /* needs req->file assigned */
861         unsigned                needs_file : 1;
862         /* hash wq insertion if file is a regular file */
863         unsigned                hash_reg_file : 1;
864         /* unbound wq insertion if file is a non-regular file */
865         unsigned                unbound_nonreg_file : 1;
866         /* opcode is not supported by this kernel */
867         unsigned                not_supported : 1;
868         /* set if opcode supports polled "wait" */
869         unsigned                pollin : 1;
870         unsigned                pollout : 1;
871         /* op supports buffer selection */
872         unsigned                buffer_select : 1;
873         /* do prep async if is going to be punted */
874         unsigned                needs_async_setup : 1;
875         /* should block plug */
876         unsigned                plug : 1;
877         /* size of async data needed, if any */
878         unsigned short          async_size;
879 };
880
881 static const struct io_op_def io_op_defs[] = {
882         [IORING_OP_NOP] = {},
883         [IORING_OP_READV] = {
884                 .needs_file             = 1,
885                 .unbound_nonreg_file    = 1,
886                 .pollin                 = 1,
887                 .buffer_select          = 1,
888                 .needs_async_setup      = 1,
889                 .plug                   = 1,
890                 .async_size             = sizeof(struct io_async_rw),
891         },
892         [IORING_OP_WRITEV] = {
893                 .needs_file             = 1,
894                 .hash_reg_file          = 1,
895                 .unbound_nonreg_file    = 1,
896                 .pollout                = 1,
897                 .needs_async_setup      = 1,
898                 .plug                   = 1,
899                 .async_size             = sizeof(struct io_async_rw),
900         },
901         [IORING_OP_FSYNC] = {
902                 .needs_file             = 1,
903         },
904         [IORING_OP_READ_FIXED] = {
905                 .needs_file             = 1,
906                 .unbound_nonreg_file    = 1,
907                 .pollin                 = 1,
908                 .plug                   = 1,
909                 .async_size             = sizeof(struct io_async_rw),
910         },
911         [IORING_OP_WRITE_FIXED] = {
912                 .needs_file             = 1,
913                 .hash_reg_file          = 1,
914                 .unbound_nonreg_file    = 1,
915                 .pollout                = 1,
916                 .plug                   = 1,
917                 .async_size             = sizeof(struct io_async_rw),
918         },
919         [IORING_OP_POLL_ADD] = {
920                 .needs_file             = 1,
921                 .unbound_nonreg_file    = 1,
922         },
923         [IORING_OP_POLL_REMOVE] = {},
924         [IORING_OP_SYNC_FILE_RANGE] = {
925                 .needs_file             = 1,
926         },
927         [IORING_OP_SENDMSG] = {
928                 .needs_file             = 1,
929                 .unbound_nonreg_file    = 1,
930                 .pollout                = 1,
931                 .needs_async_setup      = 1,
932                 .async_size             = sizeof(struct io_async_msghdr),
933         },
934         [IORING_OP_RECVMSG] = {
935                 .needs_file             = 1,
936                 .unbound_nonreg_file    = 1,
937                 .pollin                 = 1,
938                 .buffer_select          = 1,
939                 .needs_async_setup      = 1,
940                 .async_size             = sizeof(struct io_async_msghdr),
941         },
942         [IORING_OP_TIMEOUT] = {
943                 .async_size             = sizeof(struct io_timeout_data),
944         },
945         [IORING_OP_TIMEOUT_REMOVE] = {
946                 /* used by timeout updates' prep() */
947         },
948         [IORING_OP_ACCEPT] = {
949                 .needs_file             = 1,
950                 .unbound_nonreg_file    = 1,
951                 .pollin                 = 1,
952         },
953         [IORING_OP_ASYNC_CANCEL] = {},
954         [IORING_OP_LINK_TIMEOUT] = {
955                 .async_size             = sizeof(struct io_timeout_data),
956         },
957         [IORING_OP_CONNECT] = {
958                 .needs_file             = 1,
959                 .unbound_nonreg_file    = 1,
960                 .pollout                = 1,
961                 .needs_async_setup      = 1,
962                 .async_size             = sizeof(struct io_async_connect),
963         },
964         [IORING_OP_FALLOCATE] = {
965                 .needs_file             = 1,
966         },
967         [IORING_OP_OPENAT] = {},
968         [IORING_OP_CLOSE] = {},
969         [IORING_OP_FILES_UPDATE] = {},
970         [IORING_OP_STATX] = {},
971         [IORING_OP_READ] = {
972                 .needs_file             = 1,
973                 .unbound_nonreg_file    = 1,
974                 .pollin                 = 1,
975                 .buffer_select          = 1,
976                 .plug                   = 1,
977                 .async_size             = sizeof(struct io_async_rw),
978         },
979         [IORING_OP_WRITE] = {
980                 .needs_file             = 1,
981                 .unbound_nonreg_file    = 1,
982                 .pollout                = 1,
983                 .plug                   = 1,
984                 .async_size             = sizeof(struct io_async_rw),
985         },
986         [IORING_OP_FADVISE] = {
987                 .needs_file             = 1,
988         },
989         [IORING_OP_MADVISE] = {},
990         [IORING_OP_SEND] = {
991                 .needs_file             = 1,
992                 .unbound_nonreg_file    = 1,
993                 .pollout                = 1,
994         },
995         [IORING_OP_RECV] = {
996                 .needs_file             = 1,
997                 .unbound_nonreg_file    = 1,
998                 .pollin                 = 1,
999                 .buffer_select          = 1,
1000         },
1001         [IORING_OP_OPENAT2] = {
1002         },
1003         [IORING_OP_EPOLL_CTL] = {
1004                 .unbound_nonreg_file    = 1,
1005         },
1006         [IORING_OP_SPLICE] = {
1007                 .needs_file             = 1,
1008                 .hash_reg_file          = 1,
1009                 .unbound_nonreg_file    = 1,
1010         },
1011         [IORING_OP_PROVIDE_BUFFERS] = {},
1012         [IORING_OP_REMOVE_BUFFERS] = {},
1013         [IORING_OP_TEE] = {
1014                 .needs_file             = 1,
1015                 .hash_reg_file          = 1,
1016                 .unbound_nonreg_file    = 1,
1017         },
1018         [IORING_OP_SHUTDOWN] = {
1019                 .needs_file             = 1,
1020         },
1021         [IORING_OP_RENAMEAT] = {},
1022         [IORING_OP_UNLINKAT] = {},
1023 };
1024
1025 static bool io_disarm_next(struct io_kiocb *req);
1026 static void io_uring_del_task_file(unsigned long index);
1027 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1028                                          struct task_struct *task,
1029                                          struct files_struct *files);
1030 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
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->rsrc_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_destroy(struct io_rsrc_node *ref_node)
7096 {
7097         percpu_ref_exit(&ref_node->refs);
7098         kfree(ref_node);
7099 }
7100
7101 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7102                                 struct io_rsrc_data *data_to_kill)
7103 {
7104         WARN_ON_ONCE(!ctx->rsrc_backup_node);
7105         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7106
7107         if (data_to_kill) {
7108                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7109
7110                 rsrc_node->rsrc_data = data_to_kill;
7111                 io_rsrc_ref_lock(ctx);
7112                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7113                 io_rsrc_ref_unlock(ctx);
7114
7115                 percpu_ref_get(&data_to_kill->refs);
7116                 percpu_ref_kill(&rsrc_node->refs);
7117                 ctx->rsrc_node = NULL;
7118         }
7119
7120         if (!ctx->rsrc_node) {
7121                 ctx->rsrc_node = ctx->rsrc_backup_node;
7122                 ctx->rsrc_backup_node = NULL;
7123         }
7124 }
7125
7126 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7127 {
7128         if (ctx->rsrc_backup_node)
7129                 return 0;
7130         ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7131         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7132 }
7133
7134 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7135 {
7136         int ret;
7137
7138         /* As we may drop ->uring_lock, other task may have started quiesce */
7139         if (data->quiesce)
7140                 return -ENXIO;
7141
7142         data->quiesce = true;
7143         do {
7144                 ret = io_rsrc_node_switch_start(ctx);
7145                 if (ret)
7146                         break;
7147                 io_rsrc_node_switch(ctx, data);
7148
7149                 percpu_ref_kill(&data->refs);
7150                 flush_delayed_work(&ctx->rsrc_put_work);
7151
7152                 ret = wait_for_completion_interruptible(&data->done);
7153                 if (!ret)
7154                         break;
7155
7156                 percpu_ref_resurrect(&data->refs);
7157                 reinit_completion(&data->done);
7158
7159                 mutex_unlock(&ctx->uring_lock);
7160                 ret = io_run_task_work_sig();
7161                 mutex_lock(&ctx->uring_lock);
7162         } while (ret >= 0);
7163         data->quiesce = false;
7164
7165         return ret;
7166 }
7167
7168 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7169                                                rsrc_put_fn *do_put)
7170 {
7171         struct io_rsrc_data *data;
7172
7173         data = kzalloc(sizeof(*data), GFP_KERNEL);
7174         if (!data)
7175                 return NULL;
7176
7177         if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7178                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7179                 kfree(data);
7180                 return NULL;
7181         }
7182         data->ctx = ctx;
7183         data->do_put = do_put;
7184         init_completion(&data->done);
7185         return data;
7186 }
7187
7188 static void io_rsrc_data_free(struct io_rsrc_data *data)
7189 {
7190         percpu_ref_exit(&data->refs);
7191         kfree(data->table);
7192         kfree(data);
7193 }
7194
7195 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7196 {
7197         struct io_rsrc_data *data = ctx->file_data;
7198         unsigned nr_tables, i;
7199         int ret;
7200
7201         if (!data)
7202                 return -ENXIO;
7203         ret = io_rsrc_ref_quiesce(data, ctx);
7204         if (ret)
7205                 return ret;
7206
7207         __io_sqe_files_unregister(ctx);
7208         nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7209         for (i = 0; i < nr_tables; i++)
7210                 kfree(data->table[i].files);
7211         io_rsrc_data_free(data);
7212         ctx->file_data = NULL;
7213         ctx->nr_user_files = 0;
7214         return 0;
7215 }
7216
7217 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7218         __releases(&sqd->lock)
7219 {
7220         WARN_ON_ONCE(sqd->thread == current);
7221
7222         /*
7223          * Do the dance but not conditional clear_bit() because it'd race with
7224          * other threads incrementing park_pending and setting the bit.
7225          */
7226         clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7227         if (atomic_dec_return(&sqd->park_pending))
7228                 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7229         mutex_unlock(&sqd->lock);
7230 }
7231
7232 static void io_sq_thread_park(struct io_sq_data *sqd)
7233         __acquires(&sqd->lock)
7234 {
7235         WARN_ON_ONCE(sqd->thread == current);
7236
7237         atomic_inc(&sqd->park_pending);
7238         set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7239         mutex_lock(&sqd->lock);
7240         if (sqd->thread)
7241                 wake_up_process(sqd->thread);
7242 }
7243
7244 static void io_sq_thread_stop(struct io_sq_data *sqd)
7245 {
7246         WARN_ON_ONCE(sqd->thread == current);
7247
7248         mutex_lock(&sqd->lock);
7249         set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7250         if (sqd->thread)
7251                 wake_up_process(sqd->thread);
7252         mutex_unlock(&sqd->lock);
7253         wait_for_completion(&sqd->exited);
7254 }
7255
7256 static void io_put_sq_data(struct io_sq_data *sqd)
7257 {
7258         if (refcount_dec_and_test(&sqd->refs)) {
7259                 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7260
7261                 io_sq_thread_stop(sqd);
7262                 kfree(sqd);
7263         }
7264 }
7265
7266 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7267 {
7268         struct io_sq_data *sqd = ctx->sq_data;
7269
7270         if (sqd) {
7271                 io_sq_thread_park(sqd);
7272                 list_del_init(&ctx->sqd_list);
7273                 io_sqd_update_thread_idle(sqd);
7274                 io_sq_thread_unpark(sqd);
7275
7276                 io_put_sq_data(sqd);
7277                 ctx->sq_data = NULL;
7278                 if (ctx->sq_creds)
7279                         put_cred(ctx->sq_creds);
7280         }
7281 }
7282
7283 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7284 {
7285         struct io_ring_ctx *ctx_attach;
7286         struct io_sq_data *sqd;
7287         struct fd f;
7288
7289         f = fdget(p->wq_fd);
7290         if (!f.file)
7291                 return ERR_PTR(-ENXIO);
7292         if (f.file->f_op != &io_uring_fops) {
7293                 fdput(f);
7294                 return ERR_PTR(-EINVAL);
7295         }
7296
7297         ctx_attach = f.file->private_data;
7298         sqd = ctx_attach->sq_data;
7299         if (!sqd) {
7300                 fdput(f);
7301                 return ERR_PTR(-EINVAL);
7302         }
7303         if (sqd->task_tgid != current->tgid) {
7304                 fdput(f);
7305                 return ERR_PTR(-EPERM);
7306         }
7307
7308         refcount_inc(&sqd->refs);
7309         fdput(f);
7310         return sqd;
7311 }
7312
7313 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7314                                          bool *attached)
7315 {
7316         struct io_sq_data *sqd;
7317
7318         *attached = false;
7319         if (p->flags & IORING_SETUP_ATTACH_WQ) {
7320                 sqd = io_attach_sq_data(p);
7321                 if (!IS_ERR(sqd)) {
7322                         *attached = true;
7323                         return sqd;
7324                 }
7325                 /* fall through for EPERM case, setup new sqd/task */
7326                 if (PTR_ERR(sqd) != -EPERM)
7327                         return sqd;
7328         }
7329
7330         sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7331         if (!sqd)
7332                 return ERR_PTR(-ENOMEM);
7333
7334         atomic_set(&sqd->park_pending, 0);
7335         refcount_set(&sqd->refs, 1);
7336         INIT_LIST_HEAD(&sqd->ctx_list);
7337         mutex_init(&sqd->lock);
7338         init_waitqueue_head(&sqd->wait);
7339         init_completion(&sqd->exited);
7340         return sqd;
7341 }
7342
7343 #if defined(CONFIG_UNIX)
7344 /*
7345  * Ensure the UNIX gc is aware of our file set, so we are certain that
7346  * the io_uring can be safely unregistered on process exit, even if we have
7347  * loops in the file referencing.
7348  */
7349 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7350 {
7351         struct sock *sk = ctx->ring_sock->sk;
7352         struct scm_fp_list *fpl;
7353         struct sk_buff *skb;
7354         int i, nr_files;
7355
7356         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7357         if (!fpl)
7358                 return -ENOMEM;
7359
7360         skb = alloc_skb(0, GFP_KERNEL);
7361         if (!skb) {
7362                 kfree(fpl);
7363                 return -ENOMEM;
7364         }
7365
7366         skb->sk = sk;
7367
7368         nr_files = 0;
7369         fpl->user = get_uid(current_user());
7370         for (i = 0; i < nr; i++) {
7371                 struct file *file = io_file_from_index(ctx, i + offset);
7372
7373                 if (!file)
7374                         continue;
7375                 fpl->fp[nr_files] = get_file(file);
7376                 unix_inflight(fpl->user, fpl->fp[nr_files]);
7377                 nr_files++;
7378         }
7379
7380         if (nr_files) {
7381                 fpl->max = SCM_MAX_FD;
7382                 fpl->count = nr_files;
7383                 UNIXCB(skb).fp = fpl;
7384                 skb->destructor = unix_destruct_scm;
7385                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7386                 skb_queue_head(&sk->sk_receive_queue, skb);
7387
7388                 for (i = 0; i < nr_files; i++)
7389                         fput(fpl->fp[i]);
7390         } else {
7391                 kfree_skb(skb);
7392                 kfree(fpl);
7393         }
7394
7395         return 0;
7396 }
7397
7398 /*
7399  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7400  * causes regular reference counting to break down. We rely on the UNIX
7401  * garbage collection to take care of this problem for us.
7402  */
7403 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7404 {
7405         unsigned left, total;
7406         int ret = 0;
7407
7408         total = 0;
7409         left = ctx->nr_user_files;
7410         while (left) {
7411                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7412
7413                 ret = __io_sqe_files_scm(ctx, this_files, total);
7414                 if (ret)
7415                         break;
7416                 left -= this_files;
7417                 total += this_files;
7418         }
7419
7420         if (!ret)
7421                 return 0;
7422
7423         while (total < ctx->nr_user_files) {
7424                 struct file *file = io_file_from_index(ctx, total);
7425
7426                 if (file)
7427                         fput(file);
7428                 total++;
7429         }
7430
7431         return ret;
7432 }
7433 #else
7434 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7435 {
7436         return 0;
7437 }
7438 #endif
7439
7440 static int io_sqe_alloc_file_tables(struct io_rsrc_data *file_data,
7441                                     unsigned nr_tables, unsigned nr_files)
7442 {
7443         int i;
7444
7445         for (i = 0; i < nr_tables; i++) {
7446                 struct fixed_rsrc_table *table = &file_data->table[i];
7447                 unsigned this_files;
7448
7449                 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7450                 table->files = kcalloc(this_files, sizeof(struct file *),
7451                                         GFP_KERNEL);
7452                 if (!table->files)
7453                         break;
7454                 nr_files -= this_files;
7455         }
7456
7457         if (i == nr_tables)
7458                 return 0;
7459
7460         for (i = 0; i < nr_tables; i++) {
7461                 struct fixed_rsrc_table *table = &file_data->table[i];
7462                 kfree(table->files);
7463         }
7464         return 1;
7465 }
7466
7467 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7468 {
7469         struct file *file = prsrc->file;
7470 #if defined(CONFIG_UNIX)
7471         struct sock *sock = ctx->ring_sock->sk;
7472         struct sk_buff_head list, *head = &sock->sk_receive_queue;
7473         struct sk_buff *skb;
7474         int i;
7475
7476         __skb_queue_head_init(&list);
7477
7478         /*
7479          * Find the skb that holds this file in its SCM_RIGHTS. When found,
7480          * remove this entry and rearrange the file array.
7481          */
7482         skb = skb_dequeue(head);
7483         while (skb) {
7484                 struct scm_fp_list *fp;
7485
7486                 fp = UNIXCB(skb).fp;
7487                 for (i = 0; i < fp->count; i++) {
7488                         int left;
7489
7490                         if (fp->fp[i] != file)
7491                                 continue;
7492
7493                         unix_notinflight(fp->user, fp->fp[i]);
7494                         left = fp->count - 1 - i;
7495                         if (left) {
7496                                 memmove(&fp->fp[i], &fp->fp[i + 1],
7497                                                 left * sizeof(struct file *));
7498                         }
7499                         fp->count--;
7500                         if (!fp->count) {
7501                                 kfree_skb(skb);
7502                                 skb = NULL;
7503                         } else {
7504                                 __skb_queue_tail(&list, skb);
7505                         }
7506                         fput(file);
7507                         file = NULL;
7508                         break;
7509                 }
7510
7511                 if (!file)
7512                         break;
7513
7514                 __skb_queue_tail(&list, skb);
7515
7516                 skb = skb_dequeue(head);
7517         }
7518
7519         if (skb_peek(&list)) {
7520                 spin_lock_irq(&head->lock);
7521                 while ((skb = __skb_dequeue(&list)) != NULL)
7522                         __skb_queue_tail(head, skb);
7523                 spin_unlock_irq(&head->lock);
7524         }
7525 #else
7526         fput(file);
7527 #endif
7528 }
7529
7530 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7531 {
7532         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7533         struct io_ring_ctx *ctx = rsrc_data->ctx;
7534         struct io_rsrc_put *prsrc, *tmp;
7535
7536         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7537                 list_del(&prsrc->list);
7538                 rsrc_data->do_put(ctx, prsrc);
7539                 kfree(prsrc);
7540         }
7541
7542         io_rsrc_node_destroy(ref_node);
7543         percpu_ref_put(&rsrc_data->refs);
7544 }
7545
7546 static void io_rsrc_put_work(struct work_struct *work)
7547 {
7548         struct io_ring_ctx *ctx;
7549         struct llist_node *node;
7550
7551         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7552         node = llist_del_all(&ctx->rsrc_put_llist);
7553
7554         while (node) {
7555                 struct io_rsrc_node *ref_node;
7556                 struct llist_node *next = node->next;
7557
7558                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7559                 __io_rsrc_put_work(ref_node);
7560                 node = next;
7561         }
7562 }
7563
7564 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7565 {
7566         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7567         struct io_rsrc_data *data = node->rsrc_data;
7568         struct io_ring_ctx *ctx = data->ctx;
7569         bool first_add = false;
7570         int delay;
7571
7572         io_rsrc_ref_lock(ctx);
7573         node->done = true;
7574
7575         while (!list_empty(&ctx->rsrc_ref_list)) {
7576                 node = list_first_entry(&ctx->rsrc_ref_list,
7577                                             struct io_rsrc_node, node);
7578                 /* recycle ref nodes in order */
7579                 if (!node->done)
7580                         break;
7581                 list_del(&node->node);
7582                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7583         }
7584         io_rsrc_ref_unlock(ctx);
7585
7586         delay = percpu_ref_is_dying(&data->refs) ? 0 : HZ;
7587         if (first_add || !delay)
7588                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7589 }
7590
7591 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7592 {
7593         struct io_rsrc_node *ref_node;
7594
7595         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7596         if (!ref_node)
7597                 return NULL;
7598
7599         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7600                             0, GFP_KERNEL)) {
7601                 kfree(ref_node);
7602                 return NULL;
7603         }
7604         INIT_LIST_HEAD(&ref_node->node);
7605         INIT_LIST_HEAD(&ref_node->rsrc_list);
7606         ref_node->done = false;
7607         return ref_node;
7608 }
7609
7610 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7611                                  unsigned nr_args)
7612 {
7613         __s32 __user *fds = (__s32 __user *) arg;
7614         unsigned nr_tables, i;
7615         struct file *file;
7616         int fd, ret;
7617         struct io_rsrc_data *file_data;
7618
7619         if (ctx->file_data)
7620                 return -EBUSY;
7621         if (!nr_args)
7622                 return -EINVAL;
7623         if (nr_args > IORING_MAX_FIXED_FILES)
7624                 return -EMFILE;
7625         ret = io_rsrc_node_switch_start(ctx);
7626         if (ret)
7627                 return ret;
7628
7629         file_data = io_rsrc_data_alloc(ctx, io_ring_file_put);
7630         if (!file_data)
7631                 return -ENOMEM;
7632         ctx->file_data = file_data;
7633
7634         ret = -ENOMEM;
7635         nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7636         file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7637                                    GFP_KERNEL);
7638         if (!file_data->table)
7639                 goto out_free;
7640
7641         if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7642                 goto out_free;
7643
7644         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7645                 unsigned long file_ptr;
7646
7647                 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7648                         ret = -EFAULT;
7649                         goto out_fput;
7650                 }
7651                 /* allow sparse sets */
7652                 if (fd == -1)
7653                         continue;
7654
7655                 file = fget(fd);
7656                 ret = -EBADF;
7657                 if (!file)
7658                         goto out_fput;
7659
7660                 /*
7661                  * Don't allow io_uring instances to be registered. If UNIX
7662                  * isn't enabled, then this causes a reference cycle and this
7663                  * instance can never get freed. If UNIX is enabled we'll
7664                  * handle it just fine, but there's still no point in allowing
7665                  * a ring fd as it doesn't support regular read/write anyway.
7666                  */
7667                 if (file->f_op == &io_uring_fops) {
7668                         fput(file);
7669                         goto out_fput;
7670                 }
7671                 file_ptr = (unsigned long) file;
7672                 if (__io_file_supports_async(file, READ))
7673                         file_ptr |= FFS_ASYNC_READ;
7674                 if (__io_file_supports_async(file, WRITE))
7675                         file_ptr |= FFS_ASYNC_WRITE;
7676                 if (S_ISREG(file_inode(file)->i_mode))
7677                         file_ptr |= FFS_ISREG;
7678                 *io_fixed_file_slot(file_data, i) = (struct file *) file_ptr;
7679         }
7680
7681         ret = io_sqe_files_scm(ctx);
7682         if (ret) {
7683                 io_sqe_files_unregister(ctx);
7684                 return ret;
7685         }
7686
7687         io_rsrc_node_switch(ctx, NULL);
7688         return ret;
7689 out_fput:
7690         for (i = 0; i < ctx->nr_user_files; i++) {
7691                 file = io_file_from_index(ctx, i);
7692                 if (file)
7693                         fput(file);
7694         }
7695         for (i = 0; i < nr_tables; i++)
7696                 kfree(file_data->table[i].files);
7697         ctx->nr_user_files = 0;
7698 out_free:
7699         io_rsrc_data_free(ctx->file_data);
7700         ctx->file_data = NULL;
7701         return ret;
7702 }
7703
7704 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7705                                 int index)
7706 {
7707 #if defined(CONFIG_UNIX)
7708         struct sock *sock = ctx->ring_sock->sk;
7709         struct sk_buff_head *head = &sock->sk_receive_queue;
7710         struct sk_buff *skb;
7711
7712         /*
7713          * See if we can merge this file into an existing skb SCM_RIGHTS
7714          * file set. If there's no room, fall back to allocating a new skb
7715          * and filling it in.
7716          */
7717         spin_lock_irq(&head->lock);
7718         skb = skb_peek(head);
7719         if (skb) {
7720                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7721
7722                 if (fpl->count < SCM_MAX_FD) {
7723                         __skb_unlink(skb, head);
7724                         spin_unlock_irq(&head->lock);
7725                         fpl->fp[fpl->count] = get_file(file);
7726                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
7727                         fpl->count++;
7728                         spin_lock_irq(&head->lock);
7729                         __skb_queue_head(head, skb);
7730                 } else {
7731                         skb = NULL;
7732                 }
7733         }
7734         spin_unlock_irq(&head->lock);
7735
7736         if (skb) {
7737                 fput(file);
7738                 return 0;
7739         }
7740
7741         return __io_sqe_files_scm(ctx, 1, index);
7742 #else
7743         return 0;
7744 #endif
7745 }
7746
7747 static int io_queue_rsrc_removal(struct io_rsrc_data *data,
7748                                  struct io_rsrc_node *node, void *rsrc)
7749 {
7750         struct io_rsrc_put *prsrc;
7751
7752         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7753         if (!prsrc)
7754                 return -ENOMEM;
7755
7756         prsrc->rsrc = rsrc;
7757         list_add(&prsrc->list, &node->rsrc_list);
7758         return 0;
7759 }
7760
7761 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7762                                  struct io_uring_rsrc_update *up,
7763                                  unsigned nr_args)
7764 {
7765         struct io_rsrc_data *data = ctx->file_data;
7766         struct file *file, **file_slot;
7767         __s32 __user *fds;
7768         int fd, i, err;
7769         __u32 done;
7770         bool needs_switch = false;
7771
7772         if (check_add_overflow(up->offset, nr_args, &done))
7773                 return -EOVERFLOW;
7774         if (done > ctx->nr_user_files)
7775                 return -EINVAL;
7776         err = io_rsrc_node_switch_start(ctx);
7777         if (err)
7778                 return err;
7779
7780         fds = u64_to_user_ptr(up->data);
7781         for (done = 0; done < nr_args; done++) {
7782                 err = 0;
7783                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7784                         err = -EFAULT;
7785                         break;
7786                 }
7787                 if (fd == IORING_REGISTER_FILES_SKIP)
7788                         continue;
7789
7790                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7791                 file_slot = io_fixed_file_slot(ctx->file_data, i);
7792
7793                 if (*file_slot) {
7794                         file = (struct file *) ((unsigned long) *file_slot & FFS_MASK);
7795                         err = io_queue_rsrc_removal(data, ctx->rsrc_node, file);
7796                         if (err)
7797                                 break;
7798                         *file_slot = NULL;
7799                         needs_switch = true;
7800                 }
7801                 if (fd != -1) {
7802                         file = fget(fd);
7803                         if (!file) {
7804                                 err = -EBADF;
7805                                 break;
7806                         }
7807                         /*
7808                          * Don't allow io_uring instances to be registered. If
7809                          * UNIX isn't enabled, then this causes a reference
7810                          * cycle and this instance can never get freed. If UNIX
7811                          * is enabled we'll handle it just fine, but there's
7812                          * still no point in allowing a ring fd as it doesn't
7813                          * support regular read/write anyway.
7814                          */
7815                         if (file->f_op == &io_uring_fops) {
7816                                 fput(file);
7817                                 err = -EBADF;
7818                                 break;
7819                         }
7820                         *file_slot = file;
7821                         err = io_sqe_file_register(ctx, file, i);
7822                         if (err) {
7823                                 *file_slot = NULL;
7824                                 fput(file);
7825                                 break;
7826                         }
7827                 }
7828         }
7829
7830         if (needs_switch)
7831                 io_rsrc_node_switch(ctx, data);
7832         return done ? done : err;
7833 }
7834
7835 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7836                                unsigned nr_args)
7837 {
7838         struct io_uring_rsrc_update up;
7839
7840         if (!ctx->file_data)
7841                 return -ENXIO;
7842         if (!nr_args)
7843                 return -EINVAL;
7844         if (copy_from_user(&up, arg, sizeof(up)))
7845                 return -EFAULT;
7846         if (up.resv)
7847                 return -EINVAL;
7848
7849         return __io_sqe_files_update(ctx, &up, nr_args);
7850 }
7851
7852 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7853 {
7854         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7855
7856         req = io_put_req_find_next(req);
7857         return req ? &req->work : NULL;
7858 }
7859
7860 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7861                                         struct task_struct *task)
7862 {
7863         struct io_wq_hash *hash;
7864         struct io_wq_data data;
7865         unsigned int concurrency;
7866
7867         hash = ctx->hash_map;
7868         if (!hash) {
7869                 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7870                 if (!hash)
7871                         return ERR_PTR(-ENOMEM);
7872                 refcount_set(&hash->refs, 1);
7873                 init_waitqueue_head(&hash->wait);
7874                 ctx->hash_map = hash;
7875         }
7876
7877         data.hash = hash;
7878         data.task = task;
7879         data.free_work = io_free_work;
7880         data.do_work = io_wq_submit_work;
7881
7882         /* Do QD, or 4 * CPUS, whatever is smallest */
7883         concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7884
7885         return io_wq_create(concurrency, &data);
7886 }
7887
7888 static int io_uring_alloc_task_context(struct task_struct *task,
7889                                        struct io_ring_ctx *ctx)
7890 {
7891         struct io_uring_task *tctx;
7892         int ret;
7893
7894         tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7895         if (unlikely(!tctx))
7896                 return -ENOMEM;
7897
7898         ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7899         if (unlikely(ret)) {
7900                 kfree(tctx);
7901                 return ret;
7902         }
7903
7904         tctx->io_wq = io_init_wq_offload(ctx, task);
7905         if (IS_ERR(tctx->io_wq)) {
7906                 ret = PTR_ERR(tctx->io_wq);
7907                 percpu_counter_destroy(&tctx->inflight);
7908                 kfree(tctx);
7909                 return ret;
7910         }
7911
7912         xa_init(&tctx->xa);
7913         init_waitqueue_head(&tctx->wait);
7914         tctx->last = NULL;
7915         atomic_set(&tctx->in_idle, 0);
7916         task->io_uring = tctx;
7917         spin_lock_init(&tctx->task_lock);
7918         INIT_WQ_LIST(&tctx->task_list);
7919         tctx->task_state = 0;
7920         init_task_work(&tctx->task_work, tctx_task_work);
7921         return 0;
7922 }
7923
7924 void __io_uring_free(struct task_struct *tsk)
7925 {
7926         struct io_uring_task *tctx = tsk->io_uring;
7927
7928         WARN_ON_ONCE(!xa_empty(&tctx->xa));
7929         WARN_ON_ONCE(tctx->io_wq);
7930
7931         percpu_counter_destroy(&tctx->inflight);
7932         kfree(tctx);
7933         tsk->io_uring = NULL;
7934 }
7935
7936 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7937                                 struct io_uring_params *p)
7938 {
7939         int ret;
7940
7941         /* Retain compatibility with failing for an invalid attach attempt */
7942         if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7943                                 IORING_SETUP_ATTACH_WQ) {
7944                 struct fd f;
7945
7946                 f = fdget(p->wq_fd);
7947                 if (!f.file)
7948                         return -ENXIO;
7949                 if (f.file->f_op != &io_uring_fops) {
7950                         fdput(f);
7951                         return -EINVAL;
7952                 }
7953                 fdput(f);
7954         }
7955         if (ctx->flags & IORING_SETUP_SQPOLL) {
7956                 struct task_struct *tsk;
7957                 struct io_sq_data *sqd;
7958                 bool attached;
7959
7960                 sqd = io_get_sq_data(p, &attached);
7961                 if (IS_ERR(sqd)) {
7962                         ret = PTR_ERR(sqd);
7963                         goto err;
7964                 }
7965
7966                 ctx->sq_creds = get_current_cred();
7967                 ctx->sq_data = sqd;
7968                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7969                 if (!ctx->sq_thread_idle)
7970                         ctx->sq_thread_idle = HZ;
7971
7972                 ret = 0;
7973                 io_sq_thread_park(sqd);
7974                 list_add(&ctx->sqd_list, &sqd->ctx_list);
7975                 io_sqd_update_thread_idle(sqd);
7976                 /* don't attach to a dying SQPOLL thread, would be racy */
7977                 if (attached && !sqd->thread)
7978                         ret = -ENXIO;
7979                 io_sq_thread_unpark(sqd);
7980
7981                 if (ret < 0)
7982                         goto err;
7983                 if (attached)
7984                         return 0;
7985
7986                 if (p->flags & IORING_SETUP_SQ_AFF) {
7987                         int cpu = p->sq_thread_cpu;
7988
7989                         ret = -EINVAL;
7990                         if (cpu >= nr_cpu_ids)
7991                                 goto err_sqpoll;
7992                         if (!cpu_online(cpu))
7993                                 goto err_sqpoll;
7994
7995                         sqd->sq_cpu = cpu;
7996                 } else {
7997                         sqd->sq_cpu = -1;
7998                 }
7999
8000                 sqd->task_pid = current->pid;
8001                 sqd->task_tgid = current->tgid;
8002                 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8003                 if (IS_ERR(tsk)) {
8004                         ret = PTR_ERR(tsk);
8005                         goto err_sqpoll;
8006                 }
8007
8008                 sqd->thread = tsk;
8009                 ret = io_uring_alloc_task_context(tsk, ctx);
8010                 wake_up_new_task(tsk);
8011                 if (ret)
8012                         goto err;
8013         } else if (p->flags & IORING_SETUP_SQ_AFF) {
8014                 /* Can't have SQ_AFF without SQPOLL */
8015                 ret = -EINVAL;
8016                 goto err;
8017         }
8018
8019         return 0;
8020 err:
8021         io_sq_thread_finish(ctx);
8022         return ret;
8023 err_sqpoll:
8024         complete(&ctx->sq_data->exited);
8025         goto err;
8026 }
8027
8028 static inline void __io_unaccount_mem(struct user_struct *user,
8029                                       unsigned long nr_pages)
8030 {
8031         atomic_long_sub(nr_pages, &user->locked_vm);
8032 }
8033
8034 static inline int __io_account_mem(struct user_struct *user,
8035                                    unsigned long nr_pages)
8036 {
8037         unsigned long page_limit, cur_pages, new_pages;
8038
8039         /* Don't allow more pages than we can safely lock */
8040         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8041
8042         do {
8043                 cur_pages = atomic_long_read(&user->locked_vm);
8044                 new_pages = cur_pages + nr_pages;
8045                 if (new_pages > page_limit)
8046                         return -ENOMEM;
8047         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8048                                         new_pages) != cur_pages);
8049
8050         return 0;
8051 }
8052
8053 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8054 {
8055         if (ctx->user)
8056                 __io_unaccount_mem(ctx->user, nr_pages);
8057
8058         if (ctx->mm_account)
8059                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8060 }
8061
8062 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8063 {
8064         int ret;
8065
8066         if (ctx->user) {
8067                 ret = __io_account_mem(ctx->user, nr_pages);
8068                 if (ret)
8069                         return ret;
8070         }
8071
8072         if (ctx->mm_account)
8073                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8074
8075         return 0;
8076 }
8077
8078 static void io_mem_free(void *ptr)
8079 {
8080         struct page *page;
8081
8082         if (!ptr)
8083                 return;
8084
8085         page = virt_to_head_page(ptr);
8086         if (put_page_testzero(page))
8087                 free_compound_page(page);
8088 }
8089
8090 static void *io_mem_alloc(size_t size)
8091 {
8092         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8093                                 __GFP_NORETRY | __GFP_ACCOUNT;
8094
8095         return (void *) __get_free_pages(gfp_flags, get_order(size));
8096 }
8097
8098 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8099                                 size_t *sq_offset)
8100 {
8101         struct io_rings *rings;
8102         size_t off, sq_array_size;
8103
8104         off = struct_size(rings, cqes, cq_entries);
8105         if (off == SIZE_MAX)
8106                 return SIZE_MAX;
8107
8108 #ifdef CONFIG_SMP
8109         off = ALIGN(off, SMP_CACHE_BYTES);
8110         if (off == 0)
8111                 return SIZE_MAX;
8112 #endif
8113
8114         if (sq_offset)
8115                 *sq_offset = off;
8116
8117         sq_array_size = array_size(sizeof(u32), sq_entries);
8118         if (sq_array_size == SIZE_MAX)
8119                 return SIZE_MAX;
8120
8121         if (check_add_overflow(off, sq_array_size, &off))
8122                 return SIZE_MAX;
8123
8124         return off;
8125 }
8126
8127 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8128 {
8129         int i, j;
8130
8131         if (!ctx->user_bufs)
8132                 return -ENXIO;
8133
8134         for (i = 0; i < ctx->nr_user_bufs; i++) {
8135                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8136
8137                 for (j = 0; j < imu->nr_bvecs; j++)
8138                         unpin_user_page(imu->bvec[j].bv_page);
8139
8140                 if (imu->acct_pages)
8141                         io_unaccount_mem(ctx, imu->acct_pages);
8142                 kvfree(imu->bvec);
8143                 imu->nr_bvecs = 0;
8144         }
8145
8146         kfree(ctx->user_bufs);
8147         ctx->user_bufs = NULL;
8148         ctx->nr_user_bufs = 0;
8149         return 0;
8150 }
8151
8152 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8153                        void __user *arg, unsigned index)
8154 {
8155         struct iovec __user *src;
8156
8157 #ifdef CONFIG_COMPAT
8158         if (ctx->compat) {
8159                 struct compat_iovec __user *ciovs;
8160                 struct compat_iovec ciov;
8161
8162                 ciovs = (struct compat_iovec __user *) arg;
8163                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8164                         return -EFAULT;
8165
8166                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8167                 dst->iov_len = ciov.iov_len;
8168                 return 0;
8169         }
8170 #endif
8171         src = (struct iovec __user *) arg;
8172         if (copy_from_user(dst, &src[index], sizeof(*dst)))
8173                 return -EFAULT;
8174         return 0;
8175 }
8176
8177 /*
8178  * Not super efficient, but this is just a registration time. And we do cache
8179  * the last compound head, so generally we'll only do a full search if we don't
8180  * match that one.
8181  *
8182  * We check if the given compound head page has already been accounted, to
8183  * avoid double accounting it. This allows us to account the full size of the
8184  * page, not just the constituent pages of a huge page.
8185  */
8186 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8187                                   int nr_pages, struct page *hpage)
8188 {
8189         int i, j;
8190
8191         /* check current page array */
8192         for (i = 0; i < nr_pages; i++) {
8193                 if (!PageCompound(pages[i]))
8194                         continue;
8195                 if (compound_head(pages[i]) == hpage)
8196                         return true;
8197         }
8198
8199         /* check previously registered pages */
8200         for (i = 0; i < ctx->nr_user_bufs; i++) {
8201                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8202
8203                 for (j = 0; j < imu->nr_bvecs; j++) {
8204                         if (!PageCompound(imu->bvec[j].bv_page))
8205                                 continue;
8206                         if (compound_head(imu->bvec[j].bv_page) == hpage)
8207                                 return true;
8208                 }
8209         }
8210
8211         return false;
8212 }
8213
8214 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8215                                  int nr_pages, struct io_mapped_ubuf *imu,
8216                                  struct page **last_hpage)
8217 {
8218         int i, ret;
8219
8220         for (i = 0; i < nr_pages; i++) {
8221                 if (!PageCompound(pages[i])) {
8222                         imu->acct_pages++;
8223                 } else {
8224                         struct page *hpage;
8225
8226                         hpage = compound_head(pages[i]);
8227                         if (hpage == *last_hpage)
8228                                 continue;
8229                         *last_hpage = hpage;
8230                         if (headpage_already_acct(ctx, pages, i, hpage))
8231                                 continue;
8232                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8233                 }
8234         }
8235
8236         if (!imu->acct_pages)
8237                 return 0;
8238
8239         ret = io_account_mem(ctx, imu->acct_pages);
8240         if (ret)
8241                 imu->acct_pages = 0;
8242         return ret;
8243 }
8244
8245 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8246                                   struct io_mapped_ubuf *imu,
8247                                   struct page **last_hpage)
8248 {
8249         struct vm_area_struct **vmas = NULL;
8250         struct page **pages = NULL;
8251         unsigned long off, start, end, ubuf;
8252         size_t size;
8253         int ret, pret, nr_pages, i;
8254
8255         ubuf = (unsigned long) iov->iov_base;
8256         end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8257         start = ubuf >> PAGE_SHIFT;
8258         nr_pages = end - start;
8259
8260         ret = -ENOMEM;
8261
8262         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8263         if (!pages)
8264                 goto done;
8265
8266         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8267                               GFP_KERNEL);
8268         if (!vmas)
8269                 goto done;
8270
8271         imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8272                                    GFP_KERNEL);
8273         if (!imu->bvec)
8274                 goto done;
8275
8276         ret = 0;
8277         mmap_read_lock(current->mm);
8278         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8279                               pages, vmas);
8280         if (pret == nr_pages) {
8281                 /* don't support file backed memory */
8282                 for (i = 0; i < nr_pages; i++) {
8283                         struct vm_area_struct *vma = vmas[i];
8284
8285                         if (vma->vm_file &&
8286                             !is_file_hugepages(vma->vm_file)) {
8287                                 ret = -EOPNOTSUPP;
8288                                 break;
8289                         }
8290                 }
8291         } else {
8292                 ret = pret < 0 ? pret : -EFAULT;
8293         }
8294         mmap_read_unlock(current->mm);
8295         if (ret) {
8296                 /*
8297                  * if we did partial map, or found file backed vmas,
8298                  * release any pages we did get
8299                  */
8300                 if (pret > 0)
8301                         unpin_user_pages(pages, pret);
8302                 kvfree(imu->bvec);
8303                 goto done;
8304         }
8305
8306         ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8307         if (ret) {
8308                 unpin_user_pages(pages, pret);
8309                 kvfree(imu->bvec);
8310                 goto done;
8311         }
8312
8313         off = ubuf & ~PAGE_MASK;
8314         size = iov->iov_len;
8315         for (i = 0; i < nr_pages; i++) {
8316                 size_t vec_len;
8317
8318                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8319                 imu->bvec[i].bv_page = pages[i];
8320                 imu->bvec[i].bv_len = vec_len;
8321                 imu->bvec[i].bv_offset = off;
8322                 off = 0;
8323                 size -= vec_len;
8324         }
8325         /* store original address for later verification */
8326         imu->ubuf = ubuf;
8327         imu->len = iov->iov_len;
8328         imu->nr_bvecs = nr_pages;
8329         ret = 0;
8330 done:
8331         kvfree(pages);
8332         kvfree(vmas);
8333         return ret;
8334 }
8335
8336 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8337 {
8338         if (ctx->user_bufs)
8339                 return -EBUSY;
8340         if (!nr_args || nr_args > UIO_MAXIOV)
8341                 return -EINVAL;
8342
8343         ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8344                                         GFP_KERNEL);
8345         if (!ctx->user_bufs)
8346                 return -ENOMEM;
8347
8348         return 0;
8349 }
8350
8351 static int io_buffer_validate(struct iovec *iov)
8352 {
8353         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8354
8355         /*
8356          * Don't impose further limits on the size and buffer
8357          * constraints here, we'll -EINVAL later when IO is
8358          * submitted if they are wrong.
8359          */
8360         if (!iov->iov_base || !iov->iov_len)
8361                 return -EFAULT;
8362
8363         /* arbitrary limit, but we need something */
8364         if (iov->iov_len > SZ_1G)
8365                 return -EFAULT;
8366
8367         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8368                 return -EOVERFLOW;
8369
8370         return 0;
8371 }
8372
8373 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8374                                    unsigned int nr_args)
8375 {
8376         int i, ret;
8377         struct iovec iov;
8378         struct page *last_hpage = NULL;
8379
8380         ret = io_buffers_map_alloc(ctx, nr_args);
8381         if (ret)
8382                 return ret;
8383
8384         for (i = 0; i < nr_args; i++) {
8385                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8386
8387                 ret = io_copy_iov(ctx, &iov, arg, i);
8388                 if (ret)
8389                         break;
8390
8391                 ret = io_buffer_validate(&iov);
8392                 if (ret)
8393                         break;
8394
8395                 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8396                 if (ret)
8397                         break;
8398
8399                 ctx->nr_user_bufs++;
8400         }
8401
8402         if (ret)
8403                 io_sqe_buffers_unregister(ctx);
8404
8405         return ret;
8406 }
8407
8408 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8409 {
8410         __s32 __user *fds = arg;
8411         int fd;
8412
8413         if (ctx->cq_ev_fd)
8414                 return -EBUSY;
8415
8416         if (copy_from_user(&fd, fds, sizeof(*fds)))
8417                 return -EFAULT;
8418
8419         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8420         if (IS_ERR(ctx->cq_ev_fd)) {
8421                 int ret = PTR_ERR(ctx->cq_ev_fd);
8422                 ctx->cq_ev_fd = NULL;
8423                 return ret;
8424         }
8425
8426         return 0;
8427 }
8428
8429 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8430 {
8431         if (ctx->cq_ev_fd) {
8432                 eventfd_ctx_put(ctx->cq_ev_fd);
8433                 ctx->cq_ev_fd = NULL;
8434                 return 0;
8435         }
8436
8437         return -ENXIO;
8438 }
8439
8440 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8441 {
8442         struct io_buffer *buf;
8443         unsigned long index;
8444
8445         xa_for_each(&ctx->io_buffers, index, buf)
8446                 __io_remove_buffers(ctx, buf, index, -1U);
8447 }
8448
8449 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8450 {
8451         struct io_kiocb *req, *nxt;
8452
8453         list_for_each_entry_safe(req, nxt, list, compl.list) {
8454                 if (tsk && req->task != tsk)
8455                         continue;
8456                 list_del(&req->compl.list);
8457                 kmem_cache_free(req_cachep, req);
8458         }
8459 }
8460
8461 static void io_req_caches_free(struct io_ring_ctx *ctx)
8462 {
8463         struct io_submit_state *submit_state = &ctx->submit_state;
8464         struct io_comp_state *cs = &ctx->submit_state.comp;
8465
8466         mutex_lock(&ctx->uring_lock);
8467
8468         if (submit_state->free_reqs) {
8469                 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8470                                      submit_state->reqs);
8471                 submit_state->free_reqs = 0;
8472         }
8473
8474         io_flush_cached_locked_reqs(ctx, cs);
8475         io_req_cache_free(&cs->free_list, NULL);
8476         mutex_unlock(&ctx->uring_lock);
8477 }
8478
8479 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8480 {
8481         /*
8482          * Some may use context even when all refs and requests have been put,
8483          * and they are free to do so while still holding uring_lock or
8484          * completion_lock, see __io_req_task_submit(). Wait for them to finish.
8485          */
8486         mutex_lock(&ctx->uring_lock);
8487         mutex_unlock(&ctx->uring_lock);
8488         spin_lock_irq(&ctx->completion_lock);
8489         spin_unlock_irq(&ctx->completion_lock);
8490
8491         io_sq_thread_finish(ctx);
8492         io_sqe_buffers_unregister(ctx);
8493
8494         if (ctx->mm_account) {
8495                 mmdrop(ctx->mm_account);
8496                 ctx->mm_account = NULL;
8497         }
8498
8499         mutex_lock(&ctx->uring_lock);
8500         io_sqe_files_unregister(ctx);
8501         mutex_unlock(&ctx->uring_lock);
8502         io_eventfd_unregister(ctx);
8503         io_destroy_buffers(ctx);
8504
8505         /* there are no registered resources left, nobody uses it */
8506         if (ctx->rsrc_node)
8507                 io_rsrc_node_destroy(ctx->rsrc_node);
8508         if (ctx->rsrc_backup_node)
8509                 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8510         flush_delayed_work(&ctx->rsrc_put_work);
8511
8512         WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8513         WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8514
8515 #if defined(CONFIG_UNIX)
8516         if (ctx->ring_sock) {
8517                 ctx->ring_sock->file = NULL; /* so that iput() is called */
8518                 sock_release(ctx->ring_sock);
8519         }
8520 #endif
8521
8522         io_mem_free(ctx->rings);
8523         io_mem_free(ctx->sq_sqes);
8524
8525         percpu_ref_exit(&ctx->refs);
8526         free_uid(ctx->user);
8527         io_req_caches_free(ctx);
8528         if (ctx->hash_map)
8529                 io_wq_put_hash(ctx->hash_map);
8530         kfree(ctx->cancel_hash);
8531         kfree(ctx);
8532 }
8533
8534 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8535 {
8536         struct io_ring_ctx *ctx = file->private_data;
8537         __poll_t mask = 0;
8538
8539         poll_wait(file, &ctx->cq_wait, wait);
8540         /*
8541          * synchronizes with barrier from wq_has_sleeper call in
8542          * io_commit_cqring
8543          */
8544         smp_rmb();
8545         if (!io_sqring_full(ctx))
8546                 mask |= EPOLLOUT | EPOLLWRNORM;
8547
8548         /*
8549          * Don't flush cqring overflow list here, just do a simple check.
8550          * Otherwise there could possible be ABBA deadlock:
8551          *      CPU0                    CPU1
8552          *      ----                    ----
8553          * lock(&ctx->uring_lock);
8554          *                              lock(&ep->mtx);
8555          *                              lock(&ctx->uring_lock);
8556          * lock(&ep->mtx);
8557          *
8558          * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8559          * pushs them to do the flush.
8560          */
8561         if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8562                 mask |= EPOLLIN | EPOLLRDNORM;
8563
8564         return mask;
8565 }
8566
8567 static int io_uring_fasync(int fd, struct file *file, int on)
8568 {
8569         struct io_ring_ctx *ctx = file->private_data;
8570
8571         return fasync_helper(fd, file, on, &ctx->cq_fasync);
8572 }
8573
8574 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8575 {
8576         const struct cred *creds;
8577
8578         creds = xa_erase(&ctx->personalities, id);
8579         if (creds) {
8580                 put_cred(creds);
8581                 return 0;
8582         }
8583
8584         return -EINVAL;
8585 }
8586
8587 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8588 {
8589         return io_run_task_work_head(&ctx->exit_task_work);
8590 }
8591
8592 struct io_tctx_exit {
8593         struct callback_head            task_work;
8594         struct completion               completion;
8595         struct io_ring_ctx              *ctx;
8596 };
8597
8598 static void io_tctx_exit_cb(struct callback_head *cb)
8599 {
8600         struct io_uring_task *tctx = current->io_uring;
8601         struct io_tctx_exit *work;
8602
8603         work = container_of(cb, struct io_tctx_exit, task_work);
8604         /*
8605          * When @in_idle, we're in cancellation and it's racy to remove the
8606          * node. It'll be removed by the end of cancellation, just ignore it.
8607          */
8608         if (!atomic_read(&tctx->in_idle))
8609                 io_uring_del_task_file((unsigned long)work->ctx);
8610         complete(&work->completion);
8611 }
8612
8613 static void io_ring_exit_work(struct work_struct *work)
8614 {
8615         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8616         unsigned long timeout = jiffies + HZ * 60 * 5;
8617         struct io_tctx_exit exit;
8618         struct io_tctx_node *node;
8619         int ret;
8620
8621         /* prevent SQPOLL from submitting new requests */
8622         if (ctx->sq_data) {
8623                 io_sq_thread_park(ctx->sq_data);
8624                 list_del_init(&ctx->sqd_list);
8625                 io_sqd_update_thread_idle(ctx->sq_data);
8626                 io_sq_thread_unpark(ctx->sq_data);
8627         }
8628
8629         /*
8630          * If we're doing polled IO and end up having requests being
8631          * submitted async (out-of-line), then completions can come in while
8632          * we're waiting for refs to drop. We need to reap these manually,
8633          * as nobody else will be looking for them.
8634          */
8635         do {
8636                 io_uring_try_cancel_requests(ctx, NULL, NULL);
8637
8638                 WARN_ON_ONCE(time_after(jiffies, timeout));
8639         } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8640
8641         mutex_lock(&ctx->uring_lock);
8642         while (!list_empty(&ctx->tctx_list)) {
8643                 WARN_ON_ONCE(time_after(jiffies, timeout));
8644
8645                 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8646                                         ctx_node);
8647                 exit.ctx = ctx;
8648                 init_completion(&exit.completion);
8649                 init_task_work(&exit.task_work, io_tctx_exit_cb);
8650                 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8651                 if (WARN_ON_ONCE(ret))
8652                         continue;
8653                 wake_up_process(node->task);
8654
8655                 mutex_unlock(&ctx->uring_lock);
8656                 wait_for_completion(&exit.completion);
8657                 cond_resched();
8658                 mutex_lock(&ctx->uring_lock);
8659         }
8660         mutex_unlock(&ctx->uring_lock);
8661
8662         io_ring_ctx_free(ctx);
8663 }
8664
8665 /* Returns true if we found and killed one or more timeouts */
8666 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8667                              struct files_struct *files)
8668 {
8669         struct io_kiocb *req, *tmp;
8670         int canceled = 0;
8671
8672         spin_lock_irq(&ctx->completion_lock);
8673         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8674                 if (io_match_task(req, tsk, files)) {
8675                         io_kill_timeout(req, -ECANCELED);
8676                         canceled++;
8677                 }
8678         }
8679         if (canceled != 0)
8680                 io_commit_cqring(ctx);
8681         spin_unlock_irq(&ctx->completion_lock);
8682         if (canceled != 0)
8683                 io_cqring_ev_posted(ctx);
8684         return canceled != 0;
8685 }
8686
8687 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8688 {
8689         unsigned long index;
8690         struct creds *creds;
8691
8692         mutex_lock(&ctx->uring_lock);
8693         percpu_ref_kill(&ctx->refs);
8694         /* if force is set, the ring is going away. always drop after that */
8695         ctx->cq_overflow_flushed = 1;
8696         if (ctx->rings)
8697                 __io_cqring_overflow_flush(ctx, true);
8698         xa_for_each(&ctx->personalities, index, creds)
8699                 io_unregister_personality(ctx, index);
8700         mutex_unlock(&ctx->uring_lock);
8701
8702         io_kill_timeouts(ctx, NULL, NULL);
8703         io_poll_remove_all(ctx, NULL, NULL);
8704
8705         /* if we failed setting up the ctx, we might not have any rings */
8706         io_iopoll_try_reap_events(ctx);
8707
8708         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8709         /*
8710          * Use system_unbound_wq to avoid spawning tons of event kworkers
8711          * if we're exiting a ton of rings at the same time. It just adds
8712          * noise and overhead, there's no discernable change in runtime
8713          * over using system_wq.
8714          */
8715         queue_work(system_unbound_wq, &ctx->exit_work);
8716 }
8717
8718 static int io_uring_release(struct inode *inode, struct file *file)
8719 {
8720         struct io_ring_ctx *ctx = file->private_data;
8721
8722         file->private_data = NULL;
8723         io_ring_ctx_wait_and_kill(ctx);
8724         return 0;
8725 }
8726
8727 struct io_task_cancel {
8728         struct task_struct *task;
8729         struct files_struct *files;
8730 };
8731
8732 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8733 {
8734         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8735         struct io_task_cancel *cancel = data;
8736         bool ret;
8737
8738         if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8739                 unsigned long flags;
8740                 struct io_ring_ctx *ctx = req->ctx;
8741
8742                 /* protect against races with linked timeouts */
8743                 spin_lock_irqsave(&ctx->completion_lock, flags);
8744                 ret = io_match_task(req, cancel->task, cancel->files);
8745                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8746         } else {
8747                 ret = io_match_task(req, cancel->task, cancel->files);
8748         }
8749         return ret;
8750 }
8751
8752 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8753                                   struct task_struct *task,
8754                                   struct files_struct *files)
8755 {
8756         struct io_defer_entry *de;
8757         LIST_HEAD(list);
8758
8759         spin_lock_irq(&ctx->completion_lock);
8760         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8761                 if (io_match_task(de->req, task, files)) {
8762                         list_cut_position(&list, &ctx->defer_list, &de->list);
8763                         break;
8764                 }
8765         }
8766         spin_unlock_irq(&ctx->completion_lock);
8767         if (list_empty(&list))
8768                 return false;
8769
8770         while (!list_empty(&list)) {
8771                 de = list_first_entry(&list, struct io_defer_entry, list);
8772                 list_del_init(&de->list);
8773                 io_req_complete_failed(de->req, -ECANCELED);
8774                 kfree(de);
8775         }
8776         return true;
8777 }
8778
8779 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8780 {
8781         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8782
8783         return req->ctx == data;
8784 }
8785
8786 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8787 {
8788         struct io_tctx_node *node;
8789         enum io_wq_cancel cret;
8790         bool ret = false;
8791
8792         mutex_lock(&ctx->uring_lock);
8793         list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8794                 struct io_uring_task *tctx = node->task->io_uring;
8795
8796                 /*
8797                  * io_wq will stay alive while we hold uring_lock, because it's
8798                  * killed after ctx nodes, which requires to take the lock.
8799                  */
8800                 if (!tctx || !tctx->io_wq)
8801                         continue;
8802                 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8803                 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8804         }
8805         mutex_unlock(&ctx->uring_lock);
8806
8807         return ret;
8808 }
8809
8810 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8811                                          struct task_struct *task,
8812                                          struct files_struct *files)
8813 {
8814         struct io_task_cancel cancel = { .task = task, .files = files, };
8815         struct io_uring_task *tctx = task ? task->io_uring : NULL;
8816
8817         while (1) {
8818                 enum io_wq_cancel cret;
8819                 bool ret = false;
8820
8821                 if (!task) {
8822                         ret |= io_uring_try_cancel_iowq(ctx);
8823                 } else if (tctx && tctx->io_wq) {
8824                         /*
8825                          * Cancels requests of all rings, not only @ctx, but
8826                          * it's fine as the task is in exit/exec.
8827                          */
8828                         cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8829                                                &cancel, true);
8830                         ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8831                 }
8832
8833                 /* SQPOLL thread does its own polling */
8834                 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8835                     (ctx->sq_data && ctx->sq_data->thread == current)) {
8836                         while (!list_empty_careful(&ctx->iopoll_list)) {
8837                                 io_iopoll_try_reap_events(ctx);
8838                                 ret = true;
8839                         }
8840                 }
8841
8842                 ret |= io_cancel_defer_files(ctx, task, files);
8843                 ret |= io_poll_remove_all(ctx, task, files);
8844                 ret |= io_kill_timeouts(ctx, task, files);
8845                 ret |= io_run_task_work();
8846                 ret |= io_run_ctx_fallback(ctx);
8847                 if (!ret)
8848                         break;
8849                 cond_resched();
8850         }
8851 }
8852
8853 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8854                                    struct task_struct *task,
8855                                    struct files_struct *files)
8856 {
8857         struct io_kiocb *req;
8858         int cnt = 0;
8859
8860         spin_lock_irq(&ctx->inflight_lock);
8861         list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8862                 cnt += io_match_task(req, task, files);
8863         spin_unlock_irq(&ctx->inflight_lock);
8864         return cnt;
8865 }
8866
8867 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8868                                   struct task_struct *task,
8869                                   struct files_struct *files)
8870 {
8871         while (!list_empty_careful(&ctx->inflight_list)) {
8872                 DEFINE_WAIT(wait);
8873                 int inflight;
8874
8875                 inflight = io_uring_count_inflight(ctx, task, files);
8876                 if (!inflight)
8877                         break;
8878
8879                 io_uring_try_cancel_requests(ctx, task, files);
8880
8881                 prepare_to_wait(&task->io_uring->wait, &wait,
8882                                 TASK_UNINTERRUPTIBLE);
8883                 if (inflight == io_uring_count_inflight(ctx, task, files))
8884                         schedule();
8885                 finish_wait(&task->io_uring->wait, &wait);
8886         }
8887 }
8888
8889 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8890 {
8891         struct io_uring_task *tctx = current->io_uring;
8892         struct io_tctx_node *node;
8893         int ret;
8894
8895         if (unlikely(!tctx)) {
8896                 ret = io_uring_alloc_task_context(current, ctx);
8897                 if (unlikely(ret))
8898                         return ret;
8899                 tctx = current->io_uring;
8900         }
8901         if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8902                 node = kmalloc(sizeof(*node), GFP_KERNEL);
8903                 if (!node)
8904                         return -ENOMEM;
8905                 node->ctx = ctx;
8906                 node->task = current;
8907
8908                 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8909                                         node, GFP_KERNEL));
8910                 if (ret) {
8911                         kfree(node);
8912                         return ret;
8913                 }
8914
8915                 mutex_lock(&ctx->uring_lock);
8916                 list_add(&node->ctx_node, &ctx->tctx_list);
8917                 mutex_unlock(&ctx->uring_lock);
8918         }
8919         tctx->last = ctx;
8920         return 0;
8921 }
8922
8923 /*
8924  * Note that this task has used io_uring. We use it for cancelation purposes.
8925  */
8926 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8927 {
8928         struct io_uring_task *tctx = current->io_uring;
8929
8930         if (likely(tctx && tctx->last == ctx))
8931                 return 0;
8932         return __io_uring_add_task_file(ctx);
8933 }
8934
8935 /*
8936  * Remove this io_uring_file -> task mapping.
8937  */
8938 static void io_uring_del_task_file(unsigned long index)
8939 {
8940         struct io_uring_task *tctx = current->io_uring;
8941         struct io_tctx_node *node;
8942
8943         if (!tctx)
8944                 return;
8945         node = xa_erase(&tctx->xa, index);
8946         if (!node)
8947                 return;
8948
8949         WARN_ON_ONCE(current != node->task);
8950         WARN_ON_ONCE(list_empty(&node->ctx_node));
8951
8952         mutex_lock(&node->ctx->uring_lock);
8953         list_del(&node->ctx_node);
8954         mutex_unlock(&node->ctx->uring_lock);
8955
8956         if (tctx->last == node->ctx)
8957                 tctx->last = NULL;
8958         kfree(node);
8959 }
8960
8961 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8962 {
8963         struct io_tctx_node *node;
8964         unsigned long index;
8965
8966         xa_for_each(&tctx->xa, index, node)
8967                 io_uring_del_task_file(index);
8968         if (tctx->io_wq) {
8969                 io_wq_put_and_exit(tctx->io_wq);
8970                 tctx->io_wq = NULL;
8971         }
8972 }
8973
8974 static s64 tctx_inflight(struct io_uring_task *tctx)
8975 {
8976         return percpu_counter_sum(&tctx->inflight);
8977 }
8978
8979 static void io_sqpoll_cancel_cb(struct callback_head *cb)
8980 {
8981         struct io_tctx_exit *work = container_of(cb, struct io_tctx_exit, task_work);
8982         struct io_ring_ctx *ctx = work->ctx;
8983         struct io_sq_data *sqd = ctx->sq_data;
8984
8985         if (sqd->thread)
8986                 io_uring_cancel_sqpoll(ctx);
8987         complete(&work->completion);
8988 }
8989
8990 static void io_sqpoll_cancel_sync(struct io_ring_ctx *ctx)
8991 {
8992         struct io_sq_data *sqd = ctx->sq_data;
8993         struct io_tctx_exit work = { .ctx = ctx, };
8994         struct task_struct *task;
8995
8996         io_sq_thread_park(sqd);
8997         list_del_init(&ctx->sqd_list);
8998         io_sqd_update_thread_idle(sqd);
8999         task = sqd->thread;
9000         if (task) {
9001                 init_completion(&work.completion);
9002                 init_task_work(&work.task_work, io_sqpoll_cancel_cb);
9003                 io_task_work_add_head(&sqd->park_task_work, &work.task_work);
9004                 wake_up_process(task);
9005         }
9006         io_sq_thread_unpark(sqd);
9007
9008         if (task)
9009                 wait_for_completion(&work.completion);
9010 }
9011
9012 void __io_uring_files_cancel(struct files_struct *files)
9013 {
9014         struct io_uring_task *tctx = current->io_uring;
9015         struct io_tctx_node *node;
9016         unsigned long index;
9017
9018         /* make sure overflow events are dropped */
9019         atomic_inc(&tctx->in_idle);
9020         xa_for_each(&tctx->xa, index, node) {
9021                 struct io_ring_ctx *ctx = node->ctx;
9022
9023                 if (ctx->sq_data) {
9024                         io_sqpoll_cancel_sync(ctx);
9025                         continue;
9026                 }
9027                 io_uring_cancel_files(ctx, current, files);
9028                 if (!files)
9029                         io_uring_try_cancel_requests(ctx, current, NULL);
9030         }
9031         atomic_dec(&tctx->in_idle);
9032
9033         if (files)
9034                 io_uring_clean_tctx(tctx);
9035 }
9036
9037 /* should only be called by SQPOLL task */
9038 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9039 {
9040         struct io_sq_data *sqd = ctx->sq_data;
9041         struct io_uring_task *tctx = current->io_uring;
9042         s64 inflight;
9043         DEFINE_WAIT(wait);
9044
9045         WARN_ON_ONCE(!sqd || ctx->sq_data->thread != current);
9046
9047         atomic_inc(&tctx->in_idle);
9048         do {
9049                 /* read completions before cancelations */
9050                 inflight = tctx_inflight(tctx);
9051                 if (!inflight)
9052                         break;
9053                 io_uring_try_cancel_requests(ctx, current, NULL);
9054
9055                 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9056                 /*
9057                  * If we've seen completions, retry without waiting. This
9058                  * avoids a race where a completion comes in before we did
9059                  * prepare_to_wait().
9060                  */
9061                 if (inflight == tctx_inflight(tctx))
9062                         schedule();
9063                 finish_wait(&tctx->wait, &wait);
9064         } while (1);
9065         atomic_dec(&tctx->in_idle);
9066 }
9067
9068 /*
9069  * Find any io_uring fd that this task has registered or done IO on, and cancel
9070  * requests.
9071  */
9072 void __io_uring_task_cancel(void)
9073 {
9074         struct io_uring_task *tctx = current->io_uring;
9075         DEFINE_WAIT(wait);
9076         s64 inflight;
9077
9078         /* make sure overflow events are dropped */
9079         atomic_inc(&tctx->in_idle);
9080         __io_uring_files_cancel(NULL);
9081
9082         do {
9083                 /* read completions before cancelations */
9084                 inflight = tctx_inflight(tctx);
9085                 if (!inflight)
9086                         break;
9087                 __io_uring_files_cancel(NULL);
9088
9089                 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9090
9091                 /*
9092                  * If we've seen completions, retry without waiting. This
9093                  * avoids a race where a completion comes in before we did
9094                  * prepare_to_wait().
9095                  */
9096                 if (inflight == tctx_inflight(tctx))
9097                         schedule();
9098                 finish_wait(&tctx->wait, &wait);
9099         } while (1);
9100
9101         atomic_dec(&tctx->in_idle);
9102
9103         io_uring_clean_tctx(tctx);
9104         /* all current's requests should be gone, we can kill tctx */
9105         __io_uring_free(current);
9106 }
9107
9108 static void *io_uring_validate_mmap_request(struct file *file,
9109                                             loff_t pgoff, size_t sz)
9110 {
9111         struct io_ring_ctx *ctx = file->private_data;
9112         loff_t offset = pgoff << PAGE_SHIFT;
9113         struct page *page;
9114         void *ptr;
9115
9116         switch (offset) {
9117         case IORING_OFF_SQ_RING:
9118         case IORING_OFF_CQ_RING:
9119                 ptr = ctx->rings;
9120                 break;
9121         case IORING_OFF_SQES:
9122                 ptr = ctx->sq_sqes;
9123                 break;
9124         default:
9125                 return ERR_PTR(-EINVAL);
9126         }
9127
9128         page = virt_to_head_page(ptr);
9129         if (sz > page_size(page))
9130                 return ERR_PTR(-EINVAL);
9131
9132         return ptr;
9133 }
9134
9135 #ifdef CONFIG_MMU
9136
9137 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9138 {
9139         size_t sz = vma->vm_end - vma->vm_start;
9140         unsigned long pfn;
9141         void *ptr;
9142
9143         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9144         if (IS_ERR(ptr))
9145                 return PTR_ERR(ptr);
9146
9147         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9148         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9149 }
9150
9151 #else /* !CONFIG_MMU */
9152
9153 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9154 {
9155         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9156 }
9157
9158 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9159 {
9160         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9161 }
9162
9163 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9164         unsigned long addr, unsigned long len,
9165         unsigned long pgoff, unsigned long flags)
9166 {
9167         void *ptr;
9168
9169         ptr = io_uring_validate_mmap_request(file, pgoff, len);
9170         if (IS_ERR(ptr))
9171                 return PTR_ERR(ptr);
9172
9173         return (unsigned long) ptr;
9174 }
9175
9176 #endif /* !CONFIG_MMU */
9177
9178 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9179 {
9180         DEFINE_WAIT(wait);
9181
9182         do {
9183                 if (!io_sqring_full(ctx))
9184                         break;
9185                 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9186
9187                 if (!io_sqring_full(ctx))
9188                         break;
9189                 schedule();
9190         } while (!signal_pending(current));
9191
9192         finish_wait(&ctx->sqo_sq_wait, &wait);
9193         return 0;
9194 }
9195
9196 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9197                           struct __kernel_timespec __user **ts,
9198                           const sigset_t __user **sig)
9199 {
9200         struct io_uring_getevents_arg arg;
9201
9202         /*
9203          * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9204          * is just a pointer to the sigset_t.
9205          */
9206         if (!(flags & IORING_ENTER_EXT_ARG)) {
9207                 *sig = (const sigset_t __user *) argp;
9208                 *ts = NULL;
9209                 return 0;
9210         }
9211
9212         /*
9213          * EXT_ARG is set - ensure we agree on the size of it and copy in our
9214          * timespec and sigset_t pointers if good.
9215          */
9216         if (*argsz != sizeof(arg))
9217                 return -EINVAL;
9218         if (copy_from_user(&arg, argp, sizeof(arg)))
9219                 return -EFAULT;
9220         *sig = u64_to_user_ptr(arg.sigmask);
9221         *argsz = arg.sigmask_sz;
9222         *ts = u64_to_user_ptr(arg.ts);
9223         return 0;
9224 }
9225
9226 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9227                 u32, min_complete, u32, flags, const void __user *, argp,
9228                 size_t, argsz)
9229 {
9230         struct io_ring_ctx *ctx;
9231         int submitted = 0;
9232         struct fd f;
9233         long ret;
9234
9235         io_run_task_work();
9236
9237         if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9238                                IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9239                 return -EINVAL;
9240
9241         f = fdget(fd);
9242         if (unlikely(!f.file))
9243                 return -EBADF;
9244
9245         ret = -EOPNOTSUPP;
9246         if (unlikely(f.file->f_op != &io_uring_fops))
9247                 goto out_fput;
9248
9249         ret = -ENXIO;
9250         ctx = f.file->private_data;
9251         if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9252                 goto out_fput;
9253
9254         ret = -EBADFD;
9255         if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9256                 goto out;
9257
9258         /*
9259          * For SQ polling, the thread will do all submissions and completions.
9260          * Just return the requested submit count, and wake the thread if
9261          * we were asked to.
9262          */
9263         ret = 0;
9264         if (ctx->flags & IORING_SETUP_SQPOLL) {
9265                 io_cqring_overflow_flush(ctx, false);
9266
9267                 ret = -EOWNERDEAD;
9268                 if (unlikely(ctx->sq_data->thread == NULL)) {
9269                         goto out;
9270                 }
9271                 if (flags & IORING_ENTER_SQ_WAKEUP)
9272                         wake_up(&ctx->sq_data->wait);
9273                 if (flags & IORING_ENTER_SQ_WAIT) {
9274                         ret = io_sqpoll_wait_sq(ctx);
9275                         if (ret)
9276                                 goto out;
9277                 }
9278                 submitted = to_submit;
9279         } else if (to_submit) {
9280                 ret = io_uring_add_task_file(ctx);
9281                 if (unlikely(ret))
9282                         goto out;
9283                 mutex_lock(&ctx->uring_lock);
9284                 submitted = io_submit_sqes(ctx, to_submit);
9285                 mutex_unlock(&ctx->uring_lock);
9286
9287                 if (submitted != to_submit)
9288                         goto out;
9289         }
9290         if (flags & IORING_ENTER_GETEVENTS) {
9291                 const sigset_t __user *sig;
9292                 struct __kernel_timespec __user *ts;
9293
9294                 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9295                 if (unlikely(ret))
9296                         goto out;
9297
9298                 min_complete = min(min_complete, ctx->cq_entries);
9299
9300                 /*
9301                  * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9302                  * space applications don't need to do io completion events
9303                  * polling again, they can rely on io_sq_thread to do polling
9304                  * work, which can reduce cpu usage and uring_lock contention.
9305                  */
9306                 if (ctx->flags & IORING_SETUP_IOPOLL &&
9307                     !(ctx->flags & IORING_SETUP_SQPOLL)) {
9308                         ret = io_iopoll_check(ctx, min_complete);
9309                 } else {
9310                         ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9311                 }
9312         }
9313
9314 out:
9315         percpu_ref_put(&ctx->refs);
9316 out_fput:
9317         fdput(f);
9318         return submitted ? submitted : ret;
9319 }
9320
9321 #ifdef CONFIG_PROC_FS
9322 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9323                 const struct cred *cred)
9324 {
9325         struct user_namespace *uns = seq_user_ns(m);
9326         struct group_info *gi;
9327         kernel_cap_t cap;
9328         unsigned __capi;
9329         int g;
9330
9331         seq_printf(m, "%5d\n", id);
9332         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9333         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9334         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9335         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9336         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9337         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9338         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9339         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9340         seq_puts(m, "\n\tGroups:\t");
9341         gi = cred->group_info;
9342         for (g = 0; g < gi->ngroups; g++) {
9343                 seq_put_decimal_ull(m, g ? " " : "",
9344                                         from_kgid_munged(uns, gi->gid[g]));
9345         }
9346         seq_puts(m, "\n\tCapEff:\t");
9347         cap = cred->cap_effective;
9348         CAP_FOR_EACH_U32(__capi)
9349                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9350         seq_putc(m, '\n');
9351         return 0;
9352 }
9353
9354 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9355 {
9356         struct io_sq_data *sq = NULL;
9357         bool has_lock;
9358         int i;
9359
9360         /*
9361          * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9362          * since fdinfo case grabs it in the opposite direction of normal use
9363          * cases. If we fail to get the lock, we just don't iterate any
9364          * structures that could be going away outside the io_uring mutex.
9365          */
9366         has_lock = mutex_trylock(&ctx->uring_lock);
9367
9368         if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9369                 sq = ctx->sq_data;
9370                 if (!sq->thread)
9371                         sq = NULL;
9372         }
9373
9374         seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9375         seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9376         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9377         for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9378                 struct file *f = io_file_from_index(ctx, i);
9379
9380                 if (f)
9381                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9382                 else
9383                         seq_printf(m, "%5u: <none>\n", i);
9384         }
9385         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9386         for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9387                 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9388
9389                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9390                                                 (unsigned int) buf->len);
9391         }
9392         if (has_lock && !xa_empty(&ctx->personalities)) {
9393                 unsigned long index;
9394                 const struct cred *cred;
9395
9396                 seq_printf(m, "Personalities:\n");
9397                 xa_for_each(&ctx->personalities, index, cred)
9398                         io_uring_show_cred(m, index, cred);
9399         }
9400         seq_printf(m, "PollList:\n");
9401         spin_lock_irq(&ctx->completion_lock);
9402         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9403                 struct hlist_head *list = &ctx->cancel_hash[i];
9404                 struct io_kiocb *req;
9405
9406                 hlist_for_each_entry(req, list, hash_node)
9407                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
9408                                         req->task->task_works != NULL);
9409         }
9410         spin_unlock_irq(&ctx->completion_lock);
9411         if (has_lock)
9412                 mutex_unlock(&ctx->uring_lock);
9413 }
9414
9415 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9416 {
9417         struct io_ring_ctx *ctx = f->private_data;
9418
9419         if (percpu_ref_tryget(&ctx->refs)) {
9420                 __io_uring_show_fdinfo(ctx, m);
9421                 percpu_ref_put(&ctx->refs);
9422         }
9423 }
9424 #endif
9425
9426 static const struct file_operations io_uring_fops = {
9427         .release        = io_uring_release,
9428         .mmap           = io_uring_mmap,
9429 #ifndef CONFIG_MMU
9430         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9431         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9432 #endif
9433         .poll           = io_uring_poll,
9434         .fasync         = io_uring_fasync,
9435 #ifdef CONFIG_PROC_FS
9436         .show_fdinfo    = io_uring_show_fdinfo,
9437 #endif
9438 };
9439
9440 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9441                                   struct io_uring_params *p)
9442 {
9443         struct io_rings *rings;
9444         size_t size, sq_array_offset;
9445
9446         /* make sure these are sane, as we already accounted them */
9447         ctx->sq_entries = p->sq_entries;
9448         ctx->cq_entries = p->cq_entries;
9449
9450         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9451         if (size == SIZE_MAX)
9452                 return -EOVERFLOW;
9453
9454         rings = io_mem_alloc(size);
9455         if (!rings)
9456                 return -ENOMEM;
9457
9458         ctx->rings = rings;
9459         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9460         rings->sq_ring_mask = p->sq_entries - 1;
9461         rings->cq_ring_mask = p->cq_entries - 1;
9462         rings->sq_ring_entries = p->sq_entries;
9463         rings->cq_ring_entries = p->cq_entries;
9464         ctx->sq_mask = rings->sq_ring_mask;
9465         ctx->cq_mask = rings->cq_ring_mask;
9466
9467         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9468         if (size == SIZE_MAX) {
9469                 io_mem_free(ctx->rings);
9470                 ctx->rings = NULL;
9471                 return -EOVERFLOW;
9472         }
9473
9474         ctx->sq_sqes = io_mem_alloc(size);
9475         if (!ctx->sq_sqes) {
9476                 io_mem_free(ctx->rings);
9477                 ctx->rings = NULL;
9478                 return -ENOMEM;
9479         }
9480
9481         return 0;
9482 }
9483
9484 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9485 {
9486         int ret, fd;
9487
9488         fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9489         if (fd < 0)
9490                 return fd;
9491
9492         ret = io_uring_add_task_file(ctx);
9493         if (ret) {
9494                 put_unused_fd(fd);
9495                 return ret;
9496         }
9497         fd_install(fd, file);
9498         return fd;
9499 }
9500
9501 /*
9502  * Allocate an anonymous fd, this is what constitutes the application
9503  * visible backing of an io_uring instance. The application mmaps this
9504  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9505  * we have to tie this fd to a socket for file garbage collection purposes.
9506  */
9507 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9508 {
9509         struct file *file;
9510 #if defined(CONFIG_UNIX)
9511         int ret;
9512
9513         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9514                                 &ctx->ring_sock);
9515         if (ret)
9516                 return ERR_PTR(ret);
9517 #endif
9518
9519         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9520                                         O_RDWR | O_CLOEXEC);
9521 #if defined(CONFIG_UNIX)
9522         if (IS_ERR(file)) {
9523                 sock_release(ctx->ring_sock);
9524                 ctx->ring_sock = NULL;
9525         } else {
9526                 ctx->ring_sock->file = file;
9527         }
9528 #endif
9529         return file;
9530 }
9531
9532 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9533                            struct io_uring_params __user *params)
9534 {
9535         struct io_ring_ctx *ctx;
9536         struct file *file;
9537         int ret;
9538
9539         if (!entries)
9540                 return -EINVAL;
9541         if (entries > IORING_MAX_ENTRIES) {
9542                 if (!(p->flags & IORING_SETUP_CLAMP))
9543                         return -EINVAL;
9544                 entries = IORING_MAX_ENTRIES;
9545         }
9546
9547         /*
9548          * Use twice as many entries for the CQ ring. It's possible for the
9549          * application to drive a higher depth than the size of the SQ ring,
9550          * since the sqes are only used at submission time. This allows for
9551          * some flexibility in overcommitting a bit. If the application has
9552          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9553          * of CQ ring entries manually.
9554          */
9555         p->sq_entries = roundup_pow_of_two(entries);
9556         if (p->flags & IORING_SETUP_CQSIZE) {
9557                 /*
9558                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
9559                  * to a power-of-two, if it isn't already. We do NOT impose
9560                  * any cq vs sq ring sizing.
9561                  */
9562                 if (!p->cq_entries)
9563                         return -EINVAL;
9564                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9565                         if (!(p->flags & IORING_SETUP_CLAMP))
9566                                 return -EINVAL;
9567                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
9568                 }
9569                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9570                 if (p->cq_entries < p->sq_entries)
9571                         return -EINVAL;
9572         } else {
9573                 p->cq_entries = 2 * p->sq_entries;
9574         }
9575
9576         ctx = io_ring_ctx_alloc(p);
9577         if (!ctx)
9578                 return -ENOMEM;
9579         ctx->compat = in_compat_syscall();
9580         if (!capable(CAP_IPC_LOCK))
9581                 ctx->user = get_uid(current_user());
9582
9583         /*
9584          * This is just grabbed for accounting purposes. When a process exits,
9585          * the mm is exited and dropped before the files, hence we need to hang
9586          * on to this mm purely for the purposes of being able to unaccount
9587          * memory (locked/pinned vm). It's not used for anything else.
9588          */
9589         mmgrab(current->mm);
9590         ctx->mm_account = current->mm;
9591
9592         ret = io_allocate_scq_urings(ctx, p);
9593         if (ret)
9594                 goto err;
9595
9596         ret = io_sq_offload_create(ctx, p);
9597         if (ret)
9598                 goto err;
9599
9600         memset(&p->sq_off, 0, sizeof(p->sq_off));
9601         p->sq_off.head = offsetof(struct io_rings, sq.head);
9602         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9603         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9604         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9605         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9606         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9607         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9608
9609         memset(&p->cq_off, 0, sizeof(p->cq_off));
9610         p->cq_off.head = offsetof(struct io_rings, cq.head);
9611         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9612         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9613         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9614         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9615         p->cq_off.cqes = offsetof(struct io_rings, cqes);
9616         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9617
9618         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9619                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9620                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9621                         IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9622                         IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9623
9624         if (copy_to_user(params, p, sizeof(*p))) {
9625                 ret = -EFAULT;
9626                 goto err;
9627         }
9628
9629         file = io_uring_get_file(ctx);
9630         if (IS_ERR(file)) {
9631                 ret = PTR_ERR(file);
9632                 goto err;
9633         }
9634
9635         /*
9636          * Install ring fd as the very last thing, so we don't risk someone
9637          * having closed it before we finish setup
9638          */
9639         ret = io_uring_install_fd(ctx, file);
9640         if (ret < 0) {
9641                 /* fput will clean it up */
9642                 fput(file);
9643                 return ret;
9644         }
9645
9646         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9647         return ret;
9648 err:
9649         io_ring_ctx_wait_and_kill(ctx);
9650         return ret;
9651 }
9652
9653 /*
9654  * Sets up an aio uring context, and returns the fd. Applications asks for a
9655  * ring size, we return the actual sq/cq ring sizes (among other things) in the
9656  * params structure passed in.
9657  */
9658 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9659 {
9660         struct io_uring_params p;
9661         int i;
9662
9663         if (copy_from_user(&p, params, sizeof(p)))
9664                 return -EFAULT;
9665         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9666                 if (p.resv[i])
9667                         return -EINVAL;
9668         }
9669
9670         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9671                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9672                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9673                         IORING_SETUP_R_DISABLED))
9674                 return -EINVAL;
9675
9676         return  io_uring_create(entries, &p, params);
9677 }
9678
9679 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9680                 struct io_uring_params __user *, params)
9681 {
9682         return io_uring_setup(entries, params);
9683 }
9684
9685 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9686 {
9687         struct io_uring_probe *p;
9688         size_t size;
9689         int i, ret;
9690
9691         size = struct_size(p, ops, nr_args);
9692         if (size == SIZE_MAX)
9693                 return -EOVERFLOW;
9694         p = kzalloc(size, GFP_KERNEL);
9695         if (!p)
9696                 return -ENOMEM;
9697
9698         ret = -EFAULT;
9699         if (copy_from_user(p, arg, size))
9700                 goto out;
9701         ret = -EINVAL;
9702         if (memchr_inv(p, 0, size))
9703                 goto out;
9704
9705         p->last_op = IORING_OP_LAST - 1;
9706         if (nr_args > IORING_OP_LAST)
9707                 nr_args = IORING_OP_LAST;
9708
9709         for (i = 0; i < nr_args; i++) {
9710                 p->ops[i].op = i;
9711                 if (!io_op_defs[i].not_supported)
9712                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
9713         }
9714         p->ops_len = i;
9715
9716         ret = 0;
9717         if (copy_to_user(arg, p, size))
9718                 ret = -EFAULT;
9719 out:
9720         kfree(p);
9721         return ret;
9722 }
9723
9724 static int io_register_personality(struct io_ring_ctx *ctx)
9725 {
9726         const struct cred *creds;
9727         u32 id;
9728         int ret;
9729
9730         creds = get_current_cred();
9731
9732         ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9733                         XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9734         if (!ret)
9735                 return id;
9736         put_cred(creds);
9737         return ret;
9738 }
9739
9740 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9741                                     unsigned int nr_args)
9742 {
9743         struct io_uring_restriction *res;
9744         size_t size;
9745         int i, ret;
9746
9747         /* Restrictions allowed only if rings started disabled */
9748         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9749                 return -EBADFD;
9750
9751         /* We allow only a single restrictions registration */
9752         if (ctx->restrictions.registered)
9753                 return -EBUSY;
9754
9755         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9756                 return -EINVAL;
9757
9758         size = array_size(nr_args, sizeof(*res));
9759         if (size == SIZE_MAX)
9760                 return -EOVERFLOW;
9761
9762         res = memdup_user(arg, size);
9763         if (IS_ERR(res))
9764                 return PTR_ERR(res);
9765
9766         ret = 0;
9767
9768         for (i = 0; i < nr_args; i++) {
9769                 switch (res[i].opcode) {
9770                 case IORING_RESTRICTION_REGISTER_OP:
9771                         if (res[i].register_op >= IORING_REGISTER_LAST) {
9772                                 ret = -EINVAL;
9773                                 goto out;
9774                         }
9775
9776                         __set_bit(res[i].register_op,
9777                                   ctx->restrictions.register_op);
9778                         break;
9779                 case IORING_RESTRICTION_SQE_OP:
9780                         if (res[i].sqe_op >= IORING_OP_LAST) {
9781                                 ret = -EINVAL;
9782                                 goto out;
9783                         }
9784
9785                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9786                         break;
9787                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9788                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9789                         break;
9790                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9791                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9792                         break;
9793                 default:
9794                         ret = -EINVAL;
9795                         goto out;
9796                 }
9797         }
9798
9799 out:
9800         /* Reset all restrictions if an error happened */
9801         if (ret != 0)
9802                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9803         else
9804                 ctx->restrictions.registered = true;
9805
9806         kfree(res);
9807         return ret;
9808 }
9809
9810 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9811 {
9812         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9813                 return -EBADFD;
9814
9815         if (ctx->restrictions.registered)
9816                 ctx->restricted = 1;
9817
9818         ctx->flags &= ~IORING_SETUP_R_DISABLED;
9819         if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9820                 wake_up(&ctx->sq_data->wait);
9821         return 0;
9822 }
9823
9824 static bool io_register_op_must_quiesce(int op)
9825 {
9826         switch (op) {
9827         case IORING_UNREGISTER_FILES:
9828         case IORING_REGISTER_FILES_UPDATE:
9829         case IORING_REGISTER_PROBE:
9830         case IORING_REGISTER_PERSONALITY:
9831         case IORING_UNREGISTER_PERSONALITY:
9832                 return false;
9833         default:
9834                 return true;
9835         }
9836 }
9837
9838 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9839                                void __user *arg, unsigned nr_args)
9840         __releases(ctx->uring_lock)
9841         __acquires(ctx->uring_lock)
9842 {
9843         int ret;
9844
9845         /*
9846          * We're inside the ring mutex, if the ref is already dying, then
9847          * someone else killed the ctx or is already going through
9848          * io_uring_register().
9849          */
9850         if (percpu_ref_is_dying(&ctx->refs))
9851                 return -ENXIO;
9852
9853         if (io_register_op_must_quiesce(opcode)) {
9854                 percpu_ref_kill(&ctx->refs);
9855
9856                 /*
9857                  * Drop uring mutex before waiting for references to exit. If
9858                  * another thread is currently inside io_uring_enter() it might
9859                  * need to grab the uring_lock to make progress. If we hold it
9860                  * here across the drain wait, then we can deadlock. It's safe
9861                  * to drop the mutex here, since no new references will come in
9862                  * after we've killed the percpu ref.
9863                  */
9864                 mutex_unlock(&ctx->uring_lock);
9865                 do {
9866                         ret = wait_for_completion_interruptible(&ctx->ref_comp);
9867                         if (!ret)
9868                                 break;
9869                         ret = io_run_task_work_sig();
9870                         if (ret < 0)
9871                                 break;
9872                 } while (1);
9873
9874                 mutex_lock(&ctx->uring_lock);
9875
9876                 if (ret) {
9877                         percpu_ref_resurrect(&ctx->refs);
9878                         goto out_quiesce;
9879                 }
9880         }
9881
9882         if (ctx->restricted) {
9883                 if (opcode >= IORING_REGISTER_LAST) {
9884                         ret = -EINVAL;
9885                         goto out;
9886                 }
9887
9888                 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9889                         ret = -EACCES;
9890                         goto out;
9891                 }
9892         }
9893
9894         switch (opcode) {
9895         case IORING_REGISTER_BUFFERS:
9896                 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9897                 break;
9898         case IORING_UNREGISTER_BUFFERS:
9899                 ret = -EINVAL;
9900                 if (arg || nr_args)
9901                         break;
9902                 ret = io_sqe_buffers_unregister(ctx);
9903                 break;
9904         case IORING_REGISTER_FILES:
9905                 ret = io_sqe_files_register(ctx, arg, nr_args);
9906                 break;
9907         case IORING_UNREGISTER_FILES:
9908                 ret = -EINVAL;
9909                 if (arg || nr_args)
9910                         break;
9911                 ret = io_sqe_files_unregister(ctx);
9912                 break;
9913         case IORING_REGISTER_FILES_UPDATE:
9914                 ret = io_sqe_files_update(ctx, arg, nr_args);
9915                 break;
9916         case IORING_REGISTER_EVENTFD:
9917         case IORING_REGISTER_EVENTFD_ASYNC:
9918                 ret = -EINVAL;
9919                 if (nr_args != 1)
9920                         break;
9921                 ret = io_eventfd_register(ctx, arg);
9922                 if (ret)
9923                         break;
9924                 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9925                         ctx->eventfd_async = 1;
9926                 else
9927                         ctx->eventfd_async = 0;
9928                 break;
9929         case IORING_UNREGISTER_EVENTFD:
9930                 ret = -EINVAL;
9931                 if (arg || nr_args)
9932                         break;
9933                 ret = io_eventfd_unregister(ctx);
9934                 break;
9935         case IORING_REGISTER_PROBE:
9936                 ret = -EINVAL;
9937                 if (!arg || nr_args > 256)
9938                         break;
9939                 ret = io_probe(ctx, arg, nr_args);
9940                 break;
9941         case IORING_REGISTER_PERSONALITY:
9942                 ret = -EINVAL;
9943                 if (arg || nr_args)
9944                         break;
9945                 ret = io_register_personality(ctx);
9946                 break;
9947         case IORING_UNREGISTER_PERSONALITY:
9948                 ret = -EINVAL;
9949                 if (arg)
9950                         break;
9951                 ret = io_unregister_personality(ctx, nr_args);
9952                 break;
9953         case IORING_REGISTER_ENABLE_RINGS:
9954                 ret = -EINVAL;
9955                 if (arg || nr_args)
9956                         break;
9957                 ret = io_register_enable_rings(ctx);
9958                 break;
9959         case IORING_REGISTER_RESTRICTIONS:
9960                 ret = io_register_restrictions(ctx, arg, nr_args);
9961                 break;
9962         default:
9963                 ret = -EINVAL;
9964                 break;
9965         }
9966
9967 out:
9968         if (io_register_op_must_quiesce(opcode)) {
9969                 /* bring the ctx back to life */
9970                 percpu_ref_reinit(&ctx->refs);
9971 out_quiesce:
9972                 reinit_completion(&ctx->ref_comp);
9973         }
9974         return ret;
9975 }
9976
9977 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9978                 void __user *, arg, unsigned int, nr_args)
9979 {
9980         struct io_ring_ctx *ctx;
9981         long ret = -EBADF;
9982         struct fd f;
9983
9984         f = fdget(fd);
9985         if (!f.file)
9986                 return -EBADF;
9987
9988         ret = -EOPNOTSUPP;
9989         if (f.file->f_op != &io_uring_fops)
9990                 goto out_fput;
9991
9992         ctx = f.file->private_data;
9993
9994         io_run_task_work();
9995
9996         mutex_lock(&ctx->uring_lock);
9997         ret = __io_uring_register(ctx, opcode, arg, nr_args);
9998         mutex_unlock(&ctx->uring_lock);
9999         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10000                                                         ctx->cq_ev_fd != NULL, ret);
10001 out_fput:
10002         fdput(f);
10003         return ret;
10004 }
10005
10006 static int __init io_uring_init(void)
10007 {
10008 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10009         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10010         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10011 } while (0)
10012
10013 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10014         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10015         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10016         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
10017         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
10018         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
10019         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
10020         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
10021         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
10022         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
10023         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
10024         BUILD_BUG_SQE_ELEM(24, __u32,  len);
10025         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
10026         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
10027         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10028         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
10029         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
10030         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
10031         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
10032         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
10033         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
10034         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
10035         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
10036         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
10037         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
10038         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
10039         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
10040         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
10041         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
10042         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
10043         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
10044
10045         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10046         BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10047         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10048                                 SLAB_ACCOUNT);
10049         return 0;
10050 };
10051 __initcall(io_uring_init);