OSDN Git Service

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