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