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