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