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