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