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