io_uring: enable READ/WRITE to use deferred completions
[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/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
64 #include <net/sock.h>
65 #include <net/af_unix.h>
66 #include <net/scm.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
85
86 #include <uapi/linux/io_uring.h>
87
88 #include "internal.h"
89 #include "io-wq.h"
90
91 #define IORING_MAX_ENTRIES      32768
92 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
93
94 /*
95  * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96  */
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE  (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK  (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES  (64 * IORING_MAX_FILES_TABLE)
101
102 struct io_uring {
103         u32 head ____cacheline_aligned_in_smp;
104         u32 tail ____cacheline_aligned_in_smp;
105 };
106
107 /*
108  * This data is shared with the application through the mmap at offsets
109  * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
110  *
111  * The offsets to the member fields are published through struct
112  * io_sqring_offsets when calling io_uring_setup.
113  */
114 struct io_rings {
115         /*
116          * Head and tail offsets into the ring; the offsets need to be
117          * masked to get valid indices.
118          *
119          * The kernel controls head of the sq ring and the tail of the cq ring,
120          * and the application controls tail of the sq ring and the head of the
121          * cq ring.
122          */
123         struct io_uring         sq, cq;
124         /*
125          * Bitmasks to apply to head and tail offsets (constant, equals
126          * ring_entries - 1)
127          */
128         u32                     sq_ring_mask, cq_ring_mask;
129         /* Ring sizes (constant, power of 2) */
130         u32                     sq_ring_entries, cq_ring_entries;
131         /*
132          * Number of invalid entries dropped by the kernel due to
133          * invalid index stored in array
134          *
135          * Written by the kernel, shouldn't be modified by the
136          * application (i.e. get number of "new events" by comparing to
137          * cached value).
138          *
139          * After a new SQ head value was read by the application this
140          * counter includes all submissions that were dropped reaching
141          * the new SQ head (and possibly more).
142          */
143         u32                     sq_dropped;
144         /*
145          * Runtime SQ flags
146          *
147          * Written by the kernel, shouldn't be modified by the
148          * application.
149          *
150          * The application needs a full memory barrier before checking
151          * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
152          */
153         u32                     sq_flags;
154         /*
155          * Runtime CQ flags
156          *
157          * Written by the application, shouldn't be modified by the
158          * kernel.
159          */
160         u32                     cq_flags;
161         /*
162          * Number of completion events lost because the queue was full;
163          * this should be avoided by the application by making sure
164          * there are not more requests pending than there is space in
165          * the completion queue.
166          *
167          * Written by the kernel, shouldn't be modified by the
168          * application (i.e. get number of "new events" by comparing to
169          * cached value).
170          *
171          * As completion events come in out of order this counter is not
172          * ordered with any other data.
173          */
174         u32                     cq_overflow;
175         /*
176          * Ring buffer of completion events.
177          *
178          * The kernel writes completion events fresh every time they are
179          * produced, so the application is allowed to modify pending
180          * entries.
181          */
182         struct io_uring_cqe     cqes[] ____cacheline_aligned_in_smp;
183 };
184
185 struct io_mapped_ubuf {
186         u64             ubuf;
187         size_t          len;
188         struct          bio_vec *bvec;
189         unsigned int    nr_bvecs;
190 };
191
192 struct fixed_file_table {
193         struct file             **files;
194 };
195
196 struct fixed_file_ref_node {
197         struct percpu_ref               refs;
198         struct list_head                node;
199         struct list_head                file_list;
200         struct fixed_file_data          *file_data;
201         struct llist_node               llist;
202 };
203
204 struct fixed_file_data {
205         struct fixed_file_table         *table;
206         struct io_ring_ctx              *ctx;
207
208         struct percpu_ref               *cur_refs;
209         struct percpu_ref               refs;
210         struct completion               done;
211         struct list_head                ref_list;
212         spinlock_t                      lock;
213 };
214
215 struct io_buffer {
216         struct list_head list;
217         __u64 addr;
218         __s32 len;
219         __u16 bid;
220 };
221
222 struct io_ring_ctx {
223         struct {
224                 struct percpu_ref       refs;
225         } ____cacheline_aligned_in_smp;
226
227         struct {
228                 unsigned int            flags;
229                 unsigned int            compat: 1;
230                 unsigned int            limit_mem: 1;
231                 unsigned int            cq_overflow_flushed: 1;
232                 unsigned int            drain_next: 1;
233                 unsigned int            eventfd_async: 1;
234
235                 /*
236                  * Ring buffer of indices into array of io_uring_sqe, which is
237                  * mmapped by the application using the IORING_OFF_SQES offset.
238                  *
239                  * This indirection could e.g. be used to assign fixed
240                  * io_uring_sqe entries to operations and only submit them to
241                  * the queue when needed.
242                  *
243                  * The kernel modifies neither the indices array nor the entries
244                  * array.
245                  */
246                 u32                     *sq_array;
247                 unsigned                cached_sq_head;
248                 unsigned                sq_entries;
249                 unsigned                sq_mask;
250                 unsigned                sq_thread_idle;
251                 unsigned                cached_sq_dropped;
252                 atomic_t                cached_cq_overflow;
253                 unsigned long           sq_check_overflow;
254
255                 struct list_head        defer_list;
256                 struct list_head        timeout_list;
257                 struct list_head        cq_overflow_list;
258
259                 wait_queue_head_t       inflight_wait;
260                 struct io_uring_sqe     *sq_sqes;
261         } ____cacheline_aligned_in_smp;
262
263         struct io_rings *rings;
264
265         /* IO offload */
266         struct io_wq            *io_wq;
267         struct task_struct      *sqo_thread;    /* if using sq thread polling */
268         struct mm_struct        *sqo_mm;
269         wait_queue_head_t       sqo_wait;
270
271         /*
272          * If used, fixed file set. Writers must ensure that ->refs is dead,
273          * readers must ensure that ->refs is alive as long as the file* is
274          * used. Only updated through io_uring_register(2).
275          */
276         struct fixed_file_data  *file_data;
277         unsigned                nr_user_files;
278         int                     ring_fd;
279         struct file             *ring_file;
280
281         /* if used, fixed mapped user buffers */
282         unsigned                nr_user_bufs;
283         struct io_mapped_ubuf   *user_bufs;
284
285         struct user_struct      *user;
286
287         const struct cred       *creds;
288
289         struct completion       ref_comp;
290         struct completion       sq_thread_comp;
291
292         /* if all else fails... */
293         struct io_kiocb         *fallback_req;
294
295 #if defined(CONFIG_UNIX)
296         struct socket           *ring_sock;
297 #endif
298
299         struct idr              io_buffer_idr;
300
301         struct idr              personality_idr;
302
303         struct {
304                 unsigned                cached_cq_tail;
305                 unsigned                cq_entries;
306                 unsigned                cq_mask;
307                 atomic_t                cq_timeouts;
308                 unsigned long           cq_check_overflow;
309                 struct wait_queue_head  cq_wait;
310                 struct fasync_struct    *cq_fasync;
311                 struct eventfd_ctx      *cq_ev_fd;
312         } ____cacheline_aligned_in_smp;
313
314         struct {
315                 struct mutex            uring_lock;
316                 wait_queue_head_t       wait;
317         } ____cacheline_aligned_in_smp;
318
319         struct {
320                 spinlock_t              completion_lock;
321
322                 /*
323                  * ->poll_list is protected by the ctx->uring_lock for
324                  * io_uring instances that don't use IORING_SETUP_SQPOLL.
325                  * For SQPOLL, only the single threaded io_sq_thread() will
326                  * manipulate the list, hence no extra locking is needed there.
327                  */
328                 struct list_head        poll_list;
329                 struct hlist_head       *cancel_hash;
330                 unsigned                cancel_hash_bits;
331                 bool                    poll_multi_file;
332
333                 spinlock_t              inflight_lock;
334                 struct list_head        inflight_list;
335         } ____cacheline_aligned_in_smp;
336
337         struct delayed_work             file_put_work;
338         struct llist_head               file_put_llist;
339
340         struct work_struct              exit_work;
341 };
342
343 /*
344  * First field must be the file pointer in all the
345  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
346  */
347 struct io_poll_iocb {
348         struct file                     *file;
349         union {
350                 struct wait_queue_head  *head;
351                 u64                     addr;
352         };
353         __poll_t                        events;
354         bool                            done;
355         bool                            canceled;
356         struct wait_queue_entry         wait;
357 };
358
359 struct io_close {
360         struct file                     *file;
361         struct file                     *put_file;
362         int                             fd;
363 };
364
365 struct io_timeout_data {
366         struct io_kiocb                 *req;
367         struct hrtimer                  timer;
368         struct timespec64               ts;
369         enum hrtimer_mode               mode;
370 };
371
372 struct io_accept {
373         struct file                     *file;
374         struct sockaddr __user          *addr;
375         int __user                      *addr_len;
376         int                             flags;
377         unsigned long                   nofile;
378 };
379
380 struct io_sync {
381         struct file                     *file;
382         loff_t                          len;
383         loff_t                          off;
384         int                             flags;
385         int                             mode;
386 };
387
388 struct io_cancel {
389         struct file                     *file;
390         u64                             addr;
391 };
392
393 struct io_timeout {
394         struct file                     *file;
395         u64                             addr;
396         int                             flags;
397         u32                             off;
398         u32                             target_seq;
399 };
400
401 struct io_rw {
402         /* NOTE: kiocb has the file as the first member, so don't do it here */
403         struct kiocb                    kiocb;
404         u64                             addr;
405         u64                             len;
406 };
407
408 struct io_connect {
409         struct file                     *file;
410         struct sockaddr __user          *addr;
411         int                             addr_len;
412 };
413
414 struct io_sr_msg {
415         struct file                     *file;
416         union {
417                 struct user_msghdr __user *msg;
418                 void __user             *buf;
419         };
420         int                             msg_flags;
421         int                             bgid;
422         size_t                          len;
423         struct io_buffer                *kbuf;
424 };
425
426 struct io_open {
427         struct file                     *file;
428         int                             dfd;
429         struct filename                 *filename;
430         struct open_how                 how;
431         unsigned long                   nofile;
432 };
433
434 struct io_files_update {
435         struct file                     *file;
436         u64                             arg;
437         u32                             nr_args;
438         u32                             offset;
439 };
440
441 struct io_fadvise {
442         struct file                     *file;
443         u64                             offset;
444         u32                             len;
445         u32                             advice;
446 };
447
448 struct io_madvise {
449         struct file                     *file;
450         u64                             addr;
451         u32                             len;
452         u32                             advice;
453 };
454
455 struct io_epoll {
456         struct file                     *file;
457         int                             epfd;
458         int                             op;
459         int                             fd;
460         struct epoll_event              event;
461 };
462
463 struct io_splice {
464         struct file                     *file_out;
465         struct file                     *file_in;
466         loff_t                          off_out;
467         loff_t                          off_in;
468         u64                             len;
469         unsigned int                    flags;
470 };
471
472 struct io_provide_buf {
473         struct file                     *file;
474         __u64                           addr;
475         __s32                           len;
476         __u32                           bgid;
477         __u16                           nbufs;
478         __u16                           bid;
479 };
480
481 struct io_statx {
482         struct file                     *file;
483         int                             dfd;
484         unsigned int                    mask;
485         unsigned int                    flags;
486         const char __user               *filename;
487         struct statx __user             *buffer;
488 };
489
490 struct io_async_connect {
491         struct sockaddr_storage         address;
492 };
493
494 struct io_async_msghdr {
495         struct iovec                    fast_iov[UIO_FASTIOV];
496         struct iovec                    *iov;
497         struct sockaddr __user          *uaddr;
498         struct msghdr                   msg;
499         struct sockaddr_storage         addr;
500 };
501
502 struct io_async_rw {
503         struct iovec                    fast_iov[UIO_FASTIOV];
504         struct iovec                    *iov;
505         ssize_t                         nr_segs;
506         ssize_t                         size;
507         struct wait_page_queue          wpq;
508         struct callback_head            task_work;
509 };
510
511 struct io_async_ctx {
512         union {
513                 struct io_async_rw      rw;
514                 struct io_async_msghdr  msg;
515                 struct io_async_connect connect;
516                 struct io_timeout_data  timeout;
517         };
518 };
519
520 enum {
521         REQ_F_FIXED_FILE_BIT    = IOSQE_FIXED_FILE_BIT,
522         REQ_F_IO_DRAIN_BIT      = IOSQE_IO_DRAIN_BIT,
523         REQ_F_LINK_BIT          = IOSQE_IO_LINK_BIT,
524         REQ_F_HARDLINK_BIT      = IOSQE_IO_HARDLINK_BIT,
525         REQ_F_FORCE_ASYNC_BIT   = IOSQE_ASYNC_BIT,
526         REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
527
528         REQ_F_LINK_HEAD_BIT,
529         REQ_F_LINK_NEXT_BIT,
530         REQ_F_FAIL_LINK_BIT,
531         REQ_F_INFLIGHT_BIT,
532         REQ_F_CUR_POS_BIT,
533         REQ_F_NOWAIT_BIT,
534         REQ_F_LINK_TIMEOUT_BIT,
535         REQ_F_TIMEOUT_BIT,
536         REQ_F_ISREG_BIT,
537         REQ_F_TIMEOUT_NOSEQ_BIT,
538         REQ_F_COMP_LOCKED_BIT,
539         REQ_F_NEED_CLEANUP_BIT,
540         REQ_F_OVERFLOW_BIT,
541         REQ_F_POLLED_BIT,
542         REQ_F_BUFFER_SELECTED_BIT,
543         REQ_F_NO_FILE_TABLE_BIT,
544         REQ_F_QUEUE_TIMEOUT_BIT,
545         REQ_F_WORK_INITIALIZED_BIT,
546         REQ_F_TASK_PINNED_BIT,
547
548         /* not a real bit, just to check we're not overflowing the space */
549         __REQ_F_LAST_BIT,
550 };
551
552 enum {
553         /* ctx owns file */
554         REQ_F_FIXED_FILE        = BIT(REQ_F_FIXED_FILE_BIT),
555         /* drain existing IO first */
556         REQ_F_IO_DRAIN          = BIT(REQ_F_IO_DRAIN_BIT),
557         /* linked sqes */
558         REQ_F_LINK              = BIT(REQ_F_LINK_BIT),
559         /* doesn't sever on completion < 0 */
560         REQ_F_HARDLINK          = BIT(REQ_F_HARDLINK_BIT),
561         /* IOSQE_ASYNC */
562         REQ_F_FORCE_ASYNC       = BIT(REQ_F_FORCE_ASYNC_BIT),
563         /* IOSQE_BUFFER_SELECT */
564         REQ_F_BUFFER_SELECT     = BIT(REQ_F_BUFFER_SELECT_BIT),
565
566         /* head of a link */
567         REQ_F_LINK_HEAD         = BIT(REQ_F_LINK_HEAD_BIT),
568         /* already grabbed next link */
569         REQ_F_LINK_NEXT         = BIT(REQ_F_LINK_NEXT_BIT),
570         /* fail rest of links */
571         REQ_F_FAIL_LINK         = BIT(REQ_F_FAIL_LINK_BIT),
572         /* on inflight list */
573         REQ_F_INFLIGHT          = BIT(REQ_F_INFLIGHT_BIT),
574         /* read/write uses file position */
575         REQ_F_CUR_POS           = BIT(REQ_F_CUR_POS_BIT),
576         /* must not punt to workers */
577         REQ_F_NOWAIT            = BIT(REQ_F_NOWAIT_BIT),
578         /* has linked timeout */
579         REQ_F_LINK_TIMEOUT      = BIT(REQ_F_LINK_TIMEOUT_BIT),
580         /* timeout request */
581         REQ_F_TIMEOUT           = BIT(REQ_F_TIMEOUT_BIT),
582         /* regular file */
583         REQ_F_ISREG             = BIT(REQ_F_ISREG_BIT),
584         /* no timeout sequence */
585         REQ_F_TIMEOUT_NOSEQ     = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
586         /* completion under lock */
587         REQ_F_COMP_LOCKED       = BIT(REQ_F_COMP_LOCKED_BIT),
588         /* needs cleanup */
589         REQ_F_NEED_CLEANUP      = BIT(REQ_F_NEED_CLEANUP_BIT),
590         /* in overflow list */
591         REQ_F_OVERFLOW          = BIT(REQ_F_OVERFLOW_BIT),
592         /* already went through poll handler */
593         REQ_F_POLLED            = BIT(REQ_F_POLLED_BIT),
594         /* buffer already selected */
595         REQ_F_BUFFER_SELECTED   = BIT(REQ_F_BUFFER_SELECTED_BIT),
596         /* doesn't need file table for this request */
597         REQ_F_NO_FILE_TABLE     = BIT(REQ_F_NO_FILE_TABLE_BIT),
598         /* needs to queue linked timeout */
599         REQ_F_QUEUE_TIMEOUT     = BIT(REQ_F_QUEUE_TIMEOUT_BIT),
600         /* io_wq_work is initialized */
601         REQ_F_WORK_INITIALIZED  = BIT(REQ_F_WORK_INITIALIZED_BIT),
602         /* req->task is refcounted */
603         REQ_F_TASK_PINNED       = BIT(REQ_F_TASK_PINNED_BIT),
604 };
605
606 struct async_poll {
607         struct io_poll_iocb     poll;
608         struct io_wq_work       work;
609 };
610
611 /*
612  * NOTE! Each of the iocb union members has the file pointer
613  * as the first entry in their struct definition. So you can
614  * access the file pointer through any of the sub-structs,
615  * or directly as just 'ki_filp' in this struct.
616  */
617 struct io_kiocb {
618         union {
619                 struct file             *file;
620                 struct io_rw            rw;
621                 struct io_poll_iocb     poll;
622                 struct io_accept        accept;
623                 struct io_sync          sync;
624                 struct io_cancel        cancel;
625                 struct io_timeout       timeout;
626                 struct io_connect       connect;
627                 struct io_sr_msg        sr_msg;
628                 struct io_open          open;
629                 struct io_close         close;
630                 struct io_files_update  files_update;
631                 struct io_fadvise       fadvise;
632                 struct io_madvise       madvise;
633                 struct io_epoll         epoll;
634                 struct io_splice        splice;
635                 struct io_provide_buf   pbuf;
636                 struct io_statx         statx;
637         };
638
639         struct io_async_ctx             *io;
640         int                             cflags;
641         u8                              opcode;
642         /* polled IO has completed */
643         u8                              iopoll_completed;
644
645         u16                             buf_index;
646
647         struct io_ring_ctx      *ctx;
648         struct list_head        list;
649         unsigned int            flags;
650         refcount_t              refs;
651         struct task_struct      *task;
652         unsigned long           fsize;
653         u64                     user_data;
654         u32                     result;
655         u32                     sequence;
656
657         struct list_head        link_list;
658
659         struct list_head        inflight_entry;
660
661         struct percpu_ref       *fixed_file_refs;
662
663         union {
664                 /*
665                  * Only commands that never go async can use the below fields,
666                  * obviously. Right now only IORING_OP_POLL_ADD uses them, and
667                  * async armed poll handlers for regular commands. The latter
668                  * restore the work, if needed.
669                  */
670                 struct {
671                         struct callback_head    task_work;
672                         struct hlist_node       hash_node;
673                         struct async_poll       *apoll;
674                 };
675                 struct io_wq_work       work;
676         };
677 };
678
679 #define IO_IOPOLL_BATCH                 8
680
681 struct io_comp_state {
682         unsigned int            nr;
683         struct list_head        list;
684         struct io_ring_ctx      *ctx;
685 };
686
687 struct io_submit_state {
688         struct blk_plug         plug;
689
690         /*
691          * io_kiocb alloc cache
692          */
693         void                    *reqs[IO_IOPOLL_BATCH];
694         unsigned int            free_reqs;
695
696         /*
697          * Batch completion logic
698          */
699         struct io_comp_state    comp;
700
701         /*
702          * File reference cache
703          */
704         struct file             *file;
705         unsigned int            fd;
706         unsigned int            has_refs;
707         unsigned int            used_refs;
708         unsigned int            ios_left;
709 };
710
711 struct io_op_def {
712         /* needs req->io allocated for deferral/async */
713         unsigned                async_ctx : 1;
714         /* needs current->mm setup, does mm access */
715         unsigned                needs_mm : 1;
716         /* needs req->file assigned */
717         unsigned                needs_file : 1;
718         /* don't fail if file grab fails */
719         unsigned                needs_file_no_error : 1;
720         /* hash wq insertion if file is a regular file */
721         unsigned                hash_reg_file : 1;
722         /* unbound wq insertion if file is a non-regular file */
723         unsigned                unbound_nonreg_file : 1;
724         /* opcode is not supported by this kernel */
725         unsigned                not_supported : 1;
726         /* needs file table */
727         unsigned                file_table : 1;
728         /* needs ->fs */
729         unsigned                needs_fs : 1;
730         /* set if opcode supports polled "wait" */
731         unsigned                pollin : 1;
732         unsigned                pollout : 1;
733         /* op supports buffer selection */
734         unsigned                buffer_select : 1;
735 };
736
737 static const struct io_op_def io_op_defs[] = {
738         [IORING_OP_NOP] = {},
739         [IORING_OP_READV] = {
740                 .async_ctx              = 1,
741                 .needs_mm               = 1,
742                 .needs_file             = 1,
743                 .unbound_nonreg_file    = 1,
744                 .pollin                 = 1,
745                 .buffer_select          = 1,
746         },
747         [IORING_OP_WRITEV] = {
748                 .async_ctx              = 1,
749                 .needs_mm               = 1,
750                 .needs_file             = 1,
751                 .hash_reg_file          = 1,
752                 .unbound_nonreg_file    = 1,
753                 .pollout                = 1,
754         },
755         [IORING_OP_FSYNC] = {
756                 .needs_file             = 1,
757         },
758         [IORING_OP_READ_FIXED] = {
759                 .needs_file             = 1,
760                 .unbound_nonreg_file    = 1,
761                 .pollin                 = 1,
762         },
763         [IORING_OP_WRITE_FIXED] = {
764                 .needs_file             = 1,
765                 .hash_reg_file          = 1,
766                 .unbound_nonreg_file    = 1,
767                 .pollout                = 1,
768         },
769         [IORING_OP_POLL_ADD] = {
770                 .needs_file             = 1,
771                 .unbound_nonreg_file    = 1,
772         },
773         [IORING_OP_POLL_REMOVE] = {},
774         [IORING_OP_SYNC_FILE_RANGE] = {
775                 .needs_file             = 1,
776         },
777         [IORING_OP_SENDMSG] = {
778                 .async_ctx              = 1,
779                 .needs_mm               = 1,
780                 .needs_file             = 1,
781                 .unbound_nonreg_file    = 1,
782                 .needs_fs               = 1,
783                 .pollout                = 1,
784         },
785         [IORING_OP_RECVMSG] = {
786                 .async_ctx              = 1,
787                 .needs_mm               = 1,
788                 .needs_file             = 1,
789                 .unbound_nonreg_file    = 1,
790                 .needs_fs               = 1,
791                 .pollin                 = 1,
792                 .buffer_select          = 1,
793         },
794         [IORING_OP_TIMEOUT] = {
795                 .async_ctx              = 1,
796                 .needs_mm               = 1,
797         },
798         [IORING_OP_TIMEOUT_REMOVE] = {},
799         [IORING_OP_ACCEPT] = {
800                 .needs_mm               = 1,
801                 .needs_file             = 1,
802                 .unbound_nonreg_file    = 1,
803                 .file_table             = 1,
804                 .pollin                 = 1,
805         },
806         [IORING_OP_ASYNC_CANCEL] = {},
807         [IORING_OP_LINK_TIMEOUT] = {
808                 .async_ctx              = 1,
809                 .needs_mm               = 1,
810         },
811         [IORING_OP_CONNECT] = {
812                 .async_ctx              = 1,
813                 .needs_mm               = 1,
814                 .needs_file             = 1,
815                 .unbound_nonreg_file    = 1,
816                 .pollout                = 1,
817         },
818         [IORING_OP_FALLOCATE] = {
819                 .needs_file             = 1,
820         },
821         [IORING_OP_OPENAT] = {
822                 .file_table             = 1,
823                 .needs_fs               = 1,
824         },
825         [IORING_OP_CLOSE] = {
826                 .needs_file             = 1,
827                 .needs_file_no_error    = 1,
828                 .file_table             = 1,
829         },
830         [IORING_OP_FILES_UPDATE] = {
831                 .needs_mm               = 1,
832                 .file_table             = 1,
833         },
834         [IORING_OP_STATX] = {
835                 .needs_mm               = 1,
836                 .needs_fs               = 1,
837                 .file_table             = 1,
838         },
839         [IORING_OP_READ] = {
840                 .needs_mm               = 1,
841                 .needs_file             = 1,
842                 .unbound_nonreg_file    = 1,
843                 .pollin                 = 1,
844                 .buffer_select          = 1,
845         },
846         [IORING_OP_WRITE] = {
847                 .needs_mm               = 1,
848                 .needs_file             = 1,
849                 .unbound_nonreg_file    = 1,
850                 .pollout                = 1,
851         },
852         [IORING_OP_FADVISE] = {
853                 .needs_file             = 1,
854         },
855         [IORING_OP_MADVISE] = {
856                 .needs_mm               = 1,
857         },
858         [IORING_OP_SEND] = {
859                 .needs_mm               = 1,
860                 .needs_file             = 1,
861                 .unbound_nonreg_file    = 1,
862                 .pollout                = 1,
863         },
864         [IORING_OP_RECV] = {
865                 .needs_mm               = 1,
866                 .needs_file             = 1,
867                 .unbound_nonreg_file    = 1,
868                 .pollin                 = 1,
869                 .buffer_select          = 1,
870         },
871         [IORING_OP_OPENAT2] = {
872                 .file_table             = 1,
873                 .needs_fs               = 1,
874         },
875         [IORING_OP_EPOLL_CTL] = {
876                 .unbound_nonreg_file    = 1,
877                 .file_table             = 1,
878         },
879         [IORING_OP_SPLICE] = {
880                 .needs_file             = 1,
881                 .hash_reg_file          = 1,
882                 .unbound_nonreg_file    = 1,
883         },
884         [IORING_OP_PROVIDE_BUFFERS] = {},
885         [IORING_OP_REMOVE_BUFFERS] = {},
886         [IORING_OP_TEE] = {
887                 .needs_file             = 1,
888                 .hash_reg_file          = 1,
889                 .unbound_nonreg_file    = 1,
890         },
891 };
892
893 enum io_mem_account {
894         ACCT_LOCKED,
895         ACCT_PINNED,
896 };
897
898 static void io_wq_submit_work(struct io_wq_work **workptr);
899 static void io_cqring_fill_event(struct io_kiocb *req, long res);
900 static void io_put_req(struct io_kiocb *req);
901 static void __io_double_put_req(struct io_kiocb *req);
902 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
903 static void io_queue_linked_timeout(struct io_kiocb *req);
904 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
905                                  struct io_uring_files_update *ip,
906                                  unsigned nr_args);
907 static int io_grab_files(struct io_kiocb *req);
908 static void io_cleanup_req(struct io_kiocb *req);
909 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
910                        int fd, struct file **out_file, bool fixed);
911 static void __io_queue_sqe(struct io_kiocb *req,
912                            const struct io_uring_sqe *sqe,
913                            struct io_comp_state *cs);
914
915 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
916                                struct iovec **iovec, struct iov_iter *iter,
917                                bool needs_lock);
918 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
919                              struct iovec *iovec, struct iovec *fast_iov,
920                              struct iov_iter *iter);
921
922 static struct kmem_cache *req_cachep;
923
924 static const struct file_operations io_uring_fops;
925
926 struct sock *io_uring_get_socket(struct file *file)
927 {
928 #if defined(CONFIG_UNIX)
929         if (file->f_op == &io_uring_fops) {
930                 struct io_ring_ctx *ctx = file->private_data;
931
932                 return ctx->ring_sock->sk;
933         }
934 #endif
935         return NULL;
936 }
937 EXPORT_SYMBOL(io_uring_get_socket);
938
939 static void io_get_req_task(struct io_kiocb *req)
940 {
941         if (req->flags & REQ_F_TASK_PINNED)
942                 return;
943         get_task_struct(req->task);
944         req->flags |= REQ_F_TASK_PINNED;
945 }
946
947 /* not idempotent -- it doesn't clear REQ_F_TASK_PINNED */
948 static void __io_put_req_task(struct io_kiocb *req)
949 {
950         if (req->flags & REQ_F_TASK_PINNED)
951                 put_task_struct(req->task);
952 }
953
954 static void io_file_put_work(struct work_struct *work);
955
956 /*
957  * Note: must call io_req_init_async() for the first time you
958  * touch any members of io_wq_work.
959  */
960 static inline void io_req_init_async(struct io_kiocb *req)
961 {
962         if (req->flags & REQ_F_WORK_INITIALIZED)
963                 return;
964
965         memset(&req->work, 0, sizeof(req->work));
966         req->flags |= REQ_F_WORK_INITIALIZED;
967 }
968
969 static inline bool io_async_submit(struct io_ring_ctx *ctx)
970 {
971         return ctx->flags & IORING_SETUP_SQPOLL;
972 }
973
974 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
975 {
976         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
977
978         complete(&ctx->ref_comp);
979 }
980
981 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
982 {
983         struct io_ring_ctx *ctx;
984         int hash_bits;
985
986         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
987         if (!ctx)
988                 return NULL;
989
990         ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
991         if (!ctx->fallback_req)
992                 goto err;
993
994         /*
995          * Use 5 bits less than the max cq entries, that should give us around
996          * 32 entries per hash list if totally full and uniformly spread.
997          */
998         hash_bits = ilog2(p->cq_entries);
999         hash_bits -= 5;
1000         if (hash_bits <= 0)
1001                 hash_bits = 1;
1002         ctx->cancel_hash_bits = hash_bits;
1003         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1004                                         GFP_KERNEL);
1005         if (!ctx->cancel_hash)
1006                 goto err;
1007         __hash_init(ctx->cancel_hash, 1U << hash_bits);
1008
1009         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1010                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1011                 goto err;
1012
1013         ctx->flags = p->flags;
1014         init_waitqueue_head(&ctx->sqo_wait);
1015         init_waitqueue_head(&ctx->cq_wait);
1016         INIT_LIST_HEAD(&ctx->cq_overflow_list);
1017         init_completion(&ctx->ref_comp);
1018         init_completion(&ctx->sq_thread_comp);
1019         idr_init(&ctx->io_buffer_idr);
1020         idr_init(&ctx->personality_idr);
1021         mutex_init(&ctx->uring_lock);
1022         init_waitqueue_head(&ctx->wait);
1023         spin_lock_init(&ctx->completion_lock);
1024         INIT_LIST_HEAD(&ctx->poll_list);
1025         INIT_LIST_HEAD(&ctx->defer_list);
1026         INIT_LIST_HEAD(&ctx->timeout_list);
1027         init_waitqueue_head(&ctx->inflight_wait);
1028         spin_lock_init(&ctx->inflight_lock);
1029         INIT_LIST_HEAD(&ctx->inflight_list);
1030         INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1031         init_llist_head(&ctx->file_put_llist);
1032         return ctx;
1033 err:
1034         if (ctx->fallback_req)
1035                 kmem_cache_free(req_cachep, ctx->fallback_req);
1036         kfree(ctx->cancel_hash);
1037         kfree(ctx);
1038         return NULL;
1039 }
1040
1041 static inline bool __req_need_defer(struct io_kiocb *req)
1042 {
1043         struct io_ring_ctx *ctx = req->ctx;
1044
1045         return req->sequence != ctx->cached_cq_tail
1046                                 + atomic_read(&ctx->cached_cq_overflow);
1047 }
1048
1049 static inline bool req_need_defer(struct io_kiocb *req)
1050 {
1051         if (unlikely(req->flags & REQ_F_IO_DRAIN))
1052                 return __req_need_defer(req);
1053
1054         return false;
1055 }
1056
1057 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1058 {
1059         struct io_rings *rings = ctx->rings;
1060
1061         /* order cqe stores with ring update */
1062         smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1063
1064         if (wq_has_sleeper(&ctx->cq_wait)) {
1065                 wake_up_interruptible(&ctx->cq_wait);
1066                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1067         }
1068 }
1069
1070 static inline void io_req_work_grab_env(struct io_kiocb *req,
1071                                         const struct io_op_def *def)
1072 {
1073         if (!req->work.mm && def->needs_mm) {
1074                 mmgrab(current->mm);
1075                 req->work.mm = current->mm;
1076         }
1077         if (!req->work.creds)
1078                 req->work.creds = get_current_cred();
1079         if (!req->work.fs && def->needs_fs) {
1080                 spin_lock(&current->fs->lock);
1081                 if (!current->fs->in_exec) {
1082                         req->work.fs = current->fs;
1083                         req->work.fs->users++;
1084                 } else {
1085                         req->work.flags |= IO_WQ_WORK_CANCEL;
1086                 }
1087                 spin_unlock(&current->fs->lock);
1088         }
1089 }
1090
1091 static inline void io_req_work_drop_env(struct io_kiocb *req)
1092 {
1093         if (!(req->flags & REQ_F_WORK_INITIALIZED))
1094                 return;
1095
1096         if (req->work.mm) {
1097                 mmdrop(req->work.mm);
1098                 req->work.mm = NULL;
1099         }
1100         if (req->work.creds) {
1101                 put_cred(req->work.creds);
1102                 req->work.creds = NULL;
1103         }
1104         if (req->work.fs) {
1105                 struct fs_struct *fs = req->work.fs;
1106
1107                 spin_lock(&req->work.fs->lock);
1108                 if (--fs->users)
1109                         fs = NULL;
1110                 spin_unlock(&req->work.fs->lock);
1111                 if (fs)
1112                         free_fs_struct(fs);
1113         }
1114 }
1115
1116 static inline void io_prep_async_work(struct io_kiocb *req,
1117                                       struct io_kiocb **link)
1118 {
1119         const struct io_op_def *def = &io_op_defs[req->opcode];
1120
1121         if (req->flags & REQ_F_ISREG) {
1122                 if (def->hash_reg_file)
1123                         io_wq_hash_work(&req->work, file_inode(req->file));
1124         } else {
1125                 if (def->unbound_nonreg_file)
1126                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1127         }
1128
1129         io_req_init_async(req);
1130         io_req_work_grab_env(req, def);
1131
1132         *link = io_prep_linked_timeout(req);
1133 }
1134
1135 static inline void io_queue_async_work(struct io_kiocb *req)
1136 {
1137         struct io_ring_ctx *ctx = req->ctx;
1138         struct io_kiocb *link;
1139
1140         io_prep_async_work(req, &link);
1141
1142         trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1143                                         &req->work, req->flags);
1144         io_wq_enqueue(ctx->io_wq, &req->work);
1145
1146         if (link)
1147                 io_queue_linked_timeout(link);
1148 }
1149
1150 static void io_kill_timeout(struct io_kiocb *req)
1151 {
1152         int ret;
1153
1154         ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1155         if (ret != -1) {
1156                 atomic_inc(&req->ctx->cq_timeouts);
1157                 list_del_init(&req->list);
1158                 req->flags |= REQ_F_COMP_LOCKED;
1159                 io_cqring_fill_event(req, 0);
1160                 io_put_req(req);
1161         }
1162 }
1163
1164 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1165 {
1166         struct io_kiocb *req, *tmp;
1167
1168         spin_lock_irq(&ctx->completion_lock);
1169         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1170                 io_kill_timeout(req);
1171         spin_unlock_irq(&ctx->completion_lock);
1172 }
1173
1174 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1175 {
1176         do {
1177                 struct io_kiocb *req = list_first_entry(&ctx->defer_list,
1178                                                         struct io_kiocb, list);
1179
1180                 if (req_need_defer(req))
1181                         break;
1182                 list_del_init(&req->list);
1183                 io_queue_async_work(req);
1184         } while (!list_empty(&ctx->defer_list));
1185 }
1186
1187 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1188 {
1189         while (!list_empty(&ctx->timeout_list)) {
1190                 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1191                                                         struct io_kiocb, list);
1192
1193                 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
1194                         break;
1195                 if (req->timeout.target_seq != ctx->cached_cq_tail
1196                                         - atomic_read(&ctx->cq_timeouts))
1197                         break;
1198
1199                 list_del_init(&req->list);
1200                 io_kill_timeout(req);
1201         }
1202 }
1203
1204 static void io_commit_cqring(struct io_ring_ctx *ctx)
1205 {
1206         io_flush_timeouts(ctx);
1207         __io_commit_cqring(ctx);
1208
1209         if (unlikely(!list_empty(&ctx->defer_list)))
1210                 __io_queue_deferred(ctx);
1211 }
1212
1213 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1214 {
1215         struct io_rings *rings = ctx->rings;
1216         unsigned tail;
1217
1218         tail = ctx->cached_cq_tail;
1219         /*
1220          * writes to the cq entry need to come after reading head; the
1221          * control dependency is enough as we're using WRITE_ONCE to
1222          * fill the cq entry
1223          */
1224         if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1225                 return NULL;
1226
1227         ctx->cached_cq_tail++;
1228         return &rings->cqes[tail & ctx->cq_mask];
1229 }
1230
1231 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1232 {
1233         if (!ctx->cq_ev_fd)
1234                 return false;
1235         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1236                 return false;
1237         if (!ctx->eventfd_async)
1238                 return true;
1239         return io_wq_current_is_worker();
1240 }
1241
1242 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1243 {
1244         if (waitqueue_active(&ctx->wait))
1245                 wake_up(&ctx->wait);
1246         if (waitqueue_active(&ctx->sqo_wait))
1247                 wake_up(&ctx->sqo_wait);
1248         if (io_should_trigger_evfd(ctx))
1249                 eventfd_signal(ctx->cq_ev_fd, 1);
1250 }
1251
1252 /* Returns true if there are no backlogged entries after the flush */
1253 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1254 {
1255         struct io_rings *rings = ctx->rings;
1256         struct io_uring_cqe *cqe;
1257         struct io_kiocb *req;
1258         unsigned long flags;
1259         LIST_HEAD(list);
1260
1261         if (!force) {
1262                 if (list_empty_careful(&ctx->cq_overflow_list))
1263                         return true;
1264                 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1265                     rings->cq_ring_entries))
1266                         return false;
1267         }
1268
1269         spin_lock_irqsave(&ctx->completion_lock, flags);
1270
1271         /* if force is set, the ring is going away. always drop after that */
1272         if (force)
1273                 ctx->cq_overflow_flushed = 1;
1274
1275         cqe = NULL;
1276         while (!list_empty(&ctx->cq_overflow_list)) {
1277                 cqe = io_get_cqring(ctx);
1278                 if (!cqe && !force)
1279                         break;
1280
1281                 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1282                                                 list);
1283                 list_move(&req->list, &list);
1284                 req->flags &= ~REQ_F_OVERFLOW;
1285                 if (cqe) {
1286                         WRITE_ONCE(cqe->user_data, req->user_data);
1287                         WRITE_ONCE(cqe->res, req->result);
1288                         WRITE_ONCE(cqe->flags, req->cflags);
1289                 } else {
1290                         WRITE_ONCE(ctx->rings->cq_overflow,
1291                                 atomic_inc_return(&ctx->cached_cq_overflow));
1292                 }
1293         }
1294
1295         io_commit_cqring(ctx);
1296         if (cqe) {
1297                 clear_bit(0, &ctx->sq_check_overflow);
1298                 clear_bit(0, &ctx->cq_check_overflow);
1299         }
1300         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1301         io_cqring_ev_posted(ctx);
1302
1303         while (!list_empty(&list)) {
1304                 req = list_first_entry(&list, struct io_kiocb, list);
1305                 list_del(&req->list);
1306                 io_put_req(req);
1307         }
1308
1309         return cqe != NULL;
1310 }
1311
1312 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1313 {
1314         struct io_ring_ctx *ctx = req->ctx;
1315         struct io_uring_cqe *cqe;
1316
1317         trace_io_uring_complete(ctx, req->user_data, res);
1318
1319         /*
1320          * If we can't get a cq entry, userspace overflowed the
1321          * submission (by quite a lot). Increment the overflow count in
1322          * the ring.
1323          */
1324         cqe = io_get_cqring(ctx);
1325         if (likely(cqe)) {
1326                 WRITE_ONCE(cqe->user_data, req->user_data);
1327                 WRITE_ONCE(cqe->res, res);
1328                 WRITE_ONCE(cqe->flags, cflags);
1329         } else if (ctx->cq_overflow_flushed) {
1330                 WRITE_ONCE(ctx->rings->cq_overflow,
1331                                 atomic_inc_return(&ctx->cached_cq_overflow));
1332         } else {
1333                 if (list_empty(&ctx->cq_overflow_list)) {
1334                         set_bit(0, &ctx->sq_check_overflow);
1335                         set_bit(0, &ctx->cq_check_overflow);
1336                 }
1337                 req->flags |= REQ_F_OVERFLOW;
1338                 refcount_inc(&req->refs);
1339                 req->result = res;
1340                 req->cflags = cflags;
1341                 list_add_tail(&req->list, &ctx->cq_overflow_list);
1342         }
1343 }
1344
1345 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1346 {
1347         __io_cqring_fill_event(req, res, 0);
1348 }
1349
1350 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1351 {
1352         struct io_ring_ctx *ctx = req->ctx;
1353         unsigned long flags;
1354
1355         spin_lock_irqsave(&ctx->completion_lock, flags);
1356         __io_cqring_fill_event(req, res, cflags);
1357         io_commit_cqring(ctx);
1358         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1359
1360         io_cqring_ev_posted(ctx);
1361 }
1362
1363 static void io_submit_flush_completions(struct io_comp_state *cs)
1364 {
1365         struct io_ring_ctx *ctx = cs->ctx;
1366
1367         spin_lock_irq(&ctx->completion_lock);
1368         while (!list_empty(&cs->list)) {
1369                 struct io_kiocb *req;
1370
1371                 req = list_first_entry(&cs->list, struct io_kiocb, list);
1372                 list_del(&req->list);
1373                 io_cqring_fill_event(req, req->result);
1374                 if (!(req->flags & REQ_F_LINK_HEAD)) {
1375                         req->flags |= REQ_F_COMP_LOCKED;
1376                         io_put_req(req);
1377                 } else {
1378                         spin_unlock_irq(&ctx->completion_lock);
1379                         io_put_req(req);
1380                         spin_lock_irq(&ctx->completion_lock);
1381                 }
1382         }
1383         io_commit_cqring(ctx);
1384         spin_unlock_irq(&ctx->completion_lock);
1385
1386         io_cqring_ev_posted(ctx);
1387         cs->nr = 0;
1388 }
1389
1390 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1391                               struct io_comp_state *cs)
1392 {
1393         if (!cs) {
1394                 io_cqring_add_event(req, res, cflags);
1395                 io_put_req(req);
1396         } else {
1397                 req->result = res;
1398                 list_add_tail(&req->list, &cs->list);
1399                 if (++cs->nr >= 32)
1400                         io_submit_flush_completions(cs);
1401         }
1402 }
1403
1404 static void io_req_complete(struct io_kiocb *req, long res)
1405 {
1406         __io_req_complete(req, res, 0, NULL);
1407 }
1408
1409 static inline bool io_is_fallback_req(struct io_kiocb *req)
1410 {
1411         return req == (struct io_kiocb *)
1412                         ((unsigned long) req->ctx->fallback_req & ~1UL);
1413 }
1414
1415 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1416 {
1417         struct io_kiocb *req;
1418
1419         req = ctx->fallback_req;
1420         if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1421                 return req;
1422
1423         return NULL;
1424 }
1425
1426 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1427                                      struct io_submit_state *state)
1428 {
1429         gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1430         struct io_kiocb *req;
1431
1432         if (!state->free_reqs) {
1433                 size_t sz;
1434                 int ret;
1435
1436                 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1437                 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1438
1439                 /*
1440                  * Bulk alloc is all-or-nothing. If we fail to get a batch,
1441                  * retry single alloc to be on the safe side.
1442                  */
1443                 if (unlikely(ret <= 0)) {
1444                         state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1445                         if (!state->reqs[0])
1446                                 goto fallback;
1447                         ret = 1;
1448                 }
1449                 state->free_reqs = ret - 1;
1450                 req = state->reqs[ret - 1];
1451         } else {
1452                 state->free_reqs--;
1453                 req = state->reqs[state->free_reqs];
1454         }
1455
1456         return req;
1457 fallback:
1458         return io_get_fallback_req(ctx);
1459 }
1460
1461 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1462                           bool fixed)
1463 {
1464         if (fixed)
1465                 percpu_ref_put(req->fixed_file_refs);
1466         else
1467                 fput(file);
1468 }
1469
1470 static void __io_req_aux_free(struct io_kiocb *req)
1471 {
1472         if (req->flags & REQ_F_NEED_CLEANUP)
1473                 io_cleanup_req(req);
1474
1475         kfree(req->io);
1476         if (req->file)
1477                 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1478         __io_put_req_task(req);
1479         io_req_work_drop_env(req);
1480 }
1481
1482 static void __io_free_req(struct io_kiocb *req)
1483 {
1484         __io_req_aux_free(req);
1485
1486         if (req->flags & REQ_F_INFLIGHT) {
1487                 struct io_ring_ctx *ctx = req->ctx;
1488                 unsigned long flags;
1489
1490                 spin_lock_irqsave(&ctx->inflight_lock, flags);
1491                 list_del(&req->inflight_entry);
1492                 if (waitqueue_active(&ctx->inflight_wait))
1493                         wake_up(&ctx->inflight_wait);
1494                 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1495         }
1496
1497         percpu_ref_put(&req->ctx->refs);
1498         if (likely(!io_is_fallback_req(req)))
1499                 kmem_cache_free(req_cachep, req);
1500         else
1501                 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1502 }
1503
1504 struct req_batch {
1505         void *reqs[IO_IOPOLL_BATCH];
1506         int to_free;
1507         int need_iter;
1508 };
1509
1510 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1511 {
1512         if (!rb->to_free)
1513                 return;
1514         if (rb->need_iter) {
1515                 int i, inflight = 0;
1516                 unsigned long flags;
1517
1518                 for (i = 0; i < rb->to_free; i++) {
1519                         struct io_kiocb *req = rb->reqs[i];
1520
1521                         if (req->flags & REQ_F_INFLIGHT)
1522                                 inflight++;
1523                         __io_req_aux_free(req);
1524                 }
1525                 if (!inflight)
1526                         goto do_free;
1527
1528                 spin_lock_irqsave(&ctx->inflight_lock, flags);
1529                 for (i = 0; i < rb->to_free; i++) {
1530                         struct io_kiocb *req = rb->reqs[i];
1531
1532                         if (req->flags & REQ_F_INFLIGHT) {
1533                                 list_del(&req->inflight_entry);
1534                                 if (!--inflight)
1535                                         break;
1536                         }
1537                 }
1538                 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1539
1540                 if (waitqueue_active(&ctx->inflight_wait))
1541                         wake_up(&ctx->inflight_wait);
1542         }
1543 do_free:
1544         kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1545         percpu_ref_put_many(&ctx->refs, rb->to_free);
1546         rb->to_free = rb->need_iter = 0;
1547 }
1548
1549 static bool io_link_cancel_timeout(struct io_kiocb *req)
1550 {
1551         struct io_ring_ctx *ctx = req->ctx;
1552         int ret;
1553
1554         ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1555         if (ret != -1) {
1556                 io_cqring_fill_event(req, -ECANCELED);
1557                 io_commit_cqring(ctx);
1558                 req->flags &= ~REQ_F_LINK_HEAD;
1559                 io_put_req(req);
1560                 return true;
1561         }
1562
1563         return false;
1564 }
1565
1566 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1567 {
1568         struct io_ring_ctx *ctx = req->ctx;
1569         bool wake_ev = false;
1570
1571         /* Already got next link */
1572         if (req->flags & REQ_F_LINK_NEXT)
1573                 return;
1574
1575         /*
1576          * The list should never be empty when we are called here. But could
1577          * potentially happen if the chain is messed up, check to be on the
1578          * safe side.
1579          */
1580         while (!list_empty(&req->link_list)) {
1581                 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1582                                                 struct io_kiocb, link_list);
1583
1584                 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1585                              (nxt->flags & REQ_F_TIMEOUT))) {
1586                         list_del_init(&nxt->link_list);
1587                         wake_ev |= io_link_cancel_timeout(nxt);
1588                         req->flags &= ~REQ_F_LINK_TIMEOUT;
1589                         continue;
1590                 }
1591
1592                 list_del_init(&req->link_list);
1593                 if (!list_empty(&nxt->link_list))
1594                         nxt->flags |= REQ_F_LINK_HEAD;
1595                 *nxtptr = nxt;
1596                 break;
1597         }
1598
1599         req->flags |= REQ_F_LINK_NEXT;
1600         if (wake_ev)
1601                 io_cqring_ev_posted(ctx);
1602 }
1603
1604 /*
1605  * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1606  */
1607 static void io_fail_links(struct io_kiocb *req)
1608 {
1609         struct io_ring_ctx *ctx = req->ctx;
1610         unsigned long flags;
1611
1612         spin_lock_irqsave(&ctx->completion_lock, flags);
1613
1614         while (!list_empty(&req->link_list)) {
1615                 struct io_kiocb *link = list_first_entry(&req->link_list,
1616                                                 struct io_kiocb, link_list);
1617
1618                 list_del_init(&link->link_list);
1619                 trace_io_uring_fail_link(req, link);
1620
1621                 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1622                     link->opcode == IORING_OP_LINK_TIMEOUT) {
1623                         io_link_cancel_timeout(link);
1624                 } else {
1625                         io_cqring_fill_event(link, -ECANCELED);
1626                         __io_double_put_req(link);
1627                 }
1628                 req->flags &= ~REQ_F_LINK_TIMEOUT;
1629         }
1630
1631         io_commit_cqring(ctx);
1632         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1633         io_cqring_ev_posted(ctx);
1634 }
1635
1636 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1637 {
1638         if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1639                 return;
1640
1641         /*
1642          * If LINK is set, we have dependent requests in this chain. If we
1643          * didn't fail this request, queue the first one up, moving any other
1644          * dependencies to the next request. In case of failure, fail the rest
1645          * of the chain.
1646          */
1647         if (req->flags & REQ_F_FAIL_LINK) {
1648                 io_fail_links(req);
1649         } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1650                         REQ_F_LINK_TIMEOUT) {
1651                 struct io_ring_ctx *ctx = req->ctx;
1652                 unsigned long flags;
1653
1654                 /*
1655                  * If this is a timeout link, we could be racing with the
1656                  * timeout timer. Grab the completion lock for this case to
1657                  * protect against that.
1658                  */
1659                 spin_lock_irqsave(&ctx->completion_lock, flags);
1660                 io_req_link_next(req, nxt);
1661                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1662         } else {
1663                 io_req_link_next(req, nxt);
1664         }
1665 }
1666
1667 static void io_free_req(struct io_kiocb *req)
1668 {
1669         struct io_kiocb *nxt = NULL;
1670
1671         io_req_find_next(req, &nxt);
1672         __io_free_req(req);
1673
1674         if (nxt)
1675                 io_queue_async_work(nxt);
1676 }
1677
1678 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
1679 {
1680         struct io_kiocb *link;
1681         const struct io_op_def *def = &io_op_defs[nxt->opcode];
1682
1683         if ((nxt->flags & REQ_F_ISREG) && def->hash_reg_file)
1684                 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1685
1686         *workptr = &nxt->work;
1687         link = io_prep_linked_timeout(nxt);
1688         if (link)
1689                 nxt->flags |= REQ_F_QUEUE_TIMEOUT;
1690 }
1691
1692 /*
1693  * Drop reference to request, return next in chain (if there is one) if this
1694  * was the last reference to this request.
1695  */
1696 __attribute__((nonnull))
1697 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1698 {
1699         if (refcount_dec_and_test(&req->refs)) {
1700                 io_req_find_next(req, nxtptr);
1701                 __io_free_req(req);
1702         }
1703 }
1704
1705 static void io_put_req(struct io_kiocb *req)
1706 {
1707         if (refcount_dec_and_test(&req->refs))
1708                 io_free_req(req);
1709 }
1710
1711 static void io_steal_work(struct io_kiocb *req,
1712                           struct io_wq_work **workptr)
1713 {
1714         /*
1715          * It's in an io-wq worker, so there always should be at least
1716          * one reference, which will be dropped in io_put_work() just
1717          * after the current handler returns.
1718          *
1719          * It also means, that if the counter dropped to 1, then there is
1720          * no asynchronous users left, so it's safe to steal the next work.
1721          */
1722         if (refcount_read(&req->refs) == 1) {
1723                 struct io_kiocb *nxt = NULL;
1724
1725                 io_req_find_next(req, &nxt);
1726                 if (nxt)
1727                         io_wq_assign_next(workptr, nxt);
1728         }
1729 }
1730
1731 /*
1732  * Must only be used if we don't need to care about links, usually from
1733  * within the completion handling itself.
1734  */
1735 static void __io_double_put_req(struct io_kiocb *req)
1736 {
1737         /* drop both submit and complete references */
1738         if (refcount_sub_and_test(2, &req->refs))
1739                 __io_free_req(req);
1740 }
1741
1742 static void io_double_put_req(struct io_kiocb *req)
1743 {
1744         /* drop both submit and complete references */
1745         if (refcount_sub_and_test(2, &req->refs))
1746                 io_free_req(req);
1747 }
1748
1749 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1750 {
1751         struct io_rings *rings = ctx->rings;
1752
1753         if (test_bit(0, &ctx->cq_check_overflow)) {
1754                 /*
1755                  * noflush == true is from the waitqueue handler, just ensure
1756                  * we wake up the task, and the next invocation will flush the
1757                  * entries. We cannot safely to it from here.
1758                  */
1759                 if (noflush && !list_empty(&ctx->cq_overflow_list))
1760                         return -1U;
1761
1762                 io_cqring_overflow_flush(ctx, false);
1763         }
1764
1765         /* See comment at the top of this file */
1766         smp_rmb();
1767         return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1768 }
1769
1770 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1771 {
1772         struct io_rings *rings = ctx->rings;
1773
1774         /* make sure SQ entry isn't read before tail */
1775         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1776 }
1777
1778 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1779 {
1780         if ((req->flags & REQ_F_LINK_HEAD) || io_is_fallback_req(req))
1781                 return false;
1782
1783         if (req->file || req->io)
1784                 rb->need_iter++;
1785
1786         rb->reqs[rb->to_free++] = req;
1787         if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1788                 io_free_req_many(req->ctx, rb);
1789         return true;
1790 }
1791
1792 static int io_put_kbuf(struct io_kiocb *req)
1793 {
1794         struct io_buffer *kbuf;
1795         int cflags;
1796
1797         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1798         cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1799         cflags |= IORING_CQE_F_BUFFER;
1800         req->rw.addr = 0;
1801         kfree(kbuf);
1802         return cflags;
1803 }
1804
1805 static void io_iopoll_queue(struct list_head *again)
1806 {
1807         struct io_kiocb *req;
1808
1809         do {
1810                 req = list_first_entry(again, struct io_kiocb, list);
1811                 list_del(&req->list);
1812                 refcount_inc(&req->refs);
1813                 io_queue_async_work(req);
1814         } while (!list_empty(again));
1815 }
1816
1817 /*
1818  * Find and free completed poll iocbs
1819  */
1820 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1821                                struct list_head *done)
1822 {
1823         struct req_batch rb;
1824         struct io_kiocb *req;
1825         LIST_HEAD(again);
1826
1827         /* order with ->result store in io_complete_rw_iopoll() */
1828         smp_rmb();
1829
1830         rb.to_free = rb.need_iter = 0;
1831         while (!list_empty(done)) {
1832                 int cflags = 0;
1833
1834                 req = list_first_entry(done, struct io_kiocb, list);
1835                 if (READ_ONCE(req->result) == -EAGAIN) {
1836                         req->iopoll_completed = 0;
1837                         list_move_tail(&req->list, &again);
1838                         continue;
1839                 }
1840                 list_del(&req->list);
1841
1842                 if (req->flags & REQ_F_BUFFER_SELECTED)
1843                         cflags = io_put_kbuf(req);
1844
1845                 __io_cqring_fill_event(req, req->result, cflags);
1846                 (*nr_events)++;
1847
1848                 if (refcount_dec_and_test(&req->refs) &&
1849                     !io_req_multi_free(&rb, req))
1850                         io_free_req(req);
1851         }
1852
1853         io_commit_cqring(ctx);
1854         if (ctx->flags & IORING_SETUP_SQPOLL)
1855                 io_cqring_ev_posted(ctx);
1856         io_free_req_many(ctx, &rb);
1857
1858         if (!list_empty(&again))
1859                 io_iopoll_queue(&again);
1860 }
1861
1862 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1863                         long min)
1864 {
1865         struct io_kiocb *req, *tmp;
1866         LIST_HEAD(done);
1867         bool spin;
1868         int ret;
1869
1870         /*
1871          * Only spin for completions if we don't have multiple devices hanging
1872          * off our complete list, and we're under the requested amount.
1873          */
1874         spin = !ctx->poll_multi_file && *nr_events < min;
1875
1876         ret = 0;
1877         list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1878                 struct kiocb *kiocb = &req->rw.kiocb;
1879
1880                 /*
1881                  * Move completed and retryable entries to our local lists.
1882                  * If we find a request that requires polling, break out
1883                  * and complete those lists first, if we have entries there.
1884                  */
1885                 if (READ_ONCE(req->iopoll_completed)) {
1886                         list_move_tail(&req->list, &done);
1887                         continue;
1888                 }
1889                 if (!list_empty(&done))
1890                         break;
1891
1892                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1893                 if (ret < 0)
1894                         break;
1895
1896                 if (ret && spin)
1897                         spin = false;
1898                 ret = 0;
1899         }
1900
1901         if (!list_empty(&done))
1902                 io_iopoll_complete(ctx, nr_events, &done);
1903
1904         return ret;
1905 }
1906
1907 /*
1908  * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1909  * non-spinning poll check - we'll still enter the driver poll loop, but only
1910  * as a non-spinning completion check.
1911  */
1912 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1913                                 long min)
1914 {
1915         while (!list_empty(&ctx->poll_list) && !need_resched()) {
1916                 int ret;
1917
1918                 ret = io_do_iopoll(ctx, nr_events, min);
1919                 if (ret < 0)
1920                         return ret;
1921                 if (!min || *nr_events >= min)
1922                         return 0;
1923         }
1924
1925         return 1;
1926 }
1927
1928 /*
1929  * We can't just wait for polled events to come to us, we have to actively
1930  * find and complete them.
1931  */
1932 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1933 {
1934         if (!(ctx->flags & IORING_SETUP_IOPOLL))
1935                 return;
1936
1937         mutex_lock(&ctx->uring_lock);
1938         while (!list_empty(&ctx->poll_list)) {
1939                 unsigned int nr_events = 0;
1940
1941                 io_iopoll_getevents(ctx, &nr_events, 1);
1942
1943                 /*
1944                  * Ensure we allow local-to-the-cpu processing to take place,
1945                  * in this case we need to ensure that we reap all events.
1946                  */
1947                 cond_resched();
1948         }
1949         mutex_unlock(&ctx->uring_lock);
1950 }
1951
1952 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1953                            long min)
1954 {
1955         int iters = 0, ret = 0;
1956
1957         /*
1958          * We disallow the app entering submit/complete with polling, but we
1959          * still need to lock the ring to prevent racing with polled issue
1960          * that got punted to a workqueue.
1961          */
1962         mutex_lock(&ctx->uring_lock);
1963         do {
1964                 int tmin = 0;
1965
1966                 /*
1967                  * Don't enter poll loop if we already have events pending.
1968                  * If we do, we can potentially be spinning for commands that
1969                  * already triggered a CQE (eg in error).
1970                  */
1971                 if (io_cqring_events(ctx, false))
1972                         break;
1973
1974                 /*
1975                  * If a submit got punted to a workqueue, we can have the
1976                  * application entering polling for a command before it gets
1977                  * issued. That app will hold the uring_lock for the duration
1978                  * of the poll right here, so we need to take a breather every
1979                  * now and then to ensure that the issue has a chance to add
1980                  * the poll to the issued list. Otherwise we can spin here
1981                  * forever, while the workqueue is stuck trying to acquire the
1982                  * very same mutex.
1983                  */
1984                 if (!(++iters & 7)) {
1985                         mutex_unlock(&ctx->uring_lock);
1986                         mutex_lock(&ctx->uring_lock);
1987                 }
1988
1989                 if (*nr_events < min)
1990                         tmin = min - *nr_events;
1991
1992                 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1993                 if (ret <= 0)
1994                         break;
1995                 ret = 0;
1996         } while (min && !*nr_events && !need_resched());
1997
1998         mutex_unlock(&ctx->uring_lock);
1999         return ret;
2000 }
2001
2002 static void kiocb_end_write(struct io_kiocb *req)
2003 {
2004         /*
2005          * Tell lockdep we inherited freeze protection from submission
2006          * thread.
2007          */
2008         if (req->flags & REQ_F_ISREG) {
2009                 struct inode *inode = file_inode(req->file);
2010
2011                 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2012         }
2013         file_end_write(req->file);
2014 }
2015
2016 static inline void req_set_fail_links(struct io_kiocb *req)
2017 {
2018         if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
2019                 req->flags |= REQ_F_FAIL_LINK;
2020 }
2021
2022 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2023                                   struct io_comp_state *cs)
2024 {
2025         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2026         int cflags = 0;
2027
2028         if (kiocb->ki_flags & IOCB_WRITE)
2029                 kiocb_end_write(req);
2030
2031         if (res != req->result)
2032                 req_set_fail_links(req);
2033         if (req->flags & REQ_F_BUFFER_SELECTED)
2034                 cflags = io_put_kbuf(req);
2035         __io_req_complete(req, res, cflags, cs);
2036 }
2037
2038 static void io_sq_thread_drop_mm(struct io_ring_ctx *ctx)
2039 {
2040         struct mm_struct *mm = current->mm;
2041
2042         if (mm) {
2043                 kthread_unuse_mm(mm);
2044                 mmput(mm);
2045         }
2046 }
2047
2048 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
2049 {
2050         if (!current->mm) {
2051                 if (unlikely(!mmget_not_zero(ctx->sqo_mm)))
2052                         return -EFAULT;
2053                 kthread_use_mm(ctx->sqo_mm);
2054         }
2055
2056         return 0;
2057 }
2058
2059 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
2060                                    struct io_kiocb *req)
2061 {
2062         if (!io_op_defs[req->opcode].needs_mm)
2063                 return 0;
2064         return __io_sq_thread_acquire_mm(ctx);
2065 }
2066
2067 #ifdef CONFIG_BLOCK
2068 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2069 {
2070         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2071         ssize_t ret = -ECANCELED;
2072         struct iov_iter iter;
2073         int rw;
2074
2075         if (error) {
2076                 ret = error;
2077                 goto end_req;
2078         }
2079
2080         switch (req->opcode) {
2081         case IORING_OP_READV:
2082         case IORING_OP_READ_FIXED:
2083         case IORING_OP_READ:
2084                 rw = READ;
2085                 break;
2086         case IORING_OP_WRITEV:
2087         case IORING_OP_WRITE_FIXED:
2088         case IORING_OP_WRITE:
2089                 rw = WRITE;
2090                 break;
2091         default:
2092                 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2093                                 req->opcode);
2094                 goto end_req;
2095         }
2096
2097         ret = io_import_iovec(rw, req, &iovec, &iter, false);
2098         if (ret < 0)
2099                 goto end_req;
2100         ret = io_setup_async_rw(req, ret, iovec, inline_vecs, &iter);
2101         if (!ret)
2102                 return true;
2103         kfree(iovec);
2104 end_req:
2105         req_set_fail_links(req);
2106         io_req_complete(req, ret);
2107         return false;
2108 }
2109
2110 static void io_rw_resubmit(struct callback_head *cb)
2111 {
2112         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2113         struct io_ring_ctx *ctx = req->ctx;
2114         int err;
2115
2116         __set_current_state(TASK_RUNNING);
2117
2118         err = io_sq_thread_acquire_mm(ctx, req);
2119
2120         if (io_resubmit_prep(req, err)) {
2121                 refcount_inc(&req->refs);
2122                 io_queue_async_work(req);
2123         }
2124 }
2125 #endif
2126
2127 static bool io_rw_reissue(struct io_kiocb *req, long res)
2128 {
2129 #ifdef CONFIG_BLOCK
2130         struct task_struct *tsk;
2131         int ret;
2132
2133         if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2134                 return false;
2135
2136         tsk = req->task;
2137         init_task_work(&req->task_work, io_rw_resubmit);
2138         ret = task_work_add(tsk, &req->task_work, true);
2139         if (!ret)
2140                 return true;
2141 #endif
2142         return false;
2143 }
2144
2145 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2146                              struct io_comp_state *cs)
2147 {
2148         if (!io_rw_reissue(req, res))
2149                 io_complete_rw_common(&req->rw.kiocb, res, cs);
2150 }
2151
2152 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2153 {
2154         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2155
2156         __io_complete_rw(req, res, res2, NULL);
2157 }
2158
2159 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2160 {
2161         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2162
2163         if (kiocb->ki_flags & IOCB_WRITE)
2164                 kiocb_end_write(req);
2165
2166         if (res != -EAGAIN && res != req->result)
2167                 req_set_fail_links(req);
2168
2169         WRITE_ONCE(req->result, res);
2170         /* order with io_poll_complete() checking ->result */
2171         if (res != -EAGAIN) {
2172                 smp_wmb();
2173                 WRITE_ONCE(req->iopoll_completed, 1);
2174         }
2175 }
2176
2177 /*
2178  * After the iocb has been issued, it's safe to be found on the poll list.
2179  * Adding the kiocb to the list AFTER submission ensures that we don't
2180  * find it from a io_iopoll_getevents() thread before the issuer is done
2181  * accessing the kiocb cookie.
2182  */
2183 static void io_iopoll_req_issued(struct io_kiocb *req)
2184 {
2185         struct io_ring_ctx *ctx = req->ctx;
2186
2187         /*
2188          * Track whether we have multiple files in our lists. This will impact
2189          * how we do polling eventually, not spinning if we're on potentially
2190          * different devices.
2191          */
2192         if (list_empty(&ctx->poll_list)) {
2193                 ctx->poll_multi_file = false;
2194         } else if (!ctx->poll_multi_file) {
2195                 struct io_kiocb *list_req;
2196
2197                 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
2198                                                 list);
2199                 if (list_req->file != req->file)
2200                         ctx->poll_multi_file = true;
2201         }
2202
2203         /*
2204          * For fast devices, IO may have already completed. If it has, add
2205          * it to the front so we find it first.
2206          */
2207         if (READ_ONCE(req->iopoll_completed))
2208                 list_add(&req->list, &ctx->poll_list);
2209         else
2210                 list_add_tail(&req->list, &ctx->poll_list);
2211
2212         if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2213             wq_has_sleeper(&ctx->sqo_wait))
2214                 wake_up(&ctx->sqo_wait);
2215 }
2216
2217 static void __io_state_file_put(struct io_submit_state *state)
2218 {
2219         int diff = state->has_refs - state->used_refs;
2220
2221         if (diff)
2222                 fput_many(state->file, diff);
2223         state->file = NULL;
2224 }
2225
2226 static inline void io_state_file_put(struct io_submit_state *state)
2227 {
2228         if (state->file)
2229                 __io_state_file_put(state);
2230 }
2231
2232 /*
2233  * Get as many references to a file as we have IOs left in this submission,
2234  * assuming most submissions are for one file, or at least that each file
2235  * has more than one submission.
2236  */
2237 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2238 {
2239         if (!state)
2240                 return fget(fd);
2241
2242         if (state->file) {
2243                 if (state->fd == fd) {
2244                         state->used_refs++;
2245                         state->ios_left--;
2246                         return state->file;
2247                 }
2248                 __io_state_file_put(state);
2249         }
2250         state->file = fget_many(fd, state->ios_left);
2251         if (!state->file)
2252                 return NULL;
2253
2254         state->fd = fd;
2255         state->has_refs = state->ios_left;
2256         state->used_refs = 1;
2257         state->ios_left--;
2258         return state->file;
2259 }
2260
2261 static bool io_bdev_nowait(struct block_device *bdev)
2262 {
2263 #ifdef CONFIG_BLOCK
2264         return !bdev || queue_is_mq(bdev_get_queue(bdev));
2265 #else
2266         return true;
2267 #endif
2268 }
2269
2270 /*
2271  * If we tracked the file through the SCM inflight mechanism, we could support
2272  * any file. For now, just ensure that anything potentially problematic is done
2273  * inline.
2274  */
2275 static bool io_file_supports_async(struct file *file, int rw)
2276 {
2277         umode_t mode = file_inode(file)->i_mode;
2278
2279         if (S_ISBLK(mode)) {
2280                 if (io_bdev_nowait(file->f_inode->i_bdev))
2281                         return true;
2282                 return false;
2283         }
2284         if (S_ISCHR(mode) || S_ISSOCK(mode))
2285                 return true;
2286         if (S_ISREG(mode)) {
2287                 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2288                     file->f_op != &io_uring_fops)
2289                         return true;
2290                 return false;
2291         }
2292
2293         /* any ->read/write should understand O_NONBLOCK */
2294         if (file->f_flags & O_NONBLOCK)
2295                 return true;
2296
2297         if (!(file->f_mode & FMODE_NOWAIT))
2298                 return false;
2299
2300         if (rw == READ)
2301                 return file->f_op->read_iter != NULL;
2302
2303         return file->f_op->write_iter != NULL;
2304 }
2305
2306 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2307                       bool force_nonblock)
2308 {
2309         struct io_ring_ctx *ctx = req->ctx;
2310         struct kiocb *kiocb = &req->rw.kiocb;
2311         unsigned ioprio;
2312         int ret;
2313
2314         if (S_ISREG(file_inode(req->file)->i_mode))
2315                 req->flags |= REQ_F_ISREG;
2316
2317         kiocb->ki_pos = READ_ONCE(sqe->off);
2318         if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2319                 req->flags |= REQ_F_CUR_POS;
2320                 kiocb->ki_pos = req->file->f_pos;
2321         }
2322         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2323         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2324         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2325         if (unlikely(ret))
2326                 return ret;
2327
2328         ioprio = READ_ONCE(sqe->ioprio);
2329         if (ioprio) {
2330                 ret = ioprio_check_cap(ioprio);
2331                 if (ret)
2332                         return ret;
2333
2334                 kiocb->ki_ioprio = ioprio;
2335         } else
2336                 kiocb->ki_ioprio = get_current_ioprio();
2337
2338         /* don't allow async punt if RWF_NOWAIT was requested */
2339         if (kiocb->ki_flags & IOCB_NOWAIT)
2340                 req->flags |= REQ_F_NOWAIT;
2341
2342         if (kiocb->ki_flags & IOCB_DIRECT)
2343                 io_get_req_task(req);
2344
2345         if (force_nonblock)
2346                 kiocb->ki_flags |= IOCB_NOWAIT;
2347
2348         if (ctx->flags & IORING_SETUP_IOPOLL) {
2349                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2350                     !kiocb->ki_filp->f_op->iopoll)
2351                         return -EOPNOTSUPP;
2352
2353                 kiocb->ki_flags |= IOCB_HIPRI;
2354                 kiocb->ki_complete = io_complete_rw_iopoll;
2355                 req->result = 0;
2356                 req->iopoll_completed = 0;
2357         } else {
2358                 if (kiocb->ki_flags & IOCB_HIPRI)
2359                         return -EINVAL;
2360                 kiocb->ki_complete = io_complete_rw;
2361         }
2362
2363         req->rw.addr = READ_ONCE(sqe->addr);
2364         req->rw.len = READ_ONCE(sqe->len);
2365         req->buf_index = READ_ONCE(sqe->buf_index);
2366         return 0;
2367 }
2368
2369 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2370 {
2371         switch (ret) {
2372         case -EIOCBQUEUED:
2373                 break;
2374         case -ERESTARTSYS:
2375         case -ERESTARTNOINTR:
2376         case -ERESTARTNOHAND:
2377         case -ERESTART_RESTARTBLOCK:
2378                 /*
2379                  * We can't just restart the syscall, since previously
2380                  * submitted sqes may already be in progress. Just fail this
2381                  * IO with EINTR.
2382                  */
2383                 ret = -EINTR;
2384                 /* fall through */
2385         default:
2386                 kiocb->ki_complete(kiocb, ret, 0);
2387         }
2388 }
2389
2390 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2391                        struct io_comp_state *cs)
2392 {
2393         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2394
2395         if (req->flags & REQ_F_CUR_POS)
2396                 req->file->f_pos = kiocb->ki_pos;
2397         if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2398                 __io_complete_rw(req, ret, 0, cs);
2399         else
2400                 io_rw_done(kiocb, ret);
2401 }
2402
2403 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2404                                struct iov_iter *iter)
2405 {
2406         struct io_ring_ctx *ctx = req->ctx;
2407         size_t len = req->rw.len;
2408         struct io_mapped_ubuf *imu;
2409         u16 index, buf_index;
2410         size_t offset;
2411         u64 buf_addr;
2412
2413         /* attempt to use fixed buffers without having provided iovecs */
2414         if (unlikely(!ctx->user_bufs))
2415                 return -EFAULT;
2416
2417         buf_index = req->buf_index;
2418         if (unlikely(buf_index >= ctx->nr_user_bufs))
2419                 return -EFAULT;
2420
2421         index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2422         imu = &ctx->user_bufs[index];
2423         buf_addr = req->rw.addr;
2424
2425         /* overflow */
2426         if (buf_addr + len < buf_addr)
2427                 return -EFAULT;
2428         /* not inside the mapped region */
2429         if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2430                 return -EFAULT;
2431
2432         /*
2433          * May not be a start of buffer, set size appropriately
2434          * and advance us to the beginning.
2435          */
2436         offset = buf_addr - imu->ubuf;
2437         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2438
2439         if (offset) {
2440                 /*
2441                  * Don't use iov_iter_advance() here, as it's really slow for
2442                  * using the latter parts of a big fixed buffer - it iterates
2443                  * over each segment manually. We can cheat a bit here, because
2444                  * we know that:
2445                  *
2446                  * 1) it's a BVEC iter, we set it up
2447                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2448                  *    first and last bvec
2449                  *
2450                  * So just find our index, and adjust the iterator afterwards.
2451                  * If the offset is within the first bvec (or the whole first
2452                  * bvec, just use iov_iter_advance(). This makes it easier
2453                  * since we can just skip the first segment, which may not
2454                  * be PAGE_SIZE aligned.
2455                  */
2456                 const struct bio_vec *bvec = imu->bvec;
2457
2458                 if (offset <= bvec->bv_len) {
2459                         iov_iter_advance(iter, offset);
2460                 } else {
2461                         unsigned long seg_skip;
2462
2463                         /* skip first vec */
2464                         offset -= bvec->bv_len;
2465                         seg_skip = 1 + (offset >> PAGE_SHIFT);
2466
2467                         iter->bvec = bvec + seg_skip;
2468                         iter->nr_segs -= seg_skip;
2469                         iter->count -= bvec->bv_len + offset;
2470                         iter->iov_offset = offset & ~PAGE_MASK;
2471                 }
2472         }
2473
2474         return len;
2475 }
2476
2477 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2478 {
2479         if (needs_lock)
2480                 mutex_unlock(&ctx->uring_lock);
2481 }
2482
2483 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2484 {
2485         /*
2486          * "Normal" inline submissions always hold the uring_lock, since we
2487          * grab it from the system call. Same is true for the SQPOLL offload.
2488          * The only exception is when we've detached the request and issue it
2489          * from an async worker thread, grab the lock for that case.
2490          */
2491         if (needs_lock)
2492                 mutex_lock(&ctx->uring_lock);
2493 }
2494
2495 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2496                                           int bgid, struct io_buffer *kbuf,
2497                                           bool needs_lock)
2498 {
2499         struct io_buffer *head;
2500
2501         if (req->flags & REQ_F_BUFFER_SELECTED)
2502                 return kbuf;
2503
2504         io_ring_submit_lock(req->ctx, needs_lock);
2505
2506         lockdep_assert_held(&req->ctx->uring_lock);
2507
2508         head = idr_find(&req->ctx->io_buffer_idr, bgid);
2509         if (head) {
2510                 if (!list_empty(&head->list)) {
2511                         kbuf = list_last_entry(&head->list, struct io_buffer,
2512                                                         list);
2513                         list_del(&kbuf->list);
2514                 } else {
2515                         kbuf = head;
2516                         idr_remove(&req->ctx->io_buffer_idr, bgid);
2517                 }
2518                 if (*len > kbuf->len)
2519                         *len = kbuf->len;
2520         } else {
2521                 kbuf = ERR_PTR(-ENOBUFS);
2522         }
2523
2524         io_ring_submit_unlock(req->ctx, needs_lock);
2525
2526         return kbuf;
2527 }
2528
2529 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2530                                         bool needs_lock)
2531 {
2532         struct io_buffer *kbuf;
2533         u16 bgid;
2534
2535         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2536         bgid = req->buf_index;
2537         kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2538         if (IS_ERR(kbuf))
2539                 return kbuf;
2540         req->rw.addr = (u64) (unsigned long) kbuf;
2541         req->flags |= REQ_F_BUFFER_SELECTED;
2542         return u64_to_user_ptr(kbuf->addr);
2543 }
2544
2545 #ifdef CONFIG_COMPAT
2546 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2547                                 bool needs_lock)
2548 {
2549         struct compat_iovec __user *uiov;
2550         compat_ssize_t clen;
2551         void __user *buf;
2552         ssize_t len;
2553
2554         uiov = u64_to_user_ptr(req->rw.addr);
2555         if (!access_ok(uiov, sizeof(*uiov)))
2556                 return -EFAULT;
2557         if (__get_user(clen, &uiov->iov_len))
2558                 return -EFAULT;
2559         if (clen < 0)
2560                 return -EINVAL;
2561
2562         len = clen;
2563         buf = io_rw_buffer_select(req, &len, needs_lock);
2564         if (IS_ERR(buf))
2565                 return PTR_ERR(buf);
2566         iov[0].iov_base = buf;
2567         iov[0].iov_len = (compat_size_t) len;
2568         return 0;
2569 }
2570 #endif
2571
2572 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2573                                       bool needs_lock)
2574 {
2575         struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2576         void __user *buf;
2577         ssize_t len;
2578
2579         if (copy_from_user(iov, uiov, sizeof(*uiov)))
2580                 return -EFAULT;
2581
2582         len = iov[0].iov_len;
2583         if (len < 0)
2584                 return -EINVAL;
2585         buf = io_rw_buffer_select(req, &len, needs_lock);
2586         if (IS_ERR(buf))
2587                 return PTR_ERR(buf);
2588         iov[0].iov_base = buf;
2589         iov[0].iov_len = len;
2590         return 0;
2591 }
2592
2593 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2594                                     bool needs_lock)
2595 {
2596         if (req->flags & REQ_F_BUFFER_SELECTED) {
2597                 struct io_buffer *kbuf;
2598
2599                 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2600                 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2601                 iov[0].iov_len = kbuf->len;
2602                 return 0;
2603         }
2604         if (!req->rw.len)
2605                 return 0;
2606         else if (req->rw.len > 1)
2607                 return -EINVAL;
2608
2609 #ifdef CONFIG_COMPAT
2610         if (req->ctx->compat)
2611                 return io_compat_import(req, iov, needs_lock);
2612 #endif
2613
2614         return __io_iov_buffer_select(req, iov, needs_lock);
2615 }
2616
2617 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2618                                struct iovec **iovec, struct iov_iter *iter,
2619                                bool needs_lock)
2620 {
2621         void __user *buf = u64_to_user_ptr(req->rw.addr);
2622         size_t sqe_len = req->rw.len;
2623         ssize_t ret;
2624         u8 opcode;
2625
2626         opcode = req->opcode;
2627         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2628                 *iovec = NULL;
2629                 return io_import_fixed(req, rw, iter);
2630         }
2631
2632         /* buffer index only valid with fixed read/write, or buffer select  */
2633         if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2634                 return -EINVAL;
2635
2636         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2637                 if (req->flags & REQ_F_BUFFER_SELECT) {
2638                         buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2639                         if (IS_ERR(buf)) {
2640                                 *iovec = NULL;
2641                                 return PTR_ERR(buf);
2642                         }
2643                         req->rw.len = sqe_len;
2644                 }
2645
2646                 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2647                 *iovec = NULL;
2648                 return ret < 0 ? ret : sqe_len;
2649         }
2650
2651         if (req->io) {
2652                 struct io_async_rw *iorw = &req->io->rw;
2653
2654                 *iovec = iorw->iov;
2655                 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2656                 if (iorw->iov == iorw->fast_iov)
2657                         *iovec = NULL;
2658                 return iorw->size;
2659         }
2660
2661         if (req->flags & REQ_F_BUFFER_SELECT) {
2662                 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2663                 if (!ret) {
2664                         ret = (*iovec)->iov_len;
2665                         iov_iter_init(iter, rw, *iovec, 1, ret);
2666                 }
2667                 *iovec = NULL;
2668                 return ret;
2669         }
2670
2671 #ifdef CONFIG_COMPAT
2672         if (req->ctx->compat)
2673                 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2674                                                 iovec, iter);
2675 #endif
2676
2677         return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2678 }
2679
2680 /*
2681  * For files that don't have ->read_iter() and ->write_iter(), handle them
2682  * by looping over ->read() or ->write() manually.
2683  */
2684 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2685                            struct iov_iter *iter)
2686 {
2687         ssize_t ret = 0;
2688
2689         /*
2690          * Don't support polled IO through this interface, and we can't
2691          * support non-blocking either. For the latter, this just causes
2692          * the kiocb to be handled from an async context.
2693          */
2694         if (kiocb->ki_flags & IOCB_HIPRI)
2695                 return -EOPNOTSUPP;
2696         if (kiocb->ki_flags & IOCB_NOWAIT)
2697                 return -EAGAIN;
2698
2699         while (iov_iter_count(iter)) {
2700                 struct iovec iovec;
2701                 ssize_t nr;
2702
2703                 if (!iov_iter_is_bvec(iter)) {
2704                         iovec = iov_iter_iovec(iter);
2705                 } else {
2706                         /* fixed buffers import bvec */
2707                         iovec.iov_base = kmap(iter->bvec->bv_page)
2708                                                 + iter->iov_offset;
2709                         iovec.iov_len = min(iter->count,
2710                                         iter->bvec->bv_len - iter->iov_offset);
2711                 }
2712
2713                 if (rw == READ) {
2714                         nr = file->f_op->read(file, iovec.iov_base,
2715                                               iovec.iov_len, &kiocb->ki_pos);
2716                 } else {
2717                         nr = file->f_op->write(file, iovec.iov_base,
2718                                                iovec.iov_len, &kiocb->ki_pos);
2719                 }
2720
2721                 if (iov_iter_is_bvec(iter))
2722                         kunmap(iter->bvec->bv_page);
2723
2724                 if (nr < 0) {
2725                         if (!ret)
2726                                 ret = nr;
2727                         break;
2728                 }
2729                 ret += nr;
2730                 if (nr != iovec.iov_len)
2731                         break;
2732                 iov_iter_advance(iter, nr);
2733         }
2734
2735         return ret;
2736 }
2737
2738 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2739                           struct iovec *iovec, struct iovec *fast_iov,
2740                           struct iov_iter *iter)
2741 {
2742         req->io->rw.nr_segs = iter->nr_segs;
2743         req->io->rw.size = io_size;
2744         req->io->rw.iov = iovec;
2745         if (!req->io->rw.iov) {
2746                 req->io->rw.iov = req->io->rw.fast_iov;
2747                 if (req->io->rw.iov != fast_iov)
2748                         memcpy(req->io->rw.iov, fast_iov,
2749                                sizeof(struct iovec) * iter->nr_segs);
2750         } else {
2751                 req->flags |= REQ_F_NEED_CLEANUP;
2752         }
2753 }
2754
2755 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2756 {
2757         req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2758         return req->io == NULL;
2759 }
2760
2761 static int io_alloc_async_ctx(struct io_kiocb *req)
2762 {
2763         if (!io_op_defs[req->opcode].async_ctx)
2764                 return 0;
2765
2766         return  __io_alloc_async_ctx(req);
2767 }
2768
2769 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2770                              struct iovec *iovec, struct iovec *fast_iov,
2771                              struct iov_iter *iter)
2772 {
2773         if (!io_op_defs[req->opcode].async_ctx)
2774                 return 0;
2775         if (!req->io) {
2776                 if (__io_alloc_async_ctx(req))
2777                         return -ENOMEM;
2778
2779                 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2780         }
2781         return 0;
2782 }
2783
2784 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2785                         bool force_nonblock)
2786 {
2787         struct io_async_ctx *io;
2788         struct iov_iter iter;
2789         ssize_t ret;
2790
2791         ret = io_prep_rw(req, sqe, force_nonblock);
2792         if (ret)
2793                 return ret;
2794
2795         if (unlikely(!(req->file->f_mode & FMODE_READ)))
2796                 return -EBADF;
2797
2798         /* either don't need iovec imported or already have it */
2799         if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2800                 return 0;
2801
2802         io = req->io;
2803         io->rw.iov = io->rw.fast_iov;
2804         req->io = NULL;
2805         ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2806         req->io = io;
2807         if (ret < 0)
2808                 return ret;
2809
2810         io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2811         return 0;
2812 }
2813
2814 static void __io_async_buf_error(struct io_kiocb *req, int error)
2815 {
2816         struct io_ring_ctx *ctx = req->ctx;
2817
2818         spin_lock_irq(&ctx->completion_lock);
2819         io_cqring_fill_event(req, error);
2820         io_commit_cqring(ctx);
2821         spin_unlock_irq(&ctx->completion_lock);
2822
2823         io_cqring_ev_posted(ctx);
2824         req_set_fail_links(req);
2825         io_double_put_req(req);
2826 }
2827
2828 static void io_async_buf_cancel(struct callback_head *cb)
2829 {
2830         struct io_async_rw *rw;
2831         struct io_kiocb *req;
2832
2833         rw = container_of(cb, struct io_async_rw, task_work);
2834         req = rw->wpq.wait.private;
2835         __io_async_buf_error(req, -ECANCELED);
2836 }
2837
2838 static void io_async_buf_retry(struct callback_head *cb)
2839 {
2840         struct io_async_rw *rw;
2841         struct io_ring_ctx *ctx;
2842         struct io_kiocb *req;
2843
2844         rw = container_of(cb, struct io_async_rw, task_work);
2845         req = rw->wpq.wait.private;
2846         ctx = req->ctx;
2847
2848         __set_current_state(TASK_RUNNING);
2849         if (!__io_sq_thread_acquire_mm(ctx)) {
2850                 mutex_lock(&ctx->uring_lock);
2851                 __io_queue_sqe(req, NULL, NULL);
2852                 mutex_unlock(&ctx->uring_lock);
2853         } else {
2854                 __io_async_buf_error(req, -EFAULT);
2855         }
2856 }
2857
2858 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2859                              int sync, void *arg)
2860 {
2861         struct wait_page_queue *wpq;
2862         struct io_kiocb *req = wait->private;
2863         struct io_async_rw *rw = &req->io->rw;
2864         struct wait_page_key *key = arg;
2865         struct task_struct *tsk;
2866         int ret;
2867
2868         wpq = container_of(wait, struct wait_page_queue, wait);
2869
2870         ret = wake_page_match(wpq, key);
2871         if (ret != 1)
2872                 return ret;
2873
2874         list_del_init(&wait->entry);
2875
2876         init_task_work(&rw->task_work, io_async_buf_retry);
2877         /* submit ref gets dropped, acquire a new one */
2878         refcount_inc(&req->refs);
2879         tsk = req->task;
2880         ret = task_work_add(tsk, &rw->task_work, true);
2881         if (unlikely(ret)) {
2882                 /* queue just for cancelation */
2883                 init_task_work(&rw->task_work, io_async_buf_cancel);
2884                 tsk = io_wq_get_task(req->ctx->io_wq);
2885                 task_work_add(tsk, &rw->task_work, true);
2886         }
2887         wake_up_process(tsk);
2888         return 1;
2889 }
2890
2891 static bool io_rw_should_retry(struct io_kiocb *req)
2892 {
2893         struct kiocb *kiocb = &req->rw.kiocb;
2894         int ret;
2895
2896         /* never retry for NOWAIT, we just complete with -EAGAIN */
2897         if (req->flags & REQ_F_NOWAIT)
2898                 return false;
2899
2900         /* already tried, or we're doing O_DIRECT */
2901         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_WAITQ))
2902                 return false;
2903         /*
2904          * just use poll if we can, and don't attempt if the fs doesn't
2905          * support callback based unlocks
2906          */
2907         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2908                 return false;
2909
2910         /*
2911          * If request type doesn't require req->io to defer in general,
2912          * we need to allocate it here
2913          */
2914         if (!req->io && __io_alloc_async_ctx(req))
2915                 return false;
2916
2917         ret = kiocb_wait_page_queue_init(kiocb, &req->io->rw.wpq,
2918                                                 io_async_buf_func, req);
2919         if (!ret) {
2920                 io_get_req_task(req);
2921                 return true;
2922         }
2923
2924         return false;
2925 }
2926
2927 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
2928 {
2929         if (req->file->f_op->read_iter)
2930                 return call_read_iter(req->file, &req->rw.kiocb, iter);
2931         return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
2932 }
2933
2934 static int io_read(struct io_kiocb *req, bool force_nonblock,
2935                    struct io_comp_state *cs)
2936 {
2937         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2938         struct kiocb *kiocb = &req->rw.kiocb;
2939         struct iov_iter iter;
2940         size_t iov_count;
2941         ssize_t io_size, ret;
2942
2943         ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2944         if (ret < 0)
2945                 return ret;
2946
2947         /* Ensure we clear previously set non-block flag */
2948         if (!force_nonblock)
2949                 kiocb->ki_flags &= ~IOCB_NOWAIT;
2950
2951         req->result = 0;
2952         io_size = ret;
2953         if (req->flags & REQ_F_LINK_HEAD)
2954                 req->result = io_size;
2955
2956         /* If the file doesn't support async, just async punt */
2957         if (force_nonblock && !io_file_supports_async(req->file, READ))
2958                 goto copy_iov;
2959
2960         iov_count = iov_iter_count(&iter);
2961         ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2962         if (!ret) {
2963                 unsigned long nr_segs = iter.nr_segs;
2964                 ssize_t ret2 = 0;
2965
2966                 ret2 = io_iter_do_read(req, &iter);
2967
2968                 /* Catch -EAGAIN return for forced non-blocking submission */
2969                 if (!force_nonblock || (ret2 != -EAGAIN && ret2 != -EIO)) {
2970                         kiocb_done(kiocb, ret2, cs);
2971                 } else {
2972                         iter.count = iov_count;
2973                         iter.nr_segs = nr_segs;
2974 copy_iov:
2975                         ret = io_setup_async_rw(req, io_size, iovec,
2976                                                 inline_vecs, &iter);
2977                         if (ret)
2978                                 goto out_free;
2979                         /* if we can retry, do so with the callbacks armed */
2980                         if (io_rw_should_retry(req)) {
2981                                 ret2 = io_iter_do_read(req, &iter);
2982                                 if (ret2 == -EIOCBQUEUED) {
2983                                         goto out_free;
2984                                 } else if (ret2 != -EAGAIN) {
2985                                         kiocb_done(kiocb, ret2, cs);
2986                                         goto out_free;
2987                                 }
2988                         }
2989                         kiocb->ki_flags &= ~IOCB_WAITQ;
2990                         return -EAGAIN;
2991                 }
2992         }
2993 out_free:
2994         if (!(req->flags & REQ_F_NEED_CLEANUP))
2995                 kfree(iovec);
2996         return ret;
2997 }
2998
2999 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
3000                          bool force_nonblock)
3001 {
3002         struct io_async_ctx *io;
3003         struct iov_iter iter;
3004         ssize_t ret;
3005
3006         ret = io_prep_rw(req, sqe, force_nonblock);
3007         if (ret)
3008                 return ret;
3009
3010         if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3011                 return -EBADF;
3012
3013         req->fsize = rlimit(RLIMIT_FSIZE);
3014
3015         /* either don't need iovec imported or already have it */
3016         if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3017                 return 0;
3018
3019         io = req->io;
3020         io->rw.iov = io->rw.fast_iov;
3021         req->io = NULL;
3022         ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
3023         req->io = io;
3024         if (ret < 0)
3025                 return ret;
3026
3027         io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
3028         return 0;
3029 }
3030
3031 static int io_write(struct io_kiocb *req, bool force_nonblock,
3032                     struct io_comp_state *cs)
3033 {
3034         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3035         struct kiocb *kiocb = &req->rw.kiocb;
3036         struct iov_iter iter;
3037         size_t iov_count;
3038         ssize_t ret, io_size;
3039
3040         ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
3041         if (ret < 0)
3042                 return ret;
3043
3044         /* Ensure we clear previously set non-block flag */
3045         if (!force_nonblock)
3046                 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
3047
3048         req->result = 0;
3049         io_size = ret;
3050         if (req->flags & REQ_F_LINK_HEAD)
3051                 req->result = io_size;
3052
3053         /* If the file doesn't support async, just async punt */
3054         if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3055                 goto copy_iov;
3056
3057         /* file path doesn't support NOWAIT for non-direct_IO */
3058         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3059             (req->flags & REQ_F_ISREG))
3060                 goto copy_iov;
3061
3062         iov_count = iov_iter_count(&iter);
3063         ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
3064         if (!ret) {
3065                 unsigned long nr_segs = iter.nr_segs;
3066                 ssize_t ret2;
3067
3068                 /*
3069                  * Open-code file_start_write here to grab freeze protection,
3070                  * which will be released by another thread in
3071                  * io_complete_rw().  Fool lockdep by telling it the lock got
3072                  * released so that it doesn't complain about the held lock when
3073                  * we return to userspace.
3074                  */
3075                 if (req->flags & REQ_F_ISREG) {
3076                         __sb_start_write(file_inode(req->file)->i_sb,
3077                                                 SB_FREEZE_WRITE, true);
3078                         __sb_writers_release(file_inode(req->file)->i_sb,
3079                                                 SB_FREEZE_WRITE);
3080                 }
3081                 kiocb->ki_flags |= IOCB_WRITE;
3082
3083                 if (!force_nonblock)
3084                         current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3085
3086                 if (req->file->f_op->write_iter)
3087                         ret2 = call_write_iter(req->file, kiocb, &iter);
3088                 else
3089                         ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
3090
3091                 if (!force_nonblock)
3092                         current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3093
3094                 /*
3095                  * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3096                  * retry them without IOCB_NOWAIT.
3097                  */
3098                 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3099                         ret2 = -EAGAIN;
3100                 if (!force_nonblock || ret2 != -EAGAIN) {
3101                         kiocb_done(kiocb, ret2, cs);
3102                 } else {
3103                         iter.count = iov_count;
3104                         iter.nr_segs = nr_segs;
3105 copy_iov:
3106                         ret = io_setup_async_rw(req, io_size, iovec,
3107                                                 inline_vecs, &iter);
3108                         if (ret)
3109                                 goto out_free;
3110                         return -EAGAIN;
3111                 }
3112         }
3113 out_free:
3114         if (!(req->flags & REQ_F_NEED_CLEANUP))
3115                 kfree(iovec);
3116         return ret;
3117 }
3118
3119 static int __io_splice_prep(struct io_kiocb *req,
3120                             const struct io_uring_sqe *sqe)
3121 {
3122         struct io_splice* sp = &req->splice;
3123         unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3124         int ret;
3125
3126         if (req->flags & REQ_F_NEED_CLEANUP)
3127                 return 0;
3128         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3129                 return -EINVAL;
3130
3131         sp->file_in = NULL;
3132         sp->len = READ_ONCE(sqe->len);
3133         sp->flags = READ_ONCE(sqe->splice_flags);
3134
3135         if (unlikely(sp->flags & ~valid_flags))
3136                 return -EINVAL;
3137
3138         ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3139                           (sp->flags & SPLICE_F_FD_IN_FIXED));
3140         if (ret)
3141                 return ret;
3142         req->flags |= REQ_F_NEED_CLEANUP;
3143
3144         if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3145                 /*
3146                  * Splice operation will be punted aync, and here need to
3147                  * modify io_wq_work.flags, so initialize io_wq_work firstly.
3148                  */
3149                 io_req_init_async(req);
3150                 req->work.flags |= IO_WQ_WORK_UNBOUND;
3151         }
3152
3153         return 0;
3154 }
3155
3156 static int io_tee_prep(struct io_kiocb *req,
3157                        const struct io_uring_sqe *sqe)
3158 {
3159         if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3160                 return -EINVAL;
3161         return __io_splice_prep(req, sqe);
3162 }
3163
3164 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3165 {
3166         struct io_splice *sp = &req->splice;
3167         struct file *in = sp->file_in;
3168         struct file *out = sp->file_out;
3169         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3170         long ret = 0;
3171
3172         if (force_nonblock)
3173                 return -EAGAIN;
3174         if (sp->len)
3175                 ret = do_tee(in, out, sp->len, flags);
3176
3177         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3178         req->flags &= ~REQ_F_NEED_CLEANUP;
3179
3180         if (ret != sp->len)
3181                 req_set_fail_links(req);
3182         io_req_complete(req, ret);
3183         return 0;
3184 }
3185
3186 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3187 {
3188         struct io_splice* sp = &req->splice;
3189
3190         sp->off_in = READ_ONCE(sqe->splice_off_in);
3191         sp->off_out = READ_ONCE(sqe->off);
3192         return __io_splice_prep(req, sqe);
3193 }
3194
3195 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3196 {
3197         struct io_splice *sp = &req->splice;
3198         struct file *in = sp->file_in;
3199         struct file *out = sp->file_out;
3200         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3201         loff_t *poff_in, *poff_out;
3202         long ret = 0;
3203
3204         if (force_nonblock)
3205                 return -EAGAIN;
3206
3207         poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3208         poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3209
3210         if (sp->len)
3211                 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3212
3213         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3214         req->flags &= ~REQ_F_NEED_CLEANUP;
3215
3216         if (ret != sp->len)
3217                 req_set_fail_links(req);
3218         io_req_complete(req, ret);
3219         return 0;
3220 }
3221
3222 /*
3223  * IORING_OP_NOP just posts a completion event, nothing else.
3224  */
3225 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3226 {
3227         struct io_ring_ctx *ctx = req->ctx;
3228
3229         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3230                 return -EINVAL;
3231
3232         __io_req_complete(req, 0, 0, cs);
3233         return 0;
3234 }
3235
3236 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3237 {
3238         struct io_ring_ctx *ctx = req->ctx;
3239
3240         if (!req->file)
3241                 return -EBADF;
3242
3243         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3244                 return -EINVAL;
3245         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3246                 return -EINVAL;
3247
3248         req->sync.flags = READ_ONCE(sqe->fsync_flags);
3249         if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3250                 return -EINVAL;
3251
3252         req->sync.off = READ_ONCE(sqe->off);
3253         req->sync.len = READ_ONCE(sqe->len);
3254         return 0;
3255 }
3256
3257 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3258 {
3259         loff_t end = req->sync.off + req->sync.len;
3260         int ret;
3261
3262         /* fsync always requires a blocking context */
3263         if (force_nonblock)
3264                 return -EAGAIN;
3265
3266         ret = vfs_fsync_range(req->file, req->sync.off,
3267                                 end > 0 ? end : LLONG_MAX,
3268                                 req->sync.flags & IORING_FSYNC_DATASYNC);
3269         if (ret < 0)
3270                 req_set_fail_links(req);
3271         io_req_complete(req, ret);
3272         return 0;
3273 }
3274
3275 static int io_fallocate_prep(struct io_kiocb *req,
3276                              const struct io_uring_sqe *sqe)
3277 {
3278         if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3279                 return -EINVAL;
3280         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3281                 return -EINVAL;
3282
3283         req->sync.off = READ_ONCE(sqe->off);
3284         req->sync.len = READ_ONCE(sqe->addr);
3285         req->sync.mode = READ_ONCE(sqe->len);
3286         req->fsize = rlimit(RLIMIT_FSIZE);
3287         return 0;
3288 }
3289
3290 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3291 {
3292         int ret;
3293
3294         /* fallocate always requiring blocking context */
3295         if (force_nonblock)
3296                 return -EAGAIN;
3297
3298         current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3299         ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3300                                 req->sync.len);
3301         current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3302         if (ret < 0)
3303                 req_set_fail_links(req);
3304         io_req_complete(req, ret);
3305         return 0;
3306 }
3307
3308 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3309 {
3310         const char __user *fname;
3311         int ret;
3312
3313         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3314                 return -EINVAL;
3315         if (unlikely(sqe->ioprio || sqe->buf_index))
3316                 return -EINVAL;
3317         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3318                 return -EBADF;
3319
3320         /* open.how should be already initialised */
3321         if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3322                 req->open.how.flags |= O_LARGEFILE;
3323
3324         req->open.dfd = READ_ONCE(sqe->fd);
3325         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3326         req->open.filename = getname(fname);
3327         if (IS_ERR(req->open.filename)) {
3328                 ret = PTR_ERR(req->open.filename);
3329                 req->open.filename = NULL;
3330                 return ret;
3331         }
3332         req->open.nofile = rlimit(RLIMIT_NOFILE);
3333         req->flags |= REQ_F_NEED_CLEANUP;
3334         return 0;
3335 }
3336
3337 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3338 {
3339         u64 flags, mode;
3340
3341         if (req->flags & REQ_F_NEED_CLEANUP)
3342                 return 0;
3343         mode = READ_ONCE(sqe->len);
3344         flags = READ_ONCE(sqe->open_flags);
3345         req->open.how = build_open_how(flags, mode);
3346         return __io_openat_prep(req, sqe);
3347 }
3348
3349 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3350 {
3351         struct open_how __user *how;
3352         size_t len;
3353         int ret;
3354
3355         if (req->flags & REQ_F_NEED_CLEANUP)
3356                 return 0;
3357         how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3358         len = READ_ONCE(sqe->len);
3359         if (len < OPEN_HOW_SIZE_VER0)
3360                 return -EINVAL;
3361
3362         ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3363                                         len);
3364         if (ret)
3365                 return ret;
3366
3367         return __io_openat_prep(req, sqe);
3368 }
3369
3370 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3371 {
3372         struct open_flags op;
3373         struct file *file;
3374         int ret;
3375
3376         if (force_nonblock)
3377                 return -EAGAIN;
3378
3379         ret = build_open_flags(&req->open.how, &op);
3380         if (ret)
3381                 goto err;
3382
3383         ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3384         if (ret < 0)
3385                 goto err;
3386
3387         file = do_filp_open(req->open.dfd, req->open.filename, &op);
3388         if (IS_ERR(file)) {
3389                 put_unused_fd(ret);
3390                 ret = PTR_ERR(file);
3391         } else {
3392                 fsnotify_open(file);
3393                 fd_install(ret, file);
3394         }
3395 err:
3396         putname(req->open.filename);
3397         req->flags &= ~REQ_F_NEED_CLEANUP;
3398         if (ret < 0)
3399                 req_set_fail_links(req);
3400         io_req_complete(req, ret);
3401         return 0;
3402 }
3403
3404 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3405 {
3406         return io_openat2(req, force_nonblock);
3407 }
3408
3409 static int io_remove_buffers_prep(struct io_kiocb *req,
3410                                   const struct io_uring_sqe *sqe)
3411 {
3412         struct io_provide_buf *p = &req->pbuf;
3413         u64 tmp;
3414
3415         if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3416                 return -EINVAL;
3417
3418         tmp = READ_ONCE(sqe->fd);
3419         if (!tmp || tmp > USHRT_MAX)
3420                 return -EINVAL;
3421
3422         memset(p, 0, sizeof(*p));
3423         p->nbufs = tmp;
3424         p->bgid = READ_ONCE(sqe->buf_group);
3425         return 0;
3426 }
3427
3428 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3429                                int bgid, unsigned nbufs)
3430 {
3431         unsigned i = 0;
3432
3433         /* shouldn't happen */
3434         if (!nbufs)
3435                 return 0;
3436
3437         /* the head kbuf is the list itself */
3438         while (!list_empty(&buf->list)) {
3439                 struct io_buffer *nxt;
3440
3441                 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3442                 list_del(&nxt->list);
3443                 kfree(nxt);
3444                 if (++i == nbufs)
3445                         return i;
3446         }
3447         i++;
3448         kfree(buf);
3449         idr_remove(&ctx->io_buffer_idr, bgid);
3450
3451         return i;
3452 }
3453
3454 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3455                              struct io_comp_state *cs)
3456 {
3457         struct io_provide_buf *p = &req->pbuf;
3458         struct io_ring_ctx *ctx = req->ctx;
3459         struct io_buffer *head;
3460         int ret = 0;
3461
3462         io_ring_submit_lock(ctx, !force_nonblock);
3463
3464         lockdep_assert_held(&ctx->uring_lock);
3465
3466         ret = -ENOENT;
3467         head = idr_find(&ctx->io_buffer_idr, p->bgid);
3468         if (head)
3469                 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3470
3471         io_ring_submit_lock(ctx, !force_nonblock);
3472         if (ret < 0)
3473                 req_set_fail_links(req);
3474         __io_req_complete(req, ret, 0, cs);
3475         return 0;
3476 }
3477
3478 static int io_provide_buffers_prep(struct io_kiocb *req,
3479                                    const struct io_uring_sqe *sqe)
3480 {
3481         struct io_provide_buf *p = &req->pbuf;
3482         u64 tmp;
3483
3484         if (sqe->ioprio || sqe->rw_flags)
3485                 return -EINVAL;
3486
3487         tmp = READ_ONCE(sqe->fd);
3488         if (!tmp || tmp > USHRT_MAX)
3489                 return -E2BIG;
3490         p->nbufs = tmp;
3491         p->addr = READ_ONCE(sqe->addr);
3492         p->len = READ_ONCE(sqe->len);
3493
3494         if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3495                 return -EFAULT;
3496
3497         p->bgid = READ_ONCE(sqe->buf_group);
3498         tmp = READ_ONCE(sqe->off);
3499         if (tmp > USHRT_MAX)
3500                 return -E2BIG;
3501         p->bid = tmp;
3502         return 0;
3503 }
3504
3505 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3506 {
3507         struct io_buffer *buf;
3508         u64 addr = pbuf->addr;
3509         int i, bid = pbuf->bid;
3510
3511         for (i = 0; i < pbuf->nbufs; i++) {
3512                 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3513                 if (!buf)
3514                         break;
3515
3516                 buf->addr = addr;
3517                 buf->len = pbuf->len;
3518                 buf->bid = bid;
3519                 addr += pbuf->len;
3520                 bid++;
3521                 if (!*head) {
3522                         INIT_LIST_HEAD(&buf->list);
3523                         *head = buf;
3524                 } else {
3525                         list_add_tail(&buf->list, &(*head)->list);
3526                 }
3527         }
3528
3529         return i ? i : -ENOMEM;
3530 }
3531
3532 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3533                               struct io_comp_state *cs)
3534 {
3535         struct io_provide_buf *p = &req->pbuf;
3536         struct io_ring_ctx *ctx = req->ctx;
3537         struct io_buffer *head, *list;
3538         int ret = 0;
3539
3540         io_ring_submit_lock(ctx, !force_nonblock);
3541
3542         lockdep_assert_held(&ctx->uring_lock);
3543
3544         list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3545
3546         ret = io_add_buffers(p, &head);
3547         if (ret < 0)
3548                 goto out;
3549
3550         if (!list) {
3551                 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3552                                         GFP_KERNEL);
3553                 if (ret < 0) {
3554                         __io_remove_buffers(ctx, head, p->bgid, -1U);
3555                         goto out;
3556                 }
3557         }
3558 out:
3559         io_ring_submit_unlock(ctx, !force_nonblock);
3560         if (ret < 0)
3561                 req_set_fail_links(req);
3562         __io_req_complete(req, ret, 0, cs);
3563         return 0;
3564 }
3565
3566 static int io_epoll_ctl_prep(struct io_kiocb *req,
3567                              const struct io_uring_sqe *sqe)
3568 {
3569 #if defined(CONFIG_EPOLL)
3570         if (sqe->ioprio || sqe->buf_index)
3571                 return -EINVAL;
3572         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3573                 return -EINVAL;
3574
3575         req->epoll.epfd = READ_ONCE(sqe->fd);
3576         req->epoll.op = READ_ONCE(sqe->len);
3577         req->epoll.fd = READ_ONCE(sqe->off);
3578
3579         if (ep_op_has_event(req->epoll.op)) {
3580                 struct epoll_event __user *ev;
3581
3582                 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3583                 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3584                         return -EFAULT;
3585         }
3586
3587         return 0;
3588 #else
3589         return -EOPNOTSUPP;
3590 #endif
3591 }
3592
3593 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3594                         struct io_comp_state *cs)
3595 {
3596 #if defined(CONFIG_EPOLL)
3597         struct io_epoll *ie = &req->epoll;
3598         int ret;
3599
3600         ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3601         if (force_nonblock && ret == -EAGAIN)
3602                 return -EAGAIN;
3603
3604         if (ret < 0)
3605                 req_set_fail_links(req);
3606         __io_req_complete(req, ret, 0, cs);
3607         return 0;
3608 #else
3609         return -EOPNOTSUPP;
3610 #endif
3611 }
3612
3613 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3614 {
3615 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3616         if (sqe->ioprio || sqe->buf_index || sqe->off)
3617                 return -EINVAL;
3618         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3619                 return -EINVAL;
3620
3621         req->madvise.addr = READ_ONCE(sqe->addr);
3622         req->madvise.len = READ_ONCE(sqe->len);
3623         req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3624         return 0;
3625 #else
3626         return -EOPNOTSUPP;
3627 #endif
3628 }
3629
3630 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3631 {
3632 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3633         struct io_madvise *ma = &req->madvise;
3634         int ret;
3635
3636         if (force_nonblock)
3637                 return -EAGAIN;
3638
3639         ret = do_madvise(ma->addr, ma->len, ma->advice);
3640         if (ret < 0)
3641                 req_set_fail_links(req);
3642         io_req_complete(req, ret);
3643         return 0;
3644 #else
3645         return -EOPNOTSUPP;
3646 #endif
3647 }
3648
3649 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3650 {
3651         if (sqe->ioprio || sqe->buf_index || sqe->addr)
3652                 return -EINVAL;
3653         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3654                 return -EINVAL;
3655
3656         req->fadvise.offset = READ_ONCE(sqe->off);
3657         req->fadvise.len = READ_ONCE(sqe->len);
3658         req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3659         return 0;
3660 }
3661
3662 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3663 {
3664         struct io_fadvise *fa = &req->fadvise;
3665         int ret;
3666
3667         if (force_nonblock) {
3668                 switch (fa->advice) {
3669                 case POSIX_FADV_NORMAL:
3670                 case POSIX_FADV_RANDOM:
3671                 case POSIX_FADV_SEQUENTIAL:
3672                         break;
3673                 default:
3674                         return -EAGAIN;
3675                 }
3676         }
3677
3678         ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3679         if (ret < 0)
3680                 req_set_fail_links(req);
3681         io_req_complete(req, ret);
3682         return 0;
3683 }
3684
3685 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3686 {
3687         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3688                 return -EINVAL;
3689         if (sqe->ioprio || sqe->buf_index)
3690                 return -EINVAL;
3691         if (req->flags & REQ_F_FIXED_FILE)
3692                 return -EBADF;
3693
3694         req->statx.dfd = READ_ONCE(sqe->fd);
3695         req->statx.mask = READ_ONCE(sqe->len);
3696         req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3697         req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3698         req->statx.flags = READ_ONCE(sqe->statx_flags);
3699
3700         return 0;
3701 }
3702
3703 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3704 {
3705         struct io_statx *ctx = &req->statx;
3706         int ret;
3707
3708         if (force_nonblock) {
3709                 /* only need file table for an actual valid fd */
3710                 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3711                         req->flags |= REQ_F_NO_FILE_TABLE;
3712                 return -EAGAIN;
3713         }
3714
3715         ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3716                        ctx->buffer);
3717
3718         if (ret < 0)
3719                 req_set_fail_links(req);
3720         io_req_complete(req, ret);
3721         return 0;
3722 }
3723
3724 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3725 {
3726         /*
3727          * If we queue this for async, it must not be cancellable. That would
3728          * leave the 'file' in an undeterminate state, and here need to modify
3729          * io_wq_work.flags, so initialize io_wq_work firstly.
3730          */
3731         io_req_init_async(req);
3732         req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3733
3734         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3735                 return -EINVAL;
3736         if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3737             sqe->rw_flags || sqe->buf_index)
3738                 return -EINVAL;
3739         if (req->flags & REQ_F_FIXED_FILE)
3740                 return -EBADF;
3741
3742         req->close.fd = READ_ONCE(sqe->fd);
3743         if ((req->file && req->file->f_op == &io_uring_fops) ||
3744             req->close.fd == req->ctx->ring_fd)
3745                 return -EBADF;
3746
3747         req->close.put_file = NULL;
3748         return 0;
3749 }
3750
3751 static int io_close(struct io_kiocb *req, bool force_nonblock,
3752                     struct io_comp_state *cs)
3753 {
3754         struct io_close *close = &req->close;
3755         int ret;
3756
3757         /* might be already done during nonblock submission */
3758         if (!close->put_file) {
3759                 ret = __close_fd_get_file(close->fd, &close->put_file);
3760                 if (ret < 0)
3761                         return (ret == -ENOENT) ? -EBADF : ret;
3762         }
3763
3764         /* if the file has a flush method, be safe and punt to async */
3765         if (close->put_file->f_op->flush && force_nonblock) {
3766                 /* was never set, but play safe */
3767                 req->flags &= ~REQ_F_NOWAIT;
3768                 /* avoid grabbing files - we don't need the files */
3769                 req->flags |= REQ_F_NO_FILE_TABLE;
3770                 return -EAGAIN;
3771         }
3772
3773         /* No ->flush() or already async, safely close from here */
3774         ret = filp_close(close->put_file, req->work.files);
3775         if (ret < 0)
3776                 req_set_fail_links(req);
3777         fput(close->put_file);
3778         close->put_file = NULL;
3779         __io_req_complete(req, ret, 0, cs);
3780         return 0;
3781 }
3782
3783 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3784 {
3785         struct io_ring_ctx *ctx = req->ctx;
3786
3787         if (!req->file)
3788                 return -EBADF;
3789
3790         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3791                 return -EINVAL;
3792         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3793                 return -EINVAL;
3794
3795         req->sync.off = READ_ONCE(sqe->off);
3796         req->sync.len = READ_ONCE(sqe->len);
3797         req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3798         return 0;
3799 }
3800
3801 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3802 {
3803         int ret;
3804
3805         /* sync_file_range always requires a blocking context */
3806         if (force_nonblock)
3807                 return -EAGAIN;
3808
3809         ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3810                                 req->sync.flags);
3811         if (ret < 0)
3812                 req_set_fail_links(req);
3813         io_req_complete(req, ret);
3814         return 0;
3815 }
3816
3817 #if defined(CONFIG_NET)
3818 static int io_setup_async_msg(struct io_kiocb *req,
3819                               struct io_async_msghdr *kmsg)
3820 {
3821         if (req->io)
3822                 return -EAGAIN;
3823         if (io_alloc_async_ctx(req)) {
3824                 if (kmsg->iov != kmsg->fast_iov)
3825                         kfree(kmsg->iov);
3826                 return -ENOMEM;
3827         }
3828         req->flags |= REQ_F_NEED_CLEANUP;
3829         memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3830         return -EAGAIN;
3831 }
3832
3833 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3834 {
3835         struct io_sr_msg *sr = &req->sr_msg;
3836         struct io_async_ctx *io = req->io;
3837         int ret;
3838
3839         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3840                 return -EINVAL;
3841
3842         sr->msg_flags = READ_ONCE(sqe->msg_flags);
3843         sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3844         sr->len = READ_ONCE(sqe->len);
3845
3846 #ifdef CONFIG_COMPAT
3847         if (req->ctx->compat)
3848                 sr->msg_flags |= MSG_CMSG_COMPAT;
3849 #endif
3850
3851         if (!io || req->opcode == IORING_OP_SEND)
3852                 return 0;
3853         /* iovec is already imported */
3854         if (req->flags & REQ_F_NEED_CLEANUP)
3855                 return 0;
3856
3857         io->msg.iov = io->msg.fast_iov;
3858         ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3859                                         &io->msg.iov);
3860         if (!ret)
3861                 req->flags |= REQ_F_NEED_CLEANUP;
3862         return ret;
3863 }
3864
3865 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
3866                       struct io_comp_state *cs)
3867 {
3868         struct io_async_msghdr *kmsg = NULL;
3869         struct socket *sock;
3870         int ret;
3871
3872         sock = sock_from_file(req->file, &ret);
3873         if (sock) {
3874                 struct io_async_ctx io;
3875                 unsigned flags;
3876
3877                 if (req->io) {
3878                         kmsg = &req->io->msg;
3879                         kmsg->msg.msg_name = &req->io->msg.addr;
3880                         /* if iov is set, it's allocated already */
3881                         if (!kmsg->iov)
3882                                 kmsg->iov = kmsg->fast_iov;
3883                         kmsg->msg.msg_iter.iov = kmsg->iov;
3884                 } else {
3885                         struct io_sr_msg *sr = &req->sr_msg;
3886
3887                         kmsg = &io.msg;
3888                         kmsg->msg.msg_name = &io.msg.addr;
3889
3890                         io.msg.iov = io.msg.fast_iov;
3891                         ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3892                                         sr->msg_flags, &io.msg.iov);
3893                         if (ret)
3894                                 return ret;
3895                 }
3896
3897                 flags = req->sr_msg.msg_flags;
3898                 if (flags & MSG_DONTWAIT)
3899                         req->flags |= REQ_F_NOWAIT;
3900                 else if (force_nonblock)
3901                         flags |= MSG_DONTWAIT;
3902
3903                 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3904                 if (force_nonblock && ret == -EAGAIN)
3905                         return io_setup_async_msg(req, kmsg);
3906                 if (ret == -ERESTARTSYS)
3907                         ret = -EINTR;
3908         }
3909
3910         if (kmsg && kmsg->iov != kmsg->fast_iov)
3911                 kfree(kmsg->iov);
3912         req->flags &= ~REQ_F_NEED_CLEANUP;
3913         if (ret < 0)
3914                 req_set_fail_links(req);
3915         __io_req_complete(req, ret, 0, cs);
3916         return 0;
3917 }
3918
3919 static int io_send(struct io_kiocb *req, bool force_nonblock,
3920                    struct io_comp_state *cs)
3921 {
3922         struct socket *sock;
3923         int ret;
3924
3925         sock = sock_from_file(req->file, &ret);
3926         if (sock) {
3927                 struct io_sr_msg *sr = &req->sr_msg;
3928                 struct msghdr msg;
3929                 struct iovec iov;
3930                 unsigned flags;
3931
3932                 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3933                                                 &msg.msg_iter);
3934                 if (ret)
3935                         return ret;
3936
3937                 msg.msg_name = NULL;
3938                 msg.msg_control = NULL;
3939                 msg.msg_controllen = 0;
3940                 msg.msg_namelen = 0;
3941
3942                 flags = req->sr_msg.msg_flags;
3943                 if (flags & MSG_DONTWAIT)
3944                         req->flags |= REQ_F_NOWAIT;
3945                 else if (force_nonblock)
3946                         flags |= MSG_DONTWAIT;
3947
3948                 msg.msg_flags = flags;
3949                 ret = sock_sendmsg(sock, &msg);
3950                 if (force_nonblock && ret == -EAGAIN)
3951                         return -EAGAIN;
3952                 if (ret == -ERESTARTSYS)
3953                         ret = -EINTR;
3954         }
3955
3956         if (ret < 0)
3957                 req_set_fail_links(req);
3958         __io_req_complete(req, ret, 0, cs);
3959         return 0;
3960 }
3961
3962 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3963 {
3964         struct io_sr_msg *sr = &req->sr_msg;
3965         struct iovec __user *uiov;
3966         size_t iov_len;
3967         int ret;
3968
3969         ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3970                                         &uiov, &iov_len);
3971         if (ret)
3972                 return ret;
3973
3974         if (req->flags & REQ_F_BUFFER_SELECT) {
3975                 if (iov_len > 1)
3976                         return -EINVAL;
3977                 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3978                         return -EFAULT;
3979                 sr->len = io->msg.iov[0].iov_len;
3980                 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3981                                 sr->len);
3982                 io->msg.iov = NULL;
3983         } else {
3984                 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3985                                         &io->msg.iov, &io->msg.msg.msg_iter);
3986                 if (ret > 0)
3987                         ret = 0;
3988         }
3989
3990         return ret;
3991 }
3992
3993 #ifdef CONFIG_COMPAT
3994 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
3995                                         struct io_async_ctx *io)
3996 {
3997         struct compat_msghdr __user *msg_compat;
3998         struct io_sr_msg *sr = &req->sr_msg;
3999         struct compat_iovec __user *uiov;
4000         compat_uptr_t ptr;
4001         compat_size_t len;
4002         int ret;
4003
4004         msg_compat = (struct compat_msghdr __user *) sr->msg;
4005         ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
4006                                         &ptr, &len);
4007         if (ret)
4008                 return ret;
4009
4010         uiov = compat_ptr(ptr);
4011         if (req->flags & REQ_F_BUFFER_SELECT) {
4012                 compat_ssize_t clen;
4013
4014                 if (len > 1)
4015                         return -EINVAL;
4016                 if (!access_ok(uiov, sizeof(*uiov)))
4017                         return -EFAULT;
4018                 if (__get_user(clen, &uiov->iov_len))
4019                         return -EFAULT;
4020                 if (clen < 0)
4021                         return -EINVAL;
4022                 sr->len = io->msg.iov[0].iov_len;
4023                 io->msg.iov = NULL;
4024         } else {
4025                 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
4026                                                 &io->msg.iov,
4027                                                 &io->msg.msg.msg_iter);
4028                 if (ret < 0)
4029                         return ret;
4030         }
4031
4032         return 0;
4033 }
4034 #endif
4035
4036 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
4037 {
4038         io->msg.iov = io->msg.fast_iov;
4039
4040 #ifdef CONFIG_COMPAT
4041         if (req->ctx->compat)
4042                 return __io_compat_recvmsg_copy_hdr(req, io);
4043 #endif
4044
4045         return __io_recvmsg_copy_hdr(req, io);
4046 }
4047
4048 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4049                                                int *cflags, bool needs_lock)
4050 {
4051         struct io_sr_msg *sr = &req->sr_msg;
4052         struct io_buffer *kbuf;
4053
4054         if (!(req->flags & REQ_F_BUFFER_SELECT))
4055                 return NULL;
4056
4057         kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4058         if (IS_ERR(kbuf))
4059                 return kbuf;
4060
4061         sr->kbuf = kbuf;
4062         req->flags |= REQ_F_BUFFER_SELECTED;
4063
4064         *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
4065         *cflags |= IORING_CQE_F_BUFFER;
4066         return kbuf;
4067 }
4068
4069 static int io_recvmsg_prep(struct io_kiocb *req,
4070                            const struct io_uring_sqe *sqe)
4071 {
4072         struct io_sr_msg *sr = &req->sr_msg;
4073         struct io_async_ctx *io = req->io;
4074         int ret;
4075
4076         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4077                 return -EINVAL;
4078
4079         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4080         sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4081         sr->len = READ_ONCE(sqe->len);
4082         sr->bgid = READ_ONCE(sqe->buf_group);
4083
4084 #ifdef CONFIG_COMPAT
4085         if (req->ctx->compat)
4086                 sr->msg_flags |= MSG_CMSG_COMPAT;
4087 #endif
4088
4089         if (!io || req->opcode == IORING_OP_RECV)
4090                 return 0;
4091         /* iovec is already imported */
4092         if (req->flags & REQ_F_NEED_CLEANUP)
4093                 return 0;
4094
4095         ret = io_recvmsg_copy_hdr(req, io);
4096         if (!ret)
4097                 req->flags |= REQ_F_NEED_CLEANUP;
4098         return ret;
4099 }
4100
4101 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4102                       struct io_comp_state *cs)
4103 {
4104         struct io_async_msghdr *kmsg = NULL;
4105         struct socket *sock;
4106         int ret, cflags = 0;
4107
4108         sock = sock_from_file(req->file, &ret);
4109         if (sock) {
4110                 struct io_buffer *kbuf;
4111                 struct io_async_ctx io;
4112                 unsigned flags;
4113
4114                 if (req->io) {
4115                         kmsg = &req->io->msg;
4116                         kmsg->msg.msg_name = &req->io->msg.addr;
4117                         /* if iov is set, it's allocated already */
4118                         if (!kmsg->iov)
4119                                 kmsg->iov = kmsg->fast_iov;
4120                         kmsg->msg.msg_iter.iov = kmsg->iov;
4121                 } else {
4122                         kmsg = &io.msg;
4123                         kmsg->msg.msg_name = &io.msg.addr;
4124
4125                         ret = io_recvmsg_copy_hdr(req, &io);
4126                         if (ret)
4127                                 return ret;
4128                 }
4129
4130                 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4131                 if (IS_ERR(kbuf)) {
4132                         return PTR_ERR(kbuf);
4133                 } else if (kbuf) {
4134                         kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4135                         iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4136                                         1, req->sr_msg.len);
4137                 }
4138
4139                 flags = req->sr_msg.msg_flags;
4140                 if (flags & MSG_DONTWAIT)
4141                         req->flags |= REQ_F_NOWAIT;
4142                 else if (force_nonblock)
4143                         flags |= MSG_DONTWAIT;
4144
4145                 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
4146                                                 kmsg->uaddr, flags);
4147                 if (force_nonblock && ret == -EAGAIN)
4148                         return io_setup_async_msg(req, kmsg);
4149                 if (ret == -ERESTARTSYS)
4150                         ret = -EINTR;
4151         }
4152
4153         if (kmsg && kmsg->iov != kmsg->fast_iov)
4154                 kfree(kmsg->iov);
4155         req->flags &= ~REQ_F_NEED_CLEANUP;
4156         if (ret < 0)
4157                 req_set_fail_links(req);
4158         __io_req_complete(req, ret, cflags, cs);
4159         return 0;
4160 }
4161
4162 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4163                    struct io_comp_state *cs)
4164 {
4165         struct io_buffer *kbuf = NULL;
4166         struct socket *sock;
4167         int ret, cflags = 0;
4168
4169         sock = sock_from_file(req->file, &ret);
4170         if (sock) {
4171                 struct io_sr_msg *sr = &req->sr_msg;
4172                 void __user *buf = sr->buf;
4173                 struct msghdr msg;
4174                 struct iovec iov;
4175                 unsigned flags;
4176
4177                 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4178                 if (IS_ERR(kbuf))
4179                         return PTR_ERR(kbuf);
4180                 else if (kbuf)
4181                         buf = u64_to_user_ptr(kbuf->addr);
4182
4183                 ret = import_single_range(READ, buf, sr->len, &iov,
4184                                                 &msg.msg_iter);
4185                 if (ret) {
4186                         kfree(kbuf);
4187                         return ret;
4188                 }
4189
4190                 req->flags |= REQ_F_NEED_CLEANUP;
4191                 msg.msg_name = NULL;
4192                 msg.msg_control = NULL;
4193                 msg.msg_controllen = 0;
4194                 msg.msg_namelen = 0;
4195                 msg.msg_iocb = NULL;
4196                 msg.msg_flags = 0;
4197
4198                 flags = req->sr_msg.msg_flags;
4199                 if (flags & MSG_DONTWAIT)
4200                         req->flags |= REQ_F_NOWAIT;
4201                 else if (force_nonblock)
4202                         flags |= MSG_DONTWAIT;
4203
4204                 ret = sock_recvmsg(sock, &msg, flags);
4205                 if (force_nonblock && ret == -EAGAIN)
4206                         return -EAGAIN;
4207                 if (ret == -ERESTARTSYS)
4208                         ret = -EINTR;
4209         }
4210
4211         kfree(kbuf);
4212         req->flags &= ~REQ_F_NEED_CLEANUP;
4213         if (ret < 0)
4214                 req_set_fail_links(req);
4215         __io_req_complete(req, ret, cflags, cs);
4216         return 0;
4217 }
4218
4219 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4220 {
4221         struct io_accept *accept = &req->accept;
4222
4223         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4224                 return -EINVAL;
4225         if (sqe->ioprio || sqe->len || sqe->buf_index)
4226                 return -EINVAL;
4227
4228         accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4229         accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4230         accept->flags = READ_ONCE(sqe->accept_flags);
4231         accept->nofile = rlimit(RLIMIT_NOFILE);
4232         return 0;
4233 }
4234
4235 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4236                      struct io_comp_state *cs)
4237 {
4238         struct io_accept *accept = &req->accept;
4239         unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4240         int ret;
4241
4242         if (req->file->f_flags & O_NONBLOCK)
4243                 req->flags |= REQ_F_NOWAIT;
4244
4245         ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4246                                         accept->addr_len, accept->flags,
4247                                         accept->nofile);
4248         if (ret == -EAGAIN && force_nonblock)
4249                 return -EAGAIN;
4250         if (ret < 0) {
4251                 if (ret == -ERESTARTSYS)
4252                         ret = -EINTR;
4253                 req_set_fail_links(req);
4254         }
4255         __io_req_complete(req, ret, 0, cs);
4256         return 0;
4257 }
4258
4259 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4260 {
4261         struct io_connect *conn = &req->connect;
4262         struct io_async_ctx *io = req->io;
4263
4264         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4265                 return -EINVAL;
4266         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4267                 return -EINVAL;
4268
4269         conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4270         conn->addr_len =  READ_ONCE(sqe->addr2);
4271
4272         if (!io)
4273                 return 0;
4274
4275         return move_addr_to_kernel(conn->addr, conn->addr_len,
4276                                         &io->connect.address);
4277 }
4278
4279 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4280                       struct io_comp_state *cs)
4281 {
4282         struct io_async_ctx __io, *io;
4283         unsigned file_flags;
4284         int ret;
4285
4286         if (req->io) {
4287                 io = req->io;
4288         } else {
4289                 ret = move_addr_to_kernel(req->connect.addr,
4290                                                 req->connect.addr_len,
4291                                                 &__io.connect.address);
4292                 if (ret)
4293                         goto out;
4294                 io = &__io;
4295         }
4296
4297         file_flags = force_nonblock ? O_NONBLOCK : 0;
4298
4299         ret = __sys_connect_file(req->file, &io->connect.address,
4300                                         req->connect.addr_len, file_flags);
4301         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4302                 if (req->io)
4303                         return -EAGAIN;
4304                 if (io_alloc_async_ctx(req)) {
4305                         ret = -ENOMEM;
4306                         goto out;
4307                 }
4308                 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4309                 return -EAGAIN;
4310         }
4311         if (ret == -ERESTARTSYS)
4312                 ret = -EINTR;
4313 out:
4314         if (ret < 0)
4315                 req_set_fail_links(req);
4316         __io_req_complete(req, ret, 0, cs);
4317         return 0;
4318 }
4319 #else /* !CONFIG_NET */
4320 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4321 {
4322         return -EOPNOTSUPP;
4323 }
4324
4325 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
4326 {
4327         return -EOPNOTSUPP;
4328 }
4329
4330 static int io_send(struct io_kiocb *req, bool force_nonblock)
4331 {
4332         return -EOPNOTSUPP;
4333 }
4334
4335 static int io_recvmsg_prep(struct io_kiocb *req,
4336                            const struct io_uring_sqe *sqe)
4337 {
4338         return -EOPNOTSUPP;
4339 }
4340
4341 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
4342 {
4343         return -EOPNOTSUPP;
4344 }
4345
4346 static int io_recv(struct io_kiocb *req, bool force_nonblock)
4347 {
4348         return -EOPNOTSUPP;
4349 }
4350
4351 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4352 {
4353         return -EOPNOTSUPP;
4354 }
4355
4356 static int io_accept(struct io_kiocb *req, bool force_nonblock)
4357 {
4358         return -EOPNOTSUPP;
4359 }
4360
4361 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4362 {
4363         return -EOPNOTSUPP;
4364 }
4365
4366 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4367 {
4368         return -EOPNOTSUPP;
4369 }
4370 #endif /* CONFIG_NET */
4371
4372 struct io_poll_table {
4373         struct poll_table_struct pt;
4374         struct io_kiocb *req;
4375         int error;
4376 };
4377
4378 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4379                            __poll_t mask, task_work_func_t func)
4380 {
4381         struct task_struct *tsk;
4382         int ret;
4383
4384         /* for instances that support it check for an event match first: */
4385         if (mask && !(mask & poll->events))
4386                 return 0;
4387
4388         trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4389
4390         list_del_init(&poll->wait.entry);
4391
4392         tsk = req->task;
4393         req->result = mask;
4394         init_task_work(&req->task_work, func);
4395         /*
4396          * If this fails, then the task is exiting. When a task exits, the
4397          * work gets canceled, so just cancel this request as well instead
4398          * of executing it. We can't safely execute it anyway, as we may not
4399          * have the needed state needed for it anyway.
4400          */
4401         ret = task_work_add(tsk, &req->task_work, true);
4402         if (unlikely(ret)) {
4403                 WRITE_ONCE(poll->canceled, true);
4404                 tsk = io_wq_get_task(req->ctx->io_wq);
4405                 task_work_add(tsk, &req->task_work, true);
4406         }
4407         wake_up_process(tsk);
4408         return 1;
4409 }
4410
4411 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4412         __acquires(&req->ctx->completion_lock)
4413 {
4414         struct io_ring_ctx *ctx = req->ctx;
4415
4416         if (!req->result && !READ_ONCE(poll->canceled)) {
4417                 struct poll_table_struct pt = { ._key = poll->events };
4418
4419                 req->result = vfs_poll(req->file, &pt) & poll->events;
4420         }
4421
4422         spin_lock_irq(&ctx->completion_lock);
4423         if (!req->result && !READ_ONCE(poll->canceled)) {
4424                 add_wait_queue(poll->head, &poll->wait);
4425                 return true;
4426         }
4427
4428         return false;
4429 }
4430
4431 static void io_poll_remove_double(struct io_kiocb *req)
4432 {
4433         struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4434
4435         lockdep_assert_held(&req->ctx->completion_lock);
4436
4437         if (poll && poll->head) {
4438                 struct wait_queue_head *head = poll->head;
4439
4440                 spin_lock(&head->lock);
4441                 list_del_init(&poll->wait.entry);
4442                 if (poll->wait.private)
4443                         refcount_dec(&req->refs);
4444                 poll->head = NULL;
4445                 spin_unlock(&head->lock);
4446         }
4447 }
4448
4449 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4450 {
4451         struct io_ring_ctx *ctx = req->ctx;
4452
4453         io_poll_remove_double(req);
4454         req->poll.done = true;
4455         io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4456         io_commit_cqring(ctx);
4457 }
4458
4459 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4460 {
4461         struct io_ring_ctx *ctx = req->ctx;
4462
4463         if (io_poll_rewait(req, &req->poll)) {
4464                 spin_unlock_irq(&ctx->completion_lock);
4465                 return;
4466         }
4467
4468         hash_del(&req->hash_node);
4469         io_poll_complete(req, req->result, 0);
4470         req->flags |= REQ_F_COMP_LOCKED;
4471         io_put_req_find_next(req, nxt);
4472         spin_unlock_irq(&ctx->completion_lock);
4473
4474         io_cqring_ev_posted(ctx);
4475 }
4476
4477 static void io_poll_task_func(struct callback_head *cb)
4478 {
4479         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4480         struct io_kiocb *nxt = NULL;
4481
4482         io_poll_task_handler(req, &nxt);
4483         if (nxt) {
4484                 struct io_ring_ctx *ctx = nxt->ctx;
4485
4486                 mutex_lock(&ctx->uring_lock);
4487                 __io_queue_sqe(nxt, NULL, NULL);
4488                 mutex_unlock(&ctx->uring_lock);
4489         }
4490 }
4491
4492 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4493                                int sync, void *key)
4494 {
4495         struct io_kiocb *req = wait->private;
4496         struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4497         __poll_t mask = key_to_poll(key);
4498
4499         /* for instances that support it check for an event match first: */
4500         if (mask && !(mask & poll->events))
4501                 return 0;
4502
4503         if (req->poll.head) {
4504                 bool done;
4505
4506                 spin_lock(&req->poll.head->lock);
4507                 done = list_empty(&req->poll.wait.entry);
4508                 if (!done)
4509                         list_del_init(&req->poll.wait.entry);
4510                 spin_unlock(&req->poll.head->lock);
4511                 if (!done)
4512                         __io_async_wake(req, poll, mask, io_poll_task_func);
4513         }
4514         refcount_dec(&req->refs);
4515         return 1;
4516 }
4517
4518 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4519                               wait_queue_func_t wake_func)
4520 {
4521         poll->head = NULL;
4522         poll->done = false;
4523         poll->canceled = false;
4524         poll->events = events;
4525         INIT_LIST_HEAD(&poll->wait.entry);
4526         init_waitqueue_func_entry(&poll->wait, wake_func);
4527 }
4528
4529 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4530                             struct wait_queue_head *head)
4531 {
4532         struct io_kiocb *req = pt->req;
4533
4534         /*
4535          * If poll->head is already set, it's because the file being polled
4536          * uses multiple waitqueues for poll handling (eg one for read, one
4537          * for write). Setup a separate io_poll_iocb if this happens.
4538          */
4539         if (unlikely(poll->head)) {
4540                 /* already have a 2nd entry, fail a third attempt */
4541                 if (req->io) {
4542                         pt->error = -EINVAL;
4543                         return;
4544                 }
4545                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4546                 if (!poll) {
4547                         pt->error = -ENOMEM;
4548                         return;
4549                 }
4550                 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4551                 refcount_inc(&req->refs);
4552                 poll->wait.private = req;
4553                 req->io = (void *) poll;
4554         }
4555
4556         pt->error = 0;
4557         poll->head = head;
4558
4559         if (poll->events & EPOLLEXCLUSIVE)
4560                 add_wait_queue_exclusive(head, &poll->wait);
4561         else
4562                 add_wait_queue(head, &poll->wait);
4563 }
4564
4565 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4566                                struct poll_table_struct *p)
4567 {
4568         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4569
4570         __io_queue_proc(&pt->req->apoll->poll, pt, head);
4571 }
4572
4573 static void io_async_task_func(struct callback_head *cb)
4574 {
4575         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4576         struct async_poll *apoll = req->apoll;
4577         struct io_ring_ctx *ctx = req->ctx;
4578         bool canceled = false;
4579
4580         trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4581
4582         if (io_poll_rewait(req, &apoll->poll)) {
4583                 spin_unlock_irq(&ctx->completion_lock);
4584                 return;
4585         }
4586
4587         /* If req is still hashed, it cannot have been canceled. Don't check. */
4588         if (hash_hashed(&req->hash_node)) {
4589                 hash_del(&req->hash_node);
4590         } else {
4591                 canceled = READ_ONCE(apoll->poll.canceled);
4592                 if (canceled) {
4593                         io_cqring_fill_event(req, -ECANCELED);
4594                         io_commit_cqring(ctx);
4595                 }
4596         }
4597
4598         spin_unlock_irq(&ctx->completion_lock);
4599
4600         /* restore ->work in case we need to retry again */
4601         if (req->flags & REQ_F_WORK_INITIALIZED)
4602                 memcpy(&req->work, &apoll->work, sizeof(req->work));
4603         kfree(apoll);
4604
4605         if (!canceled) {
4606                 __set_current_state(TASK_RUNNING);
4607                 if (io_sq_thread_acquire_mm(ctx, req)) {
4608                         io_cqring_add_event(req, -EFAULT, 0);
4609                         goto end_req;
4610                 }
4611                 mutex_lock(&ctx->uring_lock);
4612                 __io_queue_sqe(req, NULL, NULL);
4613                 mutex_unlock(&ctx->uring_lock);
4614         } else {
4615                 io_cqring_ev_posted(ctx);
4616 end_req:
4617                 req_set_fail_links(req);
4618                 io_double_put_req(req);
4619         }
4620 }
4621
4622 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4623                         void *key)
4624 {
4625         struct io_kiocb *req = wait->private;
4626         struct io_poll_iocb *poll = &req->apoll->poll;
4627
4628         trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4629                                         key_to_poll(key));
4630
4631         return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4632 }
4633
4634 static void io_poll_req_insert(struct io_kiocb *req)
4635 {
4636         struct io_ring_ctx *ctx = req->ctx;
4637         struct hlist_head *list;
4638
4639         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4640         hlist_add_head(&req->hash_node, list);
4641 }
4642
4643 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4644                                       struct io_poll_iocb *poll,
4645                                       struct io_poll_table *ipt, __poll_t mask,
4646                                       wait_queue_func_t wake_func)
4647         __acquires(&ctx->completion_lock)
4648 {
4649         struct io_ring_ctx *ctx = req->ctx;
4650         bool cancel = false;
4651
4652         io_init_poll_iocb(poll, mask, wake_func);
4653         poll->file = req->file;
4654         poll->wait.private = req;
4655
4656         ipt->pt._key = mask;
4657         ipt->req = req;
4658         ipt->error = -EINVAL;
4659
4660         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4661
4662         spin_lock_irq(&ctx->completion_lock);
4663         if (likely(poll->head)) {
4664                 spin_lock(&poll->head->lock);
4665                 if (unlikely(list_empty(&poll->wait.entry))) {
4666                         if (ipt->error)
4667                                 cancel = true;
4668                         ipt->error = 0;
4669                         mask = 0;
4670                 }
4671                 if (mask || ipt->error)
4672                         list_del_init(&poll->wait.entry);
4673                 else if (cancel)
4674                         WRITE_ONCE(poll->canceled, true);
4675                 else if (!poll->done) /* actually waiting for an event */
4676                         io_poll_req_insert(req);
4677                 spin_unlock(&poll->head->lock);
4678         }
4679
4680         return mask;
4681 }
4682
4683 static bool io_arm_poll_handler(struct io_kiocb *req)
4684 {
4685         const struct io_op_def *def = &io_op_defs[req->opcode];
4686         struct io_ring_ctx *ctx = req->ctx;
4687         struct async_poll *apoll;
4688         struct io_poll_table ipt;
4689         __poll_t mask, ret;
4690         bool had_io;
4691
4692         if (!req->file || !file_can_poll(req->file))
4693                 return false;
4694         if (req->flags & REQ_F_POLLED)
4695                 return false;
4696         if (!def->pollin && !def->pollout)
4697                 return false;
4698
4699         apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4700         if (unlikely(!apoll))
4701                 return false;
4702
4703         req->flags |= REQ_F_POLLED;
4704         if (req->flags & REQ_F_WORK_INITIALIZED)
4705                 memcpy(&apoll->work, &req->work, sizeof(req->work));
4706         had_io = req->io != NULL;
4707
4708         io_get_req_task(req);
4709         req->apoll = apoll;
4710         INIT_HLIST_NODE(&req->hash_node);
4711
4712         mask = 0;
4713         if (def->pollin)
4714                 mask |= POLLIN | POLLRDNORM;
4715         if (def->pollout)
4716                 mask |= POLLOUT | POLLWRNORM;
4717         mask |= POLLERR | POLLPRI;
4718
4719         ipt.pt._qproc = io_async_queue_proc;
4720
4721         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4722                                         io_async_wake);
4723         if (ret) {
4724                 ipt.error = 0;
4725                 /* only remove double add if we did it here */
4726                 if (!had_io)
4727                         io_poll_remove_double(req);
4728                 spin_unlock_irq(&ctx->completion_lock);
4729                 if (req->flags & REQ_F_WORK_INITIALIZED)
4730                         memcpy(&req->work, &apoll->work, sizeof(req->work));
4731                 kfree(apoll);
4732                 return false;
4733         }
4734         spin_unlock_irq(&ctx->completion_lock);
4735         trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4736                                         apoll->poll.events);
4737         return true;
4738 }
4739
4740 static bool __io_poll_remove_one(struct io_kiocb *req,
4741                                  struct io_poll_iocb *poll)
4742 {
4743         bool do_complete = false;
4744
4745         spin_lock(&poll->head->lock);
4746         WRITE_ONCE(poll->canceled, true);
4747         if (!list_empty(&poll->wait.entry)) {
4748                 list_del_init(&poll->wait.entry);
4749                 do_complete = true;
4750         }
4751         spin_unlock(&poll->head->lock);
4752         hash_del(&req->hash_node);
4753         return do_complete;
4754 }
4755
4756 static bool io_poll_remove_one(struct io_kiocb *req)
4757 {
4758         bool do_complete;
4759
4760         if (req->opcode == IORING_OP_POLL_ADD) {
4761                 io_poll_remove_double(req);
4762                 do_complete = __io_poll_remove_one(req, &req->poll);
4763         } else {
4764                 struct async_poll *apoll = req->apoll;
4765
4766                 /* non-poll requests have submit ref still */
4767                 do_complete = __io_poll_remove_one(req, &apoll->poll);
4768                 if (do_complete) {
4769                         io_put_req(req);
4770                         /*
4771                          * restore ->work because we will call
4772                          * io_req_work_drop_env below when dropping the
4773                          * final reference.
4774                          */
4775                         if (req->flags & REQ_F_WORK_INITIALIZED)
4776                                 memcpy(&req->work, &apoll->work,
4777                                        sizeof(req->work));
4778                         kfree(apoll);
4779                 }
4780         }
4781
4782         if (do_complete) {
4783                 io_cqring_fill_event(req, -ECANCELED);
4784                 io_commit_cqring(req->ctx);
4785                 req->flags |= REQ_F_COMP_LOCKED;
4786                 io_put_req(req);
4787         }
4788
4789         return do_complete;
4790 }
4791
4792 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4793 {
4794         struct hlist_node *tmp;
4795         struct io_kiocb *req;
4796         int posted = 0, i;
4797
4798         spin_lock_irq(&ctx->completion_lock);
4799         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4800                 struct hlist_head *list;
4801
4802                 list = &ctx->cancel_hash[i];
4803                 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4804                         posted += io_poll_remove_one(req);
4805         }
4806         spin_unlock_irq(&ctx->completion_lock);
4807
4808         if (posted)
4809                 io_cqring_ev_posted(ctx);
4810 }
4811
4812 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4813 {
4814         struct hlist_head *list;
4815         struct io_kiocb *req;
4816
4817         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4818         hlist_for_each_entry(req, list, hash_node) {
4819                 if (sqe_addr != req->user_data)
4820                         continue;
4821                 if (io_poll_remove_one(req))
4822                         return 0;
4823                 return -EALREADY;
4824         }
4825
4826         return -ENOENT;
4827 }
4828
4829 static int io_poll_remove_prep(struct io_kiocb *req,
4830                                const struct io_uring_sqe *sqe)
4831 {
4832         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4833                 return -EINVAL;
4834         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4835             sqe->poll_events)
4836                 return -EINVAL;
4837
4838         req->poll.addr = READ_ONCE(sqe->addr);
4839         return 0;
4840 }
4841
4842 /*
4843  * Find a running poll command that matches one specified in sqe->addr,
4844  * and remove it if found.
4845  */
4846 static int io_poll_remove(struct io_kiocb *req)
4847 {
4848         struct io_ring_ctx *ctx = req->ctx;
4849         u64 addr;
4850         int ret;
4851
4852         addr = req->poll.addr;
4853         spin_lock_irq(&ctx->completion_lock);
4854         ret = io_poll_cancel(ctx, addr);
4855         spin_unlock_irq(&ctx->completion_lock);
4856
4857         if (ret < 0)
4858                 req_set_fail_links(req);
4859         io_req_complete(req, ret);
4860         return 0;
4861 }
4862
4863 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4864                         void *key)
4865 {
4866         struct io_kiocb *req = wait->private;
4867         struct io_poll_iocb *poll = &req->poll;
4868
4869         return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4870 }
4871
4872 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4873                                struct poll_table_struct *p)
4874 {
4875         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4876
4877         __io_queue_proc(&pt->req->poll, pt, head);
4878 }
4879
4880 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4881 {
4882         struct io_poll_iocb *poll = &req->poll;
4883         u32 events;
4884
4885         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4886                 return -EINVAL;
4887         if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4888                 return -EINVAL;
4889         if (!poll->file)
4890                 return -EBADF;
4891
4892         events = READ_ONCE(sqe->poll32_events);
4893 #ifdef __BIG_ENDIAN
4894         events = swahw32(events);
4895 #endif
4896         poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
4897                        (events & EPOLLEXCLUSIVE);
4898
4899         io_get_req_task(req);
4900         return 0;
4901 }
4902
4903 static int io_poll_add(struct io_kiocb *req)
4904 {
4905         struct io_poll_iocb *poll = &req->poll;
4906         struct io_ring_ctx *ctx = req->ctx;
4907         struct io_poll_table ipt;
4908         __poll_t mask;
4909
4910         INIT_HLIST_NODE(&req->hash_node);
4911         INIT_LIST_HEAD(&req->list);
4912         ipt.pt._qproc = io_poll_queue_proc;
4913
4914         mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4915                                         io_poll_wake);
4916
4917         if (mask) { /* no async, we'd stolen it */
4918                 ipt.error = 0;
4919                 io_poll_complete(req, mask, 0);
4920         }
4921         spin_unlock_irq(&ctx->completion_lock);
4922
4923         if (mask) {
4924                 io_cqring_ev_posted(ctx);
4925                 io_put_req(req);
4926         }
4927         return ipt.error;
4928 }
4929
4930 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4931 {
4932         struct io_timeout_data *data = container_of(timer,
4933                                                 struct io_timeout_data, timer);
4934         struct io_kiocb *req = data->req;
4935         struct io_ring_ctx *ctx = req->ctx;
4936         unsigned long flags;
4937
4938         atomic_inc(&ctx->cq_timeouts);
4939
4940         spin_lock_irqsave(&ctx->completion_lock, flags);
4941         /*
4942          * We could be racing with timeout deletion. If the list is empty,
4943          * then timeout lookup already found it and will be handling it.
4944          */
4945         if (!list_empty(&req->list))
4946                 list_del_init(&req->list);
4947
4948         io_cqring_fill_event(req, -ETIME);
4949         io_commit_cqring(ctx);
4950         spin_unlock_irqrestore(&ctx->completion_lock, flags);
4951
4952         io_cqring_ev_posted(ctx);
4953         req_set_fail_links(req);
4954         io_put_req(req);
4955         return HRTIMER_NORESTART;
4956 }
4957
4958 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4959 {
4960         struct io_kiocb *req;
4961         int ret = -ENOENT;
4962
4963         list_for_each_entry(req, &ctx->timeout_list, list) {
4964                 if (user_data == req->user_data) {
4965                         list_del_init(&req->list);
4966                         ret = 0;
4967                         break;
4968                 }
4969         }
4970
4971         if (ret == -ENOENT)
4972                 return ret;
4973
4974         ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4975         if (ret == -1)
4976                 return -EALREADY;
4977
4978         req_set_fail_links(req);
4979         io_cqring_fill_event(req, -ECANCELED);
4980         io_put_req(req);
4981         return 0;
4982 }
4983
4984 static int io_timeout_remove_prep(struct io_kiocb *req,
4985                                   const struct io_uring_sqe *sqe)
4986 {
4987         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4988                 return -EINVAL;
4989         if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4990                 return -EINVAL;
4991
4992         req->timeout.addr = READ_ONCE(sqe->addr);
4993         req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4994         if (req->timeout.flags)
4995                 return -EINVAL;
4996
4997         return 0;
4998 }
4999
5000 /*
5001  * Remove or update an existing timeout command
5002  */
5003 static int io_timeout_remove(struct io_kiocb *req)
5004 {
5005         struct io_ring_ctx *ctx = req->ctx;
5006         int ret;
5007
5008         spin_lock_irq(&ctx->completion_lock);
5009         ret = io_timeout_cancel(ctx, req->timeout.addr);
5010
5011         io_cqring_fill_event(req, ret);
5012         io_commit_cqring(ctx);
5013         spin_unlock_irq(&ctx->completion_lock);
5014         io_cqring_ev_posted(ctx);
5015         if (ret < 0)
5016                 req_set_fail_links(req);
5017         io_put_req(req);
5018         return 0;
5019 }
5020
5021 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5022                            bool is_timeout_link)
5023 {
5024         struct io_timeout_data *data;
5025         unsigned flags;
5026         u32 off = READ_ONCE(sqe->off);
5027
5028         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5029                 return -EINVAL;
5030         if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5031                 return -EINVAL;
5032         if (off && is_timeout_link)
5033                 return -EINVAL;
5034         flags = READ_ONCE(sqe->timeout_flags);
5035         if (flags & ~IORING_TIMEOUT_ABS)
5036                 return -EINVAL;
5037
5038         req->timeout.off = off;
5039
5040         if (!req->io && io_alloc_async_ctx(req))
5041                 return -ENOMEM;
5042
5043         data = &req->io->timeout;
5044         data->req = req;
5045         req->flags |= REQ_F_TIMEOUT;
5046
5047         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5048                 return -EFAULT;
5049
5050         if (flags & IORING_TIMEOUT_ABS)
5051                 data->mode = HRTIMER_MODE_ABS;
5052         else
5053                 data->mode = HRTIMER_MODE_REL;
5054
5055         hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5056         return 0;
5057 }
5058
5059 static int io_timeout(struct io_kiocb *req)
5060 {
5061         struct io_ring_ctx *ctx = req->ctx;
5062         struct io_timeout_data *data = &req->io->timeout;
5063         struct list_head *entry;
5064         u32 tail, off = req->timeout.off;
5065
5066         spin_lock_irq(&ctx->completion_lock);
5067
5068         /*
5069          * sqe->off holds how many events that need to occur for this
5070          * timeout event to be satisfied. If it isn't set, then this is
5071          * a pure timeout request, sequence isn't used.
5072          */
5073         if (!off) {
5074                 req->flags |= REQ_F_TIMEOUT_NOSEQ;
5075                 entry = ctx->timeout_list.prev;
5076                 goto add;
5077         }
5078
5079         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5080         req->timeout.target_seq = tail + off;
5081
5082         /*
5083          * Insertion sort, ensuring the first entry in the list is always
5084          * the one we need first.
5085          */
5086         list_for_each_prev(entry, &ctx->timeout_list) {
5087                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5088
5089                 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
5090                         continue;
5091                 /* nxt.seq is behind @tail, otherwise would've been completed */
5092                 if (off >= nxt->timeout.target_seq - tail)
5093                         break;
5094         }
5095 add:
5096         list_add(&req->list, entry);
5097         data->timer.function = io_timeout_fn;
5098         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5099         spin_unlock_irq(&ctx->completion_lock);
5100         return 0;
5101 }
5102
5103 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5104 {
5105         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5106
5107         return req->user_data == (unsigned long) data;
5108 }
5109
5110 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5111 {
5112         enum io_wq_cancel cancel_ret;
5113         int ret = 0;
5114
5115         cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5116         switch (cancel_ret) {
5117         case IO_WQ_CANCEL_OK:
5118                 ret = 0;
5119                 break;
5120         case IO_WQ_CANCEL_RUNNING:
5121                 ret = -EALREADY;
5122                 break;
5123         case IO_WQ_CANCEL_NOTFOUND:
5124                 ret = -ENOENT;
5125                 break;
5126         }
5127
5128         return ret;
5129 }
5130
5131 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5132                                      struct io_kiocb *req, __u64 sqe_addr,
5133                                      int success_ret)
5134 {
5135         unsigned long flags;
5136         int ret;
5137
5138         ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5139         if (ret != -ENOENT) {
5140                 spin_lock_irqsave(&ctx->completion_lock, flags);
5141                 goto done;
5142         }
5143
5144         spin_lock_irqsave(&ctx->completion_lock, flags);
5145         ret = io_timeout_cancel(ctx, sqe_addr);
5146         if (ret != -ENOENT)
5147                 goto done;
5148         ret = io_poll_cancel(ctx, sqe_addr);
5149 done:
5150         if (!ret)
5151                 ret = success_ret;
5152         io_cqring_fill_event(req, ret);
5153         io_commit_cqring(ctx);
5154         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5155         io_cqring_ev_posted(ctx);
5156
5157         if (ret < 0)
5158                 req_set_fail_links(req);
5159         io_put_req(req);
5160 }
5161
5162 static int io_async_cancel_prep(struct io_kiocb *req,
5163                                 const struct io_uring_sqe *sqe)
5164 {
5165         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5166                 return -EINVAL;
5167         if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
5168             sqe->cancel_flags)
5169                 return -EINVAL;
5170
5171         req->cancel.addr = READ_ONCE(sqe->addr);
5172         return 0;
5173 }
5174
5175 static int io_async_cancel(struct io_kiocb *req)
5176 {
5177         struct io_ring_ctx *ctx = req->ctx;
5178
5179         io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5180         return 0;
5181 }
5182
5183 static int io_files_update_prep(struct io_kiocb *req,
5184                                 const struct io_uring_sqe *sqe)
5185 {
5186         if (sqe->flags || sqe->ioprio || sqe->rw_flags)
5187                 return -EINVAL;
5188
5189         req->files_update.offset = READ_ONCE(sqe->off);
5190         req->files_update.nr_args = READ_ONCE(sqe->len);
5191         if (!req->files_update.nr_args)
5192                 return -EINVAL;
5193         req->files_update.arg = READ_ONCE(sqe->addr);
5194         return 0;
5195 }
5196
5197 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5198                            struct io_comp_state *cs)
5199 {
5200         struct io_ring_ctx *ctx = req->ctx;
5201         struct io_uring_files_update up;
5202         int ret;
5203
5204         if (force_nonblock)
5205                 return -EAGAIN;
5206
5207         up.offset = req->files_update.offset;
5208         up.fds = req->files_update.arg;
5209
5210         mutex_lock(&ctx->uring_lock);
5211         ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5212         mutex_unlock(&ctx->uring_lock);
5213
5214         if (ret < 0)
5215                 req_set_fail_links(req);
5216         __io_req_complete(req, ret, 0, cs);
5217         return 0;
5218 }
5219
5220 static int io_req_defer_prep(struct io_kiocb *req,
5221                              const struct io_uring_sqe *sqe)
5222 {
5223         ssize_t ret = 0;
5224
5225         if (!sqe)
5226                 return 0;
5227
5228         io_req_init_async(req);
5229
5230         if (io_op_defs[req->opcode].file_table) {
5231                 ret = io_grab_files(req);
5232                 if (unlikely(ret))
5233                         return ret;
5234         }
5235
5236         io_req_work_grab_env(req, &io_op_defs[req->opcode]);
5237
5238         switch (req->opcode) {
5239         case IORING_OP_NOP:
5240                 break;
5241         case IORING_OP_READV:
5242         case IORING_OP_READ_FIXED:
5243         case IORING_OP_READ:
5244                 ret = io_read_prep(req, sqe, true);
5245                 break;
5246         case IORING_OP_WRITEV:
5247         case IORING_OP_WRITE_FIXED:
5248         case IORING_OP_WRITE:
5249                 ret = io_write_prep(req, sqe, true);
5250                 break;
5251         case IORING_OP_POLL_ADD:
5252                 ret = io_poll_add_prep(req, sqe);
5253                 break;
5254         case IORING_OP_POLL_REMOVE:
5255                 ret = io_poll_remove_prep(req, sqe);
5256                 break;
5257         case IORING_OP_FSYNC:
5258                 ret = io_prep_fsync(req, sqe);
5259                 break;
5260         case IORING_OP_SYNC_FILE_RANGE:
5261                 ret = io_prep_sfr(req, sqe);
5262                 break;
5263         case IORING_OP_SENDMSG:
5264         case IORING_OP_SEND:
5265                 ret = io_sendmsg_prep(req, sqe);
5266                 break;
5267         case IORING_OP_RECVMSG:
5268         case IORING_OP_RECV:
5269                 ret = io_recvmsg_prep(req, sqe);
5270                 break;
5271         case IORING_OP_CONNECT:
5272                 ret = io_connect_prep(req, sqe);
5273                 break;
5274         case IORING_OP_TIMEOUT:
5275                 ret = io_timeout_prep(req, sqe, false);
5276                 break;
5277         case IORING_OP_TIMEOUT_REMOVE:
5278                 ret = io_timeout_remove_prep(req, sqe);
5279                 break;
5280         case IORING_OP_ASYNC_CANCEL:
5281                 ret = io_async_cancel_prep(req, sqe);
5282                 break;
5283         case IORING_OP_LINK_TIMEOUT:
5284                 ret = io_timeout_prep(req, sqe, true);
5285                 break;
5286         case IORING_OP_ACCEPT:
5287                 ret = io_accept_prep(req, sqe);
5288                 break;
5289         case IORING_OP_FALLOCATE:
5290                 ret = io_fallocate_prep(req, sqe);
5291                 break;
5292         case IORING_OP_OPENAT:
5293                 ret = io_openat_prep(req, sqe);
5294                 break;
5295         case IORING_OP_CLOSE:
5296                 ret = io_close_prep(req, sqe);
5297                 break;
5298         case IORING_OP_FILES_UPDATE:
5299                 ret = io_files_update_prep(req, sqe);
5300                 break;
5301         case IORING_OP_STATX:
5302                 ret = io_statx_prep(req, sqe);
5303                 break;
5304         case IORING_OP_FADVISE:
5305                 ret = io_fadvise_prep(req, sqe);
5306                 break;
5307         case IORING_OP_MADVISE:
5308                 ret = io_madvise_prep(req, sqe);
5309                 break;
5310         case IORING_OP_OPENAT2:
5311                 ret = io_openat2_prep(req, sqe);
5312                 break;
5313         case IORING_OP_EPOLL_CTL:
5314                 ret = io_epoll_ctl_prep(req, sqe);
5315                 break;
5316         case IORING_OP_SPLICE:
5317                 ret = io_splice_prep(req, sqe);
5318                 break;
5319         case IORING_OP_PROVIDE_BUFFERS:
5320                 ret = io_provide_buffers_prep(req, sqe);
5321                 break;
5322         case IORING_OP_REMOVE_BUFFERS:
5323                 ret = io_remove_buffers_prep(req, sqe);
5324                 break;
5325         case IORING_OP_TEE:
5326                 ret = io_tee_prep(req, sqe);
5327                 break;
5328         default:
5329                 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5330                                 req->opcode);
5331                 ret = -EINVAL;
5332                 break;
5333         }
5334
5335         return ret;
5336 }
5337
5338 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5339 {
5340         struct io_ring_ctx *ctx = req->ctx;
5341         int ret;
5342
5343         /* Still need defer if there is pending req in defer list. */
5344         if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5345                 return 0;
5346
5347         if (!req->io) {
5348                 if (io_alloc_async_ctx(req))
5349                         return -EAGAIN;
5350                 ret = io_req_defer_prep(req, sqe);
5351                 if (ret < 0)
5352                         return ret;
5353         }
5354
5355         spin_lock_irq(&ctx->completion_lock);
5356         if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5357                 spin_unlock_irq(&ctx->completion_lock);
5358                 return 0;
5359         }
5360
5361         trace_io_uring_defer(ctx, req, req->user_data);
5362         list_add_tail(&req->list, &ctx->defer_list);
5363         spin_unlock_irq(&ctx->completion_lock);
5364         return -EIOCBQUEUED;
5365 }
5366
5367 static void io_cleanup_req(struct io_kiocb *req)
5368 {
5369         struct io_async_ctx *io = req->io;
5370
5371         switch (req->opcode) {
5372         case IORING_OP_READV:
5373         case IORING_OP_READ_FIXED:
5374         case IORING_OP_READ:
5375                 if (req->flags & REQ_F_BUFFER_SELECTED)
5376                         kfree((void *)(unsigned long)req->rw.addr);
5377                 /* fallthrough */
5378         case IORING_OP_WRITEV:
5379         case IORING_OP_WRITE_FIXED:
5380         case IORING_OP_WRITE:
5381                 if (io->rw.iov != io->rw.fast_iov)
5382                         kfree(io->rw.iov);
5383                 break;
5384         case IORING_OP_RECVMSG:
5385                 if (req->flags & REQ_F_BUFFER_SELECTED)
5386                         kfree(req->sr_msg.kbuf);
5387                 /* fallthrough */
5388         case IORING_OP_SENDMSG:
5389                 if (io->msg.iov != io->msg.fast_iov)
5390                         kfree(io->msg.iov);
5391                 break;
5392         case IORING_OP_RECV:
5393                 if (req->flags & REQ_F_BUFFER_SELECTED)
5394                         kfree(req->sr_msg.kbuf);
5395                 break;
5396         case IORING_OP_OPENAT:
5397         case IORING_OP_OPENAT2:
5398                 break;
5399         case IORING_OP_SPLICE:
5400         case IORING_OP_TEE:
5401                 io_put_file(req, req->splice.file_in,
5402                             (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5403                 break;
5404         }
5405
5406         req->flags &= ~REQ_F_NEED_CLEANUP;
5407 }
5408
5409 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5410                         bool force_nonblock, struct io_comp_state *cs)
5411 {
5412         struct io_ring_ctx *ctx = req->ctx;
5413         int ret;
5414
5415         switch (req->opcode) {
5416         case IORING_OP_NOP:
5417                 ret = io_nop(req, cs);
5418                 break;
5419         case IORING_OP_READV:
5420         case IORING_OP_READ_FIXED:
5421         case IORING_OP_READ:
5422                 if (sqe) {
5423                         ret = io_read_prep(req, sqe, force_nonblock);
5424                         if (ret < 0)
5425                                 break;
5426                 }
5427                 ret = io_read(req, force_nonblock, cs);
5428                 break;
5429         case IORING_OP_WRITEV:
5430         case IORING_OP_WRITE_FIXED:
5431         case IORING_OP_WRITE:
5432                 if (sqe) {
5433                         ret = io_write_prep(req, sqe, force_nonblock);
5434                         if (ret < 0)
5435                                 break;
5436                 }
5437                 ret = io_write(req, force_nonblock, cs);
5438                 break;
5439         case IORING_OP_FSYNC:
5440                 if (sqe) {
5441                         ret = io_prep_fsync(req, sqe);
5442                         if (ret < 0)
5443                                 break;
5444                 }
5445                 ret = io_fsync(req, force_nonblock);
5446                 break;
5447         case IORING_OP_POLL_ADD:
5448                 if (sqe) {
5449                         ret = io_poll_add_prep(req, sqe);
5450                         if (ret)
5451                                 break;
5452                 }
5453                 ret = io_poll_add(req);
5454                 break;
5455         case IORING_OP_POLL_REMOVE:
5456                 if (sqe) {
5457                         ret = io_poll_remove_prep(req, sqe);
5458                         if (ret < 0)
5459                                 break;
5460                 }
5461                 ret = io_poll_remove(req);
5462                 break;
5463         case IORING_OP_SYNC_FILE_RANGE:
5464                 if (sqe) {
5465                         ret = io_prep_sfr(req, sqe);
5466                         if (ret < 0)
5467                                 break;
5468                 }
5469                 ret = io_sync_file_range(req, force_nonblock);
5470                 break;
5471         case IORING_OP_SENDMSG:
5472         case IORING_OP_SEND:
5473                 if (sqe) {
5474                         ret = io_sendmsg_prep(req, sqe);
5475                         if (ret < 0)
5476                                 break;
5477                 }
5478                 if (req->opcode == IORING_OP_SENDMSG)
5479                         ret = io_sendmsg(req, force_nonblock, cs);
5480                 else
5481                         ret = io_send(req, force_nonblock, cs);
5482                 break;
5483         case IORING_OP_RECVMSG:
5484         case IORING_OP_RECV:
5485                 if (sqe) {
5486                         ret = io_recvmsg_prep(req, sqe);
5487                         if (ret)
5488                                 break;
5489                 }
5490                 if (req->opcode == IORING_OP_RECVMSG)
5491                         ret = io_recvmsg(req, force_nonblock, cs);
5492                 else
5493                         ret = io_recv(req, force_nonblock, cs);
5494                 break;
5495         case IORING_OP_TIMEOUT:
5496                 if (sqe) {
5497                         ret = io_timeout_prep(req, sqe, false);
5498                         if (ret)
5499                                 break;
5500                 }
5501                 ret = io_timeout(req);
5502                 break;
5503         case IORING_OP_TIMEOUT_REMOVE:
5504                 if (sqe) {
5505                         ret = io_timeout_remove_prep(req, sqe);
5506                         if (ret)
5507                                 break;
5508                 }
5509                 ret = io_timeout_remove(req);
5510                 break;
5511         case IORING_OP_ACCEPT:
5512                 if (sqe) {
5513                         ret = io_accept_prep(req, sqe);
5514                         if (ret)
5515                                 break;
5516                 }
5517                 ret = io_accept(req, force_nonblock, cs);
5518                 break;
5519         case IORING_OP_CONNECT:
5520                 if (sqe) {
5521                         ret = io_connect_prep(req, sqe);
5522                         if (ret)
5523                                 break;
5524                 }
5525                 ret = io_connect(req, force_nonblock, cs);
5526                 break;
5527         case IORING_OP_ASYNC_CANCEL:
5528                 if (sqe) {
5529                         ret = io_async_cancel_prep(req, sqe);
5530                         if (ret)
5531                                 break;
5532                 }
5533                 ret = io_async_cancel(req);
5534                 break;
5535         case IORING_OP_FALLOCATE:
5536                 if (sqe) {
5537                         ret = io_fallocate_prep(req, sqe);
5538                         if (ret)
5539                                 break;
5540                 }
5541                 ret = io_fallocate(req, force_nonblock);
5542                 break;
5543         case IORING_OP_OPENAT:
5544                 if (sqe) {
5545                         ret = io_openat_prep(req, sqe);
5546                         if (ret)
5547                                 break;
5548                 }
5549                 ret = io_openat(req, force_nonblock);
5550                 break;
5551         case IORING_OP_CLOSE:
5552                 if (sqe) {
5553                         ret = io_close_prep(req, sqe);
5554                         if (ret)
5555                                 break;
5556                 }
5557                 ret = io_close(req, force_nonblock, cs);
5558                 break;
5559         case IORING_OP_FILES_UPDATE:
5560                 if (sqe) {
5561                         ret = io_files_update_prep(req, sqe);
5562                         if (ret)
5563                                 break;
5564                 }
5565                 ret = io_files_update(req, force_nonblock, cs);
5566                 break;
5567         case IORING_OP_STATX:
5568                 if (sqe) {
5569                         ret = io_statx_prep(req, sqe);
5570                         if (ret)
5571                                 break;
5572                 }
5573                 ret = io_statx(req, force_nonblock);
5574                 break;
5575         case IORING_OP_FADVISE:
5576                 if (sqe) {
5577                         ret = io_fadvise_prep(req, sqe);
5578                         if (ret)
5579                                 break;
5580                 }
5581                 ret = io_fadvise(req, force_nonblock);
5582                 break;
5583         case IORING_OP_MADVISE:
5584                 if (sqe) {
5585                         ret = io_madvise_prep(req, sqe);
5586                         if (ret)
5587                                 break;
5588                 }
5589                 ret = io_madvise(req, force_nonblock);
5590                 break;
5591         case IORING_OP_OPENAT2:
5592                 if (sqe) {
5593                         ret = io_openat2_prep(req, sqe);
5594                         if (ret)
5595                                 break;
5596                 }
5597                 ret = io_openat2(req, force_nonblock);
5598                 break;
5599         case IORING_OP_EPOLL_CTL:
5600                 if (sqe) {
5601                         ret = io_epoll_ctl_prep(req, sqe);
5602                         if (ret)
5603                                 break;
5604                 }
5605                 ret = io_epoll_ctl(req, force_nonblock, cs);
5606                 break;
5607         case IORING_OP_SPLICE:
5608                 if (sqe) {
5609                         ret = io_splice_prep(req, sqe);
5610                         if (ret < 0)
5611                                 break;
5612                 }
5613                 ret = io_splice(req, force_nonblock);
5614                 break;
5615         case IORING_OP_PROVIDE_BUFFERS:
5616                 if (sqe) {
5617                         ret = io_provide_buffers_prep(req, sqe);
5618                         if (ret)
5619                                 break;
5620                 }
5621                 ret = io_provide_buffers(req, force_nonblock, cs);
5622                 break;
5623         case IORING_OP_REMOVE_BUFFERS:
5624                 if (sqe) {
5625                         ret = io_remove_buffers_prep(req, sqe);
5626                         if (ret)
5627                                 break;
5628                 }
5629                 ret = io_remove_buffers(req, force_nonblock, cs);
5630                 break;
5631         case IORING_OP_TEE:
5632                 if (sqe) {
5633                         ret = io_tee_prep(req, sqe);
5634                         if (ret < 0)
5635                                 break;
5636                 }
5637                 ret = io_tee(req, force_nonblock);
5638                 break;
5639         default:
5640                 ret = -EINVAL;
5641                 break;
5642         }
5643
5644         if (ret)
5645                 return ret;
5646
5647         /* If the op doesn't have a file, we're not polling for it */
5648         if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5649                 const bool in_async = io_wq_current_is_worker();
5650
5651                 if (req->result == -EAGAIN)
5652                         return -EAGAIN;
5653
5654                 /* workqueue context doesn't hold uring_lock, grab it now */
5655                 if (in_async)
5656                         mutex_lock(&ctx->uring_lock);
5657
5658                 io_iopoll_req_issued(req);
5659
5660                 if (in_async)
5661                         mutex_unlock(&ctx->uring_lock);
5662         }
5663
5664         return 0;
5665 }
5666
5667 static void io_arm_async_linked_timeout(struct io_kiocb *req)
5668 {
5669         struct io_kiocb *link;
5670
5671         /* link head's timeout is queued in io_queue_async_work() */
5672         if (!(req->flags & REQ_F_QUEUE_TIMEOUT))
5673                 return;
5674
5675         link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
5676         io_queue_linked_timeout(link);
5677 }
5678
5679 static void io_wq_submit_work(struct io_wq_work **workptr)
5680 {
5681         struct io_wq_work *work = *workptr;
5682         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5683         int ret = 0;
5684
5685         io_arm_async_linked_timeout(req);
5686
5687         /* if NO_CANCEL is set, we must still run the work */
5688         if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5689                                 IO_WQ_WORK_CANCEL) {
5690                 ret = -ECANCELED;
5691         }
5692
5693         if (!ret) {
5694                 do {
5695                         ret = io_issue_sqe(req, NULL, false, NULL);
5696                         /*
5697                          * We can get EAGAIN for polled IO even though we're
5698                          * forcing a sync submission from here, since we can't
5699                          * wait for request slots on the block side.
5700                          */
5701                         if (ret != -EAGAIN)
5702                                 break;
5703                         cond_resched();
5704                 } while (1);
5705         }
5706
5707         if (ret) {
5708                 req_set_fail_links(req);
5709                 io_req_complete(req, ret);
5710         }
5711
5712         io_steal_work(req, workptr);
5713 }
5714
5715 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5716                                               int index)
5717 {
5718         struct fixed_file_table *table;
5719
5720         table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5721         return table->files[index & IORING_FILE_TABLE_MASK];
5722 }
5723
5724 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5725                         int fd, struct file **out_file, bool fixed)
5726 {
5727         struct io_ring_ctx *ctx = req->ctx;
5728         struct file *file;
5729
5730         if (fixed) {
5731                 if (unlikely(!ctx->file_data ||
5732                     (unsigned) fd >= ctx->nr_user_files))
5733                         return -EBADF;
5734                 fd = array_index_nospec(fd, ctx->nr_user_files);
5735                 file = io_file_from_index(ctx, fd);
5736                 if (file) {
5737                         req->fixed_file_refs = ctx->file_data->cur_refs;
5738                         percpu_ref_get(req->fixed_file_refs);
5739                 }
5740         } else {
5741                 trace_io_uring_file_get(ctx, fd);
5742                 file = __io_file_get(state, fd);
5743         }
5744
5745         if (file || io_op_defs[req->opcode].needs_file_no_error) {
5746                 *out_file = file;
5747                 return 0;
5748         }
5749         return -EBADF;
5750 }
5751
5752 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5753                            int fd)
5754 {
5755         bool fixed;
5756
5757         fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5758         if (unlikely(!fixed && io_async_submit(req->ctx)))
5759                 return -EBADF;
5760
5761         return io_file_get(state, req, fd, &req->file, fixed);
5762 }
5763
5764 static int io_grab_files(struct io_kiocb *req)
5765 {
5766         int ret = -EBADF;
5767         struct io_ring_ctx *ctx = req->ctx;
5768
5769         if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5770                 return 0;
5771         if (!ctx->ring_file)
5772                 return -EBADF;
5773
5774         rcu_read_lock();
5775         spin_lock_irq(&ctx->inflight_lock);
5776         /*
5777          * We use the f_ops->flush() handler to ensure that we can flush
5778          * out work accessing these files if the fd is closed. Check if
5779          * the fd has changed since we started down this path, and disallow
5780          * this operation if it has.
5781          */
5782         if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5783                 list_add(&req->inflight_entry, &ctx->inflight_list);
5784                 req->flags |= REQ_F_INFLIGHT;
5785                 req->work.files = current->files;
5786                 ret = 0;
5787         }
5788         spin_unlock_irq(&ctx->inflight_lock);
5789         rcu_read_unlock();
5790
5791         return ret;
5792 }
5793
5794 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5795 {
5796         struct io_timeout_data *data = container_of(timer,
5797                                                 struct io_timeout_data, timer);
5798         struct io_kiocb *req = data->req;
5799         struct io_ring_ctx *ctx = req->ctx;
5800         struct io_kiocb *prev = NULL;
5801         unsigned long flags;
5802
5803         spin_lock_irqsave(&ctx->completion_lock, flags);
5804
5805         /*
5806          * We don't expect the list to be empty, that will only happen if we
5807          * race with the completion of the linked work.
5808          */
5809         if (!list_empty(&req->link_list)) {
5810                 prev = list_entry(req->link_list.prev, struct io_kiocb,
5811                                   link_list);
5812                 if (refcount_inc_not_zero(&prev->refs)) {
5813                         list_del_init(&req->link_list);
5814                         prev->flags &= ~REQ_F_LINK_TIMEOUT;
5815                 } else
5816                         prev = NULL;
5817         }
5818
5819         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5820
5821         if (prev) {
5822                 req_set_fail_links(prev);
5823                 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5824                 io_put_req(prev);
5825         } else {
5826                 io_req_complete(req, -ETIME);
5827         }
5828         return HRTIMER_NORESTART;
5829 }
5830
5831 static void io_queue_linked_timeout(struct io_kiocb *req)
5832 {
5833         struct io_ring_ctx *ctx = req->ctx;
5834
5835         /*
5836          * If the list is now empty, then our linked request finished before
5837          * we got a chance to setup the timer
5838          */
5839         spin_lock_irq(&ctx->completion_lock);
5840         if (!list_empty(&req->link_list)) {
5841                 struct io_timeout_data *data = &req->io->timeout;
5842
5843                 data->timer.function = io_link_timeout_fn;
5844                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5845                                 data->mode);
5846         }
5847         spin_unlock_irq(&ctx->completion_lock);
5848
5849         /* drop submission reference */
5850         io_put_req(req);
5851 }
5852
5853 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5854 {
5855         struct io_kiocb *nxt;
5856
5857         if (!(req->flags & REQ_F_LINK_HEAD))
5858                 return NULL;
5859         /* for polled retry, if flag is set, we already went through here */
5860         if (req->flags & REQ_F_POLLED)
5861                 return NULL;
5862
5863         nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5864                                         link_list);
5865         if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5866                 return NULL;
5867
5868         req->flags |= REQ_F_LINK_TIMEOUT;
5869         return nxt;
5870 }
5871
5872 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5873                            struct io_comp_state *cs)
5874 {
5875         struct io_kiocb *linked_timeout;
5876         struct io_kiocb *nxt;
5877         const struct cred *old_creds = NULL;
5878         int ret;
5879
5880 again:
5881         linked_timeout = io_prep_linked_timeout(req);
5882
5883         if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5884             req->work.creds != current_cred()) {
5885                 if (old_creds)
5886                         revert_creds(old_creds);
5887                 if (old_creds == req->work.creds)
5888                         old_creds = NULL; /* restored original creds */
5889                 else
5890                         old_creds = override_creds(req->work.creds);
5891         }
5892
5893         ret = io_issue_sqe(req, sqe, true, cs);
5894
5895         /*
5896          * We async punt it if the file wasn't marked NOWAIT, or if the file
5897          * doesn't support non-blocking read/write attempts
5898          */
5899         if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
5900                 if (io_arm_poll_handler(req)) {
5901                         if (linked_timeout)
5902                                 io_queue_linked_timeout(linked_timeout);
5903                         goto exit;
5904                 }
5905 punt:
5906                 io_req_init_async(req);
5907
5908                 if (io_op_defs[req->opcode].file_table) {
5909                         ret = io_grab_files(req);
5910                         if (ret)
5911                                 goto err;
5912                 }
5913
5914                 /*
5915                  * Queued up for async execution, worker will release
5916                  * submit reference when the iocb is actually submitted.
5917                  */
5918                 io_queue_async_work(req);
5919                 goto exit;
5920         }
5921
5922 err:
5923         nxt = NULL;
5924         /* drop submission reference */
5925         io_put_req_find_next(req, &nxt);
5926
5927         if (linked_timeout) {
5928                 if (!ret)
5929                         io_queue_linked_timeout(linked_timeout);
5930                 else
5931                         io_put_req(linked_timeout);
5932         }
5933
5934         /* and drop final reference, if we failed */
5935         if (ret) {
5936                 req_set_fail_links(req);
5937                 io_req_complete(req, ret);
5938         }
5939         if (nxt) {
5940                 req = nxt;
5941
5942                 if (req->flags & REQ_F_FORCE_ASYNC)
5943                         goto punt;
5944                 goto again;
5945         }
5946 exit:
5947         if (old_creds)
5948                 revert_creds(old_creds);
5949 }
5950
5951 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5952                          struct io_comp_state *cs)
5953 {
5954         int ret;
5955
5956         ret = io_req_defer(req, sqe);
5957         if (ret) {
5958                 if (ret != -EIOCBQUEUED) {
5959 fail_req:
5960                         req_set_fail_links(req);
5961                         io_put_req(req);
5962                         io_req_complete(req, ret);
5963                 }
5964         } else if (req->flags & REQ_F_FORCE_ASYNC) {
5965                 if (!req->io) {
5966                         ret = -EAGAIN;
5967                         if (io_alloc_async_ctx(req))
5968                                 goto fail_req;
5969                         ret = io_req_defer_prep(req, sqe);
5970                         if (unlikely(ret < 0))
5971                                 goto fail_req;
5972                 }
5973
5974                 /*
5975                  * Never try inline submit of IOSQE_ASYNC is set, go straight
5976                  * to async execution.
5977                  */
5978                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5979                 io_queue_async_work(req);
5980         } else {
5981                 __io_queue_sqe(req, sqe, cs);
5982         }
5983 }
5984
5985 static inline void io_queue_link_head(struct io_kiocb *req,
5986                                       struct io_comp_state *cs)
5987 {
5988         if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
5989                 io_put_req(req);
5990                 io_req_complete(req, -ECANCELED);
5991         } else
5992                 io_queue_sqe(req, NULL, cs);
5993 }
5994
5995 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5996                          struct io_kiocb **link, struct io_comp_state *cs)
5997 {
5998         struct io_ring_ctx *ctx = req->ctx;
5999         int ret;
6000
6001         /*
6002          * If we already have a head request, queue this one for async
6003          * submittal once the head completes. If we don't have a head but
6004          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6005          * submitted sync once the chain is complete. If none of those
6006          * conditions are true (normal request), then just queue it.
6007          */
6008         if (*link) {
6009                 struct io_kiocb *head = *link;
6010
6011                 /*
6012                  * Taking sequential execution of a link, draining both sides
6013                  * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6014                  * requests in the link. So, it drains the head and the
6015                  * next after the link request. The last one is done via
6016                  * drain_next flag to persist the effect across calls.
6017                  */
6018                 if (req->flags & REQ_F_IO_DRAIN) {
6019                         head->flags |= REQ_F_IO_DRAIN;
6020                         ctx->drain_next = 1;
6021                 }
6022                 if (io_alloc_async_ctx(req))
6023                         return -EAGAIN;
6024
6025                 ret = io_req_defer_prep(req, sqe);
6026                 if (ret) {
6027                         /* fail even hard links since we don't submit */
6028                         head->flags |= REQ_F_FAIL_LINK;
6029                         return ret;
6030                 }
6031                 trace_io_uring_link(ctx, req, head);
6032                 list_add_tail(&req->link_list, &head->link_list);
6033
6034                 /* last request of a link, enqueue the link */
6035                 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6036                         io_queue_link_head(head, cs);
6037                         *link = NULL;
6038                 }
6039         } else {
6040                 if (unlikely(ctx->drain_next)) {
6041                         req->flags |= REQ_F_IO_DRAIN;
6042                         ctx->drain_next = 0;
6043                 }
6044                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6045                         req->flags |= REQ_F_LINK_HEAD;
6046                         INIT_LIST_HEAD(&req->link_list);
6047
6048                         if (io_alloc_async_ctx(req))
6049                                 return -EAGAIN;
6050
6051                         ret = io_req_defer_prep(req, sqe);
6052                         if (ret)
6053                                 req->flags |= REQ_F_FAIL_LINK;
6054                         *link = req;
6055                 } else {
6056                         io_queue_sqe(req, sqe, cs);
6057                 }
6058         }
6059
6060         return 0;
6061 }
6062
6063 /*
6064  * Batched submission is done, ensure local IO is flushed out.
6065  */
6066 static void io_submit_state_end(struct io_submit_state *state)
6067 {
6068         if (!list_empty(&state->comp.list))
6069                 io_submit_flush_completions(&state->comp);
6070         blk_finish_plug(&state->plug);
6071         io_state_file_put(state);
6072         if (state->free_reqs)
6073                 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6074 }
6075
6076 /*
6077  * Start submission side cache.
6078  */
6079 static void io_submit_state_start(struct io_submit_state *state,
6080                                   struct io_ring_ctx *ctx, unsigned int max_ios)
6081 {
6082         blk_start_plug(&state->plug);
6083 #ifdef CONFIG_BLOCK
6084         state->plug.nowait = true;
6085 #endif
6086         state->comp.nr = 0;
6087         INIT_LIST_HEAD(&state->comp.list);
6088         state->comp.ctx = ctx;
6089         state->free_reqs = 0;
6090         state->file = NULL;
6091         state->ios_left = max_ios;
6092 }
6093
6094 static void io_commit_sqring(struct io_ring_ctx *ctx)
6095 {
6096         struct io_rings *rings = ctx->rings;
6097
6098         /*
6099          * Ensure any loads from the SQEs are done at this point,
6100          * since once we write the new head, the application could
6101          * write new data to them.
6102          */
6103         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6104 }
6105
6106 /*
6107  * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6108  * that is mapped by userspace. This means that care needs to be taken to
6109  * ensure that reads are stable, as we cannot rely on userspace always
6110  * being a good citizen. If members of the sqe are validated and then later
6111  * used, it's important that those reads are done through READ_ONCE() to
6112  * prevent a re-load down the line.
6113  */
6114 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6115 {
6116         u32 *sq_array = ctx->sq_array;
6117         unsigned head;
6118
6119         /*
6120          * The cached sq head (or cq tail) serves two purposes:
6121          *
6122          * 1) allows us to batch the cost of updating the user visible
6123          *    head updates.
6124          * 2) allows the kernel side to track the head on its own, even
6125          *    though the application is the one updating it.
6126          */
6127         head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6128         if (likely(head < ctx->sq_entries))
6129                 return &ctx->sq_sqes[head];
6130
6131         /* drop invalid entries */
6132         ctx->cached_sq_dropped++;
6133         WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6134         return NULL;
6135 }
6136
6137 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6138 {
6139         ctx->cached_sq_head++;
6140 }
6141
6142 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6143                                 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6144                                 IOSQE_BUFFER_SELECT)
6145
6146 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6147                        const struct io_uring_sqe *sqe,
6148                        struct io_submit_state *state)
6149 {
6150         unsigned int sqe_flags;
6151         int id;
6152
6153         /*
6154          * All io need record the previous position, if LINK vs DARIN,
6155          * it can be used to mark the position of the first IO in the
6156          * link list.
6157          */
6158         req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
6159         req->opcode = READ_ONCE(sqe->opcode);
6160         req->user_data = READ_ONCE(sqe->user_data);
6161         req->io = NULL;
6162         req->file = NULL;
6163         req->ctx = ctx;
6164         req->flags = 0;
6165         /* one is dropped after submission, the other at completion */
6166         refcount_set(&req->refs, 2);
6167         req->task = current;
6168         req->result = 0;
6169
6170         if (unlikely(req->opcode >= IORING_OP_LAST))
6171                 return -EINVAL;
6172
6173         if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6174                 return -EFAULT;
6175
6176         sqe_flags = READ_ONCE(sqe->flags);
6177         /* enforce forwards compatibility on users */
6178         if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6179                 return -EINVAL;
6180
6181         if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6182             !io_op_defs[req->opcode].buffer_select)
6183                 return -EOPNOTSUPP;
6184
6185         id = READ_ONCE(sqe->personality);
6186         if (id) {
6187                 io_req_init_async(req);
6188                 req->work.creds = idr_find(&ctx->personality_idr, id);
6189                 if (unlikely(!req->work.creds))
6190                         return -EINVAL;
6191                 get_cred(req->work.creds);
6192         }
6193
6194         /* same numerical values with corresponding REQ_F_*, safe to copy */
6195         req->flags |= sqe_flags;
6196
6197         if (!io_op_defs[req->opcode].needs_file)
6198                 return 0;
6199
6200         return io_req_set_file(state, req, READ_ONCE(sqe->fd));
6201 }
6202
6203 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
6204                           struct file *ring_file, int ring_fd)
6205 {
6206         struct io_submit_state state;
6207         struct io_kiocb *link = NULL;
6208         int i, submitted = 0;
6209
6210         /* if we have a backlog and couldn't flush it all, return BUSY */
6211         if (test_bit(0, &ctx->sq_check_overflow)) {
6212                 if (!list_empty(&ctx->cq_overflow_list) &&
6213                     !io_cqring_overflow_flush(ctx, false))
6214                         return -EBUSY;
6215         }
6216
6217         /* make sure SQ entry isn't read before tail */
6218         nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6219
6220         if (!percpu_ref_tryget_many(&ctx->refs, nr))
6221                 return -EAGAIN;
6222
6223         io_submit_state_start(&state, ctx, nr);
6224
6225         ctx->ring_fd = ring_fd;
6226         ctx->ring_file = ring_file;
6227
6228         for (i = 0; i < nr; i++) {
6229                 const struct io_uring_sqe *sqe;
6230                 struct io_kiocb *req;
6231                 int err;
6232
6233                 sqe = io_get_sqe(ctx);
6234                 if (unlikely(!sqe)) {
6235                         io_consume_sqe(ctx);
6236                         break;
6237                 }
6238                 req = io_alloc_req(ctx, &state);
6239                 if (unlikely(!req)) {
6240                         if (!submitted)
6241                                 submitted = -EAGAIN;
6242                         break;
6243                 }
6244
6245                 err = io_init_req(ctx, req, sqe, &state);
6246                 io_consume_sqe(ctx);
6247                 /* will complete beyond this point, count as submitted */
6248                 submitted++;
6249
6250                 if (unlikely(err)) {
6251 fail_req:
6252                         io_put_req(req);
6253                         io_req_complete(req, err);
6254                         break;
6255                 }
6256
6257                 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6258                                                 true, io_async_submit(ctx));
6259                 err = io_submit_sqe(req, sqe, &link, &state.comp);
6260                 if (err)
6261                         goto fail_req;
6262         }
6263
6264         if (unlikely(submitted != nr)) {
6265                 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6266
6267                 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6268         }
6269         if (link)
6270                 io_queue_link_head(link, &state.comp);
6271         io_submit_state_end(&state);
6272
6273          /* Commit SQ ring head once we've consumed and submitted all SQEs */
6274         io_commit_sqring(ctx);
6275
6276         return submitted;
6277 }
6278
6279 static int io_sq_thread(void *data)
6280 {
6281         struct io_ring_ctx *ctx = data;
6282         const struct cred *old_cred;
6283         DEFINE_WAIT(wait);
6284         unsigned long timeout;
6285         int ret = 0;
6286
6287         complete(&ctx->sq_thread_comp);
6288
6289         old_cred = override_creds(ctx->creds);
6290
6291         timeout = jiffies + ctx->sq_thread_idle;
6292         while (!kthread_should_park()) {
6293                 unsigned int to_submit;
6294
6295                 if (!list_empty(&ctx->poll_list)) {
6296                         unsigned nr_events = 0;
6297
6298                         mutex_lock(&ctx->uring_lock);
6299                         if (!list_empty(&ctx->poll_list))
6300                                 io_iopoll_getevents(ctx, &nr_events, 0);
6301                         else
6302                                 timeout = jiffies + ctx->sq_thread_idle;
6303                         mutex_unlock(&ctx->uring_lock);
6304                 }
6305
6306                 to_submit = io_sqring_entries(ctx);
6307
6308                 /*
6309                  * If submit got -EBUSY, flag us as needing the application
6310                  * to enter the kernel to reap and flush events.
6311                  */
6312                 if (!to_submit || ret == -EBUSY) {
6313                         /*
6314                          * Drop cur_mm before scheduling, we can't hold it for
6315                          * long periods (or over schedule()). Do this before
6316                          * adding ourselves to the waitqueue, as the unuse/drop
6317                          * may sleep.
6318                          */
6319                         io_sq_thread_drop_mm(ctx);
6320
6321                         /*
6322                          * We're polling. If we're within the defined idle
6323                          * period, then let us spin without work before going
6324                          * to sleep. The exception is if we got EBUSY doing
6325                          * more IO, we should wait for the application to
6326                          * reap events and wake us up.
6327                          */
6328                         if (!list_empty(&ctx->poll_list) ||
6329                             (!time_after(jiffies, timeout) && ret != -EBUSY &&
6330                             !percpu_ref_is_dying(&ctx->refs))) {
6331                                 if (current->task_works)
6332                                         task_work_run();
6333                                 cond_resched();
6334                                 continue;
6335                         }
6336
6337                         prepare_to_wait(&ctx->sqo_wait, &wait,
6338                                                 TASK_INTERRUPTIBLE);
6339
6340                         /*
6341                          * While doing polled IO, before going to sleep, we need
6342                          * to check if there are new reqs added to poll_list, it
6343                          * is because reqs may have been punted to io worker and
6344                          * will be added to poll_list later, hence check the
6345                          * poll_list again.
6346                          */
6347                         if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6348                             !list_empty_careful(&ctx->poll_list)) {
6349                                 finish_wait(&ctx->sqo_wait, &wait);
6350                                 continue;
6351                         }
6352
6353                         /* Tell userspace we may need a wakeup call */
6354                         ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6355                         /* make sure to read SQ tail after writing flags */
6356                         smp_mb();
6357
6358                         to_submit = io_sqring_entries(ctx);
6359                         if (!to_submit || ret == -EBUSY) {
6360                                 if (kthread_should_park()) {
6361                                         finish_wait(&ctx->sqo_wait, &wait);
6362                                         break;
6363                                 }
6364                                 if (current->task_works) {
6365                                         task_work_run();
6366                                         finish_wait(&ctx->sqo_wait, &wait);
6367                                         continue;
6368                                 }
6369                                 if (signal_pending(current))
6370                                         flush_signals(current);
6371                                 schedule();
6372                                 finish_wait(&ctx->sqo_wait, &wait);
6373
6374                                 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6375                                 ret = 0;
6376                                 continue;
6377                         }
6378                         finish_wait(&ctx->sqo_wait, &wait);
6379
6380                         ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6381                 }
6382
6383                 mutex_lock(&ctx->uring_lock);
6384                 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6385                         ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6386                 mutex_unlock(&ctx->uring_lock);
6387                 timeout = jiffies + ctx->sq_thread_idle;
6388         }
6389
6390         if (current->task_works)
6391                 task_work_run();
6392
6393         io_sq_thread_drop_mm(ctx);
6394         revert_creds(old_cred);
6395
6396         kthread_parkme();
6397
6398         return 0;
6399 }
6400
6401 struct io_wait_queue {
6402         struct wait_queue_entry wq;
6403         struct io_ring_ctx *ctx;
6404         unsigned to_wait;
6405         unsigned nr_timeouts;
6406 };
6407
6408 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6409 {
6410         struct io_ring_ctx *ctx = iowq->ctx;
6411
6412         /*
6413          * Wake up if we have enough events, or if a timeout occurred since we
6414          * started waiting. For timeouts, we always want to return to userspace,
6415          * regardless of event count.
6416          */
6417         return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6418                         atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6419 }
6420
6421 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6422                             int wake_flags, void *key)
6423 {
6424         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6425                                                         wq);
6426
6427         /* use noflush == true, as we can't safely rely on locking context */
6428         if (!io_should_wake(iowq, true))
6429                 return -1;
6430
6431         return autoremove_wake_function(curr, mode, wake_flags, key);
6432 }
6433
6434 /*
6435  * Wait until events become available, if we don't already have some. The
6436  * application must reap them itself, as they reside on the shared cq ring.
6437  */
6438 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6439                           const sigset_t __user *sig, size_t sigsz)
6440 {
6441         struct io_wait_queue iowq = {
6442                 .wq = {
6443                         .private        = current,
6444                         .func           = io_wake_function,
6445                         .entry          = LIST_HEAD_INIT(iowq.wq.entry),
6446                 },
6447                 .ctx            = ctx,
6448                 .to_wait        = min_events,
6449         };
6450         struct io_rings *rings = ctx->rings;
6451         int ret = 0;
6452
6453         do {
6454                 if (io_cqring_events(ctx, false) >= min_events)
6455                         return 0;
6456                 if (!current->task_works)
6457                         break;
6458                 task_work_run();
6459         } while (1);
6460
6461         if (sig) {
6462 #ifdef CONFIG_COMPAT
6463                 if (in_compat_syscall())
6464                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6465                                                       sigsz);
6466                 else
6467 #endif
6468                         ret = set_user_sigmask(sig, sigsz);
6469
6470                 if (ret)
6471                         return ret;
6472         }
6473
6474         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6475         trace_io_uring_cqring_wait(ctx, min_events);
6476         do {
6477                 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6478                                                 TASK_INTERRUPTIBLE);
6479                 if (current->task_works)
6480                         task_work_run();
6481                 if (io_should_wake(&iowq, false))
6482                         break;
6483                 schedule();
6484                 if (signal_pending(current)) {
6485                         ret = -EINTR;
6486                         break;
6487                 }
6488         } while (1);
6489         finish_wait(&ctx->wait, &iowq.wq);
6490
6491         restore_saved_sigmask_unless(ret == -EINTR);
6492
6493         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6494 }
6495
6496 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6497 {
6498 #if defined(CONFIG_UNIX)
6499         if (ctx->ring_sock) {
6500                 struct sock *sock = ctx->ring_sock->sk;
6501                 struct sk_buff *skb;
6502
6503                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6504                         kfree_skb(skb);
6505         }
6506 #else
6507         int i;
6508
6509         for (i = 0; i < ctx->nr_user_files; i++) {
6510                 struct file *file;
6511
6512                 file = io_file_from_index(ctx, i);
6513                 if (file)
6514                         fput(file);
6515         }
6516 #endif
6517 }
6518
6519 static void io_file_ref_kill(struct percpu_ref *ref)
6520 {
6521         struct fixed_file_data *data;
6522
6523         data = container_of(ref, struct fixed_file_data, refs);
6524         complete(&data->done);
6525 }
6526
6527 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6528 {
6529         struct fixed_file_data *data = ctx->file_data;
6530         struct fixed_file_ref_node *ref_node = NULL;
6531         unsigned nr_tables, i;
6532
6533         if (!data)
6534                 return -ENXIO;
6535
6536         spin_lock(&data->lock);
6537         if (!list_empty(&data->ref_list))
6538                 ref_node = list_first_entry(&data->ref_list,
6539                                 struct fixed_file_ref_node, node);
6540         spin_unlock(&data->lock);
6541         if (ref_node)
6542                 percpu_ref_kill(&ref_node->refs);
6543
6544         percpu_ref_kill(&data->refs);
6545
6546         /* wait for all refs nodes to complete */
6547         flush_delayed_work(&ctx->file_put_work);
6548         wait_for_completion(&data->done);
6549
6550         __io_sqe_files_unregister(ctx);
6551         nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6552         for (i = 0; i < nr_tables; i++)
6553                 kfree(data->table[i].files);
6554         kfree(data->table);
6555         percpu_ref_exit(&data->refs);
6556         kfree(data);
6557         ctx->file_data = NULL;
6558         ctx->nr_user_files = 0;
6559         return 0;
6560 }
6561
6562 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6563 {
6564         if (ctx->sqo_thread) {
6565                 wait_for_completion(&ctx->sq_thread_comp);
6566                 /*
6567                  * The park is a bit of a work-around, without it we get
6568                  * warning spews on shutdown with SQPOLL set and affinity
6569                  * set to a single CPU.
6570                  */
6571                 kthread_park(ctx->sqo_thread);
6572                 kthread_stop(ctx->sqo_thread);
6573                 ctx->sqo_thread = NULL;
6574         }
6575 }
6576
6577 static void io_finish_async(struct io_ring_ctx *ctx)
6578 {
6579         io_sq_thread_stop(ctx);
6580
6581         if (ctx->io_wq) {
6582                 io_wq_destroy(ctx->io_wq);
6583                 ctx->io_wq = NULL;
6584         }
6585 }
6586
6587 #if defined(CONFIG_UNIX)
6588 /*
6589  * Ensure the UNIX gc is aware of our file set, so we are certain that
6590  * the io_uring can be safely unregistered on process exit, even if we have
6591  * loops in the file referencing.
6592  */
6593 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6594 {
6595         struct sock *sk = ctx->ring_sock->sk;
6596         struct scm_fp_list *fpl;
6597         struct sk_buff *skb;
6598         int i, nr_files;
6599
6600         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6601         if (!fpl)
6602                 return -ENOMEM;
6603
6604         skb = alloc_skb(0, GFP_KERNEL);
6605         if (!skb) {
6606                 kfree(fpl);
6607                 return -ENOMEM;
6608         }
6609
6610         skb->sk = sk;
6611
6612         nr_files = 0;
6613         fpl->user = get_uid(ctx->user);
6614         for (i = 0; i < nr; i++) {
6615                 struct file *file = io_file_from_index(ctx, i + offset);
6616
6617                 if (!file)
6618                         continue;
6619                 fpl->fp[nr_files] = get_file(file);
6620                 unix_inflight(fpl->user, fpl->fp[nr_files]);
6621                 nr_files++;
6622         }
6623
6624         if (nr_files) {
6625                 fpl->max = SCM_MAX_FD;
6626                 fpl->count = nr_files;
6627                 UNIXCB(skb).fp = fpl;
6628                 skb->destructor = unix_destruct_scm;
6629                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6630                 skb_queue_head(&sk->sk_receive_queue, skb);
6631
6632                 for (i = 0; i < nr_files; i++)
6633                         fput(fpl->fp[i]);
6634         } else {
6635                 kfree_skb(skb);
6636                 kfree(fpl);
6637         }
6638
6639         return 0;
6640 }
6641
6642 /*
6643  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6644  * causes regular reference counting to break down. We rely on the UNIX
6645  * garbage collection to take care of this problem for us.
6646  */
6647 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6648 {
6649         unsigned left, total;
6650         int ret = 0;
6651
6652         total = 0;
6653         left = ctx->nr_user_files;
6654         while (left) {
6655                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6656
6657                 ret = __io_sqe_files_scm(ctx, this_files, total);
6658                 if (ret)
6659                         break;
6660                 left -= this_files;
6661                 total += this_files;
6662         }
6663
6664         if (!ret)
6665                 return 0;
6666
6667         while (total < ctx->nr_user_files) {
6668                 struct file *file = io_file_from_index(ctx, total);
6669
6670                 if (file)
6671                         fput(file);
6672                 total++;
6673         }
6674
6675         return ret;
6676 }
6677 #else
6678 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6679 {
6680         return 0;
6681 }
6682 #endif
6683
6684 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6685                                     unsigned nr_files)
6686 {
6687         int i;
6688
6689         for (i = 0; i < nr_tables; i++) {
6690                 struct fixed_file_table *table = &ctx->file_data->table[i];
6691                 unsigned this_files;
6692
6693                 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6694                 table->files = kcalloc(this_files, sizeof(struct file *),
6695                                         GFP_KERNEL);
6696                 if (!table->files)
6697                         break;
6698                 nr_files -= this_files;
6699         }
6700
6701         if (i == nr_tables)
6702                 return 0;
6703
6704         for (i = 0; i < nr_tables; i++) {
6705                 struct fixed_file_table *table = &ctx->file_data->table[i];
6706                 kfree(table->files);
6707         }
6708         return 1;
6709 }
6710
6711 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6712 {
6713 #if defined(CONFIG_UNIX)
6714         struct sock *sock = ctx->ring_sock->sk;
6715         struct sk_buff_head list, *head = &sock->sk_receive_queue;
6716         struct sk_buff *skb;
6717         int i;
6718
6719         __skb_queue_head_init(&list);
6720
6721         /*
6722          * Find the skb that holds this file in its SCM_RIGHTS. When found,
6723          * remove this entry and rearrange the file array.
6724          */
6725         skb = skb_dequeue(head);
6726         while (skb) {
6727                 struct scm_fp_list *fp;
6728
6729                 fp = UNIXCB(skb).fp;
6730                 for (i = 0; i < fp->count; i++) {
6731                         int left;
6732
6733                         if (fp->fp[i] != file)
6734                                 continue;
6735
6736                         unix_notinflight(fp->user, fp->fp[i]);
6737                         left = fp->count - 1 - i;
6738                         if (left) {
6739                                 memmove(&fp->fp[i], &fp->fp[i + 1],
6740                                                 left * sizeof(struct file *));
6741                         }
6742                         fp->count--;
6743                         if (!fp->count) {
6744                                 kfree_skb(skb);
6745                                 skb = NULL;
6746                         } else {
6747                                 __skb_queue_tail(&list, skb);
6748                         }
6749                         fput(file);
6750                         file = NULL;
6751                         break;
6752                 }
6753
6754                 if (!file)
6755                         break;
6756
6757                 __skb_queue_tail(&list, skb);
6758
6759                 skb = skb_dequeue(head);
6760         }
6761
6762         if (skb_peek(&list)) {
6763                 spin_lock_irq(&head->lock);
6764                 while ((skb = __skb_dequeue(&list)) != NULL)
6765                         __skb_queue_tail(head, skb);
6766                 spin_unlock_irq(&head->lock);
6767         }
6768 #else
6769         fput(file);
6770 #endif
6771 }
6772
6773 struct io_file_put {
6774         struct list_head list;
6775         struct file *file;
6776 };
6777
6778 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6779 {
6780         struct fixed_file_data *file_data = ref_node->file_data;
6781         struct io_ring_ctx *ctx = file_data->ctx;
6782         struct io_file_put *pfile, *tmp;
6783
6784         list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6785                 list_del(&pfile->list);
6786                 io_ring_file_put(ctx, pfile->file);
6787                 kfree(pfile);
6788         }
6789
6790         spin_lock(&file_data->lock);
6791         list_del(&ref_node->node);
6792         spin_unlock(&file_data->lock);
6793
6794         percpu_ref_exit(&ref_node->refs);
6795         kfree(ref_node);
6796         percpu_ref_put(&file_data->refs);
6797 }
6798
6799 static void io_file_put_work(struct work_struct *work)
6800 {
6801         struct io_ring_ctx *ctx;
6802         struct llist_node *node;
6803
6804         ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6805         node = llist_del_all(&ctx->file_put_llist);
6806
6807         while (node) {
6808                 struct fixed_file_ref_node *ref_node;
6809                 struct llist_node *next = node->next;
6810
6811                 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6812                 __io_file_put_work(ref_node);
6813                 node = next;
6814         }
6815 }
6816
6817 static void io_file_data_ref_zero(struct percpu_ref *ref)
6818 {
6819         struct fixed_file_ref_node *ref_node;
6820         struct io_ring_ctx *ctx;
6821         bool first_add;
6822         int delay = HZ;
6823
6824         ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6825         ctx = ref_node->file_data->ctx;
6826
6827         if (percpu_ref_is_dying(&ctx->file_data->refs))
6828                 delay = 0;
6829
6830         first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6831         if (!delay)
6832                 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6833         else if (first_add)
6834                 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6835 }
6836
6837 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6838                         struct io_ring_ctx *ctx)
6839 {
6840         struct fixed_file_ref_node *ref_node;
6841
6842         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6843         if (!ref_node)
6844                 return ERR_PTR(-ENOMEM);
6845
6846         if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6847                             0, GFP_KERNEL)) {
6848                 kfree(ref_node);
6849                 return ERR_PTR(-ENOMEM);
6850         }
6851         INIT_LIST_HEAD(&ref_node->node);
6852         INIT_LIST_HEAD(&ref_node->file_list);
6853         ref_node->file_data = ctx->file_data;
6854         return ref_node;
6855 }
6856
6857 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6858 {
6859         percpu_ref_exit(&ref_node->refs);
6860         kfree(ref_node);
6861 }
6862
6863 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6864                                  unsigned nr_args)
6865 {
6866         __s32 __user *fds = (__s32 __user *) arg;
6867         unsigned nr_tables;
6868         struct file *file;
6869         int fd, ret = 0;
6870         unsigned i;
6871         struct fixed_file_ref_node *ref_node;
6872
6873         if (ctx->file_data)
6874                 return -EBUSY;
6875         if (!nr_args)
6876                 return -EINVAL;
6877         if (nr_args > IORING_MAX_FIXED_FILES)
6878                 return -EMFILE;
6879
6880         ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6881         if (!ctx->file_data)
6882                 return -ENOMEM;
6883         ctx->file_data->ctx = ctx;
6884         init_completion(&ctx->file_data->done);
6885         INIT_LIST_HEAD(&ctx->file_data->ref_list);
6886         spin_lock_init(&ctx->file_data->lock);
6887
6888         nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6889         ctx->file_data->table = kcalloc(nr_tables,
6890                                         sizeof(struct fixed_file_table),
6891                                         GFP_KERNEL);
6892         if (!ctx->file_data->table) {
6893                 kfree(ctx->file_data);
6894                 ctx->file_data = NULL;
6895                 return -ENOMEM;
6896         }
6897
6898         if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6899                                 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6900                 kfree(ctx->file_data->table);
6901                 kfree(ctx->file_data);
6902                 ctx->file_data = NULL;
6903                 return -ENOMEM;
6904         }
6905
6906         if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6907                 percpu_ref_exit(&ctx->file_data->refs);
6908                 kfree(ctx->file_data->table);
6909                 kfree(ctx->file_data);
6910                 ctx->file_data = NULL;
6911                 return -ENOMEM;
6912         }
6913
6914         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6915                 struct fixed_file_table *table;
6916                 unsigned index;
6917
6918                 ret = -EFAULT;
6919                 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6920                         break;
6921                 /* allow sparse sets */
6922                 if (fd == -1) {
6923                         ret = 0;
6924                         continue;
6925                 }
6926
6927                 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6928                 index = i & IORING_FILE_TABLE_MASK;
6929                 file = fget(fd);
6930
6931                 ret = -EBADF;
6932                 if (!file)
6933                         break;
6934
6935                 /*
6936                  * Don't allow io_uring instances to be registered. If UNIX
6937                  * isn't enabled, then this causes a reference cycle and this
6938                  * instance can never get freed. If UNIX is enabled we'll
6939                  * handle it just fine, but there's still no point in allowing
6940                  * a ring fd as it doesn't support regular read/write anyway.
6941                  */
6942                 if (file->f_op == &io_uring_fops) {
6943                         fput(file);
6944                         break;
6945                 }
6946                 ret = 0;
6947                 table->files[index] = file;
6948         }
6949
6950         if (ret) {
6951                 for (i = 0; i < ctx->nr_user_files; i++) {
6952                         file = io_file_from_index(ctx, i);
6953                         if (file)
6954                                 fput(file);
6955                 }
6956                 for (i = 0; i < nr_tables; i++)
6957                         kfree(ctx->file_data->table[i].files);
6958
6959                 kfree(ctx->file_data->table);
6960                 kfree(ctx->file_data);
6961                 ctx->file_data = NULL;
6962                 ctx->nr_user_files = 0;
6963                 return ret;
6964         }
6965
6966         ret = io_sqe_files_scm(ctx);
6967         if (ret) {
6968                 io_sqe_files_unregister(ctx);
6969                 return ret;
6970         }
6971
6972         ref_node = alloc_fixed_file_ref_node(ctx);
6973         if (IS_ERR(ref_node)) {
6974                 io_sqe_files_unregister(ctx);
6975                 return PTR_ERR(ref_node);
6976         }
6977
6978         ctx->file_data->cur_refs = &ref_node->refs;
6979         spin_lock(&ctx->file_data->lock);
6980         list_add(&ref_node->node, &ctx->file_data->ref_list);
6981         spin_unlock(&ctx->file_data->lock);
6982         percpu_ref_get(&ctx->file_data->refs);
6983         return ret;
6984 }
6985
6986 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
6987                                 int index)
6988 {
6989 #if defined(CONFIG_UNIX)
6990         struct sock *sock = ctx->ring_sock->sk;
6991         struct sk_buff_head *head = &sock->sk_receive_queue;
6992         struct sk_buff *skb;
6993
6994         /*
6995          * See if we can merge this file into an existing skb SCM_RIGHTS
6996          * file set. If there's no room, fall back to allocating a new skb
6997          * and filling it in.
6998          */
6999         spin_lock_irq(&head->lock);
7000         skb = skb_peek(head);
7001         if (skb) {
7002                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7003
7004                 if (fpl->count < SCM_MAX_FD) {
7005                         __skb_unlink(skb, head);
7006                         spin_unlock_irq(&head->lock);
7007                         fpl->fp[fpl->count] = get_file(file);
7008                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
7009                         fpl->count++;
7010                         spin_lock_irq(&head->lock);
7011                         __skb_queue_head(head, skb);
7012                 } else {
7013                         skb = NULL;
7014                 }
7015         }
7016         spin_unlock_irq(&head->lock);
7017
7018         if (skb) {
7019                 fput(file);
7020                 return 0;
7021         }
7022
7023         return __io_sqe_files_scm(ctx, 1, index);
7024 #else
7025         return 0;
7026 #endif
7027 }
7028
7029 static int io_queue_file_removal(struct fixed_file_data *data,
7030                                  struct file *file)
7031 {
7032         struct io_file_put *pfile;
7033         struct percpu_ref *refs = data->cur_refs;
7034         struct fixed_file_ref_node *ref_node;
7035
7036         pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7037         if (!pfile)
7038                 return -ENOMEM;
7039
7040         ref_node = container_of(refs, struct fixed_file_ref_node, refs);
7041         pfile->file = file;
7042         list_add(&pfile->list, &ref_node->file_list);
7043
7044         return 0;
7045 }
7046
7047 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7048                                  struct io_uring_files_update *up,
7049                                  unsigned nr_args)
7050 {
7051         struct fixed_file_data *data = ctx->file_data;
7052         struct fixed_file_ref_node *ref_node;
7053         struct file *file;
7054         __s32 __user *fds;
7055         int fd, i, err;
7056         __u32 done;
7057         bool needs_switch = false;
7058
7059         if (check_add_overflow(up->offset, nr_args, &done))
7060                 return -EOVERFLOW;
7061         if (done > ctx->nr_user_files)
7062                 return -EINVAL;
7063
7064         ref_node = alloc_fixed_file_ref_node(ctx);
7065         if (IS_ERR(ref_node))
7066                 return PTR_ERR(ref_node);
7067
7068         done = 0;
7069         fds = u64_to_user_ptr(up->fds);
7070         while (nr_args) {
7071                 struct fixed_file_table *table;
7072                 unsigned index;
7073
7074                 err = 0;
7075                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7076                         err = -EFAULT;
7077                         break;
7078                 }
7079                 i = array_index_nospec(up->offset, ctx->nr_user_files);
7080                 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7081                 index = i & IORING_FILE_TABLE_MASK;
7082                 if (table->files[index]) {
7083                         file = io_file_from_index(ctx, index);
7084                         err = io_queue_file_removal(data, file);
7085                         if (err)
7086                                 break;
7087                         table->files[index] = NULL;
7088                         needs_switch = true;
7089                 }
7090                 if (fd != -1) {
7091                         file = fget(fd);
7092                         if (!file) {
7093                                 err = -EBADF;
7094                                 break;
7095                         }
7096                         /*
7097                          * Don't allow io_uring instances to be registered. If
7098                          * UNIX isn't enabled, then this causes a reference
7099                          * cycle and this instance can never get freed. If UNIX
7100                          * is enabled we'll handle it just fine, but there's
7101                          * still no point in allowing a ring fd as it doesn't
7102                          * support regular read/write anyway.
7103                          */
7104                         if (file->f_op == &io_uring_fops) {
7105                                 fput(file);
7106                                 err = -EBADF;
7107                                 break;
7108                         }
7109                         table->files[index] = file;
7110                         err = io_sqe_file_register(ctx, file, i);
7111                         if (err)
7112                                 break;
7113                 }
7114                 nr_args--;
7115                 done++;
7116                 up->offset++;
7117         }
7118
7119         if (needs_switch) {
7120                 percpu_ref_kill(data->cur_refs);
7121                 spin_lock(&data->lock);
7122                 list_add(&ref_node->node, &data->ref_list);
7123                 data->cur_refs = &ref_node->refs;
7124                 spin_unlock(&data->lock);
7125                 percpu_ref_get(&ctx->file_data->refs);
7126         } else
7127                 destroy_fixed_file_ref_node(ref_node);
7128
7129         return done ? done : err;
7130 }
7131
7132 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7133                                unsigned nr_args)
7134 {
7135         struct io_uring_files_update up;
7136
7137         if (!ctx->file_data)
7138                 return -ENXIO;
7139         if (!nr_args)
7140                 return -EINVAL;
7141         if (copy_from_user(&up, arg, sizeof(up)))
7142                 return -EFAULT;
7143         if (up.resv)
7144                 return -EINVAL;
7145
7146         return __io_sqe_files_update(ctx, &up, nr_args);
7147 }
7148
7149 static void io_free_work(struct io_wq_work *work)
7150 {
7151         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7152
7153         /* Consider that io_steal_work() relies on this ref */
7154         io_put_req(req);
7155 }
7156
7157 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7158                               struct io_uring_params *p)
7159 {
7160         struct io_wq_data data;
7161         struct fd f;
7162         struct io_ring_ctx *ctx_attach;
7163         unsigned int concurrency;
7164         int ret = 0;
7165
7166         data.user = ctx->user;
7167         data.free_work = io_free_work;
7168         data.do_work = io_wq_submit_work;
7169
7170         if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7171                 /* Do QD, or 4 * CPUS, whatever is smallest */
7172                 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7173
7174                 ctx->io_wq = io_wq_create(concurrency, &data);
7175                 if (IS_ERR(ctx->io_wq)) {
7176                         ret = PTR_ERR(ctx->io_wq);
7177                         ctx->io_wq = NULL;
7178                 }
7179                 return ret;
7180         }
7181
7182         f = fdget(p->wq_fd);
7183         if (!f.file)
7184                 return -EBADF;
7185
7186         if (f.file->f_op != &io_uring_fops) {
7187                 ret = -EINVAL;
7188                 goto out_fput;
7189         }
7190
7191         ctx_attach = f.file->private_data;
7192         /* @io_wq is protected by holding the fd */
7193         if (!io_wq_get(ctx_attach->io_wq, &data)) {
7194                 ret = -EINVAL;
7195                 goto out_fput;
7196         }
7197
7198         ctx->io_wq = ctx_attach->io_wq;
7199 out_fput:
7200         fdput(f);
7201         return ret;
7202 }
7203
7204 static int io_sq_offload_start(struct io_ring_ctx *ctx,
7205                                struct io_uring_params *p)
7206 {
7207         int ret;
7208
7209         mmgrab(current->mm);
7210         ctx->sqo_mm = current->mm;
7211
7212         if (ctx->flags & IORING_SETUP_SQPOLL) {
7213                 ret = -EPERM;
7214                 if (!capable(CAP_SYS_ADMIN))
7215                         goto err;
7216
7217                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7218                 if (!ctx->sq_thread_idle)
7219                         ctx->sq_thread_idle = HZ;
7220
7221                 if (p->flags & IORING_SETUP_SQ_AFF) {
7222                         int cpu = p->sq_thread_cpu;
7223
7224                         ret = -EINVAL;
7225                         if (cpu >= nr_cpu_ids)
7226                                 goto err;
7227                         if (!cpu_online(cpu))
7228                                 goto err;
7229
7230                         ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7231                                                         ctx, cpu,
7232                                                         "io_uring-sq");
7233                 } else {
7234                         ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7235                                                         "io_uring-sq");
7236                 }
7237                 if (IS_ERR(ctx->sqo_thread)) {
7238                         ret = PTR_ERR(ctx->sqo_thread);
7239                         ctx->sqo_thread = NULL;
7240                         goto err;
7241                 }
7242                 wake_up_process(ctx->sqo_thread);
7243         } else if (p->flags & IORING_SETUP_SQ_AFF) {
7244                 /* Can't have SQ_AFF without SQPOLL */
7245                 ret = -EINVAL;
7246                 goto err;
7247         }
7248
7249         ret = io_init_wq_offload(ctx, p);
7250         if (ret)
7251                 goto err;
7252
7253         return 0;
7254 err:
7255         io_finish_async(ctx);
7256         mmdrop(ctx->sqo_mm);
7257         ctx->sqo_mm = NULL;
7258         return ret;
7259 }
7260
7261 static inline void __io_unaccount_mem(struct user_struct *user,
7262                                       unsigned long nr_pages)
7263 {
7264         atomic_long_sub(nr_pages, &user->locked_vm);
7265 }
7266
7267 static inline int __io_account_mem(struct user_struct *user,
7268                                    unsigned long nr_pages)
7269 {
7270         unsigned long page_limit, cur_pages, new_pages;
7271
7272         /* Don't allow more pages than we can safely lock */
7273         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7274
7275         do {
7276                 cur_pages = atomic_long_read(&user->locked_vm);
7277                 new_pages = cur_pages + nr_pages;
7278                 if (new_pages > page_limit)
7279                         return -ENOMEM;
7280         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7281                                         new_pages) != cur_pages);
7282
7283         return 0;
7284 }
7285
7286 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7287                              enum io_mem_account acct)
7288 {
7289         if (ctx->limit_mem)
7290                 __io_unaccount_mem(ctx->user, nr_pages);
7291
7292         if (ctx->sqo_mm) {
7293                 if (acct == ACCT_LOCKED)
7294                         ctx->sqo_mm->locked_vm -= nr_pages;
7295                 else if (acct == ACCT_PINNED)
7296                         atomic64_sub(nr_pages, &ctx->sqo_mm->pinned_vm);
7297         }
7298 }
7299
7300 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7301                           enum io_mem_account acct)
7302 {
7303         int ret;
7304
7305         if (ctx->limit_mem) {
7306                 ret = __io_account_mem(ctx->user, nr_pages);
7307                 if (ret)
7308                         return ret;
7309         }
7310
7311         if (ctx->sqo_mm) {
7312                 if (acct == ACCT_LOCKED)
7313                         ctx->sqo_mm->locked_vm += nr_pages;
7314                 else if (acct == ACCT_PINNED)
7315                         atomic64_add(nr_pages, &ctx->sqo_mm->pinned_vm);
7316         }
7317
7318         return 0;
7319 }
7320
7321 static void io_mem_free(void *ptr)
7322 {
7323         struct page *page;
7324
7325         if (!ptr)
7326                 return;
7327
7328         page = virt_to_head_page(ptr);
7329         if (put_page_testzero(page))
7330                 free_compound_page(page);
7331 }
7332
7333 static void *io_mem_alloc(size_t size)
7334 {
7335         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7336                                 __GFP_NORETRY;
7337
7338         return (void *) __get_free_pages(gfp_flags, get_order(size));
7339 }
7340
7341 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7342                                 size_t *sq_offset)
7343 {
7344         struct io_rings *rings;
7345         size_t off, sq_array_size;
7346
7347         off = struct_size(rings, cqes, cq_entries);
7348         if (off == SIZE_MAX)
7349                 return SIZE_MAX;
7350
7351 #ifdef CONFIG_SMP
7352         off = ALIGN(off, SMP_CACHE_BYTES);
7353         if (off == 0)
7354                 return SIZE_MAX;
7355 #endif
7356
7357         sq_array_size = array_size(sizeof(u32), sq_entries);
7358         if (sq_array_size == SIZE_MAX)
7359                 return SIZE_MAX;
7360
7361         if (check_add_overflow(off, sq_array_size, &off))
7362                 return SIZE_MAX;
7363
7364         if (sq_offset)
7365                 *sq_offset = off;
7366
7367         return off;
7368 }
7369
7370 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7371 {
7372         size_t pages;
7373
7374         pages = (size_t)1 << get_order(
7375                 rings_size(sq_entries, cq_entries, NULL));
7376         pages += (size_t)1 << get_order(
7377                 array_size(sizeof(struct io_uring_sqe), sq_entries));
7378
7379         return pages;
7380 }
7381
7382 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7383 {
7384         int i, j;
7385
7386         if (!ctx->user_bufs)
7387                 return -ENXIO;
7388
7389         for (i = 0; i < ctx->nr_user_bufs; i++) {
7390                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7391
7392                 for (j = 0; j < imu->nr_bvecs; j++)
7393                         unpin_user_page(imu->bvec[j].bv_page);
7394
7395                 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
7396                 kvfree(imu->bvec);
7397                 imu->nr_bvecs = 0;
7398         }
7399
7400         kfree(ctx->user_bufs);
7401         ctx->user_bufs = NULL;
7402         ctx->nr_user_bufs = 0;
7403         return 0;
7404 }
7405
7406 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7407                        void __user *arg, unsigned index)
7408 {
7409         struct iovec __user *src;
7410
7411 #ifdef CONFIG_COMPAT
7412         if (ctx->compat) {
7413                 struct compat_iovec __user *ciovs;
7414                 struct compat_iovec ciov;
7415
7416                 ciovs = (struct compat_iovec __user *) arg;
7417                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7418                         return -EFAULT;
7419
7420                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7421                 dst->iov_len = ciov.iov_len;
7422                 return 0;
7423         }
7424 #endif
7425         src = (struct iovec __user *) arg;
7426         if (copy_from_user(dst, &src[index], sizeof(*dst)))
7427                 return -EFAULT;
7428         return 0;
7429 }
7430
7431 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7432                                   unsigned nr_args)
7433 {
7434         struct vm_area_struct **vmas = NULL;
7435         struct page **pages = NULL;
7436         int i, j, got_pages = 0;
7437         int ret = -EINVAL;
7438
7439         if (ctx->user_bufs)
7440                 return -EBUSY;
7441         if (!nr_args || nr_args > UIO_MAXIOV)
7442                 return -EINVAL;
7443
7444         ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7445                                         GFP_KERNEL);
7446         if (!ctx->user_bufs)
7447                 return -ENOMEM;
7448
7449         for (i = 0; i < nr_args; i++) {
7450                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7451                 unsigned long off, start, end, ubuf;
7452                 int pret, nr_pages;
7453                 struct iovec iov;
7454                 size_t size;
7455
7456                 ret = io_copy_iov(ctx, &iov, arg, i);
7457                 if (ret)
7458                         goto err;
7459
7460                 /*
7461                  * Don't impose further limits on the size and buffer
7462                  * constraints here, we'll -EINVAL later when IO is
7463                  * submitted if they are wrong.
7464                  */
7465                 ret = -EFAULT;
7466                 if (!iov.iov_base || !iov.iov_len)
7467                         goto err;
7468
7469                 /* arbitrary limit, but we need something */
7470                 if (iov.iov_len > SZ_1G)
7471                         goto err;
7472
7473                 ubuf = (unsigned long) iov.iov_base;
7474                 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7475                 start = ubuf >> PAGE_SHIFT;
7476                 nr_pages = end - start;
7477
7478                 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
7479                 if (ret)
7480                         goto err;
7481
7482                 ret = 0;
7483                 if (!pages || nr_pages > got_pages) {
7484                         kvfree(vmas);
7485                         kvfree(pages);
7486                         pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7487                                                 GFP_KERNEL);
7488                         vmas = kvmalloc_array(nr_pages,
7489                                         sizeof(struct vm_area_struct *),
7490                                         GFP_KERNEL);
7491                         if (!pages || !vmas) {
7492                                 ret = -ENOMEM;
7493                                 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7494                                 goto err;
7495                         }
7496                         got_pages = nr_pages;
7497                 }
7498
7499                 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7500                                                 GFP_KERNEL);
7501                 ret = -ENOMEM;
7502                 if (!imu->bvec) {
7503                         io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7504                         goto err;
7505                 }
7506
7507                 ret = 0;
7508                 mmap_read_lock(current->mm);
7509                 pret = pin_user_pages(ubuf, nr_pages,
7510                                       FOLL_WRITE | FOLL_LONGTERM,
7511                                       pages, vmas);
7512                 if (pret == nr_pages) {
7513                         /* don't support file backed memory */
7514                         for (j = 0; j < nr_pages; j++) {
7515                                 struct vm_area_struct *vma = vmas[j];
7516
7517                                 if (vma->vm_file &&
7518                                     !is_file_hugepages(vma->vm_file)) {
7519                                         ret = -EOPNOTSUPP;
7520                                         break;
7521                                 }
7522                         }
7523                 } else {
7524                         ret = pret < 0 ? pret : -EFAULT;
7525                 }
7526                 mmap_read_unlock(current->mm);
7527                 if (ret) {
7528                         /*
7529                          * if we did partial map, or found file backed vmas,
7530                          * release any pages we did get
7531                          */
7532                         if (pret > 0)
7533                                 unpin_user_pages(pages, pret);
7534                         io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7535                         kvfree(imu->bvec);
7536                         goto err;
7537                 }
7538
7539                 off = ubuf & ~PAGE_MASK;
7540                 size = iov.iov_len;
7541                 for (j = 0; j < nr_pages; j++) {
7542                         size_t vec_len;
7543
7544                         vec_len = min_t(size_t, size, PAGE_SIZE - off);
7545                         imu->bvec[j].bv_page = pages[j];
7546                         imu->bvec[j].bv_len = vec_len;
7547                         imu->bvec[j].bv_offset = off;
7548                         off = 0;
7549                         size -= vec_len;
7550                 }
7551                 /* store original address for later verification */
7552                 imu->ubuf = ubuf;
7553                 imu->len = iov.iov_len;
7554                 imu->nr_bvecs = nr_pages;
7555
7556                 ctx->nr_user_bufs++;
7557         }
7558         kvfree(pages);
7559         kvfree(vmas);
7560         return 0;
7561 err:
7562         kvfree(pages);
7563         kvfree(vmas);
7564         io_sqe_buffer_unregister(ctx);
7565         return ret;
7566 }
7567
7568 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7569 {
7570         __s32 __user *fds = arg;
7571         int fd;
7572
7573         if (ctx->cq_ev_fd)
7574                 return -EBUSY;
7575
7576         if (copy_from_user(&fd, fds, sizeof(*fds)))
7577                 return -EFAULT;
7578
7579         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7580         if (IS_ERR(ctx->cq_ev_fd)) {
7581                 int ret = PTR_ERR(ctx->cq_ev_fd);
7582                 ctx->cq_ev_fd = NULL;
7583                 return ret;
7584         }
7585
7586         return 0;
7587 }
7588
7589 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7590 {
7591         if (ctx->cq_ev_fd) {
7592                 eventfd_ctx_put(ctx->cq_ev_fd);
7593                 ctx->cq_ev_fd = NULL;
7594                 return 0;
7595         }
7596
7597         return -ENXIO;
7598 }
7599
7600 static int __io_destroy_buffers(int id, void *p, void *data)
7601 {
7602         struct io_ring_ctx *ctx = data;
7603         struct io_buffer *buf = p;
7604
7605         __io_remove_buffers(ctx, buf, id, -1U);
7606         return 0;
7607 }
7608
7609 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7610 {
7611         idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7612         idr_destroy(&ctx->io_buffer_idr);
7613 }
7614
7615 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7616 {
7617         io_finish_async(ctx);
7618         if (ctx->sqo_mm) {
7619                 mmdrop(ctx->sqo_mm);
7620                 ctx->sqo_mm = NULL;
7621         }
7622
7623         io_iopoll_reap_events(ctx);
7624         io_sqe_buffer_unregister(ctx);
7625         io_sqe_files_unregister(ctx);
7626         io_eventfd_unregister(ctx);
7627         io_destroy_buffers(ctx);
7628         idr_destroy(&ctx->personality_idr);
7629
7630 #if defined(CONFIG_UNIX)
7631         if (ctx->ring_sock) {
7632                 ctx->ring_sock->file = NULL; /* so that iput() is called */
7633                 sock_release(ctx->ring_sock);
7634         }
7635 #endif
7636
7637         io_mem_free(ctx->rings);
7638         io_mem_free(ctx->sq_sqes);
7639
7640         percpu_ref_exit(&ctx->refs);
7641         io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
7642                          ACCT_LOCKED);
7643         free_uid(ctx->user);
7644         put_cred(ctx->creds);
7645         kfree(ctx->cancel_hash);
7646         kmem_cache_free(req_cachep, ctx->fallback_req);
7647         kfree(ctx);
7648 }
7649
7650 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7651 {
7652         struct io_ring_ctx *ctx = file->private_data;
7653         __poll_t mask = 0;
7654
7655         poll_wait(file, &ctx->cq_wait, wait);
7656         /*
7657          * synchronizes with barrier from wq_has_sleeper call in
7658          * io_commit_cqring
7659          */
7660         smp_rmb();
7661         if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7662             ctx->rings->sq_ring_entries)
7663                 mask |= EPOLLOUT | EPOLLWRNORM;
7664         if (io_cqring_events(ctx, false))
7665                 mask |= EPOLLIN | EPOLLRDNORM;
7666
7667         return mask;
7668 }
7669
7670 static int io_uring_fasync(int fd, struct file *file, int on)
7671 {
7672         struct io_ring_ctx *ctx = file->private_data;
7673
7674         return fasync_helper(fd, file, on, &ctx->cq_fasync);
7675 }
7676
7677 static int io_remove_personalities(int id, void *p, void *data)
7678 {
7679         struct io_ring_ctx *ctx = data;
7680         const struct cred *cred;
7681
7682         cred = idr_remove(&ctx->personality_idr, id);
7683         if (cred)
7684                 put_cred(cred);
7685         return 0;
7686 }
7687
7688 static void io_ring_exit_work(struct work_struct *work)
7689 {
7690         struct io_ring_ctx *ctx;
7691
7692         ctx = container_of(work, struct io_ring_ctx, exit_work);
7693         if (ctx->rings)
7694                 io_cqring_overflow_flush(ctx, true);
7695
7696         /*
7697          * If we're doing polled IO and end up having requests being
7698          * submitted async (out-of-line), then completions can come in while
7699          * we're waiting for refs to drop. We need to reap these manually,
7700          * as nobody else will be looking for them.
7701          */
7702         while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20)) {
7703                 io_iopoll_reap_events(ctx);
7704                 if (ctx->rings)
7705                         io_cqring_overflow_flush(ctx, true);
7706         }
7707         io_ring_ctx_free(ctx);
7708 }
7709
7710 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7711 {
7712         mutex_lock(&ctx->uring_lock);
7713         percpu_ref_kill(&ctx->refs);
7714         mutex_unlock(&ctx->uring_lock);
7715
7716         io_kill_timeouts(ctx);
7717         io_poll_remove_all(ctx);
7718
7719         if (ctx->io_wq)
7720                 io_wq_cancel_all(ctx->io_wq);
7721
7722         io_iopoll_reap_events(ctx);
7723         /* if we failed setting up the ctx, we might not have any rings */
7724         if (ctx->rings)
7725                 io_cqring_overflow_flush(ctx, true);
7726         idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7727         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7728         queue_work(system_wq, &ctx->exit_work);
7729 }
7730
7731 static int io_uring_release(struct inode *inode, struct file *file)
7732 {
7733         struct io_ring_ctx *ctx = file->private_data;
7734
7735         file->private_data = NULL;
7736         io_ring_ctx_wait_and_kill(ctx);
7737         return 0;
7738 }
7739
7740 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7741 {
7742         struct files_struct *files = data;
7743
7744         return work->files == files;
7745 }
7746
7747 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7748                                   struct files_struct *files)
7749 {
7750         if (list_empty_careful(&ctx->inflight_list))
7751                 return;
7752
7753         /* cancel all at once, should be faster than doing it one by one*/
7754         io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7755
7756         while (!list_empty_careful(&ctx->inflight_list)) {
7757                 struct io_kiocb *cancel_req = NULL, *req;
7758                 DEFINE_WAIT(wait);
7759
7760                 spin_lock_irq(&ctx->inflight_lock);
7761                 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7762                         if (req->work.files != files)
7763                                 continue;
7764                         /* req is being completed, ignore */
7765                         if (!refcount_inc_not_zero(&req->refs))
7766                                 continue;
7767                         cancel_req = req;
7768                         break;
7769                 }
7770                 if (cancel_req)
7771                         prepare_to_wait(&ctx->inflight_wait, &wait,
7772                                                 TASK_UNINTERRUPTIBLE);
7773                 spin_unlock_irq(&ctx->inflight_lock);
7774
7775                 /* We need to keep going until we don't find a matching req */
7776                 if (!cancel_req)
7777                         break;
7778
7779                 if (cancel_req->flags & REQ_F_OVERFLOW) {
7780                         spin_lock_irq(&ctx->completion_lock);
7781                         list_del(&cancel_req->list);
7782                         cancel_req->flags &= ~REQ_F_OVERFLOW;
7783                         if (list_empty(&ctx->cq_overflow_list)) {
7784                                 clear_bit(0, &ctx->sq_check_overflow);
7785                                 clear_bit(0, &ctx->cq_check_overflow);
7786                         }
7787                         spin_unlock_irq(&ctx->completion_lock);
7788
7789                         WRITE_ONCE(ctx->rings->cq_overflow,
7790                                 atomic_inc_return(&ctx->cached_cq_overflow));
7791
7792                         /*
7793                          * Put inflight ref and overflow ref. If that's
7794                          * all we had, then we're done with this request.
7795                          */
7796                         if (refcount_sub_and_test(2, &cancel_req->refs)) {
7797                                 io_free_req(cancel_req);
7798                                 finish_wait(&ctx->inflight_wait, &wait);
7799                                 continue;
7800                         }
7801                 } else {
7802                         io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7803                         io_put_req(cancel_req);
7804                 }
7805
7806                 schedule();
7807                 finish_wait(&ctx->inflight_wait, &wait);
7808         }
7809 }
7810
7811 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7812 {
7813         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7814         struct task_struct *task = data;
7815
7816         return req->task == task;
7817 }
7818
7819 static int io_uring_flush(struct file *file, void *data)
7820 {
7821         struct io_ring_ctx *ctx = file->private_data;
7822
7823         io_uring_cancel_files(ctx, data);
7824
7825         /*
7826          * If the task is going away, cancel work it may have pending
7827          */
7828         if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7829                 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7830
7831         return 0;
7832 }
7833
7834 static void *io_uring_validate_mmap_request(struct file *file,
7835                                             loff_t pgoff, size_t sz)
7836 {
7837         struct io_ring_ctx *ctx = file->private_data;
7838         loff_t offset = pgoff << PAGE_SHIFT;
7839         struct page *page;
7840         void *ptr;
7841
7842         switch (offset) {
7843         case IORING_OFF_SQ_RING:
7844         case IORING_OFF_CQ_RING:
7845                 ptr = ctx->rings;
7846                 break;
7847         case IORING_OFF_SQES:
7848                 ptr = ctx->sq_sqes;
7849                 break;
7850         default:
7851                 return ERR_PTR(-EINVAL);
7852         }
7853
7854         page = virt_to_head_page(ptr);
7855         if (sz > page_size(page))
7856                 return ERR_PTR(-EINVAL);
7857
7858         return ptr;
7859 }
7860
7861 #ifdef CONFIG_MMU
7862
7863 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7864 {
7865         size_t sz = vma->vm_end - vma->vm_start;
7866         unsigned long pfn;
7867         void *ptr;
7868
7869         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7870         if (IS_ERR(ptr))
7871                 return PTR_ERR(ptr);
7872
7873         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7874         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7875 }
7876
7877 #else /* !CONFIG_MMU */
7878
7879 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7880 {
7881         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7882 }
7883
7884 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7885 {
7886         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7887 }
7888
7889 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7890         unsigned long addr, unsigned long len,
7891         unsigned long pgoff, unsigned long flags)
7892 {
7893         void *ptr;
7894
7895         ptr = io_uring_validate_mmap_request(file, pgoff, len);
7896         if (IS_ERR(ptr))
7897                 return PTR_ERR(ptr);
7898
7899         return (unsigned long) ptr;
7900 }
7901
7902 #endif /* !CONFIG_MMU */
7903
7904 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7905                 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7906                 size_t, sigsz)
7907 {
7908         struct io_ring_ctx *ctx;
7909         long ret = -EBADF;
7910         int submitted = 0;
7911         struct fd f;
7912
7913         if (current->task_works)
7914                 task_work_run();
7915
7916         if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7917                 return -EINVAL;
7918
7919         f = fdget(fd);
7920         if (!f.file)
7921                 return -EBADF;
7922
7923         ret = -EOPNOTSUPP;
7924         if (f.file->f_op != &io_uring_fops)
7925                 goto out_fput;
7926
7927         ret = -ENXIO;
7928         ctx = f.file->private_data;
7929         if (!percpu_ref_tryget(&ctx->refs))
7930                 goto out_fput;
7931
7932         /*
7933          * For SQ polling, the thread will do all submissions and completions.
7934          * Just return the requested submit count, and wake the thread if
7935          * we were asked to.
7936          */
7937         ret = 0;
7938         if (ctx->flags & IORING_SETUP_SQPOLL) {
7939                 if (!list_empty_careful(&ctx->cq_overflow_list))
7940                         io_cqring_overflow_flush(ctx, false);
7941                 if (flags & IORING_ENTER_SQ_WAKEUP)
7942                         wake_up(&ctx->sqo_wait);
7943                 submitted = to_submit;
7944         } else if (to_submit) {
7945                 mutex_lock(&ctx->uring_lock);
7946                 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
7947                 mutex_unlock(&ctx->uring_lock);
7948
7949                 if (submitted != to_submit)
7950                         goto out;
7951         }
7952         if (flags & IORING_ENTER_GETEVENTS) {
7953                 unsigned nr_events = 0;
7954
7955                 min_complete = min(min_complete, ctx->cq_entries);
7956
7957                 /*
7958                  * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7959                  * space applications don't need to do io completion events
7960                  * polling again, they can rely on io_sq_thread to do polling
7961                  * work, which can reduce cpu usage and uring_lock contention.
7962                  */
7963                 if (ctx->flags & IORING_SETUP_IOPOLL &&
7964                     !(ctx->flags & IORING_SETUP_SQPOLL)) {
7965                         ret = io_iopoll_check(ctx, &nr_events, min_complete);
7966                 } else {
7967                         ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7968                 }
7969         }
7970
7971 out:
7972         percpu_ref_put(&ctx->refs);
7973 out_fput:
7974         fdput(f);
7975         return submitted ? submitted : ret;
7976 }
7977
7978 #ifdef CONFIG_PROC_FS
7979 static int io_uring_show_cred(int id, void *p, void *data)
7980 {
7981         const struct cred *cred = p;
7982         struct seq_file *m = data;
7983         struct user_namespace *uns = seq_user_ns(m);
7984         struct group_info *gi;
7985         kernel_cap_t cap;
7986         unsigned __capi;
7987         int g;
7988
7989         seq_printf(m, "%5d\n", id);
7990         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
7991         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
7992         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
7993         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
7994         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
7995         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
7996         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
7997         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
7998         seq_puts(m, "\n\tGroups:\t");
7999         gi = cred->group_info;
8000         for (g = 0; g < gi->ngroups; g++) {
8001                 seq_put_decimal_ull(m, g ? " " : "",
8002                                         from_kgid_munged(uns, gi->gid[g]));
8003         }
8004         seq_puts(m, "\n\tCapEff:\t");
8005         cap = cred->cap_effective;
8006         CAP_FOR_EACH_U32(__capi)
8007                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8008         seq_putc(m, '\n');
8009         return 0;
8010 }
8011
8012 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8013 {
8014         int i;
8015
8016         mutex_lock(&ctx->uring_lock);
8017         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8018         for (i = 0; i < ctx->nr_user_files; i++) {
8019                 struct fixed_file_table *table;
8020                 struct file *f;
8021
8022                 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8023                 f = table->files[i & IORING_FILE_TABLE_MASK];
8024                 if (f)
8025                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8026                 else
8027                         seq_printf(m, "%5u: <none>\n", i);
8028         }
8029         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8030         for (i = 0; i < ctx->nr_user_bufs; i++) {
8031                 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8032
8033                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8034                                                 (unsigned int) buf->len);
8035         }
8036         if (!idr_is_empty(&ctx->personality_idr)) {
8037                 seq_printf(m, "Personalities:\n");
8038                 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8039         }
8040         seq_printf(m, "PollList:\n");
8041         spin_lock_irq(&ctx->completion_lock);
8042         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8043                 struct hlist_head *list = &ctx->cancel_hash[i];
8044                 struct io_kiocb *req;
8045
8046                 hlist_for_each_entry(req, list, hash_node)
8047                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
8048                                         req->task->task_works != NULL);
8049         }
8050         spin_unlock_irq(&ctx->completion_lock);
8051         mutex_unlock(&ctx->uring_lock);
8052 }
8053
8054 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8055 {
8056         struct io_ring_ctx *ctx = f->private_data;
8057
8058         if (percpu_ref_tryget(&ctx->refs)) {
8059                 __io_uring_show_fdinfo(ctx, m);
8060                 percpu_ref_put(&ctx->refs);
8061         }
8062 }
8063 #endif
8064
8065 static const struct file_operations io_uring_fops = {
8066         .release        = io_uring_release,
8067         .flush          = io_uring_flush,
8068         .mmap           = io_uring_mmap,
8069 #ifndef CONFIG_MMU
8070         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8071         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8072 #endif
8073         .poll           = io_uring_poll,
8074         .fasync         = io_uring_fasync,
8075 #ifdef CONFIG_PROC_FS
8076         .show_fdinfo    = io_uring_show_fdinfo,
8077 #endif
8078 };
8079
8080 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8081                                   struct io_uring_params *p)
8082 {
8083         struct io_rings *rings;
8084         size_t size, sq_array_offset;
8085
8086         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8087         if (size == SIZE_MAX)
8088                 return -EOVERFLOW;
8089
8090         rings = io_mem_alloc(size);
8091         if (!rings)
8092                 return -ENOMEM;
8093
8094         ctx->rings = rings;
8095         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8096         rings->sq_ring_mask = p->sq_entries - 1;
8097         rings->cq_ring_mask = p->cq_entries - 1;
8098         rings->sq_ring_entries = p->sq_entries;
8099         rings->cq_ring_entries = p->cq_entries;
8100         ctx->sq_mask = rings->sq_ring_mask;
8101         ctx->cq_mask = rings->cq_ring_mask;
8102         ctx->sq_entries = rings->sq_ring_entries;
8103         ctx->cq_entries = rings->cq_ring_entries;
8104
8105         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8106         if (size == SIZE_MAX) {
8107                 io_mem_free(ctx->rings);
8108                 ctx->rings = NULL;
8109                 return -EOVERFLOW;
8110         }
8111
8112         ctx->sq_sqes = io_mem_alloc(size);
8113         if (!ctx->sq_sqes) {
8114                 io_mem_free(ctx->rings);
8115                 ctx->rings = NULL;
8116                 return -ENOMEM;
8117         }
8118
8119         return 0;
8120 }
8121
8122 /*
8123  * Allocate an anonymous fd, this is what constitutes the application
8124  * visible backing of an io_uring instance. The application mmaps this
8125  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8126  * we have to tie this fd to a socket for file garbage collection purposes.
8127  */
8128 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8129 {
8130         struct file *file;
8131         int ret;
8132
8133 #if defined(CONFIG_UNIX)
8134         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8135                                 &ctx->ring_sock);
8136         if (ret)
8137                 return ret;
8138 #endif
8139
8140         ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8141         if (ret < 0)
8142                 goto err;
8143
8144         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8145                                         O_RDWR | O_CLOEXEC);
8146         if (IS_ERR(file)) {
8147                 put_unused_fd(ret);
8148                 ret = PTR_ERR(file);
8149                 goto err;
8150         }
8151
8152 #if defined(CONFIG_UNIX)
8153         ctx->ring_sock->file = file;
8154 #endif
8155         fd_install(ret, file);
8156         return ret;
8157 err:
8158 #if defined(CONFIG_UNIX)
8159         sock_release(ctx->ring_sock);
8160         ctx->ring_sock = NULL;
8161 #endif
8162         return ret;
8163 }
8164
8165 static int io_uring_create(unsigned entries, struct io_uring_params *p,
8166                            struct io_uring_params __user *params)
8167 {
8168         struct user_struct *user = NULL;
8169         struct io_ring_ctx *ctx;
8170         bool limit_mem;
8171         int ret;
8172
8173         if (!entries)
8174                 return -EINVAL;
8175         if (entries > IORING_MAX_ENTRIES) {
8176                 if (!(p->flags & IORING_SETUP_CLAMP))
8177                         return -EINVAL;
8178                 entries = IORING_MAX_ENTRIES;
8179         }
8180
8181         /*
8182          * Use twice as many entries for the CQ ring. It's possible for the
8183          * application to drive a higher depth than the size of the SQ ring,
8184          * since the sqes are only used at submission time. This allows for
8185          * some flexibility in overcommitting a bit. If the application has
8186          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
8187          * of CQ ring entries manually.
8188          */
8189         p->sq_entries = roundup_pow_of_two(entries);
8190         if (p->flags & IORING_SETUP_CQSIZE) {
8191                 /*
8192                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
8193                  * to a power-of-two, if it isn't already. We do NOT impose
8194                  * any cq vs sq ring sizing.
8195                  */
8196                 if (p->cq_entries < p->sq_entries)
8197                         return -EINVAL;
8198                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
8199                         if (!(p->flags & IORING_SETUP_CLAMP))
8200                                 return -EINVAL;
8201                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
8202                 }
8203                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
8204         } else {
8205                 p->cq_entries = 2 * p->sq_entries;
8206         }
8207
8208         user = get_uid(current_user());
8209         limit_mem = !capable(CAP_IPC_LOCK);
8210
8211         if (limit_mem) {
8212                 ret = __io_account_mem(user,
8213                                 ring_pages(p->sq_entries, p->cq_entries));
8214                 if (ret) {
8215                         free_uid(user);
8216                         return ret;
8217                 }
8218         }
8219
8220         ctx = io_ring_ctx_alloc(p);
8221         if (!ctx) {
8222                 if (limit_mem)
8223                         __io_unaccount_mem(user, ring_pages(p->sq_entries,
8224                                                                 p->cq_entries));
8225                 free_uid(user);
8226                 return -ENOMEM;
8227         }
8228         ctx->compat = in_compat_syscall();
8229         ctx->user = user;
8230         ctx->creds = get_current_cred();
8231
8232         ret = io_allocate_scq_urings(ctx, p);
8233         if (ret)
8234                 goto err;
8235
8236         ret = io_sq_offload_start(ctx, p);
8237         if (ret)
8238                 goto err;
8239
8240         memset(&p->sq_off, 0, sizeof(p->sq_off));
8241         p->sq_off.head = offsetof(struct io_rings, sq.head);
8242         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
8243         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
8244         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
8245         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
8246         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
8247         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
8248
8249         memset(&p->cq_off, 0, sizeof(p->cq_off));
8250         p->cq_off.head = offsetof(struct io_rings, cq.head);
8251         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
8252         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
8253         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
8254         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
8255         p->cq_off.cqes = offsetof(struct io_rings, cqes);
8256         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8257
8258         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8259                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8260                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
8261                         IORING_FEAT_POLL_32BITS;
8262
8263         if (copy_to_user(params, p, sizeof(*p))) {
8264                 ret = -EFAULT;
8265                 goto err;
8266         }
8267         /*
8268          * Install ring fd as the very last thing, so we don't risk someone
8269          * having closed it before we finish setup
8270          */
8271         ret = io_uring_get_fd(ctx);
8272         if (ret < 0)
8273                 goto err;
8274
8275         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8276         io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
8277                        ACCT_LOCKED);
8278         ctx->limit_mem = limit_mem;
8279         return ret;
8280 err:
8281         io_ring_ctx_wait_and_kill(ctx);
8282         return ret;
8283 }
8284
8285 /*
8286  * Sets up an aio uring context, and returns the fd. Applications asks for a
8287  * ring size, we return the actual sq/cq ring sizes (among other things) in the
8288  * params structure passed in.
8289  */
8290 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8291 {
8292         struct io_uring_params p;
8293         int i;
8294
8295         if (copy_from_user(&p, params, sizeof(p)))
8296                 return -EFAULT;
8297         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8298                 if (p.resv[i])
8299                         return -EINVAL;
8300         }
8301
8302         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8303                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8304                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8305                 return -EINVAL;
8306
8307         return  io_uring_create(entries, &p, params);
8308 }
8309
8310 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8311                 struct io_uring_params __user *, params)
8312 {
8313         return io_uring_setup(entries, params);
8314 }
8315
8316 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8317 {
8318         struct io_uring_probe *p;
8319         size_t size;
8320         int i, ret;
8321
8322         size = struct_size(p, ops, nr_args);
8323         if (size == SIZE_MAX)
8324                 return -EOVERFLOW;
8325         p = kzalloc(size, GFP_KERNEL);
8326         if (!p)
8327                 return -ENOMEM;
8328
8329         ret = -EFAULT;
8330         if (copy_from_user(p, arg, size))
8331                 goto out;
8332         ret = -EINVAL;
8333         if (memchr_inv(p, 0, size))
8334                 goto out;
8335
8336         p->last_op = IORING_OP_LAST - 1;
8337         if (nr_args > IORING_OP_LAST)
8338                 nr_args = IORING_OP_LAST;
8339
8340         for (i = 0; i < nr_args; i++) {
8341                 p->ops[i].op = i;
8342                 if (!io_op_defs[i].not_supported)
8343                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
8344         }
8345         p->ops_len = i;
8346
8347         ret = 0;
8348         if (copy_to_user(arg, p, size))
8349                 ret = -EFAULT;
8350 out:
8351         kfree(p);
8352         return ret;
8353 }
8354
8355 static int io_register_personality(struct io_ring_ctx *ctx)
8356 {
8357         const struct cred *creds = get_current_cred();
8358         int id;
8359
8360         id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8361                                 USHRT_MAX, GFP_KERNEL);
8362         if (id < 0)
8363                 put_cred(creds);
8364         return id;
8365 }
8366
8367 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8368 {
8369         const struct cred *old_creds;
8370
8371         old_creds = idr_remove(&ctx->personality_idr, id);
8372         if (old_creds) {
8373                 put_cred(old_creds);
8374                 return 0;
8375         }
8376
8377         return -EINVAL;
8378 }
8379
8380 static bool io_register_op_must_quiesce(int op)
8381 {
8382         switch (op) {
8383         case IORING_UNREGISTER_FILES:
8384         case IORING_REGISTER_FILES_UPDATE:
8385         case IORING_REGISTER_PROBE:
8386         case IORING_REGISTER_PERSONALITY:
8387         case IORING_UNREGISTER_PERSONALITY:
8388                 return false;
8389         default:
8390                 return true;
8391         }
8392 }
8393
8394 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8395                                void __user *arg, unsigned nr_args)
8396         __releases(ctx->uring_lock)
8397         __acquires(ctx->uring_lock)
8398 {
8399         int ret;
8400
8401         /*
8402          * We're inside the ring mutex, if the ref is already dying, then
8403          * someone else killed the ctx or is already going through
8404          * io_uring_register().
8405          */
8406         if (percpu_ref_is_dying(&ctx->refs))
8407                 return -ENXIO;
8408
8409         if (io_register_op_must_quiesce(opcode)) {
8410                 percpu_ref_kill(&ctx->refs);
8411
8412                 /*
8413                  * Drop uring mutex before waiting for references to exit. If
8414                  * another thread is currently inside io_uring_enter() it might
8415                  * need to grab the uring_lock to make progress. If we hold it
8416                  * here across the drain wait, then we can deadlock. It's safe
8417                  * to drop the mutex here, since no new references will come in
8418                  * after we've killed the percpu ref.
8419                  */
8420                 mutex_unlock(&ctx->uring_lock);
8421                 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8422                 mutex_lock(&ctx->uring_lock);
8423                 if (ret) {
8424                         percpu_ref_resurrect(&ctx->refs);
8425                         ret = -EINTR;
8426                         goto out;
8427                 }
8428         }
8429
8430         switch (opcode) {
8431         case IORING_REGISTER_BUFFERS:
8432                 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8433                 break;
8434         case IORING_UNREGISTER_BUFFERS:
8435                 ret = -EINVAL;
8436                 if (arg || nr_args)
8437                         break;
8438                 ret = io_sqe_buffer_unregister(ctx);
8439                 break;
8440         case IORING_REGISTER_FILES:
8441                 ret = io_sqe_files_register(ctx, arg, nr_args);
8442                 break;
8443         case IORING_UNREGISTER_FILES:
8444                 ret = -EINVAL;
8445                 if (arg || nr_args)
8446                         break;
8447                 ret = io_sqe_files_unregister(ctx);
8448                 break;
8449         case IORING_REGISTER_FILES_UPDATE:
8450                 ret = io_sqe_files_update(ctx, arg, nr_args);
8451                 break;
8452         case IORING_REGISTER_EVENTFD:
8453         case IORING_REGISTER_EVENTFD_ASYNC:
8454                 ret = -EINVAL;
8455                 if (nr_args != 1)
8456                         break;
8457                 ret = io_eventfd_register(ctx, arg);
8458                 if (ret)
8459                         break;
8460                 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8461                         ctx->eventfd_async = 1;
8462                 else
8463                         ctx->eventfd_async = 0;
8464                 break;
8465         case IORING_UNREGISTER_EVENTFD:
8466                 ret = -EINVAL;
8467                 if (arg || nr_args)
8468                         break;
8469                 ret = io_eventfd_unregister(ctx);
8470                 break;
8471         case IORING_REGISTER_PROBE:
8472                 ret = -EINVAL;
8473                 if (!arg || nr_args > 256)
8474                         break;
8475                 ret = io_probe(ctx, arg, nr_args);
8476                 break;
8477         case IORING_REGISTER_PERSONALITY:
8478                 ret = -EINVAL;
8479                 if (arg || nr_args)
8480                         break;
8481                 ret = io_register_personality(ctx);
8482                 break;
8483         case IORING_UNREGISTER_PERSONALITY:
8484                 ret = -EINVAL;
8485                 if (arg)
8486                         break;
8487                 ret = io_unregister_personality(ctx, nr_args);
8488                 break;
8489         default:
8490                 ret = -EINVAL;
8491                 break;
8492         }
8493
8494         if (io_register_op_must_quiesce(opcode)) {
8495                 /* bring the ctx back to life */
8496                 percpu_ref_reinit(&ctx->refs);
8497 out:
8498                 reinit_completion(&ctx->ref_comp);
8499         }
8500         return ret;
8501 }
8502
8503 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8504                 void __user *, arg, unsigned int, nr_args)
8505 {
8506         struct io_ring_ctx *ctx;
8507         long ret = -EBADF;
8508         struct fd f;
8509
8510         f = fdget(fd);
8511         if (!f.file)
8512                 return -EBADF;
8513
8514         ret = -EOPNOTSUPP;
8515         if (f.file->f_op != &io_uring_fops)
8516                 goto out_fput;
8517
8518         ctx = f.file->private_data;
8519
8520         mutex_lock(&ctx->uring_lock);
8521         ret = __io_uring_register(ctx, opcode, arg, nr_args);
8522         mutex_unlock(&ctx->uring_lock);
8523         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8524                                                         ctx->cq_ev_fd != NULL, ret);
8525 out_fput:
8526         fdput(f);
8527         return ret;
8528 }
8529
8530 static int __init io_uring_init(void)
8531 {
8532 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8533         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8534         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8535 } while (0)
8536
8537 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8538         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8539         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8540         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
8541         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
8542         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
8543         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
8544         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
8545         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
8546         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
8547         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
8548         BUILD_BUG_SQE_ELEM(24, __u32,  len);
8549         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
8550         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
8551         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8552         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
8553         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
8554         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
8555         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
8556         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
8557         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
8558         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
8559         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
8560         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
8561         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
8562         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
8563         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
8564         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
8565         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
8566         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
8567         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
8568
8569         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8570         BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8571         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8572         return 0;
8573 };
8574 __initcall(io_uring_init);