OSDN Git Service

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