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