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