Revert "io_uring: mark io_uring_fops/io_op_defs as __read_mostly"
[sfrench/cifs-2.6.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 <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
51
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
64 #include <net/sock.h>
65 #include <net/af_unix.h>
66 #include <net/scm.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82 #include <linux/io_uring.h>
83 #include <linux/blk-cgroup.h>
84
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
87
88 #include <uapi/linux/io_uring.h>
89
90 #include "internal.h"
91 #include "io-wq.h"
92
93 #define IORING_MAX_ENTRIES      32768
94 #define IORING_MAX_CQ_ENTRIES   (2 * IORING_MAX_ENTRIES)
95
96 /*
97  * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
98  */
99 #define IORING_FILE_TABLE_SHIFT 9
100 #define IORING_MAX_FILES_TABLE  (1U << IORING_FILE_TABLE_SHIFT)
101 #define IORING_FILE_TABLE_MASK  (IORING_MAX_FILES_TABLE - 1)
102 #define IORING_MAX_FIXED_FILES  (64 * IORING_MAX_FILES_TABLE)
103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
104                                  IORING_REGISTER_LAST + IORING_OP_LAST)
105
106 struct io_uring {
107         u32 head ____cacheline_aligned_in_smp;
108         u32 tail ____cacheline_aligned_in_smp;
109 };
110
111 /*
112  * This data is shared with the application through the mmap at offsets
113  * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
114  *
115  * The offsets to the member fields are published through struct
116  * io_sqring_offsets when calling io_uring_setup.
117  */
118 struct io_rings {
119         /*
120          * Head and tail offsets into the ring; the offsets need to be
121          * masked to get valid indices.
122          *
123          * The kernel controls head of the sq ring and the tail of the cq ring,
124          * and the application controls tail of the sq ring and the head of the
125          * cq ring.
126          */
127         struct io_uring         sq, cq;
128         /*
129          * Bitmasks to apply to head and tail offsets (constant, equals
130          * ring_entries - 1)
131          */
132         u32                     sq_ring_mask, cq_ring_mask;
133         /* Ring sizes (constant, power of 2) */
134         u32                     sq_ring_entries, cq_ring_entries;
135         /*
136          * Number of invalid entries dropped by the kernel due to
137          * invalid index stored in array
138          *
139          * Written by the kernel, shouldn't be modified by the
140          * application (i.e. get number of "new events" by comparing to
141          * cached value).
142          *
143          * After a new SQ head value was read by the application this
144          * counter includes all submissions that were dropped reaching
145          * the new SQ head (and possibly more).
146          */
147         u32                     sq_dropped;
148         /*
149          * Runtime SQ flags
150          *
151          * Written by the kernel, shouldn't be modified by the
152          * application.
153          *
154          * The application needs a full memory barrier before checking
155          * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
156          */
157         u32                     sq_flags;
158         /*
159          * Runtime CQ flags
160          *
161          * Written by the application, shouldn't be modified by the
162          * kernel.
163          */
164         u32                     cq_flags;
165         /*
166          * Number of completion events lost because the queue was full;
167          * this should be avoided by the application by making sure
168          * there are not more requests pending than there is space in
169          * the completion queue.
170          *
171          * Written by the kernel, shouldn't be modified by the
172          * application (i.e. get number of "new events" by comparing to
173          * cached value).
174          *
175          * As completion events come in out of order this counter is not
176          * ordered with any other data.
177          */
178         u32                     cq_overflow;
179         /*
180          * Ring buffer of completion events.
181          *
182          * The kernel writes completion events fresh every time they are
183          * produced, so the application is allowed to modify pending
184          * entries.
185          */
186         struct io_uring_cqe     cqes[] ____cacheline_aligned_in_smp;
187 };
188
189 struct io_mapped_ubuf {
190         u64             ubuf;
191         size_t          len;
192         struct          bio_vec *bvec;
193         unsigned int    nr_bvecs;
194         unsigned long   acct_pages;
195 };
196
197 struct fixed_file_table {
198         struct file             **files;
199 };
200
201 struct fixed_file_ref_node {
202         struct percpu_ref               refs;
203         struct list_head                node;
204         struct list_head                file_list;
205         struct fixed_file_data          *file_data;
206         struct llist_node               llist;
207 };
208
209 struct fixed_file_data {
210         struct fixed_file_table         *table;
211         struct io_ring_ctx              *ctx;
212
213         struct fixed_file_ref_node      *node;
214         struct percpu_ref               refs;
215         struct completion               done;
216         struct list_head                ref_list;
217         spinlock_t                      lock;
218 };
219
220 struct io_buffer {
221         struct list_head list;
222         __u64 addr;
223         __s32 len;
224         __u16 bid;
225 };
226
227 struct io_restriction {
228         DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
229         DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
230         u8 sqe_flags_allowed;
231         u8 sqe_flags_required;
232         bool registered;
233 };
234
235 struct io_sq_data {
236         refcount_t              refs;
237         struct mutex            lock;
238
239         /* ctx's that are using this sqd */
240         struct list_head        ctx_list;
241         struct list_head        ctx_new_list;
242         struct mutex            ctx_lock;
243
244         struct task_struct      *thread;
245         struct wait_queue_head  wait;
246 };
247
248 struct io_ring_ctx {
249         struct {
250                 struct percpu_ref       refs;
251         } ____cacheline_aligned_in_smp;
252
253         struct {
254                 unsigned int            flags;
255                 unsigned int            compat: 1;
256                 unsigned int            limit_mem: 1;
257                 unsigned int            cq_overflow_flushed: 1;
258                 unsigned int            drain_next: 1;
259                 unsigned int            eventfd_async: 1;
260                 unsigned int            restricted: 1;
261
262                 /*
263                  * Ring buffer of indices into array of io_uring_sqe, which is
264                  * mmapped by the application using the IORING_OFF_SQES offset.
265                  *
266                  * This indirection could e.g. be used to assign fixed
267                  * io_uring_sqe entries to operations and only submit them to
268                  * the queue when needed.
269                  *
270                  * The kernel modifies neither the indices array nor the entries
271                  * array.
272                  */
273                 u32                     *sq_array;
274                 unsigned                cached_sq_head;
275                 unsigned                sq_entries;
276                 unsigned                sq_mask;
277                 unsigned                sq_thread_idle;
278                 unsigned                cached_sq_dropped;
279                 atomic_t                cached_cq_overflow;
280                 unsigned long           sq_check_overflow;
281
282                 struct list_head        defer_list;
283                 struct list_head        timeout_list;
284                 struct list_head        cq_overflow_list;
285
286                 wait_queue_head_t       inflight_wait;
287                 struct io_uring_sqe     *sq_sqes;
288         } ____cacheline_aligned_in_smp;
289
290         struct io_rings *rings;
291
292         /* IO offload */
293         struct io_wq            *io_wq;
294
295         /*
296          * For SQPOLL usage - we hold a reference to the parent task, so we
297          * have access to the ->files
298          */
299         struct task_struct      *sqo_task;
300
301         /* Only used for accounting purposes */
302         struct mm_struct        *mm_account;
303
304 #ifdef CONFIG_BLK_CGROUP
305         struct cgroup_subsys_state      *sqo_blkcg_css;
306 #endif
307
308         struct io_sq_data       *sq_data;       /* if using sq thread polling */
309
310         struct wait_queue_head  sqo_sq_wait;
311         struct wait_queue_entry sqo_wait_entry;
312         struct list_head        sqd_list;
313
314         /*
315          * If used, fixed file set. Writers must ensure that ->refs is dead,
316          * readers must ensure that ->refs is alive as long as the file* is
317          * used. Only updated through io_uring_register(2).
318          */
319         struct fixed_file_data  *file_data;
320         unsigned                nr_user_files;
321
322         /* if used, fixed mapped user buffers */
323         unsigned                nr_user_bufs;
324         struct io_mapped_ubuf   *user_bufs;
325
326         struct user_struct      *user;
327
328         const struct cred       *creds;
329
330         struct completion       ref_comp;
331         struct completion       sq_thread_comp;
332
333         /* if all else fails... */
334         struct io_kiocb         *fallback_req;
335
336 #if defined(CONFIG_UNIX)
337         struct socket           *ring_sock;
338 #endif
339
340         struct idr              io_buffer_idr;
341
342         struct idr              personality_idr;
343
344         struct {
345                 unsigned                cached_cq_tail;
346                 unsigned                cq_entries;
347                 unsigned                cq_mask;
348                 atomic_t                cq_timeouts;
349                 unsigned long           cq_check_overflow;
350                 struct wait_queue_head  cq_wait;
351                 struct fasync_struct    *cq_fasync;
352                 struct eventfd_ctx      *cq_ev_fd;
353         } ____cacheline_aligned_in_smp;
354
355         struct {
356                 struct mutex            uring_lock;
357                 wait_queue_head_t       wait;
358         } ____cacheline_aligned_in_smp;
359
360         struct {
361                 spinlock_t              completion_lock;
362
363                 /*
364                  * ->iopoll_list is protected by the ctx->uring_lock for
365                  * io_uring instances that don't use IORING_SETUP_SQPOLL.
366                  * For SQPOLL, only the single threaded io_sq_thread() will
367                  * manipulate the list, hence no extra locking is needed there.
368                  */
369                 struct list_head        iopoll_list;
370                 struct hlist_head       *cancel_hash;
371                 unsigned                cancel_hash_bits;
372                 bool                    poll_multi_file;
373
374                 spinlock_t              inflight_lock;
375                 struct list_head        inflight_list;
376         } ____cacheline_aligned_in_smp;
377
378         struct delayed_work             file_put_work;
379         struct llist_head               file_put_llist;
380
381         struct work_struct              exit_work;
382         struct io_restriction           restrictions;
383 };
384
385 /*
386  * First field must be the file pointer in all the
387  * iocb unions! See also 'struct kiocb' in <linux/fs.h>
388  */
389 struct io_poll_iocb {
390         struct file                     *file;
391         union {
392                 struct wait_queue_head  *head;
393                 u64                     addr;
394         };
395         __poll_t                        events;
396         bool                            done;
397         bool                            canceled;
398         struct wait_queue_entry         wait;
399 };
400
401 struct io_close {
402         struct file                     *file;
403         struct file                     *put_file;
404         int                             fd;
405 };
406
407 struct io_timeout_data {
408         struct io_kiocb                 *req;
409         struct hrtimer                  timer;
410         struct timespec64               ts;
411         enum hrtimer_mode               mode;
412 };
413
414 struct io_accept {
415         struct file                     *file;
416         struct sockaddr __user          *addr;
417         int __user                      *addr_len;
418         int                             flags;
419         unsigned long                   nofile;
420 };
421
422 struct io_sync {
423         struct file                     *file;
424         loff_t                          len;
425         loff_t                          off;
426         int                             flags;
427         int                             mode;
428 };
429
430 struct io_cancel {
431         struct file                     *file;
432         u64                             addr;
433 };
434
435 struct io_timeout {
436         struct file                     *file;
437         u32                             off;
438         u32                             target_seq;
439         struct list_head                list;
440 };
441
442 struct io_timeout_rem {
443         struct file                     *file;
444         u64                             addr;
445 };
446
447 struct io_rw {
448         /* NOTE: kiocb has the file as the first member, so don't do it here */
449         struct kiocb                    kiocb;
450         u64                             addr;
451         u64                             len;
452 };
453
454 struct io_connect {
455         struct file                     *file;
456         struct sockaddr __user          *addr;
457         int                             addr_len;
458 };
459
460 struct io_sr_msg {
461         struct file                     *file;
462         union {
463                 struct user_msghdr __user *umsg;
464                 void __user             *buf;
465         };
466         int                             msg_flags;
467         int                             bgid;
468         size_t                          len;
469         struct io_buffer                *kbuf;
470 };
471
472 struct io_open {
473         struct file                     *file;
474         int                             dfd;
475         struct filename                 *filename;
476         struct open_how                 how;
477         unsigned long                   nofile;
478 };
479
480 struct io_files_update {
481         struct file                     *file;
482         u64                             arg;
483         u32                             nr_args;
484         u32                             offset;
485 };
486
487 struct io_fadvise {
488         struct file                     *file;
489         u64                             offset;
490         u32                             len;
491         u32                             advice;
492 };
493
494 struct io_madvise {
495         struct file                     *file;
496         u64                             addr;
497         u32                             len;
498         u32                             advice;
499 };
500
501 struct io_epoll {
502         struct file                     *file;
503         int                             epfd;
504         int                             op;
505         int                             fd;
506         struct epoll_event              event;
507 };
508
509 struct io_splice {
510         struct file                     *file_out;
511         struct file                     *file_in;
512         loff_t                          off_out;
513         loff_t                          off_in;
514         u64                             len;
515         unsigned int                    flags;
516 };
517
518 struct io_provide_buf {
519         struct file                     *file;
520         __u64                           addr;
521         __s32                           len;
522         __u32                           bgid;
523         __u16                           nbufs;
524         __u16                           bid;
525 };
526
527 struct io_statx {
528         struct file                     *file;
529         int                             dfd;
530         unsigned int                    mask;
531         unsigned int                    flags;
532         const char __user               *filename;
533         struct statx __user             *buffer;
534 };
535
536 struct io_completion {
537         struct file                     *file;
538         struct list_head                list;
539         int                             cflags;
540 };
541
542 struct io_async_connect {
543         struct sockaddr_storage         address;
544 };
545
546 struct io_async_msghdr {
547         struct iovec                    fast_iov[UIO_FASTIOV];
548         struct iovec                    *iov;
549         struct sockaddr __user          *uaddr;
550         struct msghdr                   msg;
551         struct sockaddr_storage         addr;
552 };
553
554 struct io_async_rw {
555         struct iovec                    fast_iov[UIO_FASTIOV];
556         const struct iovec              *free_iovec;
557         struct iov_iter                 iter;
558         size_t                          bytes_done;
559         struct wait_page_queue          wpq;
560 };
561
562 enum {
563         REQ_F_FIXED_FILE_BIT    = IOSQE_FIXED_FILE_BIT,
564         REQ_F_IO_DRAIN_BIT      = IOSQE_IO_DRAIN_BIT,
565         REQ_F_LINK_BIT          = IOSQE_IO_LINK_BIT,
566         REQ_F_HARDLINK_BIT      = IOSQE_IO_HARDLINK_BIT,
567         REQ_F_FORCE_ASYNC_BIT   = IOSQE_ASYNC_BIT,
568         REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
569
570         REQ_F_LINK_HEAD_BIT,
571         REQ_F_FAIL_LINK_BIT,
572         REQ_F_INFLIGHT_BIT,
573         REQ_F_CUR_POS_BIT,
574         REQ_F_NOWAIT_BIT,
575         REQ_F_LINK_TIMEOUT_BIT,
576         REQ_F_ISREG_BIT,
577         REQ_F_NEED_CLEANUP_BIT,
578         REQ_F_POLLED_BIT,
579         REQ_F_BUFFER_SELECTED_BIT,
580         REQ_F_NO_FILE_TABLE_BIT,
581         REQ_F_WORK_INITIALIZED_BIT,
582
583         /* not a real bit, just to check we're not overflowing the space */
584         __REQ_F_LAST_BIT,
585 };
586
587 enum {
588         /* ctx owns file */
589         REQ_F_FIXED_FILE        = BIT(REQ_F_FIXED_FILE_BIT),
590         /* drain existing IO first */
591         REQ_F_IO_DRAIN          = BIT(REQ_F_IO_DRAIN_BIT),
592         /* linked sqes */
593         REQ_F_LINK              = BIT(REQ_F_LINK_BIT),
594         /* doesn't sever on completion < 0 */
595         REQ_F_HARDLINK          = BIT(REQ_F_HARDLINK_BIT),
596         /* IOSQE_ASYNC */
597         REQ_F_FORCE_ASYNC       = BIT(REQ_F_FORCE_ASYNC_BIT),
598         /* IOSQE_BUFFER_SELECT */
599         REQ_F_BUFFER_SELECT     = BIT(REQ_F_BUFFER_SELECT_BIT),
600
601         /* head of a link */
602         REQ_F_LINK_HEAD         = BIT(REQ_F_LINK_HEAD_BIT),
603         /* fail rest of links */
604         REQ_F_FAIL_LINK         = BIT(REQ_F_FAIL_LINK_BIT),
605         /* on inflight list */
606         REQ_F_INFLIGHT          = BIT(REQ_F_INFLIGHT_BIT),
607         /* read/write uses file position */
608         REQ_F_CUR_POS           = BIT(REQ_F_CUR_POS_BIT),
609         /* must not punt to workers */
610         REQ_F_NOWAIT            = BIT(REQ_F_NOWAIT_BIT),
611         /* has linked timeout */
612         REQ_F_LINK_TIMEOUT      = BIT(REQ_F_LINK_TIMEOUT_BIT),
613         /* regular file */
614         REQ_F_ISREG             = BIT(REQ_F_ISREG_BIT),
615         /* needs cleanup */
616         REQ_F_NEED_CLEANUP      = BIT(REQ_F_NEED_CLEANUP_BIT),
617         /* already went through poll handler */
618         REQ_F_POLLED            = BIT(REQ_F_POLLED_BIT),
619         /* buffer already selected */
620         REQ_F_BUFFER_SELECTED   = BIT(REQ_F_BUFFER_SELECTED_BIT),
621         /* doesn't need file table for this request */
622         REQ_F_NO_FILE_TABLE     = BIT(REQ_F_NO_FILE_TABLE_BIT),
623         /* io_wq_work is initialized */
624         REQ_F_WORK_INITIALIZED  = BIT(REQ_F_WORK_INITIALIZED_BIT),
625 };
626
627 struct async_poll {
628         struct io_poll_iocb     poll;
629         struct io_poll_iocb     *double_poll;
630 };
631
632 /*
633  * NOTE! Each of the iocb union members has the file pointer
634  * as the first entry in their struct definition. So you can
635  * access the file pointer through any of the sub-structs,
636  * or directly as just 'ki_filp' in this struct.
637  */
638 struct io_kiocb {
639         union {
640                 struct file             *file;
641                 struct io_rw            rw;
642                 struct io_poll_iocb     poll;
643                 struct io_accept        accept;
644                 struct io_sync          sync;
645                 struct io_cancel        cancel;
646                 struct io_timeout       timeout;
647                 struct io_timeout_rem   timeout_rem;
648                 struct io_connect       connect;
649                 struct io_sr_msg        sr_msg;
650                 struct io_open          open;
651                 struct io_close         close;
652                 struct io_files_update  files_update;
653                 struct io_fadvise       fadvise;
654                 struct io_madvise       madvise;
655                 struct io_epoll         epoll;
656                 struct io_splice        splice;
657                 struct io_provide_buf   pbuf;
658                 struct io_statx         statx;
659                 /* use only after cleaning per-op data, see io_clean_op() */
660                 struct io_completion    compl;
661         };
662
663         /* opcode allocated if it needs to store data for async defer */
664         void                            *async_data;
665         u8                              opcode;
666         /* polled IO has completed */
667         u8                              iopoll_completed;
668
669         u16                             buf_index;
670         u32                             result;
671
672         struct io_ring_ctx              *ctx;
673         unsigned int                    flags;
674         refcount_t                      refs;
675         struct task_struct              *task;
676         u64                             user_data;
677
678         struct list_head                link_list;
679
680         /*
681          * 1. used with ctx->iopoll_list with reads/writes
682          * 2. to track reqs with ->files (see io_op_def::file_table)
683          */
684         struct list_head                inflight_entry;
685
686         struct percpu_ref               *fixed_file_refs;
687         struct callback_head            task_work;
688         /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
689         struct hlist_node               hash_node;
690         struct async_poll               *apoll;
691         struct io_wq_work               work;
692 };
693
694 struct io_defer_entry {
695         struct list_head        list;
696         struct io_kiocb         *req;
697         u32                     seq;
698 };
699
700 #define IO_IOPOLL_BATCH                 8
701
702 struct io_comp_state {
703         unsigned int            nr;
704         struct list_head        list;
705         struct io_ring_ctx      *ctx;
706 };
707
708 struct io_submit_state {
709         struct blk_plug         plug;
710
711         /*
712          * io_kiocb alloc cache
713          */
714         void                    *reqs[IO_IOPOLL_BATCH];
715         unsigned int            free_reqs;
716
717         /*
718          * Batch completion logic
719          */
720         struct io_comp_state    comp;
721
722         /*
723          * File reference cache
724          */
725         struct file             *file;
726         unsigned int            fd;
727         unsigned int            has_refs;
728         unsigned int            ios_left;
729 };
730
731 struct io_op_def {
732         /* needs current->mm setup, does mm access */
733         unsigned                needs_mm : 1;
734         /* needs req->file assigned */
735         unsigned                needs_file : 1;
736         /* don't fail if file grab fails */
737         unsigned                needs_file_no_error : 1;
738         /* hash wq insertion if file is a regular file */
739         unsigned                hash_reg_file : 1;
740         /* unbound wq insertion if file is a non-regular file */
741         unsigned                unbound_nonreg_file : 1;
742         /* opcode is not supported by this kernel */
743         unsigned                not_supported : 1;
744         /* needs file table */
745         unsigned                file_table : 1;
746         /* needs ->fs */
747         unsigned                needs_fs : 1;
748         /* set if opcode supports polled "wait" */
749         unsigned                pollin : 1;
750         unsigned                pollout : 1;
751         /* op supports buffer selection */
752         unsigned                buffer_select : 1;
753         /* needs rlimit(RLIMIT_FSIZE) assigned */
754         unsigned                needs_fsize : 1;
755         /* must always have async data allocated */
756         unsigned                needs_async_data : 1;
757         /* needs blkcg context, issues async io potentially */
758         unsigned                needs_blkcg : 1;
759         /* size of async data needed, if any */
760         unsigned short          async_size;
761 };
762
763 static const struct io_op_def io_op_defs[] = {
764         [IORING_OP_NOP] = {},
765         [IORING_OP_READV] = {
766                 .needs_mm               = 1,
767                 .needs_file             = 1,
768                 .unbound_nonreg_file    = 1,
769                 .pollin                 = 1,
770                 .buffer_select          = 1,
771                 .needs_async_data       = 1,
772                 .needs_blkcg            = 1,
773                 .async_size             = sizeof(struct io_async_rw),
774         },
775         [IORING_OP_WRITEV] = {
776                 .needs_mm               = 1,
777                 .needs_file             = 1,
778                 .hash_reg_file          = 1,
779                 .unbound_nonreg_file    = 1,
780                 .pollout                = 1,
781                 .needs_fsize            = 1,
782                 .needs_async_data       = 1,
783                 .needs_blkcg            = 1,
784                 .async_size             = sizeof(struct io_async_rw),
785         },
786         [IORING_OP_FSYNC] = {
787                 .needs_file             = 1,
788                 .needs_blkcg            = 1,
789         },
790         [IORING_OP_READ_FIXED] = {
791                 .needs_file             = 1,
792                 .unbound_nonreg_file    = 1,
793                 .pollin                 = 1,
794                 .needs_blkcg            = 1,
795                 .async_size             = sizeof(struct io_async_rw),
796         },
797         [IORING_OP_WRITE_FIXED] = {
798                 .needs_file             = 1,
799                 .hash_reg_file          = 1,
800                 .unbound_nonreg_file    = 1,
801                 .pollout                = 1,
802                 .needs_fsize            = 1,
803                 .needs_blkcg            = 1,
804                 .async_size             = sizeof(struct io_async_rw),
805         },
806         [IORING_OP_POLL_ADD] = {
807                 .needs_file             = 1,
808                 .unbound_nonreg_file    = 1,
809         },
810         [IORING_OP_POLL_REMOVE] = {},
811         [IORING_OP_SYNC_FILE_RANGE] = {
812                 .needs_file             = 1,
813                 .needs_blkcg            = 1,
814         },
815         [IORING_OP_SENDMSG] = {
816                 .needs_mm               = 1,
817                 .needs_file             = 1,
818                 .unbound_nonreg_file    = 1,
819                 .needs_fs               = 1,
820                 .pollout                = 1,
821                 .needs_async_data       = 1,
822                 .needs_blkcg            = 1,
823                 .async_size             = sizeof(struct io_async_msghdr),
824         },
825         [IORING_OP_RECVMSG] = {
826                 .needs_mm               = 1,
827                 .needs_file             = 1,
828                 .unbound_nonreg_file    = 1,
829                 .needs_fs               = 1,
830                 .pollin                 = 1,
831                 .buffer_select          = 1,
832                 .needs_async_data       = 1,
833                 .needs_blkcg            = 1,
834                 .async_size             = sizeof(struct io_async_msghdr),
835         },
836         [IORING_OP_TIMEOUT] = {
837                 .needs_mm               = 1,
838                 .needs_async_data       = 1,
839                 .async_size             = sizeof(struct io_timeout_data),
840         },
841         [IORING_OP_TIMEOUT_REMOVE] = {},
842         [IORING_OP_ACCEPT] = {
843                 .needs_mm               = 1,
844                 .needs_file             = 1,
845                 .unbound_nonreg_file    = 1,
846                 .file_table             = 1,
847                 .pollin                 = 1,
848         },
849         [IORING_OP_ASYNC_CANCEL] = {},
850         [IORING_OP_LINK_TIMEOUT] = {
851                 .needs_mm               = 1,
852                 .needs_async_data       = 1,
853                 .async_size             = sizeof(struct io_timeout_data),
854         },
855         [IORING_OP_CONNECT] = {
856                 .needs_mm               = 1,
857                 .needs_file             = 1,
858                 .unbound_nonreg_file    = 1,
859                 .pollout                = 1,
860                 .needs_async_data       = 1,
861                 .async_size             = sizeof(struct io_async_connect),
862         },
863         [IORING_OP_FALLOCATE] = {
864                 .needs_file             = 1,
865                 .needs_fsize            = 1,
866                 .needs_blkcg            = 1,
867         },
868         [IORING_OP_OPENAT] = {
869                 .file_table             = 1,
870                 .needs_fs               = 1,
871                 .needs_blkcg            = 1,
872         },
873         [IORING_OP_CLOSE] = {
874                 .needs_file             = 1,
875                 .needs_file_no_error    = 1,
876                 .file_table             = 1,
877                 .needs_blkcg            = 1,
878         },
879         [IORING_OP_FILES_UPDATE] = {
880                 .needs_mm               = 1,
881                 .file_table             = 1,
882         },
883         [IORING_OP_STATX] = {
884                 .needs_mm               = 1,
885                 .needs_fs               = 1,
886                 .file_table             = 1,
887                 .needs_blkcg            = 1,
888         },
889         [IORING_OP_READ] = {
890                 .needs_mm               = 1,
891                 .needs_file             = 1,
892                 .unbound_nonreg_file    = 1,
893                 .pollin                 = 1,
894                 .buffer_select          = 1,
895                 .needs_blkcg            = 1,
896                 .async_size             = sizeof(struct io_async_rw),
897         },
898         [IORING_OP_WRITE] = {
899                 .needs_mm               = 1,
900                 .needs_file             = 1,
901                 .unbound_nonreg_file    = 1,
902                 .pollout                = 1,
903                 .needs_fsize            = 1,
904                 .needs_blkcg            = 1,
905                 .async_size             = sizeof(struct io_async_rw),
906         },
907         [IORING_OP_FADVISE] = {
908                 .needs_file             = 1,
909                 .needs_blkcg            = 1,
910         },
911         [IORING_OP_MADVISE] = {
912                 .needs_mm               = 1,
913                 .needs_blkcg            = 1,
914         },
915         [IORING_OP_SEND] = {
916                 .needs_mm               = 1,
917                 .needs_file             = 1,
918                 .unbound_nonreg_file    = 1,
919                 .pollout                = 1,
920                 .needs_blkcg            = 1,
921         },
922         [IORING_OP_RECV] = {
923                 .needs_mm               = 1,
924                 .needs_file             = 1,
925                 .unbound_nonreg_file    = 1,
926                 .pollin                 = 1,
927                 .buffer_select          = 1,
928                 .needs_blkcg            = 1,
929         },
930         [IORING_OP_OPENAT2] = {
931                 .file_table             = 1,
932                 .needs_fs               = 1,
933                 .needs_blkcg            = 1,
934         },
935         [IORING_OP_EPOLL_CTL] = {
936                 .unbound_nonreg_file    = 1,
937                 .file_table             = 1,
938         },
939         [IORING_OP_SPLICE] = {
940                 .needs_file             = 1,
941                 .hash_reg_file          = 1,
942                 .unbound_nonreg_file    = 1,
943                 .needs_blkcg            = 1,
944         },
945         [IORING_OP_PROVIDE_BUFFERS] = {},
946         [IORING_OP_REMOVE_BUFFERS] = {},
947         [IORING_OP_TEE] = {
948                 .needs_file             = 1,
949                 .hash_reg_file          = 1,
950                 .unbound_nonreg_file    = 1,
951         },
952 };
953
954 enum io_mem_account {
955         ACCT_LOCKED,
956         ACCT_PINNED,
957 };
958
959 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
960                              struct io_comp_state *cs);
961 static void io_cqring_fill_event(struct io_kiocb *req, long res);
962 static void io_put_req(struct io_kiocb *req);
963 static void io_put_req_deferred(struct io_kiocb *req, int nr);
964 static void io_double_put_req(struct io_kiocb *req);
965 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
966 static void __io_queue_linked_timeout(struct io_kiocb *req);
967 static void io_queue_linked_timeout(struct io_kiocb *req);
968 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
969                                  struct io_uring_files_update *ip,
970                                  unsigned nr_args);
971 static void __io_clean_op(struct io_kiocb *req);
972 static struct file *io_file_get(struct io_submit_state *state,
973                                 struct io_kiocb *req, int fd, bool fixed);
974 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs);
975 static void io_file_put_work(struct work_struct *work);
976
977 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
978                                struct iovec **iovec, struct iov_iter *iter,
979                                bool needs_lock);
980 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
981                              const struct iovec *fast_iov,
982                              struct iov_iter *iter, bool force);
983
984 static struct kmem_cache *req_cachep;
985
986 static const struct file_operations io_uring_fops;
987
988 struct sock *io_uring_get_socket(struct file *file)
989 {
990 #if defined(CONFIG_UNIX)
991         if (file->f_op == &io_uring_fops) {
992                 struct io_ring_ctx *ctx = file->private_data;
993
994                 return ctx->ring_sock->sk;
995         }
996 #endif
997         return NULL;
998 }
999 EXPORT_SYMBOL(io_uring_get_socket);
1000
1001 static inline void io_clean_op(struct io_kiocb *req)
1002 {
1003         if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1004                           REQ_F_INFLIGHT))
1005                 __io_clean_op(req);
1006 }
1007
1008 static void io_sq_thread_drop_mm(void)
1009 {
1010         struct mm_struct *mm = current->mm;
1011
1012         if (mm) {
1013                 kthread_unuse_mm(mm);
1014                 mmput(mm);
1015         }
1016 }
1017
1018 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
1019 {
1020         if (!current->mm) {
1021                 if (unlikely(!(ctx->flags & IORING_SETUP_SQPOLL) ||
1022                              !ctx->sqo_task->mm ||
1023                              !mmget_not_zero(ctx->sqo_task->mm)))
1024                         return -EFAULT;
1025                 kthread_use_mm(ctx->sqo_task->mm);
1026         }
1027
1028         return 0;
1029 }
1030
1031 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
1032                                    struct io_kiocb *req)
1033 {
1034         if (!io_op_defs[req->opcode].needs_mm)
1035                 return 0;
1036         return __io_sq_thread_acquire_mm(ctx);
1037 }
1038
1039 static void io_sq_thread_associate_blkcg(struct io_ring_ctx *ctx,
1040                                          struct cgroup_subsys_state **cur_css)
1041
1042 {
1043 #ifdef CONFIG_BLK_CGROUP
1044         /* puts the old one when swapping */
1045         if (*cur_css != ctx->sqo_blkcg_css) {
1046                 kthread_associate_blkcg(ctx->sqo_blkcg_css);
1047                 *cur_css = ctx->sqo_blkcg_css;
1048         }
1049 #endif
1050 }
1051
1052 static void io_sq_thread_unassociate_blkcg(void)
1053 {
1054 #ifdef CONFIG_BLK_CGROUP
1055         kthread_associate_blkcg(NULL);
1056 #endif
1057 }
1058
1059 static inline void req_set_fail_links(struct io_kiocb *req)
1060 {
1061         if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1062                 req->flags |= REQ_F_FAIL_LINK;
1063 }
1064
1065 /*
1066  * Note: must call io_req_init_async() for the first time you
1067  * touch any members of io_wq_work.
1068  */
1069 static inline void io_req_init_async(struct io_kiocb *req)
1070 {
1071         if (req->flags & REQ_F_WORK_INITIALIZED)
1072                 return;
1073
1074         memset(&req->work, 0, sizeof(req->work));
1075         req->flags |= REQ_F_WORK_INITIALIZED;
1076 }
1077
1078 static inline bool io_async_submit(struct io_ring_ctx *ctx)
1079 {
1080         return ctx->flags & IORING_SETUP_SQPOLL;
1081 }
1082
1083 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1084 {
1085         struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1086
1087         complete(&ctx->ref_comp);
1088 }
1089
1090 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1091 {
1092         return !req->timeout.off;
1093 }
1094
1095 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1096 {
1097         struct io_ring_ctx *ctx;
1098         int hash_bits;
1099
1100         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1101         if (!ctx)
1102                 return NULL;
1103
1104         ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
1105         if (!ctx->fallback_req)
1106                 goto err;
1107
1108         /*
1109          * Use 5 bits less than the max cq entries, that should give us around
1110          * 32 entries per hash list if totally full and uniformly spread.
1111          */
1112         hash_bits = ilog2(p->cq_entries);
1113         hash_bits -= 5;
1114         if (hash_bits <= 0)
1115                 hash_bits = 1;
1116         ctx->cancel_hash_bits = hash_bits;
1117         ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1118                                         GFP_KERNEL);
1119         if (!ctx->cancel_hash)
1120                 goto err;
1121         __hash_init(ctx->cancel_hash, 1U << hash_bits);
1122
1123         if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1124                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1125                 goto err;
1126
1127         ctx->flags = p->flags;
1128         init_waitqueue_head(&ctx->sqo_sq_wait);
1129         INIT_LIST_HEAD(&ctx->sqd_list);
1130         init_waitqueue_head(&ctx->cq_wait);
1131         INIT_LIST_HEAD(&ctx->cq_overflow_list);
1132         init_completion(&ctx->ref_comp);
1133         init_completion(&ctx->sq_thread_comp);
1134         idr_init(&ctx->io_buffer_idr);
1135         idr_init(&ctx->personality_idr);
1136         mutex_init(&ctx->uring_lock);
1137         init_waitqueue_head(&ctx->wait);
1138         spin_lock_init(&ctx->completion_lock);
1139         INIT_LIST_HEAD(&ctx->iopoll_list);
1140         INIT_LIST_HEAD(&ctx->defer_list);
1141         INIT_LIST_HEAD(&ctx->timeout_list);
1142         init_waitqueue_head(&ctx->inflight_wait);
1143         spin_lock_init(&ctx->inflight_lock);
1144         INIT_LIST_HEAD(&ctx->inflight_list);
1145         INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1146         init_llist_head(&ctx->file_put_llist);
1147         return ctx;
1148 err:
1149         if (ctx->fallback_req)
1150                 kmem_cache_free(req_cachep, ctx->fallback_req);
1151         kfree(ctx->cancel_hash);
1152         kfree(ctx);
1153         return NULL;
1154 }
1155
1156 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1157 {
1158         if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1159                 struct io_ring_ctx *ctx = req->ctx;
1160
1161                 return seq != ctx->cached_cq_tail
1162                                 + atomic_read(&ctx->cached_cq_overflow);
1163         }
1164
1165         return false;
1166 }
1167
1168 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1169 {
1170         struct io_rings *rings = ctx->rings;
1171
1172         /* order cqe stores with ring update */
1173         smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1174
1175         if (wq_has_sleeper(&ctx->cq_wait)) {
1176                 wake_up_interruptible(&ctx->cq_wait);
1177                 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1178         }
1179 }
1180
1181 static void io_req_clean_work(struct io_kiocb *req)
1182 {
1183         if (!(req->flags & REQ_F_WORK_INITIALIZED))
1184                 return;
1185
1186         req->flags &= ~REQ_F_WORK_INITIALIZED;
1187
1188         if (req->work.mm) {
1189                 mmdrop(req->work.mm);
1190                 req->work.mm = NULL;
1191         }
1192 #ifdef CONFIG_BLK_CGROUP
1193         if (req->work.blkcg_css)
1194                 css_put(req->work.blkcg_css);
1195 #endif
1196         if (req->work.creds) {
1197                 put_cred(req->work.creds);
1198                 req->work.creds = NULL;
1199         }
1200         if (req->work.fs) {
1201                 struct fs_struct *fs = req->work.fs;
1202
1203                 spin_lock(&req->work.fs->lock);
1204                 if (--fs->users)
1205                         fs = NULL;
1206                 spin_unlock(&req->work.fs->lock);
1207                 if (fs)
1208                         free_fs_struct(fs);
1209                 req->work.fs = NULL;
1210         }
1211 }
1212
1213 static void io_prep_async_work(struct io_kiocb *req)
1214 {
1215         const struct io_op_def *def = &io_op_defs[req->opcode];
1216         struct io_ring_ctx *ctx = req->ctx;
1217
1218         io_req_init_async(req);
1219
1220         if (req->flags & REQ_F_ISREG) {
1221                 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1222                         io_wq_hash_work(&req->work, file_inode(req->file));
1223         } else {
1224                 if (def->unbound_nonreg_file)
1225                         req->work.flags |= IO_WQ_WORK_UNBOUND;
1226         }
1227         if (!req->work.files && io_op_defs[req->opcode].file_table &&
1228             !(req->flags & REQ_F_NO_FILE_TABLE)) {
1229                 req->work.files = get_files_struct(current);
1230                 get_nsproxy(current->nsproxy);
1231                 req->work.nsproxy = current->nsproxy;
1232                 req->flags |= REQ_F_INFLIGHT;
1233
1234                 spin_lock_irq(&ctx->inflight_lock);
1235                 list_add(&req->inflight_entry, &ctx->inflight_list);
1236                 spin_unlock_irq(&ctx->inflight_lock);
1237         }
1238         if (!req->work.mm && def->needs_mm) {
1239                 mmgrab(current->mm);
1240                 req->work.mm = current->mm;
1241         }
1242 #ifdef CONFIG_BLK_CGROUP
1243         if (!req->work.blkcg_css && def->needs_blkcg) {
1244                 rcu_read_lock();
1245                 req->work.blkcg_css = blkcg_css();
1246                 /*
1247                  * This should be rare, either the cgroup is dying or the task
1248                  * is moving cgroups. Just punt to root for the handful of ios.
1249                  */
1250                 if (!css_tryget_online(req->work.blkcg_css))
1251                         req->work.blkcg_css = NULL;
1252                 rcu_read_unlock();
1253         }
1254 #endif
1255         if (!req->work.creds)
1256                 req->work.creds = get_current_cred();
1257         if (!req->work.fs && def->needs_fs) {
1258                 spin_lock(&current->fs->lock);
1259                 if (!current->fs->in_exec) {
1260                         req->work.fs = current->fs;
1261                         req->work.fs->users++;
1262                 } else {
1263                         req->work.flags |= IO_WQ_WORK_CANCEL;
1264                 }
1265                 spin_unlock(&current->fs->lock);
1266         }
1267         if (def->needs_fsize)
1268                 req->work.fsize = rlimit(RLIMIT_FSIZE);
1269         else
1270                 req->work.fsize = RLIM_INFINITY;
1271 }
1272
1273 static void io_prep_async_link(struct io_kiocb *req)
1274 {
1275         struct io_kiocb *cur;
1276
1277         io_prep_async_work(req);
1278         if (req->flags & REQ_F_LINK_HEAD)
1279                 list_for_each_entry(cur, &req->link_list, link_list)
1280                         io_prep_async_work(cur);
1281 }
1282
1283 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1284 {
1285         struct io_ring_ctx *ctx = req->ctx;
1286         struct io_kiocb *link = io_prep_linked_timeout(req);
1287
1288         trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1289                                         &req->work, req->flags);
1290         io_wq_enqueue(ctx->io_wq, &req->work);
1291         return link;
1292 }
1293
1294 static void io_queue_async_work(struct io_kiocb *req)
1295 {
1296         struct io_kiocb *link;
1297
1298         /* init ->work of the whole link before punting */
1299         io_prep_async_link(req);
1300         link = __io_queue_async_work(req);
1301
1302         if (link)
1303                 io_queue_linked_timeout(link);
1304 }
1305
1306 static void io_kill_timeout(struct io_kiocb *req)
1307 {
1308         struct io_timeout_data *io = req->async_data;
1309         int ret;
1310
1311         ret = hrtimer_try_to_cancel(&io->timer);
1312         if (ret != -1) {
1313                 atomic_set(&req->ctx->cq_timeouts,
1314                         atomic_read(&req->ctx->cq_timeouts) + 1);
1315                 list_del_init(&req->timeout.list);
1316                 io_cqring_fill_event(req, 0);
1317                 io_put_req_deferred(req, 1);
1318         }
1319 }
1320
1321 static bool io_task_match(struct io_kiocb *req, struct task_struct *tsk)
1322 {
1323         struct io_ring_ctx *ctx = req->ctx;
1324
1325         if (!tsk || req->task == tsk)
1326                 return true;
1327         if (ctx->flags & IORING_SETUP_SQPOLL) {
1328                 if (ctx->sq_data && req->task == ctx->sq_data->thread)
1329                         return true;
1330         }
1331         return false;
1332 }
1333
1334 /*
1335  * Returns true if we found and killed one or more timeouts
1336  */
1337 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk)
1338 {
1339         struct io_kiocb *req, *tmp;
1340         int canceled = 0;
1341
1342         spin_lock_irq(&ctx->completion_lock);
1343         list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1344                 if (io_task_match(req, tsk)) {
1345                         io_kill_timeout(req);
1346                         canceled++;
1347                 }
1348         }
1349         spin_unlock_irq(&ctx->completion_lock);
1350         return canceled != 0;
1351 }
1352
1353 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1354 {
1355         do {
1356                 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1357                                                 struct io_defer_entry, list);
1358                 struct io_kiocb *link;
1359
1360                 if (req_need_defer(de->req, de->seq))
1361                         break;
1362                 list_del_init(&de->list);
1363                 /* punt-init is done before queueing for defer */
1364                 link = __io_queue_async_work(de->req);
1365                 if (link) {
1366                         __io_queue_linked_timeout(link);
1367                         /* drop submission reference */
1368                         io_put_req_deferred(link, 1);
1369                 }
1370                 kfree(de);
1371         } while (!list_empty(&ctx->defer_list));
1372 }
1373
1374 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1375 {
1376         while (!list_empty(&ctx->timeout_list)) {
1377                 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1378                                                 struct io_kiocb, timeout.list);
1379
1380                 if (io_is_timeout_noseq(req))
1381                         break;
1382                 if (req->timeout.target_seq != ctx->cached_cq_tail
1383                                         - atomic_read(&ctx->cq_timeouts))
1384                         break;
1385
1386                 list_del_init(&req->timeout.list);
1387                 io_kill_timeout(req);
1388         }
1389 }
1390
1391 static void io_commit_cqring(struct io_ring_ctx *ctx)
1392 {
1393         io_flush_timeouts(ctx);
1394         __io_commit_cqring(ctx);
1395
1396         if (unlikely(!list_empty(&ctx->defer_list)))
1397                 __io_queue_deferred(ctx);
1398 }
1399
1400 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1401 {
1402         struct io_rings *r = ctx->rings;
1403
1404         return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1405 }
1406
1407 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1408 {
1409         struct io_rings *rings = ctx->rings;
1410         unsigned tail;
1411
1412         tail = ctx->cached_cq_tail;
1413         /*
1414          * writes to the cq entry need to come after reading head; the
1415          * control dependency is enough as we're using WRITE_ONCE to
1416          * fill the cq entry
1417          */
1418         if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1419                 return NULL;
1420
1421         ctx->cached_cq_tail++;
1422         return &rings->cqes[tail & ctx->cq_mask];
1423 }
1424
1425 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1426 {
1427         if (!ctx->cq_ev_fd)
1428                 return false;
1429         if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1430                 return false;
1431         if (!ctx->eventfd_async)
1432                 return true;
1433         return io_wq_current_is_worker();
1434 }
1435
1436 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1437 {
1438         if (waitqueue_active(&ctx->wait))
1439                 wake_up(&ctx->wait);
1440         if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1441                 wake_up(&ctx->sq_data->wait);
1442         if (io_should_trigger_evfd(ctx))
1443                 eventfd_signal(ctx->cq_ev_fd, 1);
1444 }
1445
1446 static void io_cqring_mark_overflow(struct io_ring_ctx *ctx)
1447 {
1448         if (list_empty(&ctx->cq_overflow_list)) {
1449                 clear_bit(0, &ctx->sq_check_overflow);
1450                 clear_bit(0, &ctx->cq_check_overflow);
1451                 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1452         }
1453 }
1454
1455 static inline bool io_match_files(struct io_kiocb *req,
1456                                        struct files_struct *files)
1457 {
1458         if (!files)
1459                 return true;
1460         if (req->flags & REQ_F_WORK_INITIALIZED)
1461                 return req->work.files == files;
1462         return false;
1463 }
1464
1465 /* Returns true if there are no backlogged entries after the flush */
1466 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1467                                      struct task_struct *tsk,
1468                                      struct files_struct *files)
1469 {
1470         struct io_rings *rings = ctx->rings;
1471         struct io_kiocb *req, *tmp;
1472         struct io_uring_cqe *cqe;
1473         unsigned long flags;
1474         LIST_HEAD(list);
1475
1476         if (!force) {
1477                 if (list_empty_careful(&ctx->cq_overflow_list))
1478                         return true;
1479                 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1480                     rings->cq_ring_entries))
1481                         return false;
1482         }
1483
1484         spin_lock_irqsave(&ctx->completion_lock, flags);
1485
1486         /* if force is set, the ring is going away. always drop after that */
1487         if (force)
1488                 ctx->cq_overflow_flushed = 1;
1489
1490         cqe = NULL;
1491         list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1492                 if (tsk && req->task != tsk)
1493                         continue;
1494                 if (!io_match_files(req, files))
1495                         continue;
1496
1497                 cqe = io_get_cqring(ctx);
1498                 if (!cqe && !force)
1499                         break;
1500
1501                 list_move(&req->compl.list, &list);
1502                 if (cqe) {
1503                         WRITE_ONCE(cqe->user_data, req->user_data);
1504                         WRITE_ONCE(cqe->res, req->result);
1505                         WRITE_ONCE(cqe->flags, req->compl.cflags);
1506                 } else {
1507                         WRITE_ONCE(ctx->rings->cq_overflow,
1508                                 atomic_inc_return(&ctx->cached_cq_overflow));
1509                 }
1510         }
1511
1512         io_commit_cqring(ctx);
1513         io_cqring_mark_overflow(ctx);
1514
1515         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1516         io_cqring_ev_posted(ctx);
1517
1518         while (!list_empty(&list)) {
1519                 req = list_first_entry(&list, struct io_kiocb, compl.list);
1520                 list_del(&req->compl.list);
1521                 io_put_req(req);
1522         }
1523
1524         return cqe != NULL;
1525 }
1526
1527 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1528 {
1529         struct io_ring_ctx *ctx = req->ctx;
1530         struct io_uring_cqe *cqe;
1531
1532         trace_io_uring_complete(ctx, req->user_data, res);
1533
1534         /*
1535          * If we can't get a cq entry, userspace overflowed the
1536          * submission (by quite a lot). Increment the overflow count in
1537          * the ring.
1538          */
1539         cqe = io_get_cqring(ctx);
1540         if (likely(cqe)) {
1541                 WRITE_ONCE(cqe->user_data, req->user_data);
1542                 WRITE_ONCE(cqe->res, res);
1543                 WRITE_ONCE(cqe->flags, cflags);
1544         } else if (ctx->cq_overflow_flushed || req->task->io_uring->in_idle) {
1545                 /*
1546                  * If we're in ring overflow flush mode, or in task cancel mode,
1547                  * then we cannot store the request for later flushing, we need
1548                  * to drop it on the floor.
1549                  */
1550                 WRITE_ONCE(ctx->rings->cq_overflow,
1551                                 atomic_inc_return(&ctx->cached_cq_overflow));
1552         } else {
1553                 if (list_empty(&ctx->cq_overflow_list)) {
1554                         set_bit(0, &ctx->sq_check_overflow);
1555                         set_bit(0, &ctx->cq_check_overflow);
1556                         ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1557                 }
1558                 io_clean_op(req);
1559                 req->result = res;
1560                 req->compl.cflags = cflags;
1561                 refcount_inc(&req->refs);
1562                 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1563         }
1564 }
1565
1566 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1567 {
1568         __io_cqring_fill_event(req, res, 0);
1569 }
1570
1571 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1572 {
1573         struct io_ring_ctx *ctx = req->ctx;
1574         unsigned long flags;
1575
1576         spin_lock_irqsave(&ctx->completion_lock, flags);
1577         __io_cqring_fill_event(req, res, cflags);
1578         io_commit_cqring(ctx);
1579         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1580
1581         io_cqring_ev_posted(ctx);
1582 }
1583
1584 static void io_submit_flush_completions(struct io_comp_state *cs)
1585 {
1586         struct io_ring_ctx *ctx = cs->ctx;
1587
1588         spin_lock_irq(&ctx->completion_lock);
1589         while (!list_empty(&cs->list)) {
1590                 struct io_kiocb *req;
1591
1592                 req = list_first_entry(&cs->list, struct io_kiocb, compl.list);
1593                 list_del(&req->compl.list);
1594                 __io_cqring_fill_event(req, req->result, req->compl.cflags);
1595
1596                 /*
1597                  * io_free_req() doesn't care about completion_lock unless one
1598                  * of these flags is set. REQ_F_WORK_INITIALIZED is in the list
1599                  * because of a potential deadlock with req->work.fs->lock
1600                  */
1601                 if (req->flags & (REQ_F_FAIL_LINK|REQ_F_LINK_TIMEOUT
1602                                  |REQ_F_WORK_INITIALIZED)) {
1603                         spin_unlock_irq(&ctx->completion_lock);
1604                         io_put_req(req);
1605                         spin_lock_irq(&ctx->completion_lock);
1606                 } else {
1607                         io_put_req(req);
1608                 }
1609         }
1610         io_commit_cqring(ctx);
1611         spin_unlock_irq(&ctx->completion_lock);
1612
1613         io_cqring_ev_posted(ctx);
1614         cs->nr = 0;
1615 }
1616
1617 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1618                               struct io_comp_state *cs)
1619 {
1620         if (!cs) {
1621                 io_cqring_add_event(req, res, cflags);
1622                 io_put_req(req);
1623         } else {
1624                 io_clean_op(req);
1625                 req->result = res;
1626                 req->compl.cflags = cflags;
1627                 list_add_tail(&req->compl.list, &cs->list);
1628                 if (++cs->nr >= 32)
1629                         io_submit_flush_completions(cs);
1630         }
1631 }
1632
1633 static void io_req_complete(struct io_kiocb *req, long res)
1634 {
1635         __io_req_complete(req, res, 0, NULL);
1636 }
1637
1638 static inline bool io_is_fallback_req(struct io_kiocb *req)
1639 {
1640         return req == (struct io_kiocb *)
1641                         ((unsigned long) req->ctx->fallback_req & ~1UL);
1642 }
1643
1644 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1645 {
1646         struct io_kiocb *req;
1647
1648         req = ctx->fallback_req;
1649         if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1650                 return req;
1651
1652         return NULL;
1653 }
1654
1655 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1656                                      struct io_submit_state *state)
1657 {
1658         if (!state->free_reqs) {
1659                 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1660                 size_t sz;
1661                 int ret;
1662
1663                 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1664                 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1665
1666                 /*
1667                  * Bulk alloc is all-or-nothing. If we fail to get a batch,
1668                  * retry single alloc to be on the safe side.
1669                  */
1670                 if (unlikely(ret <= 0)) {
1671                         state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1672                         if (!state->reqs[0])
1673                                 goto fallback;
1674                         ret = 1;
1675                 }
1676                 state->free_reqs = ret;
1677         }
1678
1679         state->free_reqs--;
1680         return state->reqs[state->free_reqs];
1681 fallback:
1682         return io_get_fallback_req(ctx);
1683 }
1684
1685 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1686                           bool fixed)
1687 {
1688         if (fixed)
1689                 percpu_ref_put(req->fixed_file_refs);
1690         else
1691                 fput(file);
1692 }
1693
1694 static void io_dismantle_req(struct io_kiocb *req)
1695 {
1696         io_clean_op(req);
1697
1698         if (req->async_data)
1699                 kfree(req->async_data);
1700         if (req->file)
1701                 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1702
1703         io_req_clean_work(req);
1704 }
1705
1706 static void __io_free_req(struct io_kiocb *req)
1707 {
1708         struct io_uring_task *tctx;
1709         struct io_ring_ctx *ctx;
1710
1711         io_dismantle_req(req);
1712         tctx = req->task->io_uring;
1713         ctx = req->ctx;
1714
1715         atomic_long_inc(&tctx->req_complete);
1716         if (tctx->in_idle)
1717                 wake_up(&tctx->wait);
1718         put_task_struct(req->task);
1719
1720         if (likely(!io_is_fallback_req(req)))
1721                 kmem_cache_free(req_cachep, req);
1722         else
1723                 clear_bit_unlock(0, (unsigned long *) &ctx->fallback_req);
1724         percpu_ref_put(&ctx->refs);
1725 }
1726
1727 static bool io_link_cancel_timeout(struct io_kiocb *req)
1728 {
1729         struct io_timeout_data *io = req->async_data;
1730         struct io_ring_ctx *ctx = req->ctx;
1731         int ret;
1732
1733         ret = hrtimer_try_to_cancel(&io->timer);
1734         if (ret != -1) {
1735                 io_cqring_fill_event(req, -ECANCELED);
1736                 io_commit_cqring(ctx);
1737                 req->flags &= ~REQ_F_LINK_HEAD;
1738                 io_put_req_deferred(req, 1);
1739                 return true;
1740         }
1741
1742         return false;
1743 }
1744
1745 static bool __io_kill_linked_timeout(struct io_kiocb *req)
1746 {
1747         struct io_kiocb *link;
1748         bool wake_ev;
1749
1750         if (list_empty(&req->link_list))
1751                 return false;
1752         link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1753         if (link->opcode != IORING_OP_LINK_TIMEOUT)
1754                 return false;
1755
1756         list_del_init(&link->link_list);
1757         wake_ev = io_link_cancel_timeout(link);
1758         req->flags &= ~REQ_F_LINK_TIMEOUT;
1759         return wake_ev;
1760 }
1761
1762 static void io_kill_linked_timeout(struct io_kiocb *req)
1763 {
1764         struct io_ring_ctx *ctx = req->ctx;
1765         unsigned long flags;
1766         bool wake_ev;
1767
1768         spin_lock_irqsave(&ctx->completion_lock, flags);
1769         wake_ev = __io_kill_linked_timeout(req);
1770         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1771
1772         if (wake_ev)
1773                 io_cqring_ev_posted(ctx);
1774 }
1775
1776 static struct io_kiocb *io_req_link_next(struct io_kiocb *req)
1777 {
1778         struct io_kiocb *nxt;
1779
1780         /*
1781          * The list should never be empty when we are called here. But could
1782          * potentially happen if the chain is messed up, check to be on the
1783          * safe side.
1784          */
1785         if (unlikely(list_empty(&req->link_list)))
1786                 return NULL;
1787
1788         nxt = list_first_entry(&req->link_list, struct io_kiocb, link_list);
1789         list_del_init(&req->link_list);
1790         if (!list_empty(&nxt->link_list))
1791                 nxt->flags |= REQ_F_LINK_HEAD;
1792         return nxt;
1793 }
1794
1795 /*
1796  * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1797  */
1798 static void __io_fail_links(struct io_kiocb *req)
1799 {
1800         struct io_ring_ctx *ctx = req->ctx;
1801
1802         while (!list_empty(&req->link_list)) {
1803                 struct io_kiocb *link = list_first_entry(&req->link_list,
1804                                                 struct io_kiocb, link_list);
1805
1806                 list_del_init(&link->link_list);
1807                 trace_io_uring_fail_link(req, link);
1808
1809                 io_cqring_fill_event(link, -ECANCELED);
1810
1811                 /*
1812                  * It's ok to free under spinlock as they're not linked anymore,
1813                  * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
1814                  * work.fs->lock.
1815                  */
1816                 if (link->flags & REQ_F_WORK_INITIALIZED)
1817                         io_put_req_deferred(link, 2);
1818                 else
1819                         io_double_put_req(link);
1820         }
1821
1822         io_commit_cqring(ctx);
1823 }
1824
1825 static void io_fail_links(struct io_kiocb *req)
1826 {
1827         struct io_ring_ctx *ctx = req->ctx;
1828         unsigned long flags;
1829
1830         spin_lock_irqsave(&ctx->completion_lock, flags);
1831         __io_fail_links(req);
1832         spin_unlock_irqrestore(&ctx->completion_lock, flags);
1833
1834         io_cqring_ev_posted(ctx);
1835 }
1836
1837 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1838 {
1839         req->flags &= ~REQ_F_LINK_HEAD;
1840         if (req->flags & REQ_F_LINK_TIMEOUT)
1841                 io_kill_linked_timeout(req);
1842
1843         /*
1844          * If LINK is set, we have dependent requests in this chain. If we
1845          * didn't fail this request, queue the first one up, moving any other
1846          * dependencies to the next request. In case of failure, fail the rest
1847          * of the chain.
1848          */
1849         if (likely(!(req->flags & REQ_F_FAIL_LINK)))
1850                 return io_req_link_next(req);
1851         io_fail_links(req);
1852         return NULL;
1853 }
1854
1855 static struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1856 {
1857         if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1858                 return NULL;
1859         return __io_req_find_next(req);
1860 }
1861
1862 static int io_req_task_work_add(struct io_kiocb *req, bool twa_signal_ok)
1863 {
1864         struct task_struct *tsk = req->task;
1865         struct io_ring_ctx *ctx = req->ctx;
1866         int ret, notify;
1867
1868         if (tsk->flags & PF_EXITING)
1869                 return -ESRCH;
1870
1871         /*
1872          * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1873          * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1874          * processing task_work. There's no reliable way to tell if TWA_RESUME
1875          * will do the job.
1876          */
1877         notify = 0;
1878         if (!(ctx->flags & IORING_SETUP_SQPOLL) && twa_signal_ok)
1879                 notify = TWA_SIGNAL;
1880
1881         ret = task_work_add(tsk, &req->task_work, notify);
1882         if (!ret)
1883                 wake_up_process(tsk);
1884
1885         return ret;
1886 }
1887
1888 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1889 {
1890         struct io_ring_ctx *ctx = req->ctx;
1891
1892         spin_lock_irq(&ctx->completion_lock);
1893         io_cqring_fill_event(req, error);
1894         io_commit_cqring(ctx);
1895         spin_unlock_irq(&ctx->completion_lock);
1896
1897         io_cqring_ev_posted(ctx);
1898         req_set_fail_links(req);
1899         io_double_put_req(req);
1900 }
1901
1902 static void io_req_task_cancel(struct callback_head *cb)
1903 {
1904         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1905         struct io_ring_ctx *ctx = req->ctx;
1906
1907         __io_req_task_cancel(req, -ECANCELED);
1908         percpu_ref_put(&ctx->refs);
1909 }
1910
1911 static void __io_req_task_submit(struct io_kiocb *req)
1912 {
1913         struct io_ring_ctx *ctx = req->ctx;
1914
1915         if (!__io_sq_thread_acquire_mm(ctx)) {
1916                 mutex_lock(&ctx->uring_lock);
1917                 __io_queue_sqe(req, NULL);
1918                 mutex_unlock(&ctx->uring_lock);
1919         } else {
1920                 __io_req_task_cancel(req, -EFAULT);
1921         }
1922 }
1923
1924 static void io_req_task_submit(struct callback_head *cb)
1925 {
1926         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1927         struct io_ring_ctx *ctx = req->ctx;
1928
1929         __io_req_task_submit(req);
1930         percpu_ref_put(&ctx->refs);
1931 }
1932
1933 static void io_req_task_queue(struct io_kiocb *req)
1934 {
1935         int ret;
1936
1937         init_task_work(&req->task_work, io_req_task_submit);
1938         percpu_ref_get(&req->ctx->refs);
1939
1940         ret = io_req_task_work_add(req, true);
1941         if (unlikely(ret)) {
1942                 struct task_struct *tsk;
1943
1944                 init_task_work(&req->task_work, io_req_task_cancel);
1945                 tsk = io_wq_get_task(req->ctx->io_wq);
1946                 task_work_add(tsk, &req->task_work, 0);
1947                 wake_up_process(tsk);
1948         }
1949 }
1950
1951 static void io_queue_next(struct io_kiocb *req)
1952 {
1953         struct io_kiocb *nxt = io_req_find_next(req);
1954
1955         if (nxt)
1956                 io_req_task_queue(nxt);
1957 }
1958
1959 static void io_free_req(struct io_kiocb *req)
1960 {
1961         io_queue_next(req);
1962         __io_free_req(req);
1963 }
1964
1965 struct req_batch {
1966         void *reqs[IO_IOPOLL_BATCH];
1967         int to_free;
1968
1969         struct task_struct      *task;
1970         int                     task_refs;
1971 };
1972
1973 static inline void io_init_req_batch(struct req_batch *rb)
1974 {
1975         rb->to_free = 0;
1976         rb->task_refs = 0;
1977         rb->task = NULL;
1978 }
1979
1980 static void __io_req_free_batch_flush(struct io_ring_ctx *ctx,
1981                                       struct req_batch *rb)
1982 {
1983         kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1984         percpu_ref_put_many(&ctx->refs, rb->to_free);
1985         rb->to_free = 0;
1986 }
1987
1988 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
1989                                      struct req_batch *rb)
1990 {
1991         if (rb->to_free)
1992                 __io_req_free_batch_flush(ctx, rb);
1993         if (rb->task) {
1994                 atomic_long_add(rb->task_refs, &rb->task->io_uring->req_complete);
1995                 put_task_struct_many(rb->task, rb->task_refs);
1996                 rb->task = NULL;
1997         }
1998 }
1999
2000 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req)
2001 {
2002         if (unlikely(io_is_fallback_req(req))) {
2003                 io_free_req(req);
2004                 return;
2005         }
2006         if (req->flags & REQ_F_LINK_HEAD)
2007                 io_queue_next(req);
2008
2009         if (req->task != rb->task) {
2010                 if (rb->task) {
2011                         atomic_long_add(rb->task_refs, &rb->task->io_uring->req_complete);
2012                         put_task_struct_many(rb->task, rb->task_refs);
2013                 }
2014                 rb->task = req->task;
2015                 rb->task_refs = 0;
2016         }
2017         rb->task_refs++;
2018
2019         io_dismantle_req(req);
2020         rb->reqs[rb->to_free++] = req;
2021         if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
2022                 __io_req_free_batch_flush(req->ctx, rb);
2023 }
2024
2025 /*
2026  * Drop reference to request, return next in chain (if there is one) if this
2027  * was the last reference to this request.
2028  */
2029 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2030 {
2031         struct io_kiocb *nxt = NULL;
2032
2033         if (refcount_dec_and_test(&req->refs)) {
2034                 nxt = io_req_find_next(req);
2035                 __io_free_req(req);
2036         }
2037         return nxt;
2038 }
2039
2040 static void io_put_req(struct io_kiocb *req)
2041 {
2042         if (refcount_dec_and_test(&req->refs))
2043                 io_free_req(req);
2044 }
2045
2046 static void io_put_req_deferred_cb(struct callback_head *cb)
2047 {
2048         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2049
2050         io_free_req(req);
2051 }
2052
2053 static void io_free_req_deferred(struct io_kiocb *req)
2054 {
2055         int ret;
2056
2057         init_task_work(&req->task_work, io_put_req_deferred_cb);
2058         ret = io_req_task_work_add(req, true);
2059         if (unlikely(ret)) {
2060                 struct task_struct *tsk;
2061
2062                 tsk = io_wq_get_task(req->ctx->io_wq);
2063                 task_work_add(tsk, &req->task_work, 0);
2064                 wake_up_process(tsk);
2065         }
2066 }
2067
2068 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2069 {
2070         if (refcount_sub_and_test(refs, &req->refs))
2071                 io_free_req_deferred(req);
2072 }
2073
2074 static struct io_wq_work *io_steal_work(struct io_kiocb *req)
2075 {
2076         struct io_kiocb *nxt;
2077
2078         /*
2079          * A ref is owned by io-wq in which context we're. So, if that's the
2080          * last one, it's safe to steal next work. False negatives are Ok,
2081          * it just will be re-punted async in io_put_work()
2082          */
2083         if (refcount_read(&req->refs) != 1)
2084                 return NULL;
2085
2086         nxt = io_req_find_next(req);
2087         return nxt ? &nxt->work : NULL;
2088 }
2089
2090 static void io_double_put_req(struct io_kiocb *req)
2091 {
2092         /* drop both submit and complete references */
2093         if (refcount_sub_and_test(2, &req->refs))
2094                 io_free_req(req);
2095 }
2096
2097 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
2098 {
2099         struct io_rings *rings = ctx->rings;
2100
2101         if (test_bit(0, &ctx->cq_check_overflow)) {
2102                 /*
2103                  * noflush == true is from the waitqueue handler, just ensure
2104                  * we wake up the task, and the next invocation will flush the
2105                  * entries. We cannot safely to it from here.
2106                  */
2107                 if (noflush && !list_empty(&ctx->cq_overflow_list))
2108                         return -1U;
2109
2110                 io_cqring_overflow_flush(ctx, false, NULL, NULL);
2111         }
2112
2113         /* See comment at the top of this file */
2114         smp_rmb();
2115         return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
2116 }
2117
2118 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2119 {
2120         struct io_rings *rings = ctx->rings;
2121
2122         /* make sure SQ entry isn't read before tail */
2123         return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2124 }
2125
2126 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2127 {
2128         unsigned int cflags;
2129
2130         cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2131         cflags |= IORING_CQE_F_BUFFER;
2132         req->flags &= ~REQ_F_BUFFER_SELECTED;
2133         kfree(kbuf);
2134         return cflags;
2135 }
2136
2137 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2138 {
2139         struct io_buffer *kbuf;
2140
2141         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2142         return io_put_kbuf(req, kbuf);
2143 }
2144
2145 static inline bool io_run_task_work(void)
2146 {
2147         /*
2148          * Not safe to run on exiting task, and the task_work handling will
2149          * not add work to such a task.
2150          */
2151         if (unlikely(current->flags & PF_EXITING))
2152                 return false;
2153         if (current->task_works) {
2154                 __set_current_state(TASK_RUNNING);
2155                 task_work_run();
2156                 return true;
2157         }
2158
2159         return false;
2160 }
2161
2162 static void io_iopoll_queue(struct list_head *again)
2163 {
2164         struct io_kiocb *req;
2165
2166         do {
2167                 req = list_first_entry(again, struct io_kiocb, inflight_entry);
2168                 list_del(&req->inflight_entry);
2169                 __io_complete_rw(req, -EAGAIN, 0, NULL);
2170         } while (!list_empty(again));
2171 }
2172
2173 /*
2174  * Find and free completed poll iocbs
2175  */
2176 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2177                                struct list_head *done)
2178 {
2179         struct req_batch rb;
2180         struct io_kiocb *req;
2181         LIST_HEAD(again);
2182
2183         /* order with ->result store in io_complete_rw_iopoll() */
2184         smp_rmb();
2185
2186         io_init_req_batch(&rb);
2187         while (!list_empty(done)) {
2188                 int cflags = 0;
2189
2190                 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2191                 if (READ_ONCE(req->result) == -EAGAIN) {
2192                         req->result = 0;
2193                         req->iopoll_completed = 0;
2194                         list_move_tail(&req->inflight_entry, &again);
2195                         continue;
2196                 }
2197                 list_del(&req->inflight_entry);
2198
2199                 if (req->flags & REQ_F_BUFFER_SELECTED)
2200                         cflags = io_put_rw_kbuf(req);
2201
2202                 __io_cqring_fill_event(req, req->result, cflags);
2203                 (*nr_events)++;
2204
2205                 if (refcount_dec_and_test(&req->refs))
2206                         io_req_free_batch(&rb, req);
2207         }
2208
2209         io_commit_cqring(ctx);
2210         if (ctx->flags & IORING_SETUP_SQPOLL)
2211                 io_cqring_ev_posted(ctx);
2212         io_req_free_batch_finish(ctx, &rb);
2213
2214         if (!list_empty(&again))
2215                 io_iopoll_queue(&again);
2216 }
2217
2218 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2219                         long min)
2220 {
2221         struct io_kiocb *req, *tmp;
2222         LIST_HEAD(done);
2223         bool spin;
2224         int ret;
2225
2226         /*
2227          * Only spin for completions if we don't have multiple devices hanging
2228          * off our complete list, and we're under the requested amount.
2229          */
2230         spin = !ctx->poll_multi_file && *nr_events < min;
2231
2232         ret = 0;
2233         list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2234                 struct kiocb *kiocb = &req->rw.kiocb;
2235
2236                 /*
2237                  * Move completed and retryable entries to our local lists.
2238                  * If we find a request that requires polling, break out
2239                  * and complete those lists first, if we have entries there.
2240                  */
2241                 if (READ_ONCE(req->iopoll_completed)) {
2242                         list_move_tail(&req->inflight_entry, &done);
2243                         continue;
2244                 }
2245                 if (!list_empty(&done))
2246                         break;
2247
2248                 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2249                 if (ret < 0)
2250                         break;
2251
2252                 /* iopoll may have completed current req */
2253                 if (READ_ONCE(req->iopoll_completed))
2254                         list_move_tail(&req->inflight_entry, &done);
2255
2256                 if (ret && spin)
2257                         spin = false;
2258                 ret = 0;
2259         }
2260
2261         if (!list_empty(&done))
2262                 io_iopoll_complete(ctx, nr_events, &done);
2263
2264         return ret;
2265 }
2266
2267 /*
2268  * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2269  * non-spinning poll check - we'll still enter the driver poll loop, but only
2270  * as a non-spinning completion check.
2271  */
2272 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2273                                 long min)
2274 {
2275         while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2276                 int ret;
2277
2278                 ret = io_do_iopoll(ctx, nr_events, min);
2279                 if (ret < 0)
2280                         return ret;
2281                 if (*nr_events >= min)
2282                         return 0;
2283         }
2284
2285         return 1;
2286 }
2287
2288 /*
2289  * We can't just wait for polled events to come to us, we have to actively
2290  * find and complete them.
2291  */
2292 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2293 {
2294         if (!(ctx->flags & IORING_SETUP_IOPOLL))
2295                 return;
2296
2297         mutex_lock(&ctx->uring_lock);
2298         while (!list_empty(&ctx->iopoll_list)) {
2299                 unsigned int nr_events = 0;
2300
2301                 io_do_iopoll(ctx, &nr_events, 0);
2302
2303                 /* let it sleep and repeat later if can't complete a request */
2304                 if (nr_events == 0)
2305                         break;
2306                 /*
2307                  * Ensure we allow local-to-the-cpu processing to take place,
2308                  * in this case we need to ensure that we reap all events.
2309                  * Also let task_work, etc. to progress by releasing the mutex
2310                  */
2311                 if (need_resched()) {
2312                         mutex_unlock(&ctx->uring_lock);
2313                         cond_resched();
2314                         mutex_lock(&ctx->uring_lock);
2315                 }
2316         }
2317         mutex_unlock(&ctx->uring_lock);
2318 }
2319
2320 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2321 {
2322         unsigned int nr_events = 0;
2323         int iters = 0, ret = 0;
2324
2325         /*
2326          * We disallow the app entering submit/complete with polling, but we
2327          * still need to lock the ring to prevent racing with polled issue
2328          * that got punted to a workqueue.
2329          */
2330         mutex_lock(&ctx->uring_lock);
2331         do {
2332                 /*
2333                  * Don't enter poll loop if we already have events pending.
2334                  * If we do, we can potentially be spinning for commands that
2335                  * already triggered a CQE (eg in error).
2336                  */
2337                 if (io_cqring_events(ctx, false))
2338                         break;
2339
2340                 /*
2341                  * If a submit got punted to a workqueue, we can have the
2342                  * application entering polling for a command before it gets
2343                  * issued. That app will hold the uring_lock for the duration
2344                  * of the poll right here, so we need to take a breather every
2345                  * now and then to ensure that the issue has a chance to add
2346                  * the poll to the issued list. Otherwise we can spin here
2347                  * forever, while the workqueue is stuck trying to acquire the
2348                  * very same mutex.
2349                  */
2350                 if (!(++iters & 7)) {
2351                         mutex_unlock(&ctx->uring_lock);
2352                         io_run_task_work();
2353                         mutex_lock(&ctx->uring_lock);
2354                 }
2355
2356                 ret = io_iopoll_getevents(ctx, &nr_events, min);
2357                 if (ret <= 0)
2358                         break;
2359                 ret = 0;
2360         } while (min && !nr_events && !need_resched());
2361
2362         mutex_unlock(&ctx->uring_lock);
2363         return ret;
2364 }
2365
2366 static void kiocb_end_write(struct io_kiocb *req)
2367 {
2368         /*
2369          * Tell lockdep we inherited freeze protection from submission
2370          * thread.
2371          */
2372         if (req->flags & REQ_F_ISREG) {
2373                 struct inode *inode = file_inode(req->file);
2374
2375                 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2376         }
2377         file_end_write(req->file);
2378 }
2379
2380 static void io_complete_rw_common(struct kiocb *kiocb, long res,
2381                                   struct io_comp_state *cs)
2382 {
2383         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2384         int cflags = 0;
2385
2386         if (kiocb->ki_flags & IOCB_WRITE)
2387                 kiocb_end_write(req);
2388
2389         if (res != req->result)
2390                 req_set_fail_links(req);
2391         if (req->flags & REQ_F_BUFFER_SELECTED)
2392                 cflags = io_put_rw_kbuf(req);
2393         __io_req_complete(req, res, cflags, cs);
2394 }
2395
2396 #ifdef CONFIG_BLOCK
2397 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2398 {
2399         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2400         ssize_t ret = -ECANCELED;
2401         struct iov_iter iter;
2402         int rw;
2403
2404         if (error) {
2405                 ret = error;
2406                 goto end_req;
2407         }
2408
2409         switch (req->opcode) {
2410         case IORING_OP_READV:
2411         case IORING_OP_READ_FIXED:
2412         case IORING_OP_READ:
2413                 rw = READ;
2414                 break;
2415         case IORING_OP_WRITEV:
2416         case IORING_OP_WRITE_FIXED:
2417         case IORING_OP_WRITE:
2418                 rw = WRITE;
2419                 break;
2420         default:
2421                 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2422                                 req->opcode);
2423                 goto end_req;
2424         }
2425
2426         if (!req->async_data) {
2427                 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2428                 if (ret < 0)
2429                         goto end_req;
2430                 ret = io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2431                 if (!ret)
2432                         return true;
2433                 kfree(iovec);
2434         } else {
2435                 return true;
2436         }
2437 end_req:
2438         req_set_fail_links(req);
2439         io_req_complete(req, ret);
2440         return false;
2441 }
2442 #endif
2443
2444 static bool io_rw_reissue(struct io_kiocb *req, long res)
2445 {
2446 #ifdef CONFIG_BLOCK
2447         umode_t mode = file_inode(req->file)->i_mode;
2448         int ret;
2449
2450         if (!S_ISBLK(mode) && !S_ISREG(mode))
2451                 return false;
2452         if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2453                 return false;
2454
2455         ret = io_sq_thread_acquire_mm(req->ctx, req);
2456
2457         if (io_resubmit_prep(req, ret)) {
2458                 refcount_inc(&req->refs);
2459                 io_queue_async_work(req);
2460                 return true;
2461         }
2462
2463 #endif
2464         return false;
2465 }
2466
2467 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2468                              struct io_comp_state *cs)
2469 {
2470         if (!io_rw_reissue(req, res))
2471                 io_complete_rw_common(&req->rw.kiocb, res, cs);
2472 }
2473
2474 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2475 {
2476         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2477
2478         __io_complete_rw(req, res, res2, NULL);
2479 }
2480
2481 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2482 {
2483         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2484
2485         if (kiocb->ki_flags & IOCB_WRITE)
2486                 kiocb_end_write(req);
2487
2488         if (res != -EAGAIN && res != req->result)
2489                 req_set_fail_links(req);
2490
2491         WRITE_ONCE(req->result, res);
2492         /* order with io_poll_complete() checking ->result */
2493         smp_wmb();
2494         WRITE_ONCE(req->iopoll_completed, 1);
2495 }
2496
2497 /*
2498  * After the iocb has been issued, it's safe to be found on the poll list.
2499  * Adding the kiocb to the list AFTER submission ensures that we don't
2500  * find it from a io_iopoll_getevents() thread before the issuer is done
2501  * accessing the kiocb cookie.
2502  */
2503 static void io_iopoll_req_issued(struct io_kiocb *req)
2504 {
2505         struct io_ring_ctx *ctx = req->ctx;
2506
2507         /*
2508          * Track whether we have multiple files in our lists. This will impact
2509          * how we do polling eventually, not spinning if we're on potentially
2510          * different devices.
2511          */
2512         if (list_empty(&ctx->iopoll_list)) {
2513                 ctx->poll_multi_file = false;
2514         } else if (!ctx->poll_multi_file) {
2515                 struct io_kiocb *list_req;
2516
2517                 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2518                                                 inflight_entry);
2519                 if (list_req->file != req->file)
2520                         ctx->poll_multi_file = true;
2521         }
2522
2523         /*
2524          * For fast devices, IO may have already completed. If it has, add
2525          * it to the front so we find it first.
2526          */
2527         if (READ_ONCE(req->iopoll_completed))
2528                 list_add(&req->inflight_entry, &ctx->iopoll_list);
2529         else
2530                 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2531
2532         if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2533             wq_has_sleeper(&ctx->sq_data->wait))
2534                 wake_up(&ctx->sq_data->wait);
2535 }
2536
2537 static void __io_state_file_put(struct io_submit_state *state)
2538 {
2539         if (state->has_refs)
2540                 fput_many(state->file, state->has_refs);
2541         state->file = NULL;
2542 }
2543
2544 static inline void io_state_file_put(struct io_submit_state *state)
2545 {
2546         if (state->file)
2547                 __io_state_file_put(state);
2548 }
2549
2550 /*
2551  * Get as many references to a file as we have IOs left in this submission,
2552  * assuming most submissions are for one file, or at least that each file
2553  * has more than one submission.
2554  */
2555 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2556 {
2557         if (!state)
2558                 return fget(fd);
2559
2560         if (state->file) {
2561                 if (state->fd == fd) {
2562                         state->has_refs--;
2563                         return state->file;
2564                 }
2565                 __io_state_file_put(state);
2566         }
2567         state->file = fget_many(fd, state->ios_left);
2568         if (!state->file)
2569                 return NULL;
2570
2571         state->fd = fd;
2572         state->has_refs = state->ios_left - 1;
2573         return state->file;
2574 }
2575
2576 static bool io_bdev_nowait(struct block_device *bdev)
2577 {
2578 #ifdef CONFIG_BLOCK
2579         return !bdev || queue_is_mq(bdev_get_queue(bdev));
2580 #else
2581         return true;
2582 #endif
2583 }
2584
2585 /*
2586  * If we tracked the file through the SCM inflight mechanism, we could support
2587  * any file. For now, just ensure that anything potentially problematic is done
2588  * inline.
2589  */
2590 static bool io_file_supports_async(struct file *file, int rw)
2591 {
2592         umode_t mode = file_inode(file)->i_mode;
2593
2594         if (S_ISBLK(mode)) {
2595                 if (io_bdev_nowait(file->f_inode->i_bdev))
2596                         return true;
2597                 return false;
2598         }
2599         if (S_ISCHR(mode) || S_ISSOCK(mode))
2600                 return true;
2601         if (S_ISREG(mode)) {
2602                 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2603                     file->f_op != &io_uring_fops)
2604                         return true;
2605                 return false;
2606         }
2607
2608         /* any ->read/write should understand O_NONBLOCK */
2609         if (file->f_flags & O_NONBLOCK)
2610                 return true;
2611
2612         if (!(file->f_mode & FMODE_NOWAIT))
2613                 return false;
2614
2615         if (rw == READ)
2616                 return file->f_op->read_iter != NULL;
2617
2618         return file->f_op->write_iter != NULL;
2619 }
2620
2621 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2622 {
2623         struct io_ring_ctx *ctx = req->ctx;
2624         struct kiocb *kiocb = &req->rw.kiocb;
2625         unsigned ioprio;
2626         int ret;
2627
2628         if (S_ISREG(file_inode(req->file)->i_mode))
2629                 req->flags |= REQ_F_ISREG;
2630
2631         kiocb->ki_pos = READ_ONCE(sqe->off);
2632         if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2633                 req->flags |= REQ_F_CUR_POS;
2634                 kiocb->ki_pos = req->file->f_pos;
2635         }
2636         kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2637         kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2638         ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2639         if (unlikely(ret))
2640                 return ret;
2641
2642         ioprio = READ_ONCE(sqe->ioprio);
2643         if (ioprio) {
2644                 ret = ioprio_check_cap(ioprio);
2645                 if (ret)
2646                         return ret;
2647
2648                 kiocb->ki_ioprio = ioprio;
2649         } else
2650                 kiocb->ki_ioprio = get_current_ioprio();
2651
2652         /* don't allow async punt if RWF_NOWAIT was requested */
2653         if (kiocb->ki_flags & IOCB_NOWAIT)
2654                 req->flags |= REQ_F_NOWAIT;
2655
2656         if (ctx->flags & IORING_SETUP_IOPOLL) {
2657                 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2658                     !kiocb->ki_filp->f_op->iopoll)
2659                         return -EOPNOTSUPP;
2660
2661                 kiocb->ki_flags |= IOCB_HIPRI;
2662                 kiocb->ki_complete = io_complete_rw_iopoll;
2663                 req->iopoll_completed = 0;
2664         } else {
2665                 if (kiocb->ki_flags & IOCB_HIPRI)
2666                         return -EINVAL;
2667                 kiocb->ki_complete = io_complete_rw;
2668         }
2669
2670         req->rw.addr = READ_ONCE(sqe->addr);
2671         req->rw.len = READ_ONCE(sqe->len);
2672         req->buf_index = READ_ONCE(sqe->buf_index);
2673         return 0;
2674 }
2675
2676 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2677 {
2678         switch (ret) {
2679         case -EIOCBQUEUED:
2680                 break;
2681         case -ERESTARTSYS:
2682         case -ERESTARTNOINTR:
2683         case -ERESTARTNOHAND:
2684         case -ERESTART_RESTARTBLOCK:
2685                 /*
2686                  * We can't just restart the syscall, since previously
2687                  * submitted sqes may already be in progress. Just fail this
2688                  * IO with EINTR.
2689                  */
2690                 ret = -EINTR;
2691                 fallthrough;
2692         default:
2693                 kiocb->ki_complete(kiocb, ret, 0);
2694         }
2695 }
2696
2697 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2698                        struct io_comp_state *cs)
2699 {
2700         struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2701         struct io_async_rw *io = req->async_data;
2702
2703         /* add previously done IO, if any */
2704         if (io && io->bytes_done > 0) {
2705                 if (ret < 0)
2706                         ret = io->bytes_done;
2707                 else
2708                         ret += io->bytes_done;
2709         }
2710
2711         if (req->flags & REQ_F_CUR_POS)
2712                 req->file->f_pos = kiocb->ki_pos;
2713         if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2714                 __io_complete_rw(req, ret, 0, cs);
2715         else
2716                 io_rw_done(kiocb, ret);
2717 }
2718
2719 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2720                                struct iov_iter *iter)
2721 {
2722         struct io_ring_ctx *ctx = req->ctx;
2723         size_t len = req->rw.len;
2724         struct io_mapped_ubuf *imu;
2725         u16 index, buf_index = req->buf_index;
2726         size_t offset;
2727         u64 buf_addr;
2728
2729         if (unlikely(buf_index >= ctx->nr_user_bufs))
2730                 return -EFAULT;
2731         index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2732         imu = &ctx->user_bufs[index];
2733         buf_addr = req->rw.addr;
2734
2735         /* overflow */
2736         if (buf_addr + len < buf_addr)
2737                 return -EFAULT;
2738         /* not inside the mapped region */
2739         if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2740                 return -EFAULT;
2741
2742         /*
2743          * May not be a start of buffer, set size appropriately
2744          * and advance us to the beginning.
2745          */
2746         offset = buf_addr - imu->ubuf;
2747         iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2748
2749         if (offset) {
2750                 /*
2751                  * Don't use iov_iter_advance() here, as it's really slow for
2752                  * using the latter parts of a big fixed buffer - it iterates
2753                  * over each segment manually. We can cheat a bit here, because
2754                  * we know that:
2755                  *
2756                  * 1) it's a BVEC iter, we set it up
2757                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
2758                  *    first and last bvec
2759                  *
2760                  * So just find our index, and adjust the iterator afterwards.
2761                  * If the offset is within the first bvec (or the whole first
2762                  * bvec, just use iov_iter_advance(). This makes it easier
2763                  * since we can just skip the first segment, which may not
2764                  * be PAGE_SIZE aligned.
2765                  */
2766                 const struct bio_vec *bvec = imu->bvec;
2767
2768                 if (offset <= bvec->bv_len) {
2769                         iov_iter_advance(iter, offset);
2770                 } else {
2771                         unsigned long seg_skip;
2772
2773                         /* skip first vec */
2774                         offset -= bvec->bv_len;
2775                         seg_skip = 1 + (offset >> PAGE_SHIFT);
2776
2777                         iter->bvec = bvec + seg_skip;
2778                         iter->nr_segs -= seg_skip;
2779                         iter->count -= bvec->bv_len + offset;
2780                         iter->iov_offset = offset & ~PAGE_MASK;
2781                 }
2782         }
2783
2784         return len;
2785 }
2786
2787 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2788 {
2789         if (needs_lock)
2790                 mutex_unlock(&ctx->uring_lock);
2791 }
2792
2793 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2794 {
2795         /*
2796          * "Normal" inline submissions always hold the uring_lock, since we
2797          * grab it from the system call. Same is true for the SQPOLL offload.
2798          * The only exception is when we've detached the request and issue it
2799          * from an async worker thread, grab the lock for that case.
2800          */
2801         if (needs_lock)
2802                 mutex_lock(&ctx->uring_lock);
2803 }
2804
2805 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2806                                           int bgid, struct io_buffer *kbuf,
2807                                           bool needs_lock)
2808 {
2809         struct io_buffer *head;
2810
2811         if (req->flags & REQ_F_BUFFER_SELECTED)
2812                 return kbuf;
2813
2814         io_ring_submit_lock(req->ctx, needs_lock);
2815
2816         lockdep_assert_held(&req->ctx->uring_lock);
2817
2818         head = idr_find(&req->ctx->io_buffer_idr, bgid);
2819         if (head) {
2820                 if (!list_empty(&head->list)) {
2821                         kbuf = list_last_entry(&head->list, struct io_buffer,
2822                                                         list);
2823                         list_del(&kbuf->list);
2824                 } else {
2825                         kbuf = head;
2826                         idr_remove(&req->ctx->io_buffer_idr, bgid);
2827                 }
2828                 if (*len > kbuf->len)
2829                         *len = kbuf->len;
2830         } else {
2831                 kbuf = ERR_PTR(-ENOBUFS);
2832         }
2833
2834         io_ring_submit_unlock(req->ctx, needs_lock);
2835
2836         return kbuf;
2837 }
2838
2839 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2840                                         bool needs_lock)
2841 {
2842         struct io_buffer *kbuf;
2843         u16 bgid;
2844
2845         kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2846         bgid = req->buf_index;
2847         kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2848         if (IS_ERR(kbuf))
2849                 return kbuf;
2850         req->rw.addr = (u64) (unsigned long) kbuf;
2851         req->flags |= REQ_F_BUFFER_SELECTED;
2852         return u64_to_user_ptr(kbuf->addr);
2853 }
2854
2855 #ifdef CONFIG_COMPAT
2856 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2857                                 bool needs_lock)
2858 {
2859         struct compat_iovec __user *uiov;
2860         compat_ssize_t clen;
2861         void __user *buf;
2862         ssize_t len;
2863
2864         uiov = u64_to_user_ptr(req->rw.addr);
2865         if (!access_ok(uiov, sizeof(*uiov)))
2866                 return -EFAULT;
2867         if (__get_user(clen, &uiov->iov_len))
2868                 return -EFAULT;
2869         if (clen < 0)
2870                 return -EINVAL;
2871
2872         len = clen;
2873         buf = io_rw_buffer_select(req, &len, needs_lock);
2874         if (IS_ERR(buf))
2875                 return PTR_ERR(buf);
2876         iov[0].iov_base = buf;
2877         iov[0].iov_len = (compat_size_t) len;
2878         return 0;
2879 }
2880 #endif
2881
2882 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2883                                       bool needs_lock)
2884 {
2885         struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2886         void __user *buf;
2887         ssize_t len;
2888
2889         if (copy_from_user(iov, uiov, sizeof(*uiov)))
2890                 return -EFAULT;
2891
2892         len = iov[0].iov_len;
2893         if (len < 0)
2894                 return -EINVAL;
2895         buf = io_rw_buffer_select(req, &len, needs_lock);
2896         if (IS_ERR(buf))
2897                 return PTR_ERR(buf);
2898         iov[0].iov_base = buf;
2899         iov[0].iov_len = len;
2900         return 0;
2901 }
2902
2903 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2904                                     bool needs_lock)
2905 {
2906         if (req->flags & REQ_F_BUFFER_SELECTED) {
2907                 struct io_buffer *kbuf;
2908
2909                 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2910                 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2911                 iov[0].iov_len = kbuf->len;
2912                 return 0;
2913         }
2914         if (!req->rw.len)
2915                 return 0;
2916         else if (req->rw.len > 1)
2917                 return -EINVAL;
2918
2919 #ifdef CONFIG_COMPAT
2920         if (req->ctx->compat)
2921                 return io_compat_import(req, iov, needs_lock);
2922 #endif
2923
2924         return __io_iov_buffer_select(req, iov, needs_lock);
2925 }
2926
2927 static ssize_t __io_import_iovec(int rw, struct io_kiocb *req,
2928                                  struct iovec **iovec, struct iov_iter *iter,
2929                                  bool needs_lock)
2930 {
2931         void __user *buf = u64_to_user_ptr(req->rw.addr);
2932         size_t sqe_len = req->rw.len;
2933         ssize_t ret;
2934         u8 opcode;
2935
2936         opcode = req->opcode;
2937         if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2938                 *iovec = NULL;
2939                 return io_import_fixed(req, rw, iter);
2940         }
2941
2942         /* buffer index only valid with fixed read/write, or buffer select  */
2943         if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2944                 return -EINVAL;
2945
2946         if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2947                 if (req->flags & REQ_F_BUFFER_SELECT) {
2948                         buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2949                         if (IS_ERR(buf))
2950                                 return PTR_ERR(buf);
2951                         req->rw.len = sqe_len;
2952                 }
2953
2954                 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2955                 *iovec = NULL;
2956                 return ret < 0 ? ret : sqe_len;
2957         }
2958
2959         if (req->flags & REQ_F_BUFFER_SELECT) {
2960                 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2961                 if (!ret) {
2962                         ret = (*iovec)->iov_len;
2963                         iov_iter_init(iter, rw, *iovec, 1, ret);
2964                 }
2965                 *iovec = NULL;
2966                 return ret;
2967         }
2968
2969         return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
2970                               req->ctx->compat);
2971 }
2972
2973 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2974                                struct iovec **iovec, struct iov_iter *iter,
2975                                bool needs_lock)
2976 {
2977         struct io_async_rw *iorw = req->async_data;
2978
2979         if (!iorw)
2980                 return __io_import_iovec(rw, req, iovec, iter, needs_lock);
2981         *iovec = NULL;
2982         return iov_iter_count(&iorw->iter);
2983 }
2984
2985 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2986 {
2987         return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2988 }
2989
2990 /*
2991  * For files that don't have ->read_iter() and ->write_iter(), handle them
2992  * by looping over ->read() or ->write() manually.
2993  */
2994 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2995                            struct iov_iter *iter)
2996 {
2997         ssize_t ret = 0;
2998
2999         /*
3000          * Don't support polled IO through this interface, and we can't
3001          * support non-blocking either. For the latter, this just causes
3002          * the kiocb to be handled from an async context.
3003          */
3004         if (kiocb->ki_flags & IOCB_HIPRI)
3005                 return -EOPNOTSUPP;
3006         if (kiocb->ki_flags & IOCB_NOWAIT)
3007                 return -EAGAIN;
3008
3009         while (iov_iter_count(iter)) {
3010                 struct iovec iovec;
3011                 ssize_t nr;
3012
3013                 if (!iov_iter_is_bvec(iter)) {
3014                         iovec = iov_iter_iovec(iter);
3015                 } else {
3016                         /* fixed buffers import bvec */
3017                         iovec.iov_base = kmap(iter->bvec->bv_page)
3018                                                 + iter->iov_offset;
3019                         iovec.iov_len = min(iter->count,
3020                                         iter->bvec->bv_len - iter->iov_offset);
3021                 }
3022
3023                 if (rw == READ) {
3024                         nr = file->f_op->read(file, iovec.iov_base,
3025                                               iovec.iov_len, io_kiocb_ppos(kiocb));
3026                 } else {
3027                         nr = file->f_op->write(file, iovec.iov_base,
3028                                                iovec.iov_len, io_kiocb_ppos(kiocb));
3029                 }
3030
3031                 if (iov_iter_is_bvec(iter))
3032                         kunmap(iter->bvec->bv_page);
3033
3034                 if (nr < 0) {
3035                         if (!ret)
3036                                 ret = nr;
3037                         break;
3038                 }
3039                 ret += nr;
3040                 if (nr != iovec.iov_len)
3041                         break;
3042                 iov_iter_advance(iter, nr);
3043         }
3044
3045         return ret;
3046 }
3047
3048 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3049                           const struct iovec *fast_iov, struct iov_iter *iter)
3050 {
3051         struct io_async_rw *rw = req->async_data;
3052
3053         memcpy(&rw->iter, iter, sizeof(*iter));
3054         rw->free_iovec = iovec;
3055         rw->bytes_done = 0;
3056         /* can only be fixed buffers, no need to do anything */
3057         if (iter->type == ITER_BVEC)
3058                 return;
3059         if (!iovec) {
3060                 unsigned iov_off = 0;
3061
3062                 rw->iter.iov = rw->fast_iov;
3063                 if (iter->iov != fast_iov) {
3064                         iov_off = iter->iov - fast_iov;
3065                         rw->iter.iov += iov_off;
3066                 }
3067                 if (rw->fast_iov != fast_iov)
3068                         memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3069                                sizeof(struct iovec) * iter->nr_segs);
3070         } else {
3071                 req->flags |= REQ_F_NEED_CLEANUP;
3072         }
3073 }
3074
3075 static inline int __io_alloc_async_data(struct io_kiocb *req)
3076 {
3077         WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3078         req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3079         return req->async_data == NULL;
3080 }
3081
3082 static int io_alloc_async_data(struct io_kiocb *req)
3083 {
3084         if (!io_op_defs[req->opcode].needs_async_data)
3085                 return 0;
3086
3087         return  __io_alloc_async_data(req);
3088 }
3089
3090 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3091                              const struct iovec *fast_iov,
3092                              struct iov_iter *iter, bool force)
3093 {
3094         if (!force && !io_op_defs[req->opcode].needs_async_data)
3095                 return 0;
3096         if (!req->async_data) {
3097                 if (__io_alloc_async_data(req))
3098                         return -ENOMEM;
3099
3100                 io_req_map_rw(req, iovec, fast_iov, iter);
3101         }
3102         return 0;
3103 }
3104
3105 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3106 {
3107         struct io_async_rw *iorw = req->async_data;
3108         struct iovec *iov = iorw->fast_iov;
3109         ssize_t ret;
3110
3111         ret = __io_import_iovec(rw, req, &iov, &iorw->iter, false);
3112         if (unlikely(ret < 0))
3113                 return ret;
3114
3115         iorw->bytes_done = 0;
3116         iorw->free_iovec = iov;
3117         if (iov)
3118                 req->flags |= REQ_F_NEED_CLEANUP;
3119         return 0;
3120 }
3121
3122 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3123 {
3124         ssize_t ret;
3125
3126         ret = io_prep_rw(req, sqe);
3127         if (ret)
3128                 return ret;
3129
3130         if (unlikely(!(req->file->f_mode & FMODE_READ)))
3131                 return -EBADF;
3132
3133         /* either don't need iovec imported or already have it */
3134         if (!req->async_data)
3135                 return 0;
3136         return io_rw_prep_async(req, READ);
3137 }
3138
3139 /*
3140  * This is our waitqueue callback handler, registered through lock_page_async()
3141  * when we initially tried to do the IO with the iocb armed our waitqueue.
3142  * This gets called when the page is unlocked, and we generally expect that to
3143  * happen when the page IO is completed and the page is now uptodate. This will
3144  * queue a task_work based retry of the operation, attempting to copy the data
3145  * again. If the latter fails because the page was NOT uptodate, then we will
3146  * do a thread based blocking retry of the operation. That's the unexpected
3147  * slow path.
3148  */
3149 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3150                              int sync, void *arg)
3151 {
3152         struct wait_page_queue *wpq;
3153         struct io_kiocb *req = wait->private;
3154         struct wait_page_key *key = arg;
3155         int ret;
3156
3157         wpq = container_of(wait, struct wait_page_queue, wait);
3158
3159         if (!wake_page_match(wpq, key))
3160                 return 0;
3161
3162         req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3163         list_del_init(&wait->entry);
3164
3165         init_task_work(&req->task_work, io_req_task_submit);
3166         percpu_ref_get(&req->ctx->refs);
3167
3168         /* submit ref gets dropped, acquire a new one */
3169         refcount_inc(&req->refs);
3170         ret = io_req_task_work_add(req, true);
3171         if (unlikely(ret)) {
3172                 struct task_struct *tsk;
3173
3174                 /* queue just for cancelation */
3175                 init_task_work(&req->task_work, io_req_task_cancel);
3176                 tsk = io_wq_get_task(req->ctx->io_wq);
3177                 task_work_add(tsk, &req->task_work, 0);
3178                 wake_up_process(tsk);
3179         }
3180         return 1;
3181 }
3182
3183 /*
3184  * This controls whether a given IO request should be armed for async page
3185  * based retry. If we return false here, the request is handed to the async
3186  * worker threads for retry. If we're doing buffered reads on a regular file,
3187  * we prepare a private wait_page_queue entry and retry the operation. This
3188  * will either succeed because the page is now uptodate and unlocked, or it
3189  * will register a callback when the page is unlocked at IO completion. Through
3190  * that callback, io_uring uses task_work to setup a retry of the operation.
3191  * That retry will attempt the buffered read again. The retry will generally
3192  * succeed, or in rare cases where it fails, we then fall back to using the
3193  * async worker threads for a blocking retry.
3194  */
3195 static bool io_rw_should_retry(struct io_kiocb *req)
3196 {
3197         struct io_async_rw *rw = req->async_data;
3198         struct wait_page_queue *wait = &rw->wpq;
3199         struct kiocb *kiocb = &req->rw.kiocb;
3200
3201         /* never retry for NOWAIT, we just complete with -EAGAIN */
3202         if (req->flags & REQ_F_NOWAIT)
3203                 return false;
3204
3205         /* Only for buffered IO */
3206         if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3207                 return false;
3208
3209         /*
3210          * just use poll if we can, and don't attempt if the fs doesn't
3211          * support callback based unlocks
3212          */
3213         if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3214                 return false;
3215
3216         wait->wait.func = io_async_buf_func;
3217         wait->wait.private = req;
3218         wait->wait.flags = 0;
3219         INIT_LIST_HEAD(&wait->wait.entry);
3220         kiocb->ki_flags |= IOCB_WAITQ;
3221         kiocb->ki_flags &= ~IOCB_NOWAIT;
3222         kiocb->ki_waitq = wait;
3223         return true;
3224 }
3225
3226 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3227 {
3228         if (req->file->f_op->read_iter)
3229                 return call_read_iter(req->file, &req->rw.kiocb, iter);
3230         else if (req->file->f_op->read)
3231                 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
3232         else
3233                 return -EINVAL;
3234 }
3235
3236 static int io_read(struct io_kiocb *req, bool force_nonblock,
3237                    struct io_comp_state *cs)
3238 {
3239         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3240         struct kiocb *kiocb = &req->rw.kiocb;
3241         struct iov_iter __iter, *iter = &__iter;
3242         struct io_async_rw *rw = req->async_data;
3243         ssize_t io_size, ret, ret2;
3244         size_t iov_count;
3245         bool no_async;
3246
3247         if (rw)
3248                 iter = &rw->iter;
3249
3250         ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3251         if (ret < 0)
3252                 return ret;
3253         iov_count = iov_iter_count(iter);
3254         io_size = ret;
3255         req->result = io_size;
3256         ret = 0;
3257
3258         /* Ensure we clear previously set non-block flag */
3259         if (!force_nonblock)
3260                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3261         else
3262                 kiocb->ki_flags |= IOCB_NOWAIT;
3263
3264
3265         /* If the file doesn't support async, just async punt */
3266         no_async = force_nonblock && !io_file_supports_async(req->file, READ);
3267         if (no_async)
3268                 goto copy_iov;
3269
3270         ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), iov_count);
3271         if (unlikely(ret))
3272                 goto out_free;
3273
3274         ret = io_iter_do_read(req, iter);
3275
3276         if (!ret) {
3277                 goto done;
3278         } else if (ret == -EIOCBQUEUED) {
3279                 ret = 0;
3280                 goto out_free;
3281         } else if (ret == -EAGAIN) {
3282                 /* IOPOLL retry should happen for io-wq threads */
3283                 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3284                         goto done;
3285                 /* no retry on NONBLOCK marked file */
3286                 if (req->file->f_flags & O_NONBLOCK)
3287                         goto done;
3288                 /* some cases will consume bytes even on error returns */
3289                 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
3290                 ret = 0;
3291                 goto copy_iov;
3292         } else if (ret < 0) {
3293                 /* make sure -ERESTARTSYS -> -EINTR is done */
3294                 goto done;
3295         }
3296
3297         /* read it all, or we did blocking attempt. no retry. */
3298         if (!iov_iter_count(iter) || !force_nonblock ||
3299             (req->file->f_flags & O_NONBLOCK))
3300                 goto done;
3301
3302         io_size -= ret;
3303 copy_iov:
3304         ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3305         if (ret2) {
3306                 ret = ret2;
3307                 goto out_free;
3308         }
3309         if (no_async)
3310                 return -EAGAIN;
3311         rw = req->async_data;
3312         /* it's copied and will be cleaned with ->io */
3313         iovec = NULL;
3314         /* now use our persistent iterator, if we aren't already */
3315         iter = &rw->iter;
3316 retry:
3317         rw->bytes_done += ret;
3318         /* if we can retry, do so with the callbacks armed */
3319         if (!io_rw_should_retry(req)) {
3320                 kiocb->ki_flags &= ~IOCB_WAITQ;
3321                 return -EAGAIN;
3322         }
3323
3324         /*
3325          * Now retry read with the IOCB_WAITQ parts set in the iocb. If we
3326          * get -EIOCBQUEUED, then we'll get a notification when the desired
3327          * page gets unlocked. We can also get a partial read here, and if we
3328          * do, then just retry at the new offset.
3329          */
3330         ret = io_iter_do_read(req, iter);
3331         if (ret == -EIOCBQUEUED) {
3332                 ret = 0;
3333                 goto out_free;
3334         } else if (ret > 0 && ret < io_size) {
3335                 /* we got some bytes, but not all. retry. */
3336                 goto retry;
3337         }
3338 done:
3339         kiocb_done(kiocb, ret, cs);
3340         ret = 0;
3341 out_free:
3342         /* it's reportedly faster than delegating the null check to kfree() */
3343         if (iovec)
3344                 kfree(iovec);
3345         return ret;
3346 }
3347
3348 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3349 {
3350         ssize_t ret;
3351
3352         ret = io_prep_rw(req, sqe);
3353         if (ret)
3354                 return ret;
3355
3356         if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3357                 return -EBADF;
3358
3359         /* either don't need iovec imported or already have it */
3360         if (!req->async_data)
3361                 return 0;
3362         return io_rw_prep_async(req, WRITE);
3363 }
3364
3365 static int io_write(struct io_kiocb *req, bool force_nonblock,
3366                     struct io_comp_state *cs)
3367 {
3368         struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3369         struct kiocb *kiocb = &req->rw.kiocb;
3370         struct iov_iter __iter, *iter = &__iter;
3371         struct io_async_rw *rw = req->async_data;
3372         size_t iov_count;
3373         ssize_t ret, ret2, io_size;
3374
3375         if (rw)
3376                 iter = &rw->iter;
3377
3378         ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3379         if (ret < 0)
3380                 return ret;
3381         iov_count = iov_iter_count(iter);
3382         io_size = ret;
3383         req->result = io_size;
3384
3385         /* Ensure we clear previously set non-block flag */
3386         if (!force_nonblock)
3387                 kiocb->ki_flags &= ~IOCB_NOWAIT;
3388         else
3389                 kiocb->ki_flags |= IOCB_NOWAIT;
3390
3391         /* If the file doesn't support async, just async punt */
3392         if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3393                 goto copy_iov;
3394
3395         /* file path doesn't support NOWAIT for non-direct_IO */
3396         if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3397             (req->flags & REQ_F_ISREG))
3398                 goto copy_iov;
3399
3400         ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), iov_count);
3401         if (unlikely(ret))
3402                 goto out_free;
3403
3404         /*
3405          * Open-code file_start_write here to grab freeze protection,
3406          * which will be released by another thread in
3407          * io_complete_rw().  Fool lockdep by telling it the lock got
3408          * released so that it doesn't complain about the held lock when
3409          * we return to userspace.
3410          */
3411         if (req->flags & REQ_F_ISREG) {
3412                 __sb_start_write(file_inode(req->file)->i_sb,
3413                                         SB_FREEZE_WRITE, true);
3414                 __sb_writers_release(file_inode(req->file)->i_sb,
3415                                         SB_FREEZE_WRITE);
3416         }
3417         kiocb->ki_flags |= IOCB_WRITE;
3418
3419         if (req->file->f_op->write_iter)
3420                 ret2 = call_write_iter(req->file, kiocb, iter);
3421         else if (req->file->f_op->write)
3422                 ret2 = loop_rw_iter(WRITE, req->file, kiocb, iter);
3423         else
3424                 ret2 = -EINVAL;
3425
3426         /*
3427          * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3428          * retry them without IOCB_NOWAIT.
3429          */
3430         if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3431                 ret2 = -EAGAIN;
3432         /* no retry on NONBLOCK marked file */
3433         if (ret2 == -EAGAIN && (req->file->f_flags & O_NONBLOCK))
3434                 goto done;
3435         if (!force_nonblock || ret2 != -EAGAIN) {
3436                 /* IOPOLL retry should happen for io-wq threads */
3437                 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3438                         goto copy_iov;
3439 done:
3440                 kiocb_done(kiocb, ret2, cs);
3441         } else {
3442 copy_iov:
3443                 /* some cases will consume bytes even on error returns */
3444                 iov_iter_revert(iter, iov_count - iov_iter_count(iter));
3445                 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3446                 if (!ret)
3447                         return -EAGAIN;
3448         }
3449 out_free:
3450         /* it's reportedly faster than delegating the null check to kfree() */
3451         if (iovec)
3452                 kfree(iovec);
3453         return ret;
3454 }
3455
3456 static int __io_splice_prep(struct io_kiocb *req,
3457                             const struct io_uring_sqe *sqe)
3458 {
3459         struct io_splice* sp = &req->splice;
3460         unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3461
3462         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3463                 return -EINVAL;
3464
3465         sp->file_in = NULL;
3466         sp->len = READ_ONCE(sqe->len);
3467         sp->flags = READ_ONCE(sqe->splice_flags);
3468
3469         if (unlikely(sp->flags & ~valid_flags))
3470                 return -EINVAL;
3471
3472         sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3473                                   (sp->flags & SPLICE_F_FD_IN_FIXED));
3474         if (!sp->file_in)
3475                 return -EBADF;
3476         req->flags |= REQ_F_NEED_CLEANUP;
3477
3478         if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3479                 /*
3480                  * Splice operation will be punted aync, and here need to
3481                  * modify io_wq_work.flags, so initialize io_wq_work firstly.
3482                  */
3483                 io_req_init_async(req);
3484                 req->work.flags |= IO_WQ_WORK_UNBOUND;
3485         }
3486
3487         return 0;
3488 }
3489
3490 static int io_tee_prep(struct io_kiocb *req,
3491                        const struct io_uring_sqe *sqe)
3492 {
3493         if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3494                 return -EINVAL;
3495         return __io_splice_prep(req, sqe);
3496 }
3497
3498 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3499 {
3500         struct io_splice *sp = &req->splice;
3501         struct file *in = sp->file_in;
3502         struct file *out = sp->file_out;
3503         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3504         long ret = 0;
3505
3506         if (force_nonblock)
3507                 return -EAGAIN;
3508         if (sp->len)
3509                 ret = do_tee(in, out, sp->len, flags);
3510
3511         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3512         req->flags &= ~REQ_F_NEED_CLEANUP;
3513
3514         if (ret != sp->len)
3515                 req_set_fail_links(req);
3516         io_req_complete(req, ret);
3517         return 0;
3518 }
3519
3520 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3521 {
3522         struct io_splice* sp = &req->splice;
3523
3524         sp->off_in = READ_ONCE(sqe->splice_off_in);
3525         sp->off_out = READ_ONCE(sqe->off);
3526         return __io_splice_prep(req, sqe);
3527 }
3528
3529 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3530 {
3531         struct io_splice *sp = &req->splice;
3532         struct file *in = sp->file_in;
3533         struct file *out = sp->file_out;
3534         unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3535         loff_t *poff_in, *poff_out;
3536         long ret = 0;
3537
3538         if (force_nonblock)
3539                 return -EAGAIN;
3540
3541         poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3542         poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3543
3544         if (sp->len)
3545                 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3546
3547         io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3548         req->flags &= ~REQ_F_NEED_CLEANUP;
3549
3550         if (ret != sp->len)
3551                 req_set_fail_links(req);
3552         io_req_complete(req, ret);
3553         return 0;
3554 }
3555
3556 /*
3557  * IORING_OP_NOP just posts a completion event, nothing else.
3558  */
3559 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3560 {
3561         struct io_ring_ctx *ctx = req->ctx;
3562
3563         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3564                 return -EINVAL;
3565
3566         __io_req_complete(req, 0, 0, cs);
3567         return 0;
3568 }
3569
3570 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3571 {
3572         struct io_ring_ctx *ctx = req->ctx;
3573
3574         if (!req->file)
3575                 return -EBADF;
3576
3577         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3578                 return -EINVAL;
3579         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3580                 return -EINVAL;
3581
3582         req->sync.flags = READ_ONCE(sqe->fsync_flags);
3583         if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3584                 return -EINVAL;
3585
3586         req->sync.off = READ_ONCE(sqe->off);
3587         req->sync.len = READ_ONCE(sqe->len);
3588         return 0;
3589 }
3590
3591 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3592 {
3593         loff_t end = req->sync.off + req->sync.len;
3594         int ret;
3595
3596         /* fsync always requires a blocking context */
3597         if (force_nonblock)
3598                 return -EAGAIN;
3599
3600         ret = vfs_fsync_range(req->file, req->sync.off,
3601                                 end > 0 ? end : LLONG_MAX,
3602                                 req->sync.flags & IORING_FSYNC_DATASYNC);
3603         if (ret < 0)
3604                 req_set_fail_links(req);
3605         io_req_complete(req, ret);
3606         return 0;
3607 }
3608
3609 static int io_fallocate_prep(struct io_kiocb *req,
3610                              const struct io_uring_sqe *sqe)
3611 {
3612         if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3613                 return -EINVAL;
3614         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3615                 return -EINVAL;
3616
3617         req->sync.off = READ_ONCE(sqe->off);
3618         req->sync.len = READ_ONCE(sqe->addr);
3619         req->sync.mode = READ_ONCE(sqe->len);
3620         return 0;
3621 }
3622
3623 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3624 {
3625         int ret;
3626
3627         /* fallocate always requiring blocking context */
3628         if (force_nonblock)
3629                 return -EAGAIN;
3630         ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3631                                 req->sync.len);
3632         if (ret < 0)
3633                 req_set_fail_links(req);
3634         io_req_complete(req, ret);
3635         return 0;
3636 }
3637
3638 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3639 {
3640         const char __user *fname;
3641         int ret;
3642
3643         if (unlikely(sqe->ioprio || sqe->buf_index))
3644                 return -EINVAL;
3645         if (unlikely(req->flags & REQ_F_FIXED_FILE))
3646                 return -EBADF;
3647
3648         /* open.how should be already initialised */
3649         if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3650                 req->open.how.flags |= O_LARGEFILE;
3651
3652         req->open.dfd = READ_ONCE(sqe->fd);
3653         fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3654         req->open.filename = getname(fname);
3655         if (IS_ERR(req->open.filename)) {
3656                 ret = PTR_ERR(req->open.filename);
3657                 req->open.filename = NULL;
3658                 return ret;
3659         }
3660         req->open.nofile = rlimit(RLIMIT_NOFILE);
3661         req->flags |= REQ_F_NEED_CLEANUP;
3662         return 0;
3663 }
3664
3665 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3666 {
3667         u64 flags, mode;
3668
3669         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3670                 return -EINVAL;
3671         mode = READ_ONCE(sqe->len);
3672         flags = READ_ONCE(sqe->open_flags);
3673         req->open.how = build_open_how(flags, mode);
3674         return __io_openat_prep(req, sqe);
3675 }
3676
3677 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3678 {
3679         struct open_how __user *how;
3680         size_t len;
3681         int ret;
3682
3683         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3684                 return -EINVAL;
3685         how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3686         len = READ_ONCE(sqe->len);
3687         if (len < OPEN_HOW_SIZE_VER0)
3688                 return -EINVAL;
3689
3690         ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3691                                         len);
3692         if (ret)
3693                 return ret;
3694
3695         return __io_openat_prep(req, sqe);
3696 }
3697
3698 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3699 {
3700         struct open_flags op;
3701         struct file *file;
3702         int ret;
3703
3704         if (force_nonblock)
3705                 return -EAGAIN;
3706
3707         ret = build_open_flags(&req->open.how, &op);
3708         if (ret)
3709                 goto err;
3710
3711         ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3712         if (ret < 0)
3713                 goto err;
3714
3715         file = do_filp_open(req->open.dfd, req->open.filename, &op);
3716         if (IS_ERR(file)) {
3717                 put_unused_fd(ret);
3718                 ret = PTR_ERR(file);
3719         } else {
3720                 fsnotify_open(file);
3721                 fd_install(ret, file);
3722         }
3723 err:
3724         putname(req->open.filename);
3725         req->flags &= ~REQ_F_NEED_CLEANUP;
3726         if (ret < 0)
3727                 req_set_fail_links(req);
3728         io_req_complete(req, ret);
3729         return 0;
3730 }
3731
3732 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3733 {
3734         return io_openat2(req, force_nonblock);
3735 }
3736
3737 static int io_remove_buffers_prep(struct io_kiocb *req,
3738                                   const struct io_uring_sqe *sqe)
3739 {
3740         struct io_provide_buf *p = &req->pbuf;
3741         u64 tmp;
3742
3743         if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3744                 return -EINVAL;
3745
3746         tmp = READ_ONCE(sqe->fd);
3747         if (!tmp || tmp > USHRT_MAX)
3748                 return -EINVAL;
3749
3750         memset(p, 0, sizeof(*p));
3751         p->nbufs = tmp;
3752         p->bgid = READ_ONCE(sqe->buf_group);
3753         return 0;
3754 }
3755
3756 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3757                                int bgid, unsigned nbufs)
3758 {
3759         unsigned i = 0;
3760
3761         /* shouldn't happen */
3762         if (!nbufs)
3763                 return 0;
3764
3765         /* the head kbuf is the list itself */
3766         while (!list_empty(&buf->list)) {
3767                 struct io_buffer *nxt;
3768
3769                 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3770                 list_del(&nxt->list);
3771                 kfree(nxt);
3772                 if (++i == nbufs)
3773                         return i;
3774         }
3775         i++;
3776         kfree(buf);
3777         idr_remove(&ctx->io_buffer_idr, bgid);
3778
3779         return i;
3780 }
3781
3782 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3783                              struct io_comp_state *cs)
3784 {
3785         struct io_provide_buf *p = &req->pbuf;
3786         struct io_ring_ctx *ctx = req->ctx;
3787         struct io_buffer *head;
3788         int ret = 0;
3789
3790         io_ring_submit_lock(ctx, !force_nonblock);
3791
3792         lockdep_assert_held(&ctx->uring_lock);
3793
3794         ret = -ENOENT;
3795         head = idr_find(&ctx->io_buffer_idr, p->bgid);
3796         if (head)
3797                 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3798
3799         io_ring_submit_lock(ctx, !force_nonblock);
3800         if (ret < 0)
3801                 req_set_fail_links(req);
3802         __io_req_complete(req, ret, 0, cs);
3803         return 0;
3804 }
3805
3806 static int io_provide_buffers_prep(struct io_kiocb *req,
3807                                    const struct io_uring_sqe *sqe)
3808 {
3809         struct io_provide_buf *p = &req->pbuf;
3810         u64 tmp;
3811
3812         if (sqe->ioprio || sqe->rw_flags)
3813                 return -EINVAL;
3814
3815         tmp = READ_ONCE(sqe->fd);
3816         if (!tmp || tmp > USHRT_MAX)
3817                 return -E2BIG;
3818         p->nbufs = tmp;
3819         p->addr = READ_ONCE(sqe->addr);
3820         p->len = READ_ONCE(sqe->len);
3821
3822         if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3823                 return -EFAULT;
3824
3825         p->bgid = READ_ONCE(sqe->buf_group);
3826         tmp = READ_ONCE(sqe->off);
3827         if (tmp > USHRT_MAX)
3828                 return -E2BIG;
3829         p->bid = tmp;
3830         return 0;
3831 }
3832
3833 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3834 {
3835         struct io_buffer *buf;
3836         u64 addr = pbuf->addr;
3837         int i, bid = pbuf->bid;
3838
3839         for (i = 0; i < pbuf->nbufs; i++) {
3840                 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3841                 if (!buf)
3842                         break;
3843
3844                 buf->addr = addr;
3845                 buf->len = pbuf->len;
3846                 buf->bid = bid;
3847                 addr += pbuf->len;
3848                 bid++;
3849                 if (!*head) {
3850                         INIT_LIST_HEAD(&buf->list);
3851                         *head = buf;
3852                 } else {
3853                         list_add_tail(&buf->list, &(*head)->list);
3854                 }
3855         }
3856
3857         return i ? i : -ENOMEM;
3858 }
3859
3860 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3861                               struct io_comp_state *cs)
3862 {
3863         struct io_provide_buf *p = &req->pbuf;
3864         struct io_ring_ctx *ctx = req->ctx;
3865         struct io_buffer *head, *list;
3866         int ret = 0;
3867
3868         io_ring_submit_lock(ctx, !force_nonblock);
3869
3870         lockdep_assert_held(&ctx->uring_lock);
3871
3872         list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3873
3874         ret = io_add_buffers(p, &head);
3875         if (ret < 0)
3876                 goto out;
3877
3878         if (!list) {
3879                 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3880                                         GFP_KERNEL);
3881                 if (ret < 0) {
3882                         __io_remove_buffers(ctx, head, p->bgid, -1U);
3883                         goto out;
3884                 }
3885         }
3886 out:
3887         io_ring_submit_unlock(ctx, !force_nonblock);
3888         if (ret < 0)
3889                 req_set_fail_links(req);
3890         __io_req_complete(req, ret, 0, cs);
3891         return 0;
3892 }
3893
3894 static int io_epoll_ctl_prep(struct io_kiocb *req,
3895                              const struct io_uring_sqe *sqe)
3896 {
3897 #if defined(CONFIG_EPOLL)
3898         if (sqe->ioprio || sqe->buf_index)
3899                 return -EINVAL;
3900         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
3901                 return -EINVAL;
3902
3903         req->epoll.epfd = READ_ONCE(sqe->fd);
3904         req->epoll.op = READ_ONCE(sqe->len);
3905         req->epoll.fd = READ_ONCE(sqe->off);
3906
3907         if (ep_op_has_event(req->epoll.op)) {
3908                 struct epoll_event __user *ev;
3909
3910                 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3911                 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3912                         return -EFAULT;
3913         }
3914
3915         return 0;
3916 #else
3917         return -EOPNOTSUPP;
3918 #endif
3919 }
3920
3921 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3922                         struct io_comp_state *cs)
3923 {
3924 #if defined(CONFIG_EPOLL)
3925         struct io_epoll *ie = &req->epoll;
3926         int ret;
3927
3928         ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3929         if (force_nonblock && ret == -EAGAIN)
3930                 return -EAGAIN;
3931
3932         if (ret < 0)
3933                 req_set_fail_links(req);
3934         __io_req_complete(req, ret, 0, cs);
3935         return 0;
3936 #else
3937         return -EOPNOTSUPP;
3938 #endif
3939 }
3940
3941 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3942 {
3943 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3944         if (sqe->ioprio || sqe->buf_index || sqe->off)
3945                 return -EINVAL;
3946         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3947                 return -EINVAL;
3948
3949         req->madvise.addr = READ_ONCE(sqe->addr);
3950         req->madvise.len = READ_ONCE(sqe->len);
3951         req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3952         return 0;
3953 #else
3954         return -EOPNOTSUPP;
3955 #endif
3956 }
3957
3958 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3959 {
3960 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3961         struct io_madvise *ma = &req->madvise;
3962         int ret;
3963
3964         if (force_nonblock)
3965                 return -EAGAIN;
3966
3967         ret = do_madvise(ma->addr, ma->len, ma->advice);
3968         if (ret < 0)
3969                 req_set_fail_links(req);
3970         io_req_complete(req, ret);
3971         return 0;
3972 #else
3973         return -EOPNOTSUPP;
3974 #endif
3975 }
3976
3977 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3978 {
3979         if (sqe->ioprio || sqe->buf_index || sqe->addr)
3980                 return -EINVAL;
3981         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3982                 return -EINVAL;
3983
3984         req->fadvise.offset = READ_ONCE(sqe->off);
3985         req->fadvise.len = READ_ONCE(sqe->len);
3986         req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3987         return 0;
3988 }
3989
3990 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3991 {
3992         struct io_fadvise *fa = &req->fadvise;
3993         int ret;
3994
3995         if (force_nonblock) {
3996                 switch (fa->advice) {
3997                 case POSIX_FADV_NORMAL:
3998                 case POSIX_FADV_RANDOM:
3999                 case POSIX_FADV_SEQUENTIAL:
4000                         break;
4001                 default:
4002                         return -EAGAIN;
4003                 }
4004         }
4005
4006         ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4007         if (ret < 0)
4008                 req_set_fail_links(req);
4009         io_req_complete(req, ret);
4010         return 0;
4011 }
4012
4013 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4014 {
4015         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4016                 return -EINVAL;
4017         if (sqe->ioprio || sqe->buf_index)
4018                 return -EINVAL;
4019         if (req->flags & REQ_F_FIXED_FILE)
4020                 return -EBADF;
4021
4022         req->statx.dfd = READ_ONCE(sqe->fd);
4023         req->statx.mask = READ_ONCE(sqe->len);
4024         req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4025         req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4026         req->statx.flags = READ_ONCE(sqe->statx_flags);
4027
4028         return 0;
4029 }
4030
4031 static int io_statx(struct io_kiocb *req, bool force_nonblock)
4032 {
4033         struct io_statx *ctx = &req->statx;
4034         int ret;
4035
4036         if (force_nonblock) {
4037                 /* only need file table for an actual valid fd */
4038                 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4039                         req->flags |= REQ_F_NO_FILE_TABLE;
4040                 return -EAGAIN;
4041         }
4042
4043         ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4044                        ctx->buffer);
4045
4046         if (ret < 0)
4047                 req_set_fail_links(req);
4048         io_req_complete(req, ret);
4049         return 0;
4050 }
4051
4052 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4053 {
4054         /*
4055          * If we queue this for async, it must not be cancellable. That would
4056          * leave the 'file' in an undeterminate state, and here need to modify
4057          * io_wq_work.flags, so initialize io_wq_work firstly.
4058          */
4059         io_req_init_async(req);
4060         req->work.flags |= IO_WQ_WORK_NO_CANCEL;
4061
4062         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4063                 return -EINVAL;
4064         if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4065             sqe->rw_flags || sqe->buf_index)
4066                 return -EINVAL;
4067         if (req->flags & REQ_F_FIXED_FILE)
4068                 return -EBADF;
4069
4070         req->close.fd = READ_ONCE(sqe->fd);
4071         if ((req->file && req->file->f_op == &io_uring_fops))
4072                 return -EBADF;
4073
4074         req->close.put_file = NULL;
4075         return 0;
4076 }
4077
4078 static int io_close(struct io_kiocb *req, bool force_nonblock,
4079                     struct io_comp_state *cs)
4080 {
4081         struct io_close *close = &req->close;
4082         int ret;
4083
4084         /* might be already done during nonblock submission */
4085         if (!close->put_file) {
4086                 ret = __close_fd_get_file(close->fd, &close->put_file);
4087                 if (ret < 0)
4088                         return (ret == -ENOENT) ? -EBADF : ret;
4089         }
4090
4091         /* if the file has a flush method, be safe and punt to async */
4092         if (close->put_file->f_op->flush && force_nonblock) {
4093                 /* was never set, but play safe */
4094                 req->flags &= ~REQ_F_NOWAIT;
4095                 /* avoid grabbing files - we don't need the files */
4096                 req->flags |= REQ_F_NO_FILE_TABLE;
4097                 return -EAGAIN;
4098         }
4099
4100         /* No ->flush() or already async, safely close from here */
4101         ret = filp_close(close->put_file, req->work.files);
4102         if (ret < 0)
4103                 req_set_fail_links(req);
4104         fput(close->put_file);
4105         close->put_file = NULL;
4106         __io_req_complete(req, ret, 0, cs);
4107         return 0;
4108 }
4109
4110 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4111 {
4112         struct io_ring_ctx *ctx = req->ctx;
4113
4114         if (!req->file)
4115                 return -EBADF;
4116
4117         if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4118                 return -EINVAL;
4119         if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4120                 return -EINVAL;
4121
4122         req->sync.off = READ_ONCE(sqe->off);
4123         req->sync.len = READ_ONCE(sqe->len);
4124         req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4125         return 0;
4126 }
4127
4128 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
4129 {
4130         int ret;
4131
4132         /* sync_file_range always requires a blocking context */
4133         if (force_nonblock)
4134                 return -EAGAIN;
4135
4136         ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4137                                 req->sync.flags);
4138         if (ret < 0)
4139                 req_set_fail_links(req);
4140         io_req_complete(req, ret);
4141         return 0;
4142 }
4143
4144 #if defined(CONFIG_NET)
4145 static int io_setup_async_msg(struct io_kiocb *req,
4146                               struct io_async_msghdr *kmsg)
4147 {
4148         struct io_async_msghdr *async_msg = req->async_data;
4149
4150         if (async_msg)
4151                 return -EAGAIN;
4152         if (io_alloc_async_data(req)) {
4153                 if (kmsg->iov != kmsg->fast_iov)
4154                         kfree(kmsg->iov);
4155                 return -ENOMEM;
4156         }
4157         async_msg = req->async_data;
4158         req->flags |= REQ_F_NEED_CLEANUP;
4159         memcpy(async_msg, kmsg, sizeof(*kmsg));
4160         return -EAGAIN;
4161 }
4162
4163 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4164                                struct io_async_msghdr *iomsg)
4165 {
4166         iomsg->iov = iomsg->fast_iov;
4167         iomsg->msg.msg_name = &iomsg->addr;
4168         return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4169                                    req->sr_msg.msg_flags, &iomsg->iov);
4170 }
4171
4172 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4173 {
4174         struct io_async_msghdr *async_msg = req->async_data;
4175         struct io_sr_msg *sr = &req->sr_msg;
4176         int ret;
4177
4178         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4179                 return -EINVAL;
4180
4181         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4182         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4183         sr->len = READ_ONCE(sqe->len);
4184
4185 #ifdef CONFIG_COMPAT
4186         if (req->ctx->compat)
4187                 sr->msg_flags |= MSG_CMSG_COMPAT;
4188 #endif
4189
4190         if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4191                 return 0;
4192         ret = io_sendmsg_copy_hdr(req, async_msg);
4193         if (!ret)
4194                 req->flags |= REQ_F_NEED_CLEANUP;
4195         return ret;
4196 }
4197
4198 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4199                       struct io_comp_state *cs)
4200 {
4201         struct io_async_msghdr iomsg, *kmsg;
4202         struct socket *sock;
4203         unsigned flags;
4204         int ret;
4205
4206         sock = sock_from_file(req->file, &ret);
4207         if (unlikely(!sock))
4208                 return ret;
4209
4210         if (req->async_data) {
4211                 kmsg = req->async_data;
4212                 kmsg->msg.msg_name = &kmsg->addr;
4213                 /* if iov is set, it's allocated already */
4214                 if (!kmsg->iov)
4215                         kmsg->iov = kmsg->fast_iov;
4216                 kmsg->msg.msg_iter.iov = kmsg->iov;
4217         } else {
4218                 ret = io_sendmsg_copy_hdr(req, &iomsg);
4219                 if (ret)
4220                         return ret;
4221                 kmsg = &iomsg;
4222         }
4223
4224         flags = req->sr_msg.msg_flags;
4225         if (flags & MSG_DONTWAIT)
4226                 req->flags |= REQ_F_NOWAIT;
4227         else if (force_nonblock)
4228                 flags |= MSG_DONTWAIT;
4229
4230         ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4231         if (force_nonblock && ret == -EAGAIN)
4232                 return io_setup_async_msg(req, kmsg);
4233         if (ret == -ERESTARTSYS)
4234                 ret = -EINTR;
4235
4236         if (kmsg->iov != kmsg->fast_iov)
4237                 kfree(kmsg->iov);
4238         req->flags &= ~REQ_F_NEED_CLEANUP;
4239         if (ret < 0)
4240                 req_set_fail_links(req);
4241         __io_req_complete(req, ret, 0, cs);
4242         return 0;
4243 }
4244
4245 static int io_send(struct io_kiocb *req, bool force_nonblock,
4246                    struct io_comp_state *cs)
4247 {
4248         struct io_sr_msg *sr = &req->sr_msg;
4249         struct msghdr msg;
4250         struct iovec iov;
4251         struct socket *sock;
4252         unsigned flags;
4253         int ret;
4254
4255         sock = sock_from_file(req->file, &ret);
4256         if (unlikely(!sock))
4257                 return ret;
4258
4259         ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4260         if (unlikely(ret))
4261                 return ret;
4262
4263         msg.msg_name = NULL;
4264         msg.msg_control = NULL;
4265         msg.msg_controllen = 0;
4266         msg.msg_namelen = 0;
4267
4268         flags = req->sr_msg.msg_flags;
4269         if (flags & MSG_DONTWAIT)
4270                 req->flags |= REQ_F_NOWAIT;
4271         else if (force_nonblock)
4272                 flags |= MSG_DONTWAIT;
4273
4274         msg.msg_flags = flags;
4275         ret = sock_sendmsg(sock, &msg);
4276         if (force_nonblock && ret == -EAGAIN)
4277                 return -EAGAIN;
4278         if (ret == -ERESTARTSYS)
4279                 ret = -EINTR;
4280
4281         if (ret < 0)
4282                 req_set_fail_links(req);
4283         __io_req_complete(req, ret, 0, cs);
4284         return 0;
4285 }
4286
4287 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4288                                  struct io_async_msghdr *iomsg)
4289 {
4290         struct io_sr_msg *sr = &req->sr_msg;
4291         struct iovec __user *uiov;
4292         size_t iov_len;
4293         int ret;
4294
4295         ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4296                                         &iomsg->uaddr, &uiov, &iov_len);
4297         if (ret)
4298                 return ret;
4299
4300         if (req->flags & REQ_F_BUFFER_SELECT) {
4301                 if (iov_len > 1)
4302                         return -EINVAL;
4303                 if (copy_from_user(iomsg->iov, uiov, sizeof(*uiov)))
4304                         return -EFAULT;
4305                 sr->len = iomsg->iov[0].iov_len;
4306                 iov_iter_init(&iomsg->msg.msg_iter, READ, iomsg->iov, 1,
4307                                 sr->len);
4308                 iomsg->iov = NULL;
4309         } else {
4310                 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4311                                      &iomsg->iov, &iomsg->msg.msg_iter,
4312                                      false);
4313                 if (ret > 0)
4314                         ret = 0;
4315         }
4316
4317         return ret;
4318 }
4319
4320 #ifdef CONFIG_COMPAT
4321 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4322                                         struct io_async_msghdr *iomsg)
4323 {
4324         struct compat_msghdr __user *msg_compat;
4325         struct io_sr_msg *sr = &req->sr_msg;
4326         struct compat_iovec __user *uiov;
4327         compat_uptr_t ptr;
4328         compat_size_t len;
4329         int ret;
4330
4331         msg_compat = (struct compat_msghdr __user *) sr->umsg;
4332         ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4333                                         &ptr, &len);
4334         if (ret)
4335                 return ret;
4336
4337         uiov = compat_ptr(ptr);
4338         if (req->flags & REQ_F_BUFFER_SELECT) {
4339                 compat_ssize_t clen;
4340
4341                 if (len > 1)
4342                         return -EINVAL;
4343                 if (!access_ok(uiov, sizeof(*uiov)))
4344                         return -EFAULT;
4345                 if (__get_user(clen, &uiov->iov_len))
4346                         return -EFAULT;
4347                 if (clen < 0)
4348                         return -EINVAL;
4349                 sr->len = iomsg->iov[0].iov_len;
4350                 iomsg->iov = NULL;
4351         } else {
4352                 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4353                                    UIO_FASTIOV, &iomsg->iov,
4354                                    &iomsg->msg.msg_iter, true);
4355                 if (ret < 0)
4356                         return ret;
4357         }
4358
4359         return 0;
4360 }
4361 #endif
4362
4363 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4364                                struct io_async_msghdr *iomsg)
4365 {
4366         iomsg->msg.msg_name = &iomsg->addr;
4367         iomsg->iov = iomsg->fast_iov;
4368
4369 #ifdef CONFIG_COMPAT
4370         if (req->ctx->compat)
4371                 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4372 #endif
4373
4374         return __io_recvmsg_copy_hdr(req, iomsg);
4375 }
4376
4377 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4378                                                bool needs_lock)
4379 {
4380         struct io_sr_msg *sr = &req->sr_msg;
4381         struct io_buffer *kbuf;
4382
4383         kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4384         if (IS_ERR(kbuf))
4385                 return kbuf;
4386
4387         sr->kbuf = kbuf;
4388         req->flags |= REQ_F_BUFFER_SELECTED;
4389         return kbuf;
4390 }
4391
4392 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4393 {
4394         return io_put_kbuf(req, req->sr_msg.kbuf);
4395 }
4396
4397 static int io_recvmsg_prep(struct io_kiocb *req,
4398                            const struct io_uring_sqe *sqe)
4399 {
4400         struct io_async_msghdr *async_msg = req->async_data;
4401         struct io_sr_msg *sr = &req->sr_msg;
4402         int ret;
4403
4404         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4405                 return -EINVAL;
4406
4407         sr->msg_flags = READ_ONCE(sqe->msg_flags);
4408         sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4409         sr->len = READ_ONCE(sqe->len);
4410         sr->bgid = READ_ONCE(sqe->buf_group);
4411
4412 #ifdef CONFIG_COMPAT
4413         if (req->ctx->compat)
4414                 sr->msg_flags |= MSG_CMSG_COMPAT;
4415 #endif
4416
4417         if (!async_msg || !io_op_defs[req->opcode].needs_async_data)
4418                 return 0;
4419         ret = io_recvmsg_copy_hdr(req, async_msg);
4420         if (!ret)
4421                 req->flags |= REQ_F_NEED_CLEANUP;
4422         return ret;
4423 }
4424
4425 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4426                       struct io_comp_state *cs)
4427 {
4428         struct io_async_msghdr iomsg, *kmsg;
4429         struct socket *sock;
4430         struct io_buffer *kbuf;
4431         unsigned flags;
4432         int ret, cflags = 0;
4433
4434         sock = sock_from_file(req->file, &ret);
4435         if (unlikely(!sock))
4436                 return ret;
4437
4438         if (req->async_data) {
4439                 kmsg = req->async_data;
4440                 kmsg->msg.msg_name = &kmsg->addr;
4441                 /* if iov is set, it's allocated already */
4442                 if (!kmsg->iov)
4443                         kmsg->iov = kmsg->fast_iov;
4444                 kmsg->msg.msg_iter.iov = kmsg->iov;
4445         } else {
4446                 ret = io_recvmsg_copy_hdr(req, &iomsg);
4447                 if (ret)
4448                         return ret;
4449                 kmsg = &iomsg;
4450         }
4451
4452         if (req->flags & REQ_F_BUFFER_SELECT) {
4453                 kbuf = io_recv_buffer_select(req, !force_nonblock);
4454                 if (IS_ERR(kbuf))
4455                         return PTR_ERR(kbuf);
4456                 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4457                 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4458                                 1, req->sr_msg.len);
4459         }
4460
4461         flags = req->sr_msg.msg_flags;
4462         if (flags & MSG_DONTWAIT)
4463                 req->flags |= REQ_F_NOWAIT;
4464         else if (force_nonblock)
4465                 flags |= MSG_DONTWAIT;
4466
4467         ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4468                                         kmsg->uaddr, flags);
4469         if (force_nonblock && ret == -EAGAIN)
4470                 return io_setup_async_msg(req, kmsg);
4471         if (ret == -ERESTARTSYS)
4472                 ret = -EINTR;
4473
4474         if (req->flags & REQ_F_BUFFER_SELECTED)
4475                 cflags = io_put_recv_kbuf(req);
4476         if (kmsg->iov != kmsg->fast_iov)
4477                 kfree(kmsg->iov);
4478         req->flags &= ~REQ_F_NEED_CLEANUP;
4479         if (ret < 0)
4480                 req_set_fail_links(req);
4481         __io_req_complete(req, ret, cflags, cs);
4482         return 0;
4483 }
4484
4485 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4486                    struct io_comp_state *cs)
4487 {
4488         struct io_buffer *kbuf;
4489         struct io_sr_msg *sr = &req->sr_msg;
4490         struct msghdr msg;
4491         void __user *buf = sr->buf;
4492         struct socket *sock;
4493         struct iovec iov;
4494         unsigned flags;
4495         int ret, cflags = 0;
4496
4497         sock = sock_from_file(req->file, &ret);
4498         if (unlikely(!sock))
4499                 return ret;
4500
4501         if (req->flags & REQ_F_BUFFER_SELECT) {
4502                 kbuf = io_recv_buffer_select(req, !force_nonblock);
4503                 if (IS_ERR(kbuf))
4504                         return PTR_ERR(kbuf);
4505                 buf = u64_to_user_ptr(kbuf->addr);
4506         }
4507
4508         ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4509         if (unlikely(ret))
4510                 goto out_free;
4511
4512         msg.msg_name = NULL;
4513         msg.msg_control = NULL;
4514         msg.msg_controllen = 0;
4515         msg.msg_namelen = 0;
4516         msg.msg_iocb = NULL;
4517         msg.msg_flags = 0;
4518
4519         flags = req->sr_msg.msg_flags;
4520         if (flags & MSG_DONTWAIT)
4521                 req->flags |= REQ_F_NOWAIT;
4522         else if (force_nonblock)
4523                 flags |= MSG_DONTWAIT;
4524
4525         ret = sock_recvmsg(sock, &msg, flags);
4526         if (force_nonblock && ret == -EAGAIN)
4527                 return -EAGAIN;
4528         if (ret == -ERESTARTSYS)
4529                 ret = -EINTR;
4530 out_free:
4531         if (req->flags & REQ_F_BUFFER_SELECTED)
4532                 cflags = io_put_recv_kbuf(req);
4533         if (ret < 0)
4534                 req_set_fail_links(req);
4535         __io_req_complete(req, ret, cflags, cs);
4536         return 0;
4537 }
4538
4539 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4540 {
4541         struct io_accept *accept = &req->accept;
4542
4543         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4544                 return -EINVAL;
4545         if (sqe->ioprio || sqe->len || sqe->buf_index)
4546                 return -EINVAL;
4547
4548         accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4549         accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4550         accept->flags = READ_ONCE(sqe->accept_flags);
4551         accept->nofile = rlimit(RLIMIT_NOFILE);
4552         return 0;
4553 }
4554
4555 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4556                      struct io_comp_state *cs)
4557 {
4558         struct io_accept *accept = &req->accept;
4559         unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4560         int ret;
4561
4562         if (req->file->f_flags & O_NONBLOCK)
4563                 req->flags |= REQ_F_NOWAIT;
4564
4565         ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4566                                         accept->addr_len, accept->flags,
4567                                         accept->nofile);
4568         if (ret == -EAGAIN && force_nonblock)
4569                 return -EAGAIN;
4570         if (ret < 0) {
4571                 if (ret == -ERESTARTSYS)
4572                         ret = -EINTR;
4573                 req_set_fail_links(req);
4574         }
4575         __io_req_complete(req, ret, 0, cs);
4576         return 0;
4577 }
4578
4579 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4580 {
4581         struct io_connect *conn = &req->connect;
4582         struct io_async_connect *io = req->async_data;
4583
4584         if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4585                 return -EINVAL;
4586         if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4587                 return -EINVAL;
4588
4589         conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4590         conn->addr_len =  READ_ONCE(sqe->addr2);
4591
4592         if (!io)
4593                 return 0;
4594
4595         return move_addr_to_kernel(conn->addr, conn->addr_len,
4596                                         &io->address);
4597 }
4598
4599 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4600                       struct io_comp_state *cs)
4601 {
4602         struct io_async_connect __io, *io;
4603         unsigned file_flags;
4604         int ret;
4605
4606         if (req->async_data) {
4607                 io = req->async_data;
4608         } else {
4609                 ret = move_addr_to_kernel(req->connect.addr,
4610                                                 req->connect.addr_len,
4611                                                 &__io.address);
4612                 if (ret)
4613                         goto out;
4614                 io = &__io;
4615         }
4616
4617         file_flags = force_nonblock ? O_NONBLOCK : 0;
4618
4619         ret = __sys_connect_file(req->file, &io->address,
4620                                         req->connect.addr_len, file_flags);
4621         if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4622                 if (req->async_data)
4623                         return -EAGAIN;
4624                 if (io_alloc_async_data(req)) {
4625                         ret = -ENOMEM;
4626                         goto out;
4627                 }
4628                 io = req->async_data;
4629                 memcpy(req->async_data, &__io, sizeof(__io));
4630                 return -EAGAIN;
4631         }
4632         if (ret == -ERESTARTSYS)
4633                 ret = -EINTR;
4634 out:
4635         if (ret < 0)
4636                 req_set_fail_links(req);
4637         __io_req_complete(req, ret, 0, cs);
4638         return 0;
4639 }
4640 #else /* !CONFIG_NET */
4641 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4642 {
4643         return -EOPNOTSUPP;
4644 }
4645
4646 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
4647                       struct io_comp_state *cs)
4648 {
4649         return -EOPNOTSUPP;
4650 }
4651
4652 static int io_send(struct io_kiocb *req, bool force_nonblock,
4653                    struct io_comp_state *cs)
4654 {
4655         return -EOPNOTSUPP;
4656 }
4657
4658 static int io_recvmsg_prep(struct io_kiocb *req,
4659                            const struct io_uring_sqe *sqe)
4660 {
4661         return -EOPNOTSUPP;
4662 }
4663
4664 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4665                       struct io_comp_state *cs)
4666 {
4667         return -EOPNOTSUPP;
4668 }
4669
4670 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4671                    struct io_comp_state *cs)
4672 {
4673         return -EOPNOTSUPP;
4674 }
4675
4676 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4677 {
4678         return -EOPNOTSUPP;
4679 }
4680
4681 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4682                      struct io_comp_state *cs)
4683 {
4684         return -EOPNOTSUPP;
4685 }
4686
4687 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4688 {
4689         return -EOPNOTSUPP;
4690 }
4691
4692 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4693                       struct io_comp_state *cs)
4694 {
4695         return -EOPNOTSUPP;
4696 }
4697 #endif /* CONFIG_NET */
4698
4699 struct io_poll_table {
4700         struct poll_table_struct pt;
4701         struct io_kiocb *req;
4702         int error;
4703 };
4704
4705 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4706                            __poll_t mask, task_work_func_t func)
4707 {
4708         bool twa_signal_ok;
4709         int ret;
4710
4711         /* for instances that support it check for an event match first: */
4712         if (mask && !(mask & poll->events))
4713                 return 0;
4714
4715         trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4716
4717         list_del_init(&poll->wait.entry);
4718
4719         req->result = mask;
4720         init_task_work(&req->task_work, func);
4721         percpu_ref_get(&req->ctx->refs);
4722
4723         /*
4724          * If we using the signalfd wait_queue_head for this wakeup, then
4725          * it's not safe to use TWA_SIGNAL as we could be recursing on the
4726          * tsk->sighand->siglock on doing the wakeup. Should not be needed
4727          * either, as the normal wakeup will suffice.
4728          */
4729         twa_signal_ok = (poll->head != &req->task->sighand->signalfd_wqh);
4730
4731         /*
4732          * If this fails, then the task is exiting. When a task exits, the
4733          * work gets canceled, so just cancel this request as well instead
4734          * of executing it. We can't safely execute it anyway, as we may not
4735          * have the needed state needed for it anyway.
4736          */
4737         ret = io_req_task_work_add(req, twa_signal_ok);
4738         if (unlikely(ret)) {
4739                 struct task_struct *tsk;
4740
4741                 WRITE_ONCE(poll->canceled, true);
4742                 tsk = io_wq_get_task(req->ctx->io_wq);
4743                 task_work_add(tsk, &req->task_work, 0);
4744                 wake_up_process(tsk);
4745         }
4746         return 1;
4747 }
4748
4749 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4750         __acquires(&req->ctx->completion_lock)
4751 {
4752         struct io_ring_ctx *ctx = req->ctx;
4753
4754         if (!req->result && !READ_ONCE(poll->canceled)) {
4755                 struct poll_table_struct pt = { ._key = poll->events };
4756
4757                 req->result = vfs_poll(req->file, &pt) & poll->events;
4758         }
4759
4760         spin_lock_irq(&ctx->completion_lock);
4761         if (!req->result && !READ_ONCE(poll->canceled)) {
4762                 add_wait_queue(poll->head, &poll->wait);
4763                 return true;
4764         }
4765
4766         return false;
4767 }
4768
4769 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4770 {
4771         /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4772         if (req->opcode == IORING_OP_POLL_ADD)
4773                 return req->async_data;
4774         return req->apoll->double_poll;
4775 }
4776
4777 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4778 {
4779         if (req->opcode == IORING_OP_POLL_ADD)
4780                 return &req->poll;
4781         return &req->apoll->poll;
4782 }
4783
4784 static void io_poll_remove_double(struct io_kiocb *req)
4785 {
4786         struct io_poll_iocb *poll = io_poll_get_double(req);
4787
4788         lockdep_assert_held(&req->ctx->completion_lock);
4789
4790         if (poll && poll->head) {
4791                 struct wait_queue_head *head = poll->head;
4792
4793                 spin_lock(&head->lock);
4794                 list_del_init(&poll->wait.entry);
4795                 if (poll->wait.private)
4796                         refcount_dec(&req->refs);
4797                 poll->head = NULL;
4798                 spin_unlock(&head->lock);
4799         }
4800 }
4801
4802 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4803 {
4804         struct io_ring_ctx *ctx = req->ctx;
4805
4806         io_poll_remove_double(req);
4807         req->poll.done = true;
4808         io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4809         io_commit_cqring(ctx);
4810 }
4811
4812 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4813 {
4814         struct io_ring_ctx *ctx = req->ctx;
4815
4816         if (io_poll_rewait(req, &req->poll)) {
4817                 spin_unlock_irq(&ctx->completion_lock);
4818                 return;
4819         }
4820
4821         hash_del(&req->hash_node);
4822         io_poll_complete(req, req->result, 0);
4823         spin_unlock_irq(&ctx->completion_lock);
4824
4825         *nxt = io_put_req_find_next(req);
4826         io_cqring_ev_posted(ctx);
4827 }
4828
4829 static void io_poll_task_func(struct callback_head *cb)
4830 {
4831         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4832         struct io_ring_ctx *ctx = req->ctx;
4833         struct io_kiocb *nxt = NULL;
4834
4835         io_poll_task_handler(req, &nxt);
4836         if (nxt)
4837                 __io_req_task_submit(nxt);
4838         percpu_ref_put(&ctx->refs);
4839 }
4840
4841 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4842                                int sync, void *key)
4843 {
4844         struct io_kiocb *req = wait->private;
4845         struct io_poll_iocb *poll = io_poll_get_single(req);
4846         __poll_t mask = key_to_poll(key);
4847
4848         /* for instances that support it check for an event match first: */
4849         if (mask && !(mask & poll->events))
4850                 return 0;
4851
4852         list_del_init(&wait->entry);
4853
4854         if (poll && poll->head) {
4855                 bool done;
4856
4857                 spin_lock(&poll->head->lock);
4858                 done = list_empty(&poll->wait.entry);
4859                 if (!done)
4860                         list_del_init(&poll->wait.entry);
4861                 /* make sure double remove sees this as being gone */
4862                 wait->private = NULL;
4863                 spin_unlock(&poll->head->lock);
4864                 if (!done)
4865                         __io_async_wake(req, poll, mask, io_poll_task_func);
4866         }
4867         refcount_dec(&req->refs);
4868         return 1;
4869 }
4870
4871 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4872                               wait_queue_func_t wake_func)
4873 {
4874         poll->head = NULL;
4875         poll->done = false;
4876         poll->canceled = false;
4877         poll->events = events;
4878         INIT_LIST_HEAD(&poll->wait.entry);
4879         init_waitqueue_func_entry(&poll->wait, wake_func);
4880 }
4881
4882 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4883                             struct wait_queue_head *head,
4884                             struct io_poll_iocb **poll_ptr)
4885 {
4886         struct io_kiocb *req = pt->req;
4887
4888         /*
4889          * If poll->head is already set, it's because the file being polled
4890          * uses multiple waitqueues for poll handling (eg one for read, one
4891          * for write). Setup a separate io_poll_iocb if this happens.
4892          */
4893         if (unlikely(poll->head)) {
4894                 /* already have a 2nd entry, fail a third attempt */
4895                 if (*poll_ptr) {
4896                         pt->error = -EINVAL;
4897                         return;
4898                 }
4899                 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4900                 if (!poll) {
4901                         pt->error = -ENOMEM;
4902                         return;
4903                 }
4904                 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4905                 refcount_inc(&req->refs);
4906                 poll->wait.private = req;
4907                 *poll_ptr = poll;
4908         }
4909
4910         pt->error = 0;
4911         poll->head = head;
4912
4913         if (poll->events & EPOLLEXCLUSIVE)
4914                 add_wait_queue_exclusive(head, &poll->wait);
4915         else
4916                 add_wait_queue(head, &poll->wait);
4917 }
4918
4919 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4920                                struct poll_table_struct *p)
4921 {
4922         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4923         struct async_poll *apoll = pt->req->apoll;
4924
4925         __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
4926 }
4927
4928 static void io_async_task_func(struct callback_head *cb)
4929 {
4930         struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4931         struct async_poll *apoll = req->apoll;
4932         struct io_ring_ctx *ctx = req->ctx;
4933
4934         trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4935
4936         if (io_poll_rewait(req, &apoll->poll)) {
4937                 spin_unlock_irq(&ctx->completion_lock);
4938                 percpu_ref_put(&ctx->refs);
4939                 return;
4940         }
4941
4942         /* If req is still hashed, it cannot have been canceled. Don't check. */
4943         if (hash_hashed(&req->hash_node))
4944                 hash_del(&req->hash_node);
4945
4946         io_poll_remove_double(req);
4947         spin_unlock_irq(&ctx->completion_lock);
4948
4949         if (!READ_ONCE(apoll->poll.canceled))
4950                 __io_req_task_submit(req);
4951         else
4952                 __io_req_task_cancel(req, -ECANCELED);
4953
4954         percpu_ref_put(&ctx->refs);
4955         kfree(apoll->double_poll);
4956         kfree(apoll);
4957 }
4958
4959 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4960                         void *key)
4961 {
4962         struct io_kiocb *req = wait->private;
4963         struct io_poll_iocb *poll = &req->apoll->poll;
4964
4965         trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4966                                         key_to_poll(key));
4967
4968         return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4969 }
4970
4971 static void io_poll_req_insert(struct io_kiocb *req)
4972 {
4973         struct io_ring_ctx *ctx = req->ctx;
4974         struct hlist_head *list;
4975
4976         list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4977         hlist_add_head(&req->hash_node, list);
4978 }
4979
4980 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4981                                       struct io_poll_iocb *poll,
4982                                       struct io_poll_table *ipt, __poll_t mask,
4983                                       wait_queue_func_t wake_func)
4984         __acquires(&ctx->completion_lock)
4985 {
4986         struct io_ring_ctx *ctx = req->ctx;
4987         bool cancel = false;
4988
4989         io_init_poll_iocb(poll, mask, wake_func);
4990         poll->file = req->file;
4991         poll->wait.private = req;
4992
4993         ipt->pt._key = mask;
4994         ipt->req = req;
4995         ipt->error = -EINVAL;
4996
4997         mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4998
4999         spin_lock_irq(&ctx->completion_lock);
5000         if (likely(poll->head)) {
5001                 spin_lock(&poll->head->lock);
5002                 if (unlikely(list_empty(&poll->wait.entry))) {
5003                         if (ipt->error)
5004                                 cancel = true;
5005                         ipt->error = 0;
5006                         mask = 0;
5007                 }
5008                 if (mask || ipt->error)
5009                         list_del_init(&poll->wait.entry);
5010                 else if (cancel)
5011                         WRITE_ONCE(poll->canceled, true);
5012                 else if (!poll->done) /* actually waiting for an event */
5013                         io_poll_req_insert(req);
5014                 spin_unlock(&poll->head->lock);
5015         }
5016
5017         return mask;
5018 }
5019
5020 static bool io_arm_poll_handler(struct io_kiocb *req)
5021 {
5022         const struct io_op_def *def = &io_op_defs[req->opcode];
5023         struct io_ring_ctx *ctx = req->ctx;
5024         struct async_poll *apoll;
5025         struct io_poll_table ipt;
5026         __poll_t mask, ret;
5027         int rw;
5028
5029         if (!req->file || !file_can_poll(req->file))
5030                 return false;
5031         if (req->flags & REQ_F_POLLED)
5032                 return false;
5033         if (def->pollin)
5034                 rw = READ;
5035         else if (def->pollout)
5036                 rw = WRITE;
5037         else
5038                 return false;
5039         /* if we can't nonblock try, then no point in arming a poll handler */
5040         if (!io_file_supports_async(req->file, rw))
5041                 return false;
5042
5043         apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5044         if (unlikely(!apoll))
5045                 return false;
5046         apoll->double_poll = NULL;
5047
5048         req->flags |= REQ_F_POLLED;
5049         req->apoll = apoll;
5050         INIT_HLIST_NODE(&req->hash_node);
5051
5052         mask = 0;
5053         if (def->pollin)
5054                 mask |= POLLIN | POLLRDNORM;
5055         if (def->pollout)
5056                 mask |= POLLOUT | POLLWRNORM;
5057
5058         /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5059         if ((req->opcode == IORING_OP_RECVMSG) &&
5060             (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5061                 mask &= ~POLLIN;
5062
5063         mask |= POLLERR | POLLPRI;
5064
5065         ipt.pt._qproc = io_async_queue_proc;
5066
5067         ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5068                                         io_async_wake);
5069         if (ret || ipt.error) {
5070                 io_poll_remove_double(req);
5071                 spin_unlock_irq(&ctx->completion_lock);
5072                 kfree(apoll->double_poll);
5073                 kfree(apoll);
5074                 return false;
5075         }
5076         spin_unlock_irq(&ctx->completion_lock);
5077         trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5078                                         apoll->poll.events);
5079         return true;
5080 }
5081
5082 static bool __io_poll_remove_one(struct io_kiocb *req,
5083                                  struct io_poll_iocb *poll)
5084 {
5085         bool do_complete = false;
5086
5087         spin_lock(&poll->head->lock);
5088         WRITE_ONCE(poll->canceled, true);
5089         if (!list_empty(&poll->wait.entry)) {
5090                 list_del_init(&poll->wait.entry);
5091                 do_complete = true;
5092         }
5093         spin_unlock(&poll->head->lock);
5094         hash_del(&req->hash_node);
5095         return do_complete;
5096 }
5097
5098 static bool io_poll_remove_one(struct io_kiocb *req)
5099 {
5100         bool do_complete;
5101
5102         io_poll_remove_double(req);
5103
5104         if (req->opcode == IORING_OP_POLL_ADD) {
5105                 do_complete = __io_poll_remove_one(req, &req->poll);
5106         } else {
5107                 struct async_poll *apoll = req->apoll;
5108
5109                 /* non-poll requests have submit ref still */
5110                 do_complete = __io_poll_remove_one(req, &apoll->poll);
5111                 if (do_complete) {
5112                         io_put_req(req);
5113                         kfree(apoll->double_poll);
5114                         kfree(apoll);
5115                 }
5116         }
5117
5118         if (do_complete) {
5119                 io_cqring_fill_event(req, -ECANCELED);
5120                 io_commit_cqring(req->ctx);
5121                 req_set_fail_links(req);
5122                 io_put_req_deferred(req, 1);
5123         }
5124
5125         return do_complete;
5126 }
5127
5128 /*
5129  * Returns true if we found and killed one or more poll requests
5130  */
5131 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk)
5132 {
5133         struct hlist_node *tmp;
5134         struct io_kiocb *req;
5135         int posted = 0, i;
5136
5137         spin_lock_irq(&ctx->completion_lock);
5138         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5139                 struct hlist_head *list;
5140
5141                 list = &ctx->cancel_hash[i];
5142                 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5143                         if (io_task_match(req, tsk))
5144                                 posted += io_poll_remove_one(req);
5145                 }
5146         }
5147         spin_unlock_irq(&ctx->completion_lock);
5148
5149         if (posted)
5150                 io_cqring_ev_posted(ctx);
5151
5152         return posted != 0;
5153 }
5154
5155 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5156 {
5157         struct hlist_head *list;
5158         struct io_kiocb *req;
5159
5160         list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5161         hlist_for_each_entry(req, list, hash_node) {
5162                 if (sqe_addr != req->user_data)
5163                         continue;
5164                 if (io_poll_remove_one(req))
5165                         return 0;
5166                 return -EALREADY;
5167         }
5168
5169         return -ENOENT;
5170 }
5171
5172 static int io_poll_remove_prep(struct io_kiocb *req,
5173                                const struct io_uring_sqe *sqe)
5174 {
5175         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5176                 return -EINVAL;
5177         if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5178             sqe->poll_events)
5179                 return -EINVAL;
5180
5181         req->poll.addr = READ_ONCE(sqe->addr);
5182         return 0;
5183 }
5184
5185 /*
5186  * Find a running poll command that matches one specified in sqe->addr,
5187  * and remove it if found.
5188  */
5189 static int io_poll_remove(struct io_kiocb *req)
5190 {
5191         struct io_ring_ctx *ctx = req->ctx;
5192         u64 addr;
5193         int ret;
5194
5195         addr = req->poll.addr;
5196         spin_lock_irq(&ctx->completion_lock);
5197         ret = io_poll_cancel(ctx, addr);
5198         spin_unlock_irq(&ctx->completion_lock);
5199
5200         if (ret < 0)
5201                 req_set_fail_links(req);
5202         io_req_complete(req, ret);
5203         return 0;
5204 }
5205
5206 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5207                         void *key)
5208 {
5209         struct io_kiocb *req = wait->private;
5210         struct io_poll_iocb *poll = &req->poll;
5211
5212         return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5213 }
5214
5215 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5216                                struct poll_table_struct *p)
5217 {
5218         struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5219
5220         __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5221 }
5222
5223 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5224 {
5225         struct io_poll_iocb *poll = &req->poll;
5226         u32 events;
5227
5228         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5229                 return -EINVAL;
5230         if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5231                 return -EINVAL;
5232         if (!poll->file)
5233                 return -EBADF;
5234
5235         events = READ_ONCE(sqe->poll32_events);
5236 #ifdef __BIG_ENDIAN
5237         events = swahw32(events);
5238 #endif
5239         poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5240                        (events & EPOLLEXCLUSIVE);
5241         return 0;
5242 }
5243
5244 static int io_poll_add(struct io_kiocb *req)
5245 {
5246         struct io_poll_iocb *poll = &req->poll;
5247         struct io_ring_ctx *ctx = req->ctx;
5248         struct io_poll_table ipt;
5249         __poll_t mask;
5250
5251         INIT_HLIST_NODE(&req->hash_node);
5252         ipt.pt._qproc = io_poll_queue_proc;
5253
5254         mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5255                                         io_poll_wake);
5256
5257         if (mask) { /* no async, we'd stolen it */
5258                 ipt.error = 0;
5259                 io_poll_complete(req, mask, 0);
5260         }
5261         spin_unlock_irq(&ctx->completion_lock);
5262
5263         if (mask) {
5264                 io_cqring_ev_posted(ctx);
5265                 io_put_req(req);
5266         }
5267         return ipt.error;
5268 }
5269
5270 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5271 {
5272         struct io_timeout_data *data = container_of(timer,
5273                                                 struct io_timeout_data, timer);
5274         struct io_kiocb *req = data->req;
5275         struct io_ring_ctx *ctx = req->ctx;
5276         unsigned long flags;
5277
5278         spin_lock_irqsave(&ctx->completion_lock, flags);
5279         list_del_init(&req->timeout.list);
5280         atomic_set(&req->ctx->cq_timeouts,
5281                 atomic_read(&req->ctx->cq_timeouts) + 1);
5282
5283         io_cqring_fill_event(req, -ETIME);
5284         io_commit_cqring(ctx);
5285         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5286
5287         io_cqring_ev_posted(ctx);
5288         req_set_fail_links(req);
5289         io_put_req(req);
5290         return HRTIMER_NORESTART;
5291 }
5292
5293 static int __io_timeout_cancel(struct io_kiocb *req)
5294 {
5295         struct io_timeout_data *io = req->async_data;
5296         int ret;
5297
5298         ret = hrtimer_try_to_cancel(&io->timer);
5299         if (ret == -1)
5300                 return -EALREADY;
5301         list_del_init(&req->timeout.list);
5302
5303         req_set_fail_links(req);
5304         io_cqring_fill_event(req, -ECANCELED);
5305         io_put_req_deferred(req, 1);
5306         return 0;
5307 }
5308
5309 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5310 {
5311         struct io_kiocb *req;
5312         int ret = -ENOENT;
5313
5314         list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5315                 if (user_data == req->user_data) {
5316                         ret = 0;
5317                         break;
5318                 }
5319         }
5320
5321         if (ret == -ENOENT)
5322                 return ret;
5323
5324         return __io_timeout_cancel(req);
5325 }
5326
5327 static int io_timeout_remove_prep(struct io_kiocb *req,
5328                                   const struct io_uring_sqe *sqe)
5329 {
5330         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5331                 return -EINVAL;
5332         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5333                 return -EINVAL;
5334         if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->timeout_flags)
5335                 return -EINVAL;
5336
5337         req->timeout_rem.addr = READ_ONCE(sqe->addr);
5338         return 0;
5339 }
5340
5341 /*
5342  * Remove or update an existing timeout command
5343  */
5344 static int io_timeout_remove(struct io_kiocb *req)
5345 {
5346         struct io_ring_ctx *ctx = req->ctx;
5347         int ret;
5348
5349         spin_lock_irq(&ctx->completion_lock);
5350         ret = io_timeout_cancel(ctx, req->timeout_rem.addr);
5351
5352         io_cqring_fill_event(req, ret);
5353         io_commit_cqring(ctx);
5354         spin_unlock_irq(&ctx->completion_lock);
5355         io_cqring_ev_posted(ctx);
5356         if (ret < 0)
5357                 req_set_fail_links(req);
5358         io_put_req(req);
5359         return 0;
5360 }
5361
5362 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5363                            bool is_timeout_link)
5364 {
5365         struct io_timeout_data *data;
5366         unsigned flags;
5367         u32 off = READ_ONCE(sqe->off);
5368
5369         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5370                 return -EINVAL;
5371         if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5372                 return -EINVAL;
5373         if (off && is_timeout_link)
5374                 return -EINVAL;
5375         flags = READ_ONCE(sqe->timeout_flags);
5376         if (flags & ~IORING_TIMEOUT_ABS)
5377                 return -EINVAL;
5378
5379         req->timeout.off = off;
5380
5381         if (!req->async_data && io_alloc_async_data(req))
5382                 return -ENOMEM;
5383
5384         data = req->async_data;
5385         data->req = req;
5386
5387         if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5388                 return -EFAULT;
5389
5390         if (flags & IORING_TIMEOUT_ABS)
5391                 data->mode = HRTIMER_MODE_ABS;
5392         else
5393                 data->mode = HRTIMER_MODE_REL;
5394
5395         hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5396         return 0;
5397 }
5398
5399 static int io_timeout(struct io_kiocb *req)
5400 {
5401         struct io_ring_ctx *ctx = req->ctx;
5402         struct io_timeout_data *data = req->async_data;
5403         struct list_head *entry;
5404         u32 tail, off = req->timeout.off;
5405
5406         spin_lock_irq(&ctx->completion_lock);
5407
5408         /*
5409          * sqe->off holds how many events that need to occur for this
5410          * timeout event to be satisfied. If it isn't set, then this is
5411          * a pure timeout request, sequence isn't used.
5412          */
5413         if (io_is_timeout_noseq(req)) {
5414                 entry = ctx->timeout_list.prev;
5415                 goto add;
5416         }
5417
5418         tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5419         req->timeout.target_seq = tail + off;
5420
5421         /*
5422          * Insertion sort, ensuring the first entry in the list is always
5423          * the one we need first.
5424          */
5425         list_for_each_prev(entry, &ctx->timeout_list) {
5426                 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5427                                                   timeout.list);
5428
5429                 if (io_is_timeout_noseq(nxt))
5430                         continue;
5431                 /* nxt.seq is behind @tail, otherwise would've been completed */
5432                 if (off >= nxt->timeout.target_seq - tail)
5433                         break;
5434         }
5435 add:
5436         list_add(&req->timeout.list, entry);
5437         data->timer.function = io_timeout_fn;
5438         hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5439         spin_unlock_irq(&ctx->completion_lock);
5440         return 0;
5441 }
5442
5443 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5444 {
5445         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5446
5447         return req->user_data == (unsigned long) data;
5448 }
5449
5450 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5451 {
5452         enum io_wq_cancel cancel_ret;
5453         int ret = 0;
5454
5455         cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5456         switch (cancel_ret) {
5457         case IO_WQ_CANCEL_OK:
5458                 ret = 0;
5459                 break;
5460         case IO_WQ_CANCEL_RUNNING:
5461                 ret = -EALREADY;
5462                 break;
5463         case IO_WQ_CANCEL_NOTFOUND:
5464                 ret = -ENOENT;
5465                 break;
5466         }
5467
5468         return ret;
5469 }
5470
5471 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5472                                      struct io_kiocb *req, __u64 sqe_addr,
5473                                      int success_ret)
5474 {
5475         unsigned long flags;
5476         int ret;
5477
5478         ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5479         if (ret != -ENOENT) {
5480                 spin_lock_irqsave(&ctx->completion_lock, flags);
5481                 goto done;
5482         }
5483
5484         spin_lock_irqsave(&ctx->completion_lock, flags);
5485         ret = io_timeout_cancel(ctx, sqe_addr);
5486         if (ret != -ENOENT)
5487                 goto done;
5488         ret = io_poll_cancel(ctx, sqe_addr);
5489 done:
5490         if (!ret)
5491                 ret = success_ret;
5492         io_cqring_fill_event(req, ret);
5493         io_commit_cqring(ctx);
5494         spin_unlock_irqrestore(&ctx->completion_lock, flags);
5495         io_cqring_ev_posted(ctx);
5496
5497         if (ret < 0)
5498                 req_set_fail_links(req);
5499         io_put_req(req);
5500 }
5501
5502 static int io_async_cancel_prep(struct io_kiocb *req,
5503                                 const struct io_uring_sqe *sqe)
5504 {
5505         if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5506                 return -EINVAL;
5507         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5508                 return -EINVAL;
5509         if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5510                 return -EINVAL;
5511
5512         req->cancel.addr = READ_ONCE(sqe->addr);
5513         return 0;
5514 }
5515
5516 static int io_async_cancel(struct io_kiocb *req)
5517 {
5518         struct io_ring_ctx *ctx = req->ctx;
5519
5520         io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5521         return 0;
5522 }
5523
5524 static int io_files_update_prep(struct io_kiocb *req,
5525                                 const struct io_uring_sqe *sqe)
5526 {
5527         if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5528                 return -EINVAL;
5529         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5530                 return -EINVAL;
5531         if (sqe->ioprio || sqe->rw_flags)
5532                 return -EINVAL;
5533
5534         req->files_update.offset = READ_ONCE(sqe->off);
5535         req->files_update.nr_args = READ_ONCE(sqe->len);
5536         if (!req->files_update.nr_args)
5537                 return -EINVAL;
5538         req->files_update.arg = READ_ONCE(sqe->addr);
5539         return 0;
5540 }
5541
5542 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5543                            struct io_comp_state *cs)
5544 {
5545         struct io_ring_ctx *ctx = req->ctx;
5546         struct io_uring_files_update up;
5547         int ret;
5548
5549         if (force_nonblock)
5550                 return -EAGAIN;
5551
5552         up.offset = req->files_update.offset;
5553         up.fds = req->files_update.arg;
5554
5555         mutex_lock(&ctx->uring_lock);
5556         ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5557         mutex_unlock(&ctx->uring_lock);
5558
5559         if (ret < 0)
5560                 req_set_fail_links(req);
5561         __io_req_complete(req, ret, 0, cs);
5562         return 0;
5563 }
5564
5565 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5566 {
5567         switch (req->opcode) {
5568         case IORING_OP_NOP:
5569                 return 0;
5570         case IORING_OP_READV:
5571         case IORING_OP_READ_FIXED:
5572         case IORING_OP_READ:
5573                 return io_read_prep(req, sqe);
5574         case IORING_OP_WRITEV:
5575         case IORING_OP_WRITE_FIXED:
5576         case IORING_OP_WRITE:
5577                 return io_write_prep(req, sqe);
5578         case IORING_OP_POLL_ADD:
5579                 return io_poll_add_prep(req, sqe);
5580         case IORING_OP_POLL_REMOVE:
5581                 return io_poll_remove_prep(req, sqe);
5582         case IORING_OP_FSYNC:
5583                 return io_prep_fsync(req, sqe);
5584         case IORING_OP_SYNC_FILE_RANGE:
5585                 return io_prep_sfr(req, sqe);
5586         case IORING_OP_SENDMSG:
5587         case IORING_OP_SEND:
5588                 return io_sendmsg_prep(req, sqe);
5589         case IORING_OP_RECVMSG:
5590         case IORING_OP_RECV:
5591                 return io_recvmsg_prep(req, sqe);
5592         case IORING_OP_CONNECT:
5593                 return io_connect_prep(req, sqe);
5594         case IORING_OP_TIMEOUT:
5595                 return io_timeout_prep(req, sqe, false);
5596         case IORING_OP_TIMEOUT_REMOVE:
5597                 return io_timeout_remove_prep(req, sqe);
5598         case IORING_OP_ASYNC_CANCEL:
5599                 return io_async_cancel_prep(req, sqe);
5600         case IORING_OP_LINK_TIMEOUT:
5601                 return io_timeout_prep(req, sqe, true);
5602         case IORING_OP_ACCEPT:
5603                 return io_accept_prep(req, sqe);
5604         case IORING_OP_FALLOCATE:
5605                 return io_fallocate_prep(req, sqe);
5606         case IORING_OP_OPENAT:
5607                 return io_openat_prep(req, sqe);
5608         case IORING_OP_CLOSE:
5609                 return io_close_prep(req, sqe);
5610         case IORING_OP_FILES_UPDATE:
5611                 return io_files_update_prep(req, sqe);
5612         case IORING_OP_STATX:
5613                 return io_statx_prep(req, sqe);
5614         case IORING_OP_FADVISE:
5615                 return io_fadvise_prep(req, sqe);
5616         case IORING_OP_MADVISE:
5617                 return io_madvise_prep(req, sqe);
5618         case IORING_OP_OPENAT2:
5619                 return io_openat2_prep(req, sqe);
5620         case IORING_OP_EPOLL_CTL:
5621                 return io_epoll_ctl_prep(req, sqe);
5622         case IORING_OP_SPLICE:
5623                 return io_splice_prep(req, sqe);
5624         case IORING_OP_PROVIDE_BUFFERS:
5625                 return io_provide_buffers_prep(req, sqe);
5626         case IORING_OP_REMOVE_BUFFERS:
5627                 return io_remove_buffers_prep(req, sqe);
5628         case IORING_OP_TEE:
5629                 return io_tee_prep(req, sqe);
5630         }
5631
5632         printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5633                         req->opcode);
5634         return-EINVAL;
5635 }
5636
5637 static int io_req_defer_prep(struct io_kiocb *req,
5638                              const struct io_uring_sqe *sqe)
5639 {
5640         if (!sqe)
5641                 return 0;
5642         if (io_alloc_async_data(req))
5643                 return -EAGAIN;
5644         return io_req_prep(req, sqe);
5645 }
5646
5647 static u32 io_get_sequence(struct io_kiocb *req)
5648 {
5649         struct io_kiocb *pos;
5650         struct io_ring_ctx *ctx = req->ctx;
5651         u32 total_submitted, nr_reqs = 1;
5652
5653         if (req->flags & REQ_F_LINK_HEAD)
5654                 list_for_each_entry(pos, &req->link_list, link_list)
5655                         nr_reqs++;
5656
5657         total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5658         return total_submitted - nr_reqs;
5659 }
5660
5661 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5662 {
5663         struct io_ring_ctx *ctx = req->ctx;
5664         struct io_defer_entry *de;
5665         int ret;
5666         u32 seq;
5667
5668         /* Still need defer if there is pending req in defer list. */
5669         if (likely(list_empty_careful(&ctx->defer_list) &&
5670                 !(req->flags & REQ_F_IO_DRAIN)))
5671                 return 0;
5672
5673         seq = io_get_sequence(req);
5674         /* Still a chance to pass the sequence check */
5675         if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5676                 return 0;
5677
5678         if (!req->async_data) {
5679                 ret = io_req_defer_prep(req, sqe);
5680                 if (ret)
5681                         return ret;
5682         }
5683         io_prep_async_link(req);
5684         de = kmalloc(sizeof(*de), GFP_KERNEL);
5685         if (!de)
5686                 return -ENOMEM;
5687
5688         spin_lock_irq(&ctx->completion_lock);
5689         if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5690                 spin_unlock_irq(&ctx->completion_lock);
5691                 kfree(de);
5692                 io_queue_async_work(req);
5693                 return -EIOCBQUEUED;
5694         }
5695
5696         trace_io_uring_defer(ctx, req, req->user_data);
5697         de->req = req;
5698         de->seq = seq;
5699         list_add_tail(&de->list, &ctx->defer_list);
5700         spin_unlock_irq(&ctx->completion_lock);
5701         return -EIOCBQUEUED;
5702 }
5703
5704 static void io_req_drop_files(struct io_kiocb *req)
5705 {
5706         struct io_ring_ctx *ctx = req->ctx;
5707         unsigned long flags;
5708
5709         spin_lock_irqsave(&ctx->inflight_lock, flags);
5710         list_del(&req->inflight_entry);
5711         if (waitqueue_active(&ctx->inflight_wait))
5712                 wake_up(&ctx->inflight_wait);
5713         spin_unlock_irqrestore(&ctx->inflight_lock, flags);
5714         req->flags &= ~REQ_F_INFLIGHT;
5715         put_files_struct(req->work.files);
5716         put_nsproxy(req->work.nsproxy);
5717         req->work.files = NULL;
5718 }
5719
5720 static void __io_clean_op(struct io_kiocb *req)
5721 {
5722         if (req->flags & REQ_F_BUFFER_SELECTED) {
5723                 switch (req->opcode) {
5724                 case IORING_OP_READV:
5725                 case IORING_OP_READ_FIXED:
5726                 case IORING_OP_READ:
5727                         kfree((void *)(unsigned long)req->rw.addr);
5728                         break;
5729                 case IORING_OP_RECVMSG:
5730                 case IORING_OP_RECV:
5731                         kfree(req->sr_msg.kbuf);
5732                         break;
5733                 }
5734                 req->flags &= ~REQ_F_BUFFER_SELECTED;
5735         }
5736
5737         if (req->flags & REQ_F_NEED_CLEANUP) {
5738                 switch (req->opcode) {
5739                 case IORING_OP_READV:
5740                 case IORING_OP_READ_FIXED:
5741                 case IORING_OP_READ:
5742                 case IORING_OP_WRITEV:
5743                 case IORING_OP_WRITE_FIXED:
5744                 case IORING_OP_WRITE: {
5745                         struct io_async_rw *io = req->async_data;
5746                         if (io->free_iovec)
5747                                 kfree(io->free_iovec);
5748                         break;
5749                         }
5750                 case IORING_OP_RECVMSG:
5751                 case IORING_OP_SENDMSG: {
5752                         struct io_async_msghdr *io = req->async_data;
5753                         if (io->iov != io->fast_iov)
5754                                 kfree(io->iov);
5755                         break;
5756                         }
5757                 case IORING_OP_SPLICE:
5758                 case IORING_OP_TEE:
5759                         io_put_file(req, req->splice.file_in,
5760                                     (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5761                         break;
5762                 case IORING_OP_OPENAT:
5763                 case IORING_OP_OPENAT2:
5764                         if (req->open.filename)
5765                                 putname(req->open.filename);
5766                         break;
5767                 }
5768                 req->flags &= ~REQ_F_NEED_CLEANUP;
5769         }
5770
5771         if (req->flags & REQ_F_INFLIGHT)
5772                 io_req_drop_files(req);
5773 }
5774
5775 static int io_issue_sqe(struct io_kiocb *req, bool force_nonblock,
5776                         struct io_comp_state *cs)
5777 {
5778         struct io_ring_ctx *ctx = req->ctx;
5779         int ret;
5780
5781         switch (req->opcode) {
5782         case IORING_OP_NOP:
5783                 ret = io_nop(req, cs);
5784                 break;
5785         case IORING_OP_READV:
5786         case IORING_OP_READ_FIXED:
5787         case IORING_OP_READ:
5788                 ret = io_read(req, force_nonblock, cs);
5789                 break;
5790         case IORING_OP_WRITEV:
5791         case IORING_OP_WRITE_FIXED:
5792         case IORING_OP_WRITE:
5793                 ret = io_write(req, force_nonblock, cs);
5794                 break;
5795         case IORING_OP_FSYNC:
5796                 ret = io_fsync(req, force_nonblock);
5797                 break;
5798         case IORING_OP_POLL_ADD:
5799                 ret = io_poll_add(req);
5800                 break;
5801         case IORING_OP_POLL_REMOVE:
5802                 ret = io_poll_remove(req);
5803                 break;
5804         case IORING_OP_SYNC_FILE_RANGE:
5805                 ret = io_sync_file_range(req, force_nonblock);
5806                 break;
5807         case IORING_OP_SENDMSG:
5808                 ret = io_sendmsg(req, force_nonblock, cs);
5809                 break;
5810         case IORING_OP_SEND:
5811                 ret = io_send(req, force_nonblock, cs);
5812                 break;
5813         case IORING_OP_RECVMSG:
5814                 ret = io_recvmsg(req, force_nonblock, cs);
5815                 break;
5816         case IORING_OP_RECV:
5817                 ret = io_recv(req, force_nonblock, cs);
5818                 break;
5819         case IORING_OP_TIMEOUT:
5820                 ret = io_timeout(req);
5821                 break;
5822         case IORING_OP_TIMEOUT_REMOVE:
5823                 ret = io_timeout_remove(req);
5824                 break;
5825         case IORING_OP_ACCEPT:
5826                 ret = io_accept(req, force_nonblock, cs);
5827                 break;
5828         case IORING_OP_CONNECT:
5829                 ret = io_connect(req, force_nonblock, cs);
5830                 break;
5831         case IORING_OP_ASYNC_CANCEL:
5832                 ret = io_async_cancel(req);
5833                 break;
5834         case IORING_OP_FALLOCATE:
5835                 ret = io_fallocate(req, force_nonblock);
5836                 break;
5837         case IORING_OP_OPENAT:
5838                 ret = io_openat(req, force_nonblock);
5839                 break;
5840         case IORING_OP_CLOSE:
5841                 ret = io_close(req, force_nonblock, cs);
5842                 break;
5843         case IORING_OP_FILES_UPDATE:
5844                 ret = io_files_update(req, force_nonblock, cs);
5845                 break;
5846         case IORING_OP_STATX:
5847                 ret = io_statx(req, force_nonblock);
5848                 break;
5849         case IORING_OP_FADVISE:
5850                 ret = io_fadvise(req, force_nonblock);
5851                 break;
5852         case IORING_OP_MADVISE:
5853                 ret = io_madvise(req, force_nonblock);
5854                 break;
5855         case IORING_OP_OPENAT2:
5856                 ret = io_openat2(req, force_nonblock);
5857                 break;
5858         case IORING_OP_EPOLL_CTL:
5859                 ret = io_epoll_ctl(req, force_nonblock, cs);
5860                 break;
5861         case IORING_OP_SPLICE:
5862                 ret = io_splice(req, force_nonblock);
5863                 break;
5864         case IORING_OP_PROVIDE_BUFFERS:
5865                 ret = io_provide_buffers(req, force_nonblock, cs);
5866                 break;
5867         case IORING_OP_REMOVE_BUFFERS:
5868                 ret = io_remove_buffers(req, force_nonblock, cs);
5869                 break;
5870         case IORING_OP_TEE:
5871                 ret = io_tee(req, force_nonblock);
5872                 break;
5873         default:
5874                 ret = -EINVAL;
5875                 break;
5876         }
5877
5878         if (ret)
5879                 return ret;
5880
5881         /* If the op doesn't have a file, we're not polling for it */
5882         if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5883                 const bool in_async = io_wq_current_is_worker();
5884
5885                 /* workqueue context doesn't hold uring_lock, grab it now */
5886                 if (in_async)
5887                         mutex_lock(&ctx->uring_lock);
5888
5889                 io_iopoll_req_issued(req);
5890
5891                 if (in_async)
5892                         mutex_unlock(&ctx->uring_lock);
5893         }
5894
5895         return 0;
5896 }
5897
5898 static struct io_wq_work *io_wq_submit_work(struct io_wq_work *work)
5899 {
5900         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5901         struct io_kiocb *timeout;
5902         int ret = 0;
5903
5904         timeout = io_prep_linked_timeout(req);
5905         if (timeout)
5906                 io_queue_linked_timeout(timeout);
5907
5908         /* if NO_CANCEL is set, we must still run the work */
5909         if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5910                                 IO_WQ_WORK_CANCEL) {
5911                 ret = -ECANCELED;
5912         }
5913
5914         if (!ret) {
5915                 do {
5916                         ret = io_issue_sqe(req, false, NULL);
5917                         /*
5918                          * We can get EAGAIN for polled IO even though we're
5919                          * forcing a sync submission from here, since we can't
5920                          * wait for request slots on the block side.
5921                          */
5922                         if (ret != -EAGAIN)
5923                                 break;
5924                         cond_resched();
5925                 } while (1);
5926         }
5927
5928         if (ret) {
5929                 req_set_fail_links(req);
5930                 io_req_complete(req, ret);
5931         }
5932
5933         return io_steal_work(req);
5934 }
5935
5936 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5937                                               int index)
5938 {
5939         struct fixed_file_table *table;
5940
5941         table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5942         return table->files[index & IORING_FILE_TABLE_MASK];
5943 }
5944
5945 static struct file *io_file_get(struct io_submit_state *state,
5946                                 struct io_kiocb *req, int fd, bool fixed)
5947 {
5948         struct io_ring_ctx *ctx = req->ctx;
5949         struct file *file;
5950
5951         if (fixed) {
5952                 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
5953                         return NULL;
5954                 fd = array_index_nospec(fd, ctx->nr_user_files);
5955                 file = io_file_from_index(ctx, fd);
5956                 if (file) {
5957                         req->fixed_file_refs = &ctx->file_data->node->refs;
5958                         percpu_ref_get(req->fixed_file_refs);
5959                 }
5960         } else {
5961                 trace_io_uring_file_get(ctx, fd);
5962                 file = __io_file_get(state, fd);
5963         }
5964
5965         return file;
5966 }
5967
5968 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5969                            int fd)
5970 {
5971         bool fixed;
5972
5973         fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5974         if (unlikely(!fixed && io_async_submit(req->ctx)))
5975                 return -EBADF;
5976
5977         req->file = io_file_get(state, req, fd, fixed);
5978         if (req->file || io_op_defs[req->opcode].needs_file_no_error)
5979                 return 0;
5980         return -EBADF;
5981 }
5982
5983 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5984 {
5985         struct io_timeout_data *data = container_of(timer,
5986                                                 struct io_timeout_data, timer);
5987         struct io_kiocb *req = data->req;
5988         struct io_ring_ctx *ctx = req->ctx;
5989         struct io_kiocb *prev = NULL;
5990         unsigned long flags;
5991
5992         spin_lock_irqsave(&ctx->completion_lock, flags);
5993
5994         /*
5995          * We don't expect the list to be empty, that will only happen if we
5996          * race with the completion of the linked work.
5997          */
5998         if (!list_empty(&req->link_list)) {
5999                 prev = list_entry(req->link_list.prev, struct io_kiocb,
6000                                   link_list);
6001                 if (refcount_inc_not_zero(&prev->refs)) {
6002                         list_del_init(&req->link_list);
6003                         prev->flags &= ~REQ_F_LINK_TIMEOUT;
6004                 } else
6005                         prev = NULL;
6006         }
6007
6008         spin_unlock_irqrestore(&ctx->completion_lock, flags);
6009
6010         if (prev) {
6011                 req_set_fail_links(prev);
6012                 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6013                 io_put_req(prev);
6014         } else {
6015                 io_req_complete(req, -ETIME);
6016         }
6017         return HRTIMER_NORESTART;
6018 }
6019
6020 static void __io_queue_linked_timeout(struct io_kiocb *req)
6021 {
6022         /*
6023          * If the list is now empty, then our linked request finished before
6024          * we got a chance to setup the timer
6025          */
6026         if (!list_empty(&req->link_list)) {
6027                 struct io_timeout_data *data = req->async_data;
6028
6029                 data->timer.function = io_link_timeout_fn;
6030                 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6031                                 data->mode);
6032         }
6033 }
6034
6035 static void io_queue_linked_timeout(struct io_kiocb *req)
6036 {
6037         struct io_ring_ctx *ctx = req->ctx;
6038
6039         spin_lock_irq(&ctx->completion_lock);
6040         __io_queue_linked_timeout(req);
6041         spin_unlock_irq(&ctx->completion_lock);
6042
6043         /* drop submission reference */
6044         io_put_req(req);
6045 }
6046
6047 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6048 {
6049         struct io_kiocb *nxt;
6050
6051         if (!(req->flags & REQ_F_LINK_HEAD))
6052                 return NULL;
6053         if (req->flags & REQ_F_LINK_TIMEOUT)
6054                 return NULL;
6055
6056         nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
6057                                         link_list);
6058         if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
6059                 return NULL;
6060
6061         req->flags |= REQ_F_LINK_TIMEOUT;
6062         return nxt;
6063 }
6064
6065 static void __io_queue_sqe(struct io_kiocb *req, struct io_comp_state *cs)
6066 {
6067         struct io_kiocb *linked_timeout;
6068         struct io_kiocb *nxt;
6069         const struct cred *old_creds = NULL;
6070         int ret;
6071
6072 again:
6073         linked_timeout = io_prep_linked_timeout(req);
6074
6075         if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
6076             req->work.creds != current_cred()) {
6077                 if (old_creds)
6078                         revert_creds(old_creds);
6079                 if (old_creds == req->work.creds)
6080                         old_creds = NULL; /* restored original creds */
6081                 else
6082                         old_creds = override_creds(req->work.creds);
6083         }
6084
6085         ret = io_issue_sqe(req, true, cs);
6086
6087         /*
6088          * We async punt it if the file wasn't marked NOWAIT, or if the file
6089          * doesn't support non-blocking read/write attempts
6090          */
6091         if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6092                 if (!io_arm_poll_handler(req)) {
6093 punt:
6094                         /*
6095                          * Queued up for async execution, worker will release
6096                          * submit reference when the iocb is actually submitted.
6097                          */
6098                         io_queue_async_work(req);
6099                 }
6100
6101                 if (linked_timeout)
6102                         io_queue_linked_timeout(linked_timeout);
6103                 goto exit;
6104         }
6105
6106         if (unlikely(ret)) {
6107                 /* un-prep timeout, so it'll be killed as any other linked */
6108                 req->flags &= ~REQ_F_LINK_TIMEOUT;
6109                 req_set_fail_links(req);
6110                 io_put_req(req);
6111                 io_req_complete(req, ret);
6112                 goto exit;
6113         }
6114
6115         /* drop submission reference */
6116         nxt = io_put_req_find_next(req);
6117         if (linked_timeout)
6118                 io_queue_linked_timeout(linked_timeout);
6119
6120         if (nxt) {
6121                 req = nxt;
6122
6123                 if (req->flags & REQ_F_FORCE_ASYNC)
6124                         goto punt;
6125                 goto again;
6126         }
6127 exit:
6128         if (old_creds)
6129                 revert_creds(old_creds);
6130 }
6131
6132 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6133                          struct io_comp_state *cs)
6134 {
6135         int ret;
6136
6137         ret = io_req_defer(req, sqe);
6138         if (ret) {
6139                 if (ret != -EIOCBQUEUED) {
6140 fail_req:
6141                         req_set_fail_links(req);
6142                         io_put_req(req);
6143                         io_req_complete(req, ret);
6144                 }
6145         } else if (req->flags & REQ_F_FORCE_ASYNC) {
6146                 if (!req->async_data) {
6147                         ret = io_req_defer_prep(req, sqe);
6148                         if (unlikely(ret))
6149                                 goto fail_req;
6150                 }
6151
6152                 /*
6153                  * Never try inline submit of IOSQE_ASYNC is set, go straight
6154                  * to async execution.
6155                  */
6156                 io_req_init_async(req);
6157                 req->work.flags |= IO_WQ_WORK_CONCURRENT;
6158                 io_queue_async_work(req);
6159         } else {
6160                 if (sqe) {
6161                         ret = io_req_prep(req, sqe);
6162                         if (unlikely(ret))
6163                                 goto fail_req;
6164                 }
6165                 __io_queue_sqe(req, cs);
6166         }
6167 }
6168
6169 static inline void io_queue_link_head(struct io_kiocb *req,
6170                                       struct io_comp_state *cs)
6171 {
6172         if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
6173                 io_put_req(req);
6174                 io_req_complete(req, -ECANCELED);
6175         } else
6176                 io_queue_sqe(req, NULL, cs);
6177 }
6178
6179 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6180                          struct io_kiocb **link, struct io_comp_state *cs)
6181 {
6182         struct io_ring_ctx *ctx = req->ctx;
6183         int ret;
6184
6185         /*
6186          * If we already have a head request, queue this one for async
6187          * submittal once the head completes. If we don't have a head but
6188          * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6189          * submitted sync once the chain is complete. If none of those
6190          * conditions are true (normal request), then just queue it.
6191          */
6192         if (*link) {
6193                 struct io_kiocb *head = *link;
6194
6195                 /*
6196                  * Taking sequential execution of a link, draining both sides
6197                  * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6198                  * requests in the link. So, it drains the head and the
6199                  * next after the link request. The last one is done via
6200                  * drain_next flag to persist the effect across calls.
6201                  */
6202                 if (req->flags & REQ_F_IO_DRAIN) {
6203                         head->flags |= REQ_F_IO_DRAIN;
6204                         ctx->drain_next = 1;
6205                 }
6206                 ret = io_req_defer_prep(req, sqe);
6207                 if (unlikely(ret)) {
6208                         /* fail even hard links since we don't submit */
6209                         head->flags |= REQ_F_FAIL_LINK;
6210                         return ret;
6211                 }
6212                 trace_io_uring_link(ctx, req, head);
6213                 list_add_tail(&req->link_list, &head->link_list);
6214
6215                 /* last request of a link, enqueue the link */
6216                 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6217                         io_queue_link_head(head, cs);
6218                         *link = NULL;
6219                 }
6220         } else {
6221                 if (unlikely(ctx->drain_next)) {
6222                         req->flags |= REQ_F_IO_DRAIN;
6223                         ctx->drain_next = 0;
6224                 }
6225                 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6226                         req->flags |= REQ_F_LINK_HEAD;
6227                         INIT_LIST_HEAD(&req->link_list);
6228
6229                         ret = io_req_defer_prep(req, sqe);
6230                         if (unlikely(ret))
6231                                 req->flags |= REQ_F_FAIL_LINK;
6232                         *link = req;
6233                 } else {
6234                         io_queue_sqe(req, sqe, cs);
6235                 }
6236         }
6237
6238         return 0;
6239 }
6240
6241 /*
6242  * Batched submission is done, ensure local IO is flushed out.
6243  */
6244 static void io_submit_state_end(struct io_submit_state *state)
6245 {
6246         if (!list_empty(&state->comp.list))
6247                 io_submit_flush_completions(&state->comp);
6248         blk_finish_plug(&state->plug);
6249         io_state_file_put(state);
6250         if (state->free_reqs)
6251                 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6252 }
6253
6254 /*
6255  * Start submission side cache.
6256  */
6257 static void io_submit_state_start(struct io_submit_state *state,
6258                                   struct io_ring_ctx *ctx, unsigned int max_ios)
6259 {
6260         blk_start_plug(&state->plug);
6261         state->comp.nr = 0;
6262         INIT_LIST_HEAD(&state->comp.list);
6263         state->comp.ctx = ctx;
6264         state->free_reqs = 0;
6265         state->file = NULL;
6266         state->ios_left = max_ios;
6267 }
6268
6269 static void io_commit_sqring(struct io_ring_ctx *ctx)
6270 {
6271         struct io_rings *rings = ctx->rings;
6272
6273         /*
6274          * Ensure any loads from the SQEs are done at this point,
6275          * since once we write the new head, the application could
6276          * write new data to them.
6277          */
6278         smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6279 }
6280
6281 /*
6282  * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6283  * that is mapped by userspace. This means that care needs to be taken to
6284  * ensure that reads are stable, as we cannot rely on userspace always
6285  * being a good citizen. If members of the sqe are validated and then later
6286  * used, it's important that those reads are done through READ_ONCE() to
6287  * prevent a re-load down the line.
6288  */
6289 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6290 {
6291         u32 *sq_array = ctx->sq_array;
6292         unsigned head;
6293
6294         /*
6295          * The cached sq head (or cq tail) serves two purposes:
6296          *
6297          * 1) allows us to batch the cost of updating the user visible
6298          *    head updates.
6299          * 2) allows the kernel side to track the head on its own, even
6300          *    though the application is the one updating it.
6301          */
6302         head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6303         if (likely(head < ctx->sq_entries))
6304                 return &ctx->sq_sqes[head];
6305
6306         /* drop invalid entries */
6307         ctx->cached_sq_dropped++;
6308         WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6309         return NULL;
6310 }
6311
6312 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6313 {
6314         ctx->cached_sq_head++;
6315 }
6316
6317 /*
6318  * Check SQE restrictions (opcode and flags).
6319  *
6320  * Returns 'true' if SQE is allowed, 'false' otherwise.
6321  */
6322 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6323                                         struct io_kiocb *req,
6324                                         unsigned int sqe_flags)
6325 {
6326         if (!ctx->restricted)
6327                 return true;
6328
6329         if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6330                 return false;
6331
6332         if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6333             ctx->restrictions.sqe_flags_required)
6334                 return false;
6335
6336         if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6337                           ctx->restrictions.sqe_flags_required))
6338                 return false;
6339
6340         return true;
6341 }
6342
6343 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6344                                 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6345                                 IOSQE_BUFFER_SELECT)
6346
6347 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6348                        const struct io_uring_sqe *sqe,
6349                        struct io_submit_state *state)
6350 {
6351         unsigned int sqe_flags;
6352         int id, ret;
6353
6354         req->opcode = READ_ONCE(sqe->opcode);
6355         req->user_data = READ_ONCE(sqe->user_data);
6356         req->async_data = NULL;
6357         req->file = NULL;
6358         req->ctx = ctx;
6359         req->flags = 0;
6360         /* one is dropped after submission, the other at completion */
6361         refcount_set(&req->refs, 2);
6362         req->task = current;
6363         req->result = 0;
6364
6365         if (unlikely(req->opcode >= IORING_OP_LAST))
6366                 return -EINVAL;
6367
6368         if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6369                 return -EFAULT;
6370
6371         sqe_flags = READ_ONCE(sqe->flags);
6372         /* enforce forwards compatibility on users */
6373         if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6374                 return -EINVAL;
6375
6376         if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6377                 return -EACCES;
6378
6379         if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6380             !io_op_defs[req->opcode].buffer_select)
6381                 return -EOPNOTSUPP;
6382
6383         id = READ_ONCE(sqe->personality);
6384         if (id) {
6385                 io_req_init_async(req);
6386                 req->work.creds = idr_find(&ctx->personality_idr, id);
6387                 if (unlikely(!req->work.creds))
6388                         return -EINVAL;
6389                 get_cred(req->work.creds);
6390         }
6391
6392         /* same numerical values with corresponding REQ_F_*, safe to copy */
6393         req->flags |= sqe_flags;
6394
6395         if (!io_op_defs[req->opcode].needs_file)
6396                 return 0;
6397
6398         ret = io_req_set_file(state, req, READ_ONCE(sqe->fd));
6399         state->ios_left--;
6400         return ret;
6401 }
6402
6403 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6404 {
6405         struct io_submit_state state;
6406         struct io_kiocb *link = NULL;
6407         int i, submitted = 0;
6408
6409         /* if we have a backlog and couldn't flush it all, return BUSY */
6410         if (test_bit(0, &ctx->sq_check_overflow)) {
6411                 if (!list_empty(&ctx->cq_overflow_list) &&
6412                     !io_cqring_overflow_flush(ctx, false, NULL, NULL))
6413                         return -EBUSY;
6414         }
6415
6416         /* make sure SQ entry isn't read before tail */
6417         nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6418
6419         if (!percpu_ref_tryget_many(&ctx->refs, nr))
6420                 return -EAGAIN;
6421
6422         atomic_long_add(nr, &current->io_uring->req_issue);
6423         refcount_add(nr, &current->usage);
6424
6425         io_submit_state_start(&state, ctx, nr);
6426
6427         for (i = 0; i < nr; i++) {
6428                 const struct io_uring_sqe *sqe;
6429                 struct io_kiocb *req;
6430                 int err;
6431
6432                 sqe = io_get_sqe(ctx);
6433                 if (unlikely(!sqe)) {
6434                         io_consume_sqe(ctx);
6435                         break;
6436                 }
6437                 req = io_alloc_req(ctx, &state);
6438                 if (unlikely(!req)) {
6439                         if (!submitted)
6440                                 submitted = -EAGAIN;
6441                         break;
6442                 }
6443                 io_consume_sqe(ctx);
6444                 /* will complete beyond this point, count as submitted */
6445                 submitted++;
6446
6447                 err = io_init_req(ctx, req, sqe, &state);
6448                 if (unlikely(err)) {
6449 fail_req:
6450                         io_put_req(req);
6451                         io_req_complete(req, err);
6452                         break;
6453                 }
6454
6455                 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6456                                                 true, io_async_submit(ctx));
6457                 err = io_submit_sqe(req, sqe, &link, &state.comp);
6458                 if (err)
6459                         goto fail_req;
6460         }
6461
6462         if (unlikely(submitted != nr)) {
6463                 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6464
6465                 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6466                 atomic_long_sub(nr - ref_used, &current->io_uring->req_issue);
6467                 put_task_struct_many(current, nr - ref_used);
6468         }
6469         if (link)
6470                 io_queue_link_head(link, &state.comp);
6471         io_submit_state_end(&state);
6472
6473          /* Commit SQ ring head once we've consumed and submitted all SQEs */
6474         io_commit_sqring(ctx);
6475
6476         return submitted;
6477 }
6478
6479 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6480 {
6481         /* Tell userspace we may need a wakeup call */
6482         spin_lock_irq(&ctx->completion_lock);
6483         ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6484         spin_unlock_irq(&ctx->completion_lock);
6485 }
6486
6487 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6488 {
6489         spin_lock_irq(&ctx->completion_lock);
6490         ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6491         spin_unlock_irq(&ctx->completion_lock);
6492 }
6493
6494 static int io_sq_wake_function(struct wait_queue_entry *wqe, unsigned mode,
6495                                int sync, void *key)
6496 {
6497         struct io_ring_ctx *ctx = container_of(wqe, struct io_ring_ctx, sqo_wait_entry);
6498         int ret;
6499
6500         ret = autoremove_wake_function(wqe, mode, sync, key);
6501         if (ret) {
6502                 unsigned long flags;
6503
6504                 spin_lock_irqsave(&ctx->completion_lock, flags);
6505                 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6506                 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6507         }
6508         return ret;
6509 }
6510
6511 enum sq_ret {
6512         SQT_IDLE        = 1,
6513         SQT_SPIN        = 2,
6514         SQT_DID_WORK    = 4,
6515 };
6516
6517 static enum sq_ret __io_sq_thread(struct io_ring_ctx *ctx,
6518                                   unsigned long start_jiffies, bool cap_entries)
6519 {
6520         unsigned long timeout = start_jiffies + ctx->sq_thread_idle;
6521         struct io_sq_data *sqd = ctx->sq_data;
6522         unsigned int to_submit;
6523         int ret = 0;
6524
6525 again:
6526         if (!list_empty(&ctx->iopoll_list)) {
6527                 unsigned nr_events = 0;
6528
6529                 mutex_lock(&ctx->uring_lock);
6530                 if (!list_empty(&ctx->iopoll_list) && !need_resched())
6531                         io_do_iopoll(ctx, &nr_events, 0);
6532                 mutex_unlock(&ctx->uring_lock);
6533         }
6534
6535         to_submit = io_sqring_entries(ctx);
6536
6537         /*
6538          * If submit got -EBUSY, flag us as needing the application
6539          * to enter the kernel to reap and flush events.
6540          */
6541         if (!to_submit || ret == -EBUSY || need_resched()) {
6542                 /*
6543                  * Drop cur_mm before scheduling, we can't hold it for
6544                  * long periods (or over schedule()). Do this before
6545                  * adding ourselves to the waitqueue, as the unuse/drop
6546                  * may sleep.
6547                  */
6548                 io_sq_thread_drop_mm();
6549
6550                 /*
6551                  * We're polling. If we're within the defined idle
6552                  * period, then let us spin without work before going
6553                  * to sleep. The exception is if we got EBUSY doing
6554                  * more IO, we should wait for the application to
6555                  * reap events and wake us up.
6556                  */
6557                 if (!list_empty(&ctx->iopoll_list) || need_resched() ||
6558                     (!time_after(jiffies, timeout) && ret != -EBUSY &&
6559                     !percpu_ref_is_dying(&ctx->refs)))
6560                         return SQT_SPIN;
6561
6562                 prepare_to_wait(&sqd->wait, &ctx->sqo_wait_entry,
6563                                         TASK_INTERRUPTIBLE);
6564
6565                 /*
6566                  * While doing polled IO, before going to sleep, we need
6567                  * to check if there are new reqs added to iopoll_list,
6568                  * it is because reqs may have been punted to io worker
6569                  * and will be added to iopoll_list later, hence check
6570                  * the iopoll_list again.
6571                  */
6572                 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6573                     !list_empty_careful(&ctx->iopoll_list)) {
6574                         finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6575                         goto again;
6576                 }
6577
6578                 to_submit = io_sqring_entries(ctx);
6579                 if (!to_submit || ret == -EBUSY)
6580                         return SQT_IDLE;
6581         }
6582
6583         finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6584         io_ring_clear_wakeup_flag(ctx);
6585
6586         /* if we're handling multiple rings, cap submit size for fairness */
6587         if (cap_entries && to_submit > 8)
6588                 to_submit = 8;
6589
6590         mutex_lock(&ctx->uring_lock);
6591         if (likely(!percpu_ref_is_dying(&ctx->refs)))
6592                 ret = io_submit_sqes(ctx, to_submit);
6593         mutex_unlock(&ctx->uring_lock);
6594
6595         if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6596                 wake_up(&ctx->sqo_sq_wait);
6597
6598         return SQT_DID_WORK;
6599 }
6600
6601 static void io_sqd_init_new(struct io_sq_data *sqd)
6602 {
6603         struct io_ring_ctx *ctx;
6604
6605         while (!list_empty(&sqd->ctx_new_list)) {
6606                 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6607                 init_wait(&ctx->sqo_wait_entry);
6608                 ctx->sqo_wait_entry.func = io_sq_wake_function;
6609                 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6610                 complete(&ctx->sq_thread_comp);
6611         }
6612 }
6613
6614 static int io_sq_thread(void *data)
6615 {
6616         struct cgroup_subsys_state *cur_css = NULL;
6617         const struct cred *old_cred = NULL;
6618         struct io_sq_data *sqd = data;
6619         struct io_ring_ctx *ctx;
6620         unsigned long start_jiffies;
6621
6622         start_jiffies = jiffies;
6623         while (!kthread_should_stop()) {
6624                 enum sq_ret ret = 0;
6625                 bool cap_entries;
6626
6627                 /*
6628                  * Any changes to the sqd lists are synchronized through the
6629                  * kthread parking. This synchronizes the thread vs users,
6630                  * the users are synchronized on the sqd->ctx_lock.
6631                  */
6632                 if (kthread_should_park())
6633                         kthread_parkme();
6634
6635                 if (unlikely(!list_empty(&sqd->ctx_new_list)))
6636                         io_sqd_init_new(sqd);
6637
6638                 cap_entries = !list_is_singular(&sqd->ctx_list);
6639
6640                 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6641                         if (current->cred != ctx->creds) {
6642                                 if (old_cred)
6643                                         revert_creds(old_cred);
6644                                 old_cred = override_creds(ctx->creds);
6645                         }
6646                         io_sq_thread_associate_blkcg(ctx, &cur_css);
6647
6648                         ret |= __io_sq_thread(ctx, start_jiffies, cap_entries);
6649
6650                         io_sq_thread_drop_mm();
6651                 }
6652
6653                 if (ret & SQT_SPIN) {
6654                         io_run_task_work();
6655                         cond_resched();
6656                 } else if (ret == SQT_IDLE) {
6657                         if (kthread_should_park())
6658                                 continue;
6659                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6660                                 io_ring_set_wakeup_flag(ctx);
6661                         schedule();
6662                         start_jiffies = jiffies;
6663                         list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6664                                 io_ring_clear_wakeup_flag(ctx);
6665                 }
6666         }
6667
6668         io_run_task_work();
6669
6670         if (cur_css)
6671                 io_sq_thread_unassociate_blkcg();
6672         if (old_cred)
6673                 revert_creds(old_cred);
6674
6675         kthread_parkme();
6676
6677         return 0;
6678 }
6679
6680 struct io_wait_queue {
6681         struct wait_queue_entry wq;
6682         struct io_ring_ctx *ctx;
6683         unsigned to_wait;
6684         unsigned nr_timeouts;
6685 };
6686
6687 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6688 {
6689         struct io_ring_ctx *ctx = iowq->ctx;
6690
6691         /*
6692          * Wake up if we have enough events, or if a timeout occurred since we
6693          * started waiting. For timeouts, we always want to return to userspace,
6694          * regardless of event count.
6695          */
6696         return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6697                         atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6698 }
6699
6700 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6701                             int wake_flags, void *key)
6702 {
6703         struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6704                                                         wq);
6705
6706         /* use noflush == true, as we can't safely rely on locking context */
6707         if (!io_should_wake(iowq, true))
6708                 return -1;
6709
6710         return autoremove_wake_function(curr, mode, wake_flags, key);
6711 }
6712
6713 static int io_run_task_work_sig(void)
6714 {
6715         if (io_run_task_work())
6716                 return 1;
6717         if (!signal_pending(current))
6718                 return 0;
6719         if (current->jobctl & JOBCTL_TASK_WORK) {
6720                 spin_lock_irq(&current->sighand->siglock);
6721                 current->jobctl &= ~JOBCTL_TASK_WORK;
6722                 recalc_sigpending();
6723                 spin_unlock_irq(&current->sighand->siglock);
6724                 return 1;
6725         }
6726         return -EINTR;
6727 }
6728
6729 /*
6730  * Wait until events become available, if we don't already have some. The
6731  * application must reap them itself, as they reside on the shared cq ring.
6732  */
6733 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6734                           const sigset_t __user *sig, size_t sigsz)
6735 {
6736         struct io_wait_queue iowq = {
6737                 .wq = {
6738                         .private        = current,
6739                         .func           = io_wake_function,
6740                         .entry          = LIST_HEAD_INIT(iowq.wq.entry),
6741                 },
6742                 .ctx            = ctx,
6743                 .to_wait        = min_events,
6744         };
6745         struct io_rings *rings = ctx->rings;
6746         int ret = 0;
6747
6748         do {
6749                 if (io_cqring_events(ctx, false) >= min_events)
6750                         return 0;
6751                 if (!io_run_task_work())
6752                         break;
6753         } while (1);
6754
6755         if (sig) {
6756 #ifdef CONFIG_COMPAT
6757                 if (in_compat_syscall())
6758                         ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6759                                                       sigsz);
6760                 else
6761 #endif
6762                         ret = set_user_sigmask(sig, sigsz);
6763
6764                 if (ret)
6765                         return ret;
6766         }
6767
6768         iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6769         trace_io_uring_cqring_wait(ctx, min_events);
6770         do {
6771                 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6772                                                 TASK_INTERRUPTIBLE);
6773                 /* make sure we run task_work before checking for signals */
6774                 ret = io_run_task_work_sig();
6775                 if (ret > 0)
6776                         continue;
6777                 else if (ret < 0)
6778                         break;
6779                 if (io_should_wake(&iowq, false))
6780                         break;
6781                 schedule();
6782         } while (1);
6783         finish_wait(&ctx->wait, &iowq.wq);
6784
6785         restore_saved_sigmask_unless(ret == -EINTR);
6786
6787         return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6788 }
6789
6790 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6791 {
6792 #if defined(CONFIG_UNIX)
6793         if (ctx->ring_sock) {
6794                 struct sock *sock = ctx->ring_sock->sk;
6795                 struct sk_buff *skb;
6796
6797                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6798                         kfree_skb(skb);
6799         }
6800 #else
6801         int i;
6802
6803         for (i = 0; i < ctx->nr_user_files; i++) {
6804                 struct file *file;
6805
6806                 file = io_file_from_index(ctx, i);
6807                 if (file)
6808                         fput(file);
6809         }
6810 #endif
6811 }
6812
6813 static void io_file_ref_kill(struct percpu_ref *ref)
6814 {
6815         struct fixed_file_data *data;
6816
6817         data = container_of(ref, struct fixed_file_data, refs);
6818         complete(&data->done);
6819 }
6820
6821 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6822 {
6823         struct fixed_file_data *data = ctx->file_data;
6824         struct fixed_file_ref_node *ref_node = NULL;
6825         unsigned nr_tables, i;
6826
6827         if (!data)
6828                 return -ENXIO;
6829
6830         spin_lock(&data->lock);
6831         if (!list_empty(&data->ref_list))
6832                 ref_node = list_first_entry(&data->ref_list,
6833                                 struct fixed_file_ref_node, node);
6834         spin_unlock(&data->lock);
6835         if (ref_node)
6836                 percpu_ref_kill(&ref_node->refs);
6837
6838         percpu_ref_kill(&data->refs);
6839
6840         /* wait for all refs nodes to complete */
6841         flush_delayed_work(&ctx->file_put_work);
6842         wait_for_completion(&data->done);
6843
6844         __io_sqe_files_unregister(ctx);
6845         nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6846         for (i = 0; i < nr_tables; i++)
6847                 kfree(data->table[i].files);
6848         kfree(data->table);
6849         percpu_ref_exit(&data->refs);
6850         kfree(data);
6851         ctx->file_data = NULL;
6852         ctx->nr_user_files = 0;
6853         return 0;
6854 }
6855
6856 static void io_put_sq_data(struct io_sq_data *sqd)
6857 {
6858         if (refcount_dec_and_test(&sqd->refs)) {
6859                 /*
6860                  * The park is a bit of a work-around, without it we get
6861                  * warning spews on shutdown with SQPOLL set and affinity
6862                  * set to a single CPU.
6863                  */
6864                 if (sqd->thread) {
6865                         kthread_park(sqd->thread);
6866                         kthread_stop(sqd->thread);
6867                 }
6868
6869                 kfree(sqd);
6870         }
6871 }
6872
6873 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
6874 {
6875         struct io_ring_ctx *ctx_attach;
6876         struct io_sq_data *sqd;
6877         struct fd f;
6878
6879         f = fdget(p->wq_fd);
6880         if (!f.file)
6881                 return ERR_PTR(-ENXIO);
6882         if (f.file->f_op != &io_uring_fops) {
6883                 fdput(f);
6884                 return ERR_PTR(-EINVAL);
6885         }
6886
6887         ctx_attach = f.file->private_data;
6888         sqd = ctx_attach->sq_data;
6889         if (!sqd) {
6890                 fdput(f);
6891                 return ERR_PTR(-EINVAL);
6892         }
6893
6894         refcount_inc(&sqd->refs);
6895         fdput(f);
6896         return sqd;
6897 }
6898
6899 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
6900 {
6901         struct io_sq_data *sqd;
6902
6903         if (p->flags & IORING_SETUP_ATTACH_WQ)
6904                 return io_attach_sq_data(p);
6905
6906         sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
6907         if (!sqd)
6908                 return ERR_PTR(-ENOMEM);
6909
6910         refcount_set(&sqd->refs, 1);
6911         INIT_LIST_HEAD(&sqd->ctx_list);
6912         INIT_LIST_HEAD(&sqd->ctx_new_list);
6913         mutex_init(&sqd->ctx_lock);
6914         mutex_init(&sqd->lock);
6915         init_waitqueue_head(&sqd->wait);
6916         return sqd;
6917 }
6918
6919 static void io_sq_thread_unpark(struct io_sq_data *sqd)
6920         __releases(&sqd->lock)
6921 {
6922         if (!sqd->thread)
6923                 return;
6924         kthread_unpark(sqd->thread);
6925         mutex_unlock(&sqd->lock);
6926 }
6927
6928 static void io_sq_thread_park(struct io_sq_data *sqd)
6929         __acquires(&sqd->lock)
6930 {
6931         if (!sqd->thread)
6932                 return;
6933         mutex_lock(&sqd->lock);
6934         kthread_park(sqd->thread);
6935 }
6936
6937 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6938 {
6939         struct io_sq_data *sqd = ctx->sq_data;
6940
6941         if (sqd) {
6942                 if (sqd->thread) {
6943                         /*
6944                          * We may arrive here from the error branch in
6945                          * io_sq_offload_create() where the kthread is created
6946                          * without being waked up, thus wake it up now to make
6947                          * sure the wait will complete.
6948                          */
6949                         wake_up_process(sqd->thread);
6950                         wait_for_completion(&ctx->sq_thread_comp);
6951
6952                         io_sq_thread_park(sqd);
6953                 }
6954
6955                 mutex_lock(&sqd->ctx_lock);
6956                 list_del(&ctx->sqd_list);
6957                 mutex_unlock(&sqd->ctx_lock);
6958
6959                 if (sqd->thread) {
6960                         finish_wait(&sqd->wait, &ctx->sqo_wait_entry);
6961                         io_sq_thread_unpark(sqd);
6962                 }
6963
6964                 io_put_sq_data(sqd);
6965                 ctx->sq_data = NULL;
6966         }
6967 }
6968
6969 static void io_finish_async(struct io_ring_ctx *ctx)
6970 {
6971         io_sq_thread_stop(ctx);
6972
6973         if (ctx->io_wq) {
6974                 io_wq_destroy(ctx->io_wq);
6975                 ctx->io_wq = NULL;
6976         }
6977 }
6978
6979 #if defined(CONFIG_UNIX)
6980 /*
6981  * Ensure the UNIX gc is aware of our file set, so we are certain that
6982  * the io_uring can be safely unregistered on process exit, even if we have
6983  * loops in the file referencing.
6984  */
6985 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6986 {
6987         struct sock *sk = ctx->ring_sock->sk;
6988         struct scm_fp_list *fpl;
6989         struct sk_buff *skb;
6990         int i, nr_files;
6991
6992         fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6993         if (!fpl)
6994                 return -ENOMEM;
6995
6996         skb = alloc_skb(0, GFP_KERNEL);
6997         if (!skb) {
6998                 kfree(fpl);
6999                 return -ENOMEM;
7000         }
7001
7002         skb->sk = sk;
7003
7004         nr_files = 0;
7005         fpl->user = get_uid(ctx->user);
7006         for (i = 0; i < nr; i++) {
7007                 struct file *file = io_file_from_index(ctx, i + offset);
7008
7009                 if (!file)
7010                         continue;
7011                 fpl->fp[nr_files] = get_file(file);
7012                 unix_inflight(fpl->user, fpl->fp[nr_files]);
7013                 nr_files++;
7014         }
7015
7016         if (nr_files) {
7017                 fpl->max = SCM_MAX_FD;
7018                 fpl->count = nr_files;
7019                 UNIXCB(skb).fp = fpl;
7020                 skb->destructor = unix_destruct_scm;
7021                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7022                 skb_queue_head(&sk->sk_receive_queue, skb);
7023
7024                 for (i = 0; i < nr_files; i++)
7025                         fput(fpl->fp[i]);
7026         } else {
7027                 kfree_skb(skb);
7028                 kfree(fpl);
7029         }
7030
7031         return 0;
7032 }
7033
7034 /*
7035  * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7036  * causes regular reference counting to break down. We rely on the UNIX
7037  * garbage collection to take care of this problem for us.
7038  */
7039 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7040 {
7041         unsigned left, total;
7042         int ret = 0;
7043
7044         total = 0;
7045         left = ctx->nr_user_files;
7046         while (left) {
7047                 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7048
7049                 ret = __io_sqe_files_scm(ctx, this_files, total);
7050                 if (ret)
7051                         break;
7052                 left -= this_files;
7053                 total += this_files;
7054         }
7055
7056         if (!ret)
7057                 return 0;
7058
7059         while (total < ctx->nr_user_files) {
7060                 struct file *file = io_file_from_index(ctx, total);
7061
7062                 if (file)
7063                         fput(file);
7064                 total++;
7065         }
7066
7067         return ret;
7068 }
7069 #else
7070 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7071 {
7072         return 0;
7073 }
7074 #endif
7075
7076 static int io_sqe_alloc_file_tables(struct fixed_file_data *file_data,
7077                                     unsigned nr_tables, unsigned nr_files)
7078 {
7079         int i;
7080
7081         for (i = 0; i < nr_tables; i++) {
7082                 struct fixed_file_table *table = &file_data->table[i];
7083                 unsigned this_files;
7084
7085                 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7086                 table->files = kcalloc(this_files, sizeof(struct file *),
7087                                         GFP_KERNEL);
7088                 if (!table->files)
7089                         break;
7090                 nr_files -= this_files;
7091         }
7092
7093         if (i == nr_tables)
7094                 return 0;
7095
7096         for (i = 0; i < nr_tables; i++) {
7097                 struct fixed_file_table *table = &file_data->table[i];
7098                 kfree(table->files);
7099         }
7100         return 1;
7101 }
7102
7103 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
7104 {
7105 #if defined(CONFIG_UNIX)
7106         struct sock *sock = ctx->ring_sock->sk;
7107         struct sk_buff_head list, *head = &sock->sk_receive_queue;
7108         struct sk_buff *skb;
7109         int i;
7110
7111         __skb_queue_head_init(&list);
7112
7113         /*
7114          * Find the skb that holds this file in its SCM_RIGHTS. When found,
7115          * remove this entry and rearrange the file array.
7116          */
7117         skb = skb_dequeue(head);
7118         while (skb) {
7119                 struct scm_fp_list *fp;
7120
7121                 fp = UNIXCB(skb).fp;
7122                 for (i = 0; i < fp->count; i++) {
7123                         int left;
7124
7125                         if (fp->fp[i] != file)
7126                                 continue;
7127
7128                         unix_notinflight(fp->user, fp->fp[i]);
7129                         left = fp->count - 1 - i;
7130                         if (left) {
7131                                 memmove(&fp->fp[i], &fp->fp[i + 1],
7132                                                 left * sizeof(struct file *));
7133                         }
7134                         fp->count--;
7135                         if (!fp->count) {
7136                                 kfree_skb(skb);
7137                                 skb = NULL;
7138                         } else {
7139                                 __skb_queue_tail(&list, skb);
7140                         }
7141                         fput(file);
7142                         file = NULL;
7143                         break;
7144                 }
7145
7146                 if (!file)
7147                         break;
7148
7149                 __skb_queue_tail(&list, skb);
7150
7151                 skb = skb_dequeue(head);
7152         }
7153
7154         if (skb_peek(&list)) {
7155                 spin_lock_irq(&head->lock);
7156                 while ((skb = __skb_dequeue(&list)) != NULL)
7157                         __skb_queue_tail(head, skb);
7158                 spin_unlock_irq(&head->lock);
7159         }
7160 #else
7161         fput(file);
7162 #endif
7163 }
7164
7165 struct io_file_put {
7166         struct list_head list;
7167         struct file *file;
7168 };
7169
7170 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
7171 {
7172         struct fixed_file_data *file_data = ref_node->file_data;
7173         struct io_ring_ctx *ctx = file_data->ctx;
7174         struct io_file_put *pfile, *tmp;
7175
7176         list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
7177                 list_del(&pfile->list);
7178                 io_ring_file_put(ctx, pfile->file);
7179                 kfree(pfile);
7180         }
7181
7182         spin_lock(&file_data->lock);
7183         list_del(&ref_node->node);
7184         spin_unlock(&file_data->lock);
7185
7186         percpu_ref_exit(&ref_node->refs);
7187         kfree(ref_node);
7188         percpu_ref_put(&file_data->refs);
7189 }
7190
7191 static void io_file_put_work(struct work_struct *work)
7192 {
7193         struct io_ring_ctx *ctx;
7194         struct llist_node *node;
7195
7196         ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
7197         node = llist_del_all(&ctx->file_put_llist);
7198
7199         while (node) {
7200                 struct fixed_file_ref_node *ref_node;
7201                 struct llist_node *next = node->next;
7202
7203                 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
7204                 __io_file_put_work(ref_node);
7205                 node = next;
7206         }
7207 }
7208
7209 static void io_file_data_ref_zero(struct percpu_ref *ref)
7210 {
7211         struct fixed_file_ref_node *ref_node;
7212         struct io_ring_ctx *ctx;
7213         bool first_add;
7214         int delay = HZ;
7215
7216         ref_node = container_of(ref, struct fixed_file_ref_node, refs);
7217         ctx = ref_node->file_data->ctx;
7218
7219         if (percpu_ref_is_dying(&ctx->file_data->refs))
7220                 delay = 0;
7221
7222         first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
7223         if (!delay)
7224                 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
7225         else if (first_add)
7226                 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
7227 }
7228
7229 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
7230                         struct io_ring_ctx *ctx)
7231 {
7232         struct fixed_file_ref_node *ref_node;
7233
7234         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7235         if (!ref_node)
7236                 return ERR_PTR(-ENOMEM);
7237
7238         if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
7239                             0, GFP_KERNEL)) {
7240                 kfree(ref_node);
7241                 return ERR_PTR(-ENOMEM);
7242         }
7243         INIT_LIST_HEAD(&ref_node->node);
7244         INIT_LIST_HEAD(&ref_node->file_list);
7245         ref_node->file_data = ctx->file_data;
7246         return ref_node;
7247 }
7248
7249 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
7250 {
7251         percpu_ref_exit(&ref_node->refs);
7252         kfree(ref_node);
7253 }
7254
7255 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7256                                  unsigned nr_args)
7257 {
7258         __s32 __user *fds = (__s32 __user *) arg;
7259         unsigned nr_tables, i;
7260         struct file *file;
7261         int fd, ret = -ENOMEM;
7262         struct fixed_file_ref_node *ref_node;
7263         struct fixed_file_data *file_data;
7264
7265         if (ctx->file_data)
7266                 return -EBUSY;
7267         if (!nr_args)
7268                 return -EINVAL;
7269         if (nr_args > IORING_MAX_FIXED_FILES)
7270                 return -EMFILE;
7271
7272         file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
7273         if (!file_data)
7274                 return -ENOMEM;
7275         file_data->ctx = ctx;
7276         init_completion(&file_data->done);
7277         INIT_LIST_HEAD(&file_data->ref_list);
7278         spin_lock_init(&file_data->lock);
7279
7280         nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7281         file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7282                                    GFP_KERNEL);
7283         if (!file_data->table)
7284                 goto out_free;
7285
7286         if (percpu_ref_init(&file_data->refs, io_file_ref_kill,
7287                                 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
7288                 goto out_free;
7289
7290         if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7291                 goto out_ref;
7292
7293         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7294                 struct fixed_file_table *table;
7295                 unsigned index;
7296
7297                 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7298                         ret = -EFAULT;
7299                         goto out_fput;
7300                 }
7301                 /* allow sparse sets */
7302                 if (fd == -1)
7303                         continue;
7304
7305                 file = fget(fd);
7306                 ret = -EBADF;
7307                 if (!file)
7308                         goto out_fput;
7309
7310                 /*
7311                  * Don't allow io_uring instances to be registered. If UNIX
7312                  * isn't enabled, then this causes a reference cycle and this
7313                  * instance can never get freed. If UNIX is enabled we'll
7314                  * handle it just fine, but there's still no point in allowing
7315                  * a ring fd as it doesn't support regular read/write anyway.
7316                  */
7317                 if (file->f_op == &io_uring_fops) {
7318                         fput(file);
7319                         goto out_fput;
7320                 }
7321                 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7322                 index = i & IORING_FILE_TABLE_MASK;
7323                 table->files[index] = file;
7324         }
7325
7326         ctx->file_data = file_data;
7327         ret = io_sqe_files_scm(ctx);
7328         if (ret) {
7329                 io_sqe_files_unregister(ctx);
7330                 return ret;
7331         }
7332
7333         ref_node = alloc_fixed_file_ref_node(ctx);
7334         if (IS_ERR(ref_node)) {
7335                 io_sqe_files_unregister(ctx);
7336                 return PTR_ERR(ref_node);
7337         }
7338
7339         file_data->node = ref_node;
7340         spin_lock(&file_data->lock);
7341         list_add(&ref_node->node, &file_data->ref_list);
7342         spin_unlock(&file_data->lock);
7343         percpu_ref_get(&file_data->refs);
7344         return ret;
7345 out_fput:
7346         for (i = 0; i < ctx->nr_user_files; i++) {
7347                 file = io_file_from_index(ctx, i);
7348                 if (file)
7349                         fput(file);
7350         }
7351         for (i = 0; i < nr_tables; i++)
7352                 kfree(file_data->table[i].files);
7353         ctx->nr_user_files = 0;
7354 out_ref:
7355         percpu_ref_exit(&file_data->refs);
7356 out_free:
7357         kfree(file_data->table);
7358         kfree(file_data);
7359         return ret;
7360 }
7361
7362 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7363                                 int index)
7364 {
7365 #if defined(CONFIG_UNIX)
7366         struct sock *sock = ctx->ring_sock->sk;
7367         struct sk_buff_head *head = &sock->sk_receive_queue;
7368         struct sk_buff *skb;
7369
7370         /*
7371          * See if we can merge this file into an existing skb SCM_RIGHTS
7372          * file set. If there's no room, fall back to allocating a new skb
7373          * and filling it in.
7374          */
7375         spin_lock_irq(&head->lock);
7376         skb = skb_peek(head);
7377         if (skb) {
7378                 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7379
7380                 if (fpl->count < SCM_MAX_FD) {
7381                         __skb_unlink(skb, head);
7382                         spin_unlock_irq(&head->lock);
7383                         fpl->fp[fpl->count] = get_file(file);
7384                         unix_inflight(fpl->user, fpl->fp[fpl->count]);
7385                         fpl->count++;
7386                         spin_lock_irq(&head->lock);
7387                         __skb_queue_head(head, skb);
7388                 } else {
7389                         skb = NULL;
7390                 }
7391         }
7392         spin_unlock_irq(&head->lock);
7393
7394         if (skb) {
7395                 fput(file);
7396                 return 0;
7397         }
7398
7399         return __io_sqe_files_scm(ctx, 1, index);
7400 #else
7401         return 0;
7402 #endif
7403 }
7404
7405 static int io_queue_file_removal(struct fixed_file_data *data,
7406                                  struct file *file)
7407 {
7408         struct io_file_put *pfile;
7409         struct fixed_file_ref_node *ref_node = data->node;
7410
7411         pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7412         if (!pfile)
7413                 return -ENOMEM;
7414
7415         pfile->file = file;
7416         list_add(&pfile->list, &ref_node->file_list);
7417
7418         return 0;
7419 }
7420
7421 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7422                                  struct io_uring_files_update *up,
7423                                  unsigned nr_args)
7424 {
7425         struct fixed_file_data *data = ctx->file_data;
7426         struct fixed_file_ref_node *ref_node;
7427         struct file *file;
7428         __s32 __user *fds;
7429         int fd, i, err;
7430         __u32 done;
7431         bool needs_switch = false;
7432
7433         if (check_add_overflow(up->offset, nr_args, &done))
7434                 return -EOVERFLOW;
7435         if (done > ctx->nr_user_files)
7436                 return -EINVAL;
7437
7438         ref_node = alloc_fixed_file_ref_node(ctx);
7439         if (IS_ERR(ref_node))
7440                 return PTR_ERR(ref_node);
7441
7442         done = 0;
7443         fds = u64_to_user_ptr(up->fds);
7444         while (nr_args) {
7445                 struct fixed_file_table *table;
7446                 unsigned index;
7447
7448                 err = 0;
7449                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7450                         err = -EFAULT;
7451                         break;
7452                 }
7453                 i = array_index_nospec(up->offset, ctx->nr_user_files);
7454                 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7455                 index = i & IORING_FILE_TABLE_MASK;
7456                 if (table->files[index]) {
7457                         file = table->files[index];
7458                         err = io_queue_file_removal(data, file);
7459                         if (err)
7460                                 break;
7461                         table->files[index] = NULL;
7462                         needs_switch = true;
7463                 }
7464                 if (fd != -1) {
7465                         file = fget(fd);
7466                         if (!file) {
7467                                 err = -EBADF;
7468                                 break;
7469                         }
7470                         /*
7471                          * Don't allow io_uring instances to be registered. If
7472                          * UNIX isn't enabled, then this causes a reference
7473                          * cycle and this instance can never get freed. If UNIX
7474                          * is enabled we'll handle it just fine, but there's
7475                          * still no point in allowing a ring fd as it doesn't
7476                          * support regular read/write anyway.
7477                          */
7478                         if (file->f_op == &io_uring_fops) {
7479                                 fput(file);
7480                                 err = -EBADF;
7481                                 break;
7482                         }
7483                         table->files[index] = file;
7484                         err = io_sqe_file_register(ctx, file, i);
7485                         if (err) {
7486                                 table->files[index] = NULL;
7487                                 fput(file);
7488                                 break;
7489                         }
7490                 }
7491                 nr_args--;
7492                 done++;
7493                 up->offset++;
7494         }
7495
7496         if (needs_switch) {
7497                 percpu_ref_kill(&data->node->refs);
7498                 spin_lock(&data->lock);
7499                 list_add(&ref_node->node, &data->ref_list);
7500                 data->node = ref_node;
7501                 spin_unlock(&data->lock);
7502                 percpu_ref_get(&ctx->file_data->refs);
7503         } else
7504                 destroy_fixed_file_ref_node(ref_node);
7505
7506         return done ? done : err;
7507 }
7508
7509 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7510                                unsigned nr_args)
7511 {
7512         struct io_uring_files_update up;
7513
7514         if (!ctx->file_data)
7515                 return -ENXIO;
7516         if (!nr_args)
7517                 return -EINVAL;
7518         if (copy_from_user(&up, arg, sizeof(up)))
7519                 return -EFAULT;
7520         if (up.resv)
7521                 return -EINVAL;
7522
7523         return __io_sqe_files_update(ctx, &up, nr_args);
7524 }
7525
7526 static void io_free_work(struct io_wq_work *work)
7527 {
7528         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7529
7530         /* Consider that io_steal_work() relies on this ref */
7531         io_put_req(req);
7532 }
7533
7534 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7535                               struct io_uring_params *p)
7536 {
7537         struct io_wq_data data;
7538         struct fd f;
7539         struct io_ring_ctx *ctx_attach;
7540         unsigned int concurrency;
7541         int ret = 0;
7542
7543         data.user = ctx->user;
7544         data.free_work = io_free_work;
7545         data.do_work = io_wq_submit_work;
7546
7547         if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7548                 /* Do QD, or 4 * CPUS, whatever is smallest */
7549                 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7550
7551                 ctx->io_wq = io_wq_create(concurrency, &data);
7552                 if (IS_ERR(ctx->io_wq)) {
7553                         ret = PTR_ERR(ctx->io_wq);
7554                         ctx->io_wq = NULL;
7555                 }
7556                 return ret;
7557         }
7558
7559         f = fdget(p->wq_fd);
7560         if (!f.file)
7561                 return -EBADF;
7562
7563         if (f.file->f_op != &io_uring_fops) {
7564                 ret = -EINVAL;
7565                 goto out_fput;
7566         }
7567
7568         ctx_attach = f.file->private_data;
7569         /* @io_wq is protected by holding the fd */
7570         if (!io_wq_get(ctx_attach->io_wq, &data)) {
7571                 ret = -EINVAL;
7572                 goto out_fput;
7573         }
7574
7575         ctx->io_wq = ctx_attach->io_wq;
7576 out_fput:
7577         fdput(f);
7578         return ret;
7579 }
7580
7581 static int io_uring_alloc_task_context(struct task_struct *task)
7582 {
7583         struct io_uring_task *tctx;
7584
7585         tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7586         if (unlikely(!tctx))
7587                 return -ENOMEM;
7588
7589         xa_init(&tctx->xa);
7590         init_waitqueue_head(&tctx->wait);
7591         tctx->last = NULL;
7592         tctx->in_idle = 0;
7593         atomic_long_set(&tctx->req_issue, 0);
7594         atomic_long_set(&tctx->req_complete, 0);
7595         task->io_uring = tctx;
7596         return 0;
7597 }
7598
7599 void __io_uring_free(struct task_struct *tsk)
7600 {
7601         struct io_uring_task *tctx = tsk->io_uring;
7602
7603         WARN_ON_ONCE(!xa_empty(&tctx->xa));
7604         kfree(tctx);
7605         tsk->io_uring = NULL;
7606 }
7607
7608 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7609                                 struct io_uring_params *p)
7610 {
7611         int ret;
7612
7613         if (ctx->flags & IORING_SETUP_SQPOLL) {
7614                 struct io_sq_data *sqd;
7615
7616                 ret = -EPERM;
7617                 if (!capable(CAP_SYS_ADMIN))
7618                         goto err;
7619
7620                 sqd = io_get_sq_data(p);
7621                 if (IS_ERR(sqd)) {
7622                         ret = PTR_ERR(sqd);
7623                         goto err;
7624                 }
7625
7626                 ctx->sq_data = sqd;
7627                 io_sq_thread_park(sqd);
7628                 mutex_lock(&sqd->ctx_lock);
7629                 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7630                 mutex_unlock(&sqd->ctx_lock);
7631                 io_sq_thread_unpark(sqd);
7632
7633                 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7634                 if (!ctx->sq_thread_idle)
7635                         ctx->sq_thread_idle = HZ;
7636
7637                 if (sqd->thread)
7638                         goto done;
7639
7640                 if (p->flags & IORING_SETUP_SQ_AFF) {
7641                         int cpu = p->sq_thread_cpu;
7642
7643                         ret = -EINVAL;
7644                         if (cpu >= nr_cpu_ids)
7645                                 goto err;
7646                         if (!cpu_online(cpu))
7647                                 goto err;
7648
7649                         sqd->thread = kthread_create_on_cpu(io_sq_thread, sqd,
7650                                                         cpu, "io_uring-sq");
7651                 } else {
7652                         sqd->thread = kthread_create(io_sq_thread, sqd,
7653                                                         "io_uring-sq");
7654                 }
7655                 if (IS_ERR(sqd->thread)) {
7656                         ret = PTR_ERR(sqd->thread);
7657                         sqd->thread = NULL;
7658                         goto err;
7659                 }
7660                 ret = io_uring_alloc_task_context(sqd->thread);
7661                 if (ret)
7662                         goto err;
7663         } else if (p->flags & IORING_SETUP_SQ_AFF) {
7664                 /* Can't have SQ_AFF without SQPOLL */
7665                 ret = -EINVAL;
7666                 goto err;
7667         }
7668
7669 done:
7670         ret = io_init_wq_offload(ctx, p);
7671         if (ret)
7672                 goto err;
7673
7674         return 0;
7675 err:
7676         io_finish_async(ctx);
7677         return ret;
7678 }
7679
7680 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7681 {
7682         struct io_sq_data *sqd = ctx->sq_data;
7683
7684         if ((ctx->flags & IORING_SETUP_SQPOLL) && sqd->thread)
7685                 wake_up_process(sqd->thread);
7686 }
7687
7688 static inline void __io_unaccount_mem(struct user_struct *user,
7689                                       unsigned long nr_pages)
7690 {
7691         atomic_long_sub(nr_pages, &user->locked_vm);
7692 }
7693
7694 static inline int __io_account_mem(struct user_struct *user,
7695                                    unsigned long nr_pages)
7696 {
7697         unsigned long page_limit, cur_pages, new_pages;
7698
7699         /* Don't allow more pages than we can safely lock */
7700         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7701
7702         do {
7703                 cur_pages = atomic_long_read(&user->locked_vm);
7704                 new_pages = cur_pages + nr_pages;
7705                 if (new_pages > page_limit)
7706                         return -ENOMEM;
7707         } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7708                                         new_pages) != cur_pages);
7709
7710         return 0;
7711 }
7712
7713 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7714                              enum io_mem_account acct)
7715 {
7716         if (ctx->limit_mem)
7717                 __io_unaccount_mem(ctx->user, nr_pages);
7718
7719         if (ctx->mm_account) {
7720                 if (acct == ACCT_LOCKED)
7721                         ctx->mm_account->locked_vm -= nr_pages;
7722                 else if (acct == ACCT_PINNED)
7723                         atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7724         }
7725 }
7726
7727 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7728                           enum io_mem_account acct)
7729 {
7730         int ret;
7731
7732         if (ctx->limit_mem) {
7733                 ret = __io_account_mem(ctx->user, nr_pages);
7734                 if (ret)
7735                         return ret;
7736         }
7737
7738         if (ctx->mm_account) {
7739                 if (acct == ACCT_LOCKED)
7740                         ctx->mm_account->locked_vm += nr_pages;
7741                 else if (acct == ACCT_PINNED)
7742                         atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
7743         }
7744
7745         return 0;
7746 }
7747
7748 static void io_mem_free(void *ptr)
7749 {
7750         struct page *page;
7751
7752         if (!ptr)
7753                 return;
7754
7755         page = virt_to_head_page(ptr);
7756         if (put_page_testzero(page))
7757                 free_compound_page(page);
7758 }
7759
7760 static void *io_mem_alloc(size_t size)
7761 {
7762         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7763                                 __GFP_NORETRY;
7764
7765         return (void *) __get_free_pages(gfp_flags, get_order(size));
7766 }
7767
7768 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7769                                 size_t *sq_offset)
7770 {
7771         struct io_rings *rings;
7772         size_t off, sq_array_size;
7773
7774         off = struct_size(rings, cqes, cq_entries);
7775         if (off == SIZE_MAX)
7776                 return SIZE_MAX;
7777
7778 #ifdef CONFIG_SMP
7779         off = ALIGN(off, SMP_CACHE_BYTES);
7780         if (off == 0)
7781                 return SIZE_MAX;
7782 #endif
7783
7784         if (sq_offset)
7785                 *sq_offset = off;
7786
7787         sq_array_size = array_size(sizeof(u32), sq_entries);
7788         if (sq_array_size == SIZE_MAX)
7789                 return SIZE_MAX;
7790
7791         if (check_add_overflow(off, sq_array_size, &off))
7792                 return SIZE_MAX;
7793
7794         return off;
7795 }
7796
7797 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7798 {
7799         size_t pages;
7800
7801         pages = (size_t)1 << get_order(
7802                 rings_size(sq_entries, cq_entries, NULL));
7803         pages += (size_t)1 << get_order(
7804                 array_size(sizeof(struct io_uring_sqe), sq_entries));
7805
7806         return pages;
7807 }
7808
7809 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7810 {
7811         int i, j;
7812
7813         if (!ctx->user_bufs)
7814                 return -ENXIO;
7815
7816         for (i = 0; i < ctx->nr_user_bufs; i++) {
7817                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7818
7819                 for (j = 0; j < imu->nr_bvecs; j++)
7820                         unpin_user_page(imu->bvec[j].bv_page);
7821
7822                 if (imu->acct_pages)
7823                         io_unaccount_mem(ctx, imu->acct_pages, ACCT_PINNED);
7824                 kvfree(imu->bvec);
7825                 imu->nr_bvecs = 0;
7826         }
7827
7828         kfree(ctx->user_bufs);
7829         ctx->user_bufs = NULL;
7830         ctx->nr_user_bufs = 0;
7831         return 0;
7832 }
7833
7834 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7835                        void __user *arg, unsigned index)
7836 {
7837         struct iovec __user *src;
7838
7839 #ifdef CONFIG_COMPAT
7840         if (ctx->compat) {
7841                 struct compat_iovec __user *ciovs;
7842                 struct compat_iovec ciov;
7843
7844                 ciovs = (struct compat_iovec __user *) arg;
7845                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7846                         return -EFAULT;
7847
7848                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7849                 dst->iov_len = ciov.iov_len;
7850                 return 0;
7851         }
7852 #endif
7853         src = (struct iovec __user *) arg;
7854         if (copy_from_user(dst, &src[index], sizeof(*dst)))
7855                 return -EFAULT;
7856         return 0;
7857 }
7858
7859 /*
7860  * Not super efficient, but this is just a registration time. And we do cache
7861  * the last compound head, so generally we'll only do a full search if we don't
7862  * match that one.
7863  *
7864  * We check if the given compound head page has already been accounted, to
7865  * avoid double accounting it. This allows us to account the full size of the
7866  * page, not just the constituent pages of a huge page.
7867  */
7868 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
7869                                   int nr_pages, struct page *hpage)
7870 {
7871         int i, j;
7872
7873         /* check current page array */
7874         for (i = 0; i < nr_pages; i++) {
7875                 if (!PageCompound(pages[i]))
7876                         continue;
7877                 if (compound_head(pages[i]) == hpage)
7878                         return true;
7879         }
7880
7881         /* check previously registered pages */
7882         for (i = 0; i < ctx->nr_user_bufs; i++) {
7883                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7884
7885                 for (j = 0; j < imu->nr_bvecs; j++) {
7886                         if (!PageCompound(imu->bvec[j].bv_page))
7887                                 continue;
7888                         if (compound_head(imu->bvec[j].bv_page) == hpage)
7889                                 return true;
7890                 }
7891         }
7892
7893         return false;
7894 }
7895
7896 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
7897                                  int nr_pages, struct io_mapped_ubuf *imu,
7898                                  struct page **last_hpage)
7899 {
7900         int i, ret;
7901
7902         for (i = 0; i < nr_pages; i++) {
7903                 if (!PageCompound(pages[i])) {
7904                         imu->acct_pages++;
7905                 } else {
7906                         struct page *hpage;
7907
7908                         hpage = compound_head(pages[i]);
7909                         if (hpage == *last_hpage)
7910                                 continue;
7911                         *last_hpage = hpage;
7912                         if (headpage_already_acct(ctx, pages, i, hpage))
7913                                 continue;
7914                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
7915                 }
7916         }
7917
7918         if (!imu->acct_pages)
7919                 return 0;
7920
7921         ret = io_account_mem(ctx, imu->acct_pages, ACCT_PINNED);
7922         if (ret)
7923                 imu->acct_pages = 0;
7924         return ret;
7925 }
7926
7927 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7928                                   unsigned nr_args)
7929 {
7930         struct vm_area_struct **vmas = NULL;
7931         struct page **pages = NULL;
7932         struct page *last_hpage = NULL;
7933         int i, j, got_pages = 0;
7934         int ret = -EINVAL;
7935
7936         if (ctx->user_bufs)
7937                 return -EBUSY;
7938         if (!nr_args || nr_args > UIO_MAXIOV)
7939                 return -EINVAL;
7940
7941         ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7942                                         GFP_KERNEL);
7943         if (!ctx->user_bufs)
7944                 return -ENOMEM;
7945
7946         for (i = 0; i < nr_args; i++) {
7947                 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7948                 unsigned long off, start, end, ubuf;
7949                 int pret, nr_pages;
7950                 struct iovec iov;
7951                 size_t size;
7952
7953                 ret = io_copy_iov(ctx, &iov, arg, i);
7954                 if (ret)
7955                         goto err;
7956
7957                 /*
7958                  * Don't impose further limits on the size and buffer
7959                  * constraints here, we'll -EINVAL later when IO is
7960                  * submitted if they are wrong.
7961                  */
7962                 ret = -EFAULT;
7963                 if (!iov.iov_base || !iov.iov_len)
7964                         goto err;
7965
7966                 /* arbitrary limit, but we need something */
7967                 if (iov.iov_len > SZ_1G)
7968                         goto err;
7969
7970                 ubuf = (unsigned long) iov.iov_base;
7971                 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7972                 start = ubuf >> PAGE_SHIFT;
7973                 nr_pages = end - start;
7974
7975                 ret = 0;
7976                 if (!pages || nr_pages > got_pages) {
7977                         kvfree(vmas);
7978                         kvfree(pages);
7979                         pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7980                                                 GFP_KERNEL);
7981                         vmas = kvmalloc_array(nr_pages,
7982                                         sizeof(struct vm_area_struct *),
7983                                         GFP_KERNEL);
7984                         if (!pages || !vmas) {
7985                                 ret = -ENOMEM;
7986                                 goto err;
7987                         }
7988                         got_pages = nr_pages;
7989                 }
7990
7991                 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7992                                                 GFP_KERNEL);
7993                 ret = -ENOMEM;
7994                 if (!imu->bvec)
7995                         goto err;
7996
7997                 ret = 0;
7998                 mmap_read_lock(current->mm);
7999                 pret = pin_user_pages(ubuf, nr_pages,
8000                                       FOLL_WRITE | FOLL_LONGTERM,
8001                                       pages, vmas);
8002                 if (pret == nr_pages) {
8003                         /* don't support file backed memory */
8004                         for (j = 0; j < nr_pages; j++) {
8005                                 struct vm_area_struct *vma = vmas[j];
8006
8007                                 if (vma->vm_file &&
8008                                     !is_file_hugepages(vma->vm_file)) {
8009                                         ret = -EOPNOTSUPP;
8010                                         break;
8011                                 }
8012                         }
8013                 } else {
8014                         ret = pret < 0 ? pret : -EFAULT;
8015                 }
8016                 mmap_read_unlock(current->mm);
8017                 if (ret) {
8018                         /*
8019                          * if we did partial map, or found file backed vmas,
8020                          * release any pages we did get
8021                          */
8022                         if (pret > 0)
8023                                 unpin_user_pages(pages, pret);
8024                         kvfree(imu->bvec);
8025                         goto err;
8026                 }
8027
8028                 ret = io_buffer_account_pin(ctx, pages, pret, imu, &last_hpage);
8029                 if (ret) {
8030                         unpin_user_pages(pages, pret);
8031                         kvfree(imu->bvec);
8032                         goto err;
8033                 }
8034
8035                 off = ubuf & ~PAGE_MASK;
8036                 size = iov.iov_len;
8037                 for (j = 0; j < nr_pages; j++) {
8038                         size_t vec_len;
8039
8040                         vec_len = min_t(size_t, size, PAGE_SIZE - off);
8041                         imu->bvec[j].bv_page = pages[j];
8042                         imu->bvec[j].bv_len = vec_len;
8043                         imu->bvec[j].bv_offset = off;
8044                         off = 0;
8045                         size -= vec_len;
8046                 }
8047                 /* store original address for later verification */
8048                 imu->ubuf = ubuf;
8049                 imu->len = iov.iov_len;
8050                 imu->nr_bvecs = nr_pages;
8051
8052                 ctx->nr_user_bufs++;
8053         }
8054         kvfree(pages);
8055         kvfree(vmas);
8056         return 0;
8057 err:
8058         kvfree(pages);
8059         kvfree(vmas);
8060         io_sqe_buffer_unregister(ctx);
8061         return ret;
8062 }
8063
8064 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8065 {
8066         __s32 __user *fds = arg;
8067         int fd;
8068
8069         if (ctx->cq_ev_fd)
8070                 return -EBUSY;
8071
8072         if (copy_from_user(&fd, fds, sizeof(*fds)))
8073                 return -EFAULT;
8074
8075         ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8076         if (IS_ERR(ctx->cq_ev_fd)) {
8077                 int ret = PTR_ERR(ctx->cq_ev_fd);
8078                 ctx->cq_ev_fd = NULL;
8079                 return ret;
8080         }
8081
8082         return 0;
8083 }
8084
8085 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8086 {
8087         if (ctx->cq_ev_fd) {
8088                 eventfd_ctx_put(ctx->cq_ev_fd);
8089                 ctx->cq_ev_fd = NULL;
8090                 return 0;
8091         }
8092
8093         return -ENXIO;
8094 }
8095
8096 static int __io_destroy_buffers(int id, void *p, void *data)
8097 {
8098         struct io_ring_ctx *ctx = data;
8099         struct io_buffer *buf = p;
8100
8101         __io_remove_buffers(ctx, buf, id, -1U);
8102         return 0;
8103 }
8104
8105 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8106 {
8107         idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8108         idr_destroy(&ctx->io_buffer_idr);
8109 }
8110
8111 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8112 {
8113         io_finish_async(ctx);
8114         io_sqe_buffer_unregister(ctx);
8115
8116         if (ctx->sqo_task) {
8117                 put_task_struct(ctx->sqo_task);
8118                 ctx->sqo_task = NULL;
8119                 mmdrop(ctx->mm_account);
8120                 ctx->mm_account = NULL;
8121         }
8122
8123 #ifdef CONFIG_BLK_CGROUP
8124         if (ctx->sqo_blkcg_css)
8125                 css_put(ctx->sqo_blkcg_css);
8126 #endif
8127
8128         io_sqe_files_unregister(ctx);
8129         io_eventfd_unregister(ctx);
8130         io_destroy_buffers(ctx);
8131         idr_destroy(&ctx->personality_idr);
8132
8133 #if defined(CONFIG_UNIX)
8134         if (ctx->ring_sock) {
8135                 ctx->ring_sock->file = NULL; /* so that iput() is called */
8136                 sock_release(ctx->ring_sock);
8137         }
8138 #endif
8139
8140         io_mem_free(ctx->rings);
8141         io_mem_free(ctx->sq_sqes);
8142
8143         percpu_ref_exit(&ctx->refs);
8144         free_uid(ctx->user);
8145         put_cred(ctx->creds);
8146         kfree(ctx->cancel_hash);
8147         kmem_cache_free(req_cachep, ctx->fallback_req);
8148         kfree(ctx);
8149 }
8150
8151 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8152 {
8153         struct io_ring_ctx *ctx = file->private_data;
8154         __poll_t mask = 0;
8155
8156         poll_wait(file, &ctx->cq_wait, wait);
8157         /*
8158          * synchronizes with barrier from wq_has_sleeper call in
8159          * io_commit_cqring
8160          */
8161         smp_rmb();
8162         if (!io_sqring_full(ctx))
8163                 mask |= EPOLLOUT | EPOLLWRNORM;
8164         if (io_cqring_events(ctx, false))
8165                 mask |= EPOLLIN | EPOLLRDNORM;
8166
8167         return mask;
8168 }
8169
8170 static int io_uring_fasync(int fd, struct file *file, int on)
8171 {
8172         struct io_ring_ctx *ctx = file->private_data;
8173
8174         return fasync_helper(fd, file, on, &ctx->cq_fasync);
8175 }
8176
8177 static int io_remove_personalities(int id, void *p, void *data)
8178 {
8179         struct io_ring_ctx *ctx = data;
8180         const struct cred *cred;
8181
8182         cred = idr_remove(&ctx->personality_idr, id);
8183         if (cred)
8184                 put_cred(cred);
8185         return 0;
8186 }
8187
8188 static void io_ring_exit_work(struct work_struct *work)
8189 {
8190         struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8191                                                exit_work);
8192
8193         /*
8194          * If we're doing polled IO and end up having requests being
8195          * submitted async (out-of-line), then completions can come in while
8196          * we're waiting for refs to drop. We need to reap these manually,
8197          * as nobody else will be looking for them.
8198          */
8199         do {
8200                 if (ctx->rings)
8201                         io_cqring_overflow_flush(ctx, true, NULL, NULL);
8202                 io_iopoll_try_reap_events(ctx);
8203         } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8204         io_ring_ctx_free(ctx);
8205 }
8206
8207 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8208 {
8209         mutex_lock(&ctx->uring_lock);
8210         percpu_ref_kill(&ctx->refs);
8211         mutex_unlock(&ctx->uring_lock);
8212
8213         io_kill_timeouts(ctx, NULL);
8214         io_poll_remove_all(ctx, NULL);
8215
8216         if (ctx->io_wq)
8217                 io_wq_cancel_all(ctx->io_wq);
8218
8219         /* if we failed setting up the ctx, we might not have any rings */
8220         if (ctx->rings)
8221                 io_cqring_overflow_flush(ctx, true, NULL, NULL);
8222         io_iopoll_try_reap_events(ctx);
8223         idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8224
8225         /*
8226          * Do this upfront, so we won't have a grace period where the ring
8227          * is closed but resources aren't reaped yet. This can cause
8228          * spurious failure in setting up a new ring.
8229          */
8230         io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
8231                          ACCT_LOCKED);
8232
8233         INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8234         /*
8235          * Use system_unbound_wq to avoid spawning tons of event kworkers
8236          * if we're exiting a ton of rings at the same time. It just adds
8237          * noise and overhead, there's no discernable change in runtime
8238          * over using system_wq.
8239          */
8240         queue_work(system_unbound_wq, &ctx->exit_work);
8241 }
8242
8243 static int io_uring_release(struct inode *inode, struct file *file)
8244 {
8245         struct io_ring_ctx *ctx = file->private_data;
8246
8247         file->private_data = NULL;
8248         io_ring_ctx_wait_and_kill(ctx);
8249         return 0;
8250 }
8251
8252 static bool io_wq_files_match(struct io_wq_work *work, void *data)
8253 {
8254         struct files_struct *files = data;
8255
8256         return !files || work->files == files;
8257 }
8258
8259 /*
8260  * Returns true if 'preq' is the link parent of 'req'
8261  */
8262 static bool io_match_link(struct io_kiocb *preq, struct io_kiocb *req)
8263 {
8264         struct io_kiocb *link;
8265
8266         if (!(preq->flags & REQ_F_LINK_HEAD))
8267                 return false;
8268
8269         list_for_each_entry(link, &preq->link_list, link_list) {
8270                 if (link == req)
8271                         return true;
8272         }
8273
8274         return false;
8275 }
8276
8277 static bool io_match_link_files(struct io_kiocb *req,
8278                                 struct files_struct *files)
8279 {
8280         struct io_kiocb *link;
8281
8282         if (io_match_files(req, files))
8283                 return true;
8284         if (req->flags & REQ_F_LINK_HEAD) {
8285                 list_for_each_entry(link, &req->link_list, link_list) {
8286                         if (io_match_files(link, files))
8287                                 return true;
8288                 }
8289         }
8290         return false;
8291 }
8292
8293 /*
8294  * We're looking to cancel 'req' because it's holding on to our files, but
8295  * 'req' could be a link to another request. See if it is, and cancel that
8296  * parent request if so.
8297  */
8298 static bool io_poll_remove_link(struct io_ring_ctx *ctx, struct io_kiocb *req)
8299 {
8300         struct hlist_node *tmp;
8301         struct io_kiocb *preq;
8302         bool found = false;
8303         int i;
8304
8305         spin_lock_irq(&ctx->completion_lock);
8306         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8307                 struct hlist_head *list;
8308
8309                 list = &ctx->cancel_hash[i];
8310                 hlist_for_each_entry_safe(preq, tmp, list, hash_node) {
8311                         found = io_match_link(preq, req);
8312                         if (found) {
8313                                 io_poll_remove_one(preq);
8314                                 break;
8315                         }
8316                 }
8317         }
8318         spin_unlock_irq(&ctx->completion_lock);
8319         return found;
8320 }
8321
8322 static bool io_timeout_remove_link(struct io_ring_ctx *ctx,
8323                                    struct io_kiocb *req)
8324 {
8325         struct io_kiocb *preq;
8326         bool found = false;
8327
8328         spin_lock_irq(&ctx->completion_lock);
8329         list_for_each_entry(preq, &ctx->timeout_list, timeout.list) {
8330                 found = io_match_link(preq, req);
8331                 if (found) {
8332                         __io_timeout_cancel(preq);
8333                         break;
8334                 }
8335         }
8336         spin_unlock_irq(&ctx->completion_lock);
8337         return found;
8338 }
8339
8340 static bool io_cancel_link_cb(struct io_wq_work *work, void *data)
8341 {
8342         return io_match_link(container_of(work, struct io_kiocb, work), data);
8343 }
8344
8345 static void io_attempt_cancel(struct io_ring_ctx *ctx, struct io_kiocb *req)
8346 {
8347         enum io_wq_cancel cret;
8348
8349         /* cancel this particular work, if it's running */
8350         cret = io_wq_cancel_work(ctx->io_wq, &req->work);
8351         if (cret != IO_WQ_CANCEL_NOTFOUND)
8352                 return;
8353
8354         /* find links that hold this pending, cancel those */
8355         cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_link_cb, req, true);
8356         if (cret != IO_WQ_CANCEL_NOTFOUND)
8357                 return;
8358
8359         /* if we have a poll link holding this pending, cancel that */
8360         if (io_poll_remove_link(ctx, req))
8361                 return;
8362
8363         /* final option, timeout link is holding this req pending */
8364         io_timeout_remove_link(ctx, req);
8365 }
8366
8367 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8368                                   struct files_struct *files)
8369 {
8370         struct io_defer_entry *de = NULL;
8371         LIST_HEAD(list);
8372
8373         spin_lock_irq(&ctx->completion_lock);
8374         list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8375                 if (io_match_link_files(de->req, files)) {
8376                         list_cut_position(&list, &ctx->defer_list, &de->list);
8377                         break;
8378                 }
8379         }
8380         spin_unlock_irq(&ctx->completion_lock);
8381
8382         while (!list_empty(&list)) {
8383                 de = list_first_entry(&list, struct io_defer_entry, list);
8384                 list_del_init(&de->list);
8385                 req_set_fail_links(de->req);
8386                 io_put_req(de->req);
8387                 io_req_complete(de->req, -ECANCELED);
8388                 kfree(de);
8389         }
8390 }
8391
8392 /*
8393  * Returns true if we found and killed one or more files pinning requests
8394  */
8395 static bool io_uring_cancel_files(struct io_ring_ctx *ctx,
8396                                   struct files_struct *files)
8397 {
8398         if (list_empty_careful(&ctx->inflight_list))
8399                 return false;
8400
8401         io_cancel_defer_files(ctx, files);
8402         /* cancel all at once, should be faster than doing it one by one*/
8403         io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
8404
8405         while (!list_empty_careful(&ctx->inflight_list)) {
8406                 struct io_kiocb *cancel_req = NULL, *req;
8407                 DEFINE_WAIT(wait);
8408
8409                 spin_lock_irq(&ctx->inflight_lock);
8410                 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
8411                         if (files && req->work.files != files)
8412                                 continue;
8413                         /* req is being completed, ignore */
8414                         if (!refcount_inc_not_zero(&req->refs))
8415                                 continue;
8416                         cancel_req = req;
8417                         break;
8418                 }
8419                 if (cancel_req)
8420                         prepare_to_wait(&ctx->inflight_wait, &wait,
8421                                                 TASK_UNINTERRUPTIBLE);
8422                 spin_unlock_irq(&ctx->inflight_lock);
8423
8424                 /* We need to keep going until we don't find a matching req */
8425                 if (!cancel_req)
8426                         break;
8427                 /* cancel this request, or head link requests */
8428                 io_attempt_cancel(ctx, cancel_req);
8429                 io_put_req(cancel_req);
8430                 /* cancellations _may_ trigger task work */
8431                 io_run_task_work();
8432                 schedule();
8433                 finish_wait(&ctx->inflight_wait, &wait);
8434         }
8435
8436         return true;
8437 }
8438
8439 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8440 {
8441         struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8442         struct task_struct *task = data;
8443
8444         return io_task_match(req, task);
8445 }
8446
8447 static bool __io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8448                                             struct task_struct *task,
8449                                             struct files_struct *files)
8450 {
8451         bool ret;
8452
8453         ret = io_uring_cancel_files(ctx, files);
8454         if (!files) {
8455                 enum io_wq_cancel cret;
8456
8457                 cret = io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, task, true);
8458                 if (cret != IO_WQ_CANCEL_NOTFOUND)
8459                         ret = true;
8460
8461                 /* SQPOLL thread does its own polling */
8462                 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8463                         while (!list_empty_careful(&ctx->iopoll_list)) {
8464                                 io_iopoll_try_reap_events(ctx);
8465                                 ret = true;
8466                         }
8467                 }
8468
8469                 ret |= io_poll_remove_all(ctx, task);
8470                 ret |= io_kill_timeouts(ctx, task);
8471         }
8472
8473         return ret;
8474 }
8475
8476 /*
8477  * We need to iteratively cancel requests, in case a request has dependent
8478  * hard links. These persist even for failure of cancelations, hence keep
8479  * looping until none are found.
8480  */
8481 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8482                                           struct files_struct *files)
8483 {
8484         struct task_struct *task = current;
8485
8486         if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data)
8487                 task = ctx->sq_data->thread;
8488
8489         io_cqring_overflow_flush(ctx, true, task, files);
8490
8491         while (__io_uring_cancel_task_requests(ctx, task, files)) {
8492                 io_run_task_work();
8493                 cond_resched();
8494         }
8495 }
8496
8497 /*
8498  * Note that this task has used io_uring. We use it for cancelation purposes.
8499  */
8500 static int io_uring_add_task_file(struct file *file)
8501 {
8502         struct io_uring_task *tctx = current->io_uring;
8503
8504         if (unlikely(!tctx)) {
8505                 int ret;
8506
8507                 ret = io_uring_alloc_task_context(current);
8508                 if (unlikely(ret))
8509                         return ret;
8510                 tctx = current->io_uring;
8511         }
8512         if (tctx->last != file) {
8513                 void *old = xa_load(&tctx->xa, (unsigned long)file);
8514
8515                 if (!old) {
8516                         get_file(file);
8517                         xa_store(&tctx->xa, (unsigned long)file, file, GFP_KERNEL);
8518                 }
8519                 tctx->last = file;
8520         }
8521
8522         return 0;
8523 }
8524
8525 /*
8526  * Remove this io_uring_file -> task mapping.
8527  */
8528 static void io_uring_del_task_file(struct file *file)
8529 {
8530         struct io_uring_task *tctx = current->io_uring;
8531
8532         if (tctx->last == file)
8533                 tctx->last = NULL;
8534         file = xa_erase(&tctx->xa, (unsigned long)file);
8535         if (file)
8536                 fput(file);
8537 }
8538
8539 static void __io_uring_attempt_task_drop(struct file *file)
8540 {
8541         struct file *old = xa_load(&current->io_uring->xa, (unsigned long)file);
8542
8543         if (old == file)
8544                 io_uring_del_task_file(file);
8545 }
8546
8547 /*
8548  * Drop task note for this file if we're the only ones that hold it after
8549  * pending fput()
8550  */
8551 static void io_uring_attempt_task_drop(struct file *file, bool exiting)
8552 {
8553         if (!current->io_uring)
8554                 return;
8555         /*
8556          * fput() is pending, will be 2 if the only other ref is our potential
8557          * task file note. If the task is exiting, drop regardless of count.
8558          */
8559         if (!exiting && atomic_long_read(&file->f_count) != 2)
8560                 return;
8561
8562         __io_uring_attempt_task_drop(file);
8563 }
8564
8565 void __io_uring_files_cancel(struct files_struct *files)
8566 {
8567         struct io_uring_task *tctx = current->io_uring;
8568         struct file *file;
8569         unsigned long index;
8570
8571         /* make sure overflow events are dropped */
8572         tctx->in_idle = true;
8573
8574         xa_for_each(&tctx->xa, index, file) {
8575                 struct io_ring_ctx *ctx = file->private_data;
8576
8577                 io_uring_cancel_task_requests(ctx, files);
8578                 if (files)
8579                         io_uring_del_task_file(file);
8580         }
8581 }
8582
8583 static inline bool io_uring_task_idle(struct io_uring_task *tctx)
8584 {
8585         return atomic_long_read(&tctx->req_issue) ==
8586                 atomic_long_read(&tctx->req_complete);
8587 }
8588
8589 /*
8590  * Find any io_uring fd that this task has registered or done IO on, and cancel
8591  * requests.
8592  */
8593 void __io_uring_task_cancel(void)
8594 {
8595         struct io_uring_task *tctx = current->io_uring;
8596         DEFINE_WAIT(wait);
8597         long completions;
8598
8599         /* make sure overflow events are dropped */
8600         tctx->in_idle = true;
8601
8602         while (!io_uring_task_idle(tctx)) {
8603                 /* read completions before cancelations */
8604                 completions = atomic_long_read(&tctx->req_complete);
8605                 __io_uring_files_cancel(NULL);
8606
8607                 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8608
8609                 /*
8610                  * If we've seen completions, retry. This avoids a race where
8611                  * a completion comes in before we did prepare_to_wait().
8612                  */
8613                 if (completions != atomic_long_read(&tctx->req_complete))
8614                         continue;
8615                 if (io_uring_task_idle(tctx))
8616                         break;
8617                 schedule();
8618         }
8619
8620         finish_wait(&tctx->wait, &wait);
8621         tctx->in_idle = false;
8622 }
8623
8624 static int io_uring_flush(struct file *file, void *data)
8625 {
8626         struct io_ring_ctx *ctx = file->private_data;
8627
8628         /*
8629          * If the task is going away, cancel work it may have pending
8630          */
8631         if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
8632                 data = NULL;
8633
8634         io_uring_cancel_task_requests(ctx, data);
8635         io_uring_attempt_task_drop(file, !data);
8636         return 0;
8637 }
8638
8639 static void *io_uring_validate_mmap_request(struct file *file,
8640                                             loff_t pgoff, size_t sz)
8641 {
8642         struct io_ring_ctx *ctx = file->private_data;
8643         loff_t offset = pgoff << PAGE_SHIFT;
8644         struct page *page;
8645         void *ptr;
8646
8647         switch (offset) {
8648         case IORING_OFF_SQ_RING:
8649         case IORING_OFF_CQ_RING:
8650                 ptr = ctx->rings;
8651                 break;
8652         case IORING_OFF_SQES:
8653                 ptr = ctx->sq_sqes;
8654                 break;
8655         default:
8656                 return ERR_PTR(-EINVAL);
8657         }
8658
8659         page = virt_to_head_page(ptr);
8660         if (sz > page_size(page))
8661                 return ERR_PTR(-EINVAL);
8662
8663         return ptr;
8664 }
8665
8666 #ifdef CONFIG_MMU
8667
8668 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8669 {
8670         size_t sz = vma->vm_end - vma->vm_start;
8671         unsigned long pfn;
8672         void *ptr;
8673
8674         ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8675         if (IS_ERR(ptr))
8676                 return PTR_ERR(ptr);
8677
8678         pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
8679         return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
8680 }
8681
8682 #else /* !CONFIG_MMU */
8683
8684 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8685 {
8686         return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
8687 }
8688
8689 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
8690 {
8691         return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
8692 }
8693
8694 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
8695         unsigned long addr, unsigned long len,
8696         unsigned long pgoff, unsigned long flags)
8697 {
8698         void *ptr;
8699
8700         ptr = io_uring_validate_mmap_request(file, pgoff, len);
8701         if (IS_ERR(ptr))
8702                 return PTR_ERR(ptr);
8703
8704         return (unsigned long) ptr;
8705 }
8706
8707 #endif /* !CONFIG_MMU */
8708
8709 static void io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
8710 {
8711         DEFINE_WAIT(wait);
8712
8713         do {
8714                 if (!io_sqring_full(ctx))
8715                         break;
8716
8717                 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
8718
8719                 if (!io_sqring_full(ctx))
8720                         break;
8721
8722                 schedule();
8723         } while (!signal_pending(current));
8724
8725         finish_wait(&ctx->sqo_sq_wait, &wait);
8726 }
8727
8728 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
8729                 u32, min_complete, u32, flags, const sigset_t __user *, sig,
8730                 size_t, sigsz)
8731 {
8732         struct io_ring_ctx *ctx;
8733         long ret = -EBADF;
8734         int submitted = 0;
8735         struct fd f;
8736
8737         io_run_task_work();
8738
8739         if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
8740                         IORING_ENTER_SQ_WAIT))
8741                 return -EINVAL;
8742
8743         f = fdget(fd);
8744         if (!f.file)
8745                 return -EBADF;
8746
8747         ret = -EOPNOTSUPP;
8748         if (f.file->f_op != &io_uring_fops)
8749                 goto out_fput;
8750
8751         ret = -ENXIO;
8752         ctx = f.file->private_data;
8753         if (!percpu_ref_tryget(&ctx->refs))
8754                 goto out_fput;
8755
8756         ret = -EBADFD;
8757         if (ctx->flags & IORING_SETUP_R_DISABLED)
8758                 goto out;
8759
8760         /*
8761          * For SQ polling, the thread will do all submissions and completions.
8762          * Just return the requested submit count, and wake the thread if
8763          * we were asked to.
8764          */
8765         ret = 0;
8766         if (ctx->flags & IORING_SETUP_SQPOLL) {
8767                 if (!list_empty_careful(&ctx->cq_overflow_list))
8768                         io_cqring_overflow_flush(ctx, false, NULL, NULL);
8769                 if (flags & IORING_ENTER_SQ_WAKEUP)
8770                         wake_up(&ctx->sq_data->wait);
8771                 if (flags & IORING_ENTER_SQ_WAIT)
8772                         io_sqpoll_wait_sq(ctx);
8773                 submitted = to_submit;
8774         } else if (to_submit) {
8775                 ret = io_uring_add_task_file(f.file);
8776                 if (unlikely(ret))
8777                         goto out;
8778                 mutex_lock(&ctx->uring_lock);
8779                 submitted = io_submit_sqes(ctx, to_submit);
8780                 mutex_unlock(&ctx->uring_lock);
8781
8782                 if (submitted != to_submit)
8783                         goto out;
8784         }
8785         if (flags & IORING_ENTER_GETEVENTS) {
8786                 min_complete = min(min_complete, ctx->cq_entries);
8787
8788                 /*
8789                  * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
8790                  * space applications don't need to do io completion events
8791                  * polling again, they can rely on io_sq_thread to do polling
8792                  * work, which can reduce cpu usage and uring_lock contention.
8793                  */
8794                 if (ctx->flags & IORING_SETUP_IOPOLL &&
8795                     !(ctx->flags & IORING_SETUP_SQPOLL)) {
8796                         ret = io_iopoll_check(ctx, min_complete);
8797                 } else {
8798                         ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
8799                 }
8800         }
8801
8802 out:
8803         percpu_ref_put(&ctx->refs);
8804 out_fput:
8805         fdput(f);
8806         return submitted ? submitted : ret;
8807 }
8808
8809 #ifdef CONFIG_PROC_FS
8810 static int io_uring_show_cred(int id, void *p, void *data)
8811 {
8812         const struct cred *cred = p;
8813         struct seq_file *m = data;
8814         struct user_namespace *uns = seq_user_ns(m);
8815         struct group_info *gi;
8816         kernel_cap_t cap;
8817         unsigned __capi;
8818         int g;
8819
8820         seq_printf(m, "%5d\n", id);
8821         seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
8822         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
8823         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
8824         seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
8825         seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
8826         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
8827         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
8828         seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
8829         seq_puts(m, "\n\tGroups:\t");
8830         gi = cred->group_info;
8831         for (g = 0; g < gi->ngroups; g++) {
8832                 seq_put_decimal_ull(m, g ? " " : "",
8833                                         from_kgid_munged(uns, gi->gid[g]));
8834         }
8835         seq_puts(m, "\n\tCapEff:\t");
8836         cap = cred->cap_effective;
8837         CAP_FOR_EACH_U32(__capi)
8838                 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8839         seq_putc(m, '\n');
8840         return 0;
8841 }
8842
8843 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8844 {
8845         struct io_sq_data *sq = NULL;
8846         bool has_lock;
8847         int i;
8848
8849         /*
8850          * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
8851          * since fdinfo case grabs it in the opposite direction of normal use
8852          * cases. If we fail to get the lock, we just don't iterate any
8853          * structures that could be going away outside the io_uring mutex.
8854          */
8855         has_lock = mutex_trylock(&ctx->uring_lock);
8856
8857         if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL))
8858                 sq = ctx->sq_data;
8859
8860         seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
8861         seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
8862         seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8863         for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
8864                 struct fixed_file_table *table;
8865                 struct file *f;
8866
8867                 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8868                 f = table->files[i & IORING_FILE_TABLE_MASK];
8869                 if (f)
8870                         seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8871                 else
8872                         seq_printf(m, "%5u: <none>\n", i);
8873         }
8874         seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8875         for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
8876                 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8877
8878                 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8879                                                 (unsigned int) buf->len);
8880         }
8881         if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
8882                 seq_printf(m, "Personalities:\n");
8883                 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8884         }
8885         seq_printf(m, "PollList:\n");
8886         spin_lock_irq(&ctx->completion_lock);
8887         for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8888                 struct hlist_head *list = &ctx->cancel_hash[i];
8889                 struct io_kiocb *req;
8890
8891                 hlist_for_each_entry(req, list, hash_node)
8892                         seq_printf(m, "  op=%d, task_works=%d\n", req->opcode,
8893                                         req->task->task_works != NULL);
8894         }
8895         spin_unlock_irq(&ctx->completion_lock);
8896         if (has_lock)
8897                 mutex_unlock(&ctx->uring_lock);
8898 }
8899
8900 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8901 {
8902         struct io_ring_ctx *ctx = f->private_data;
8903
8904         if (percpu_ref_tryget(&ctx->refs)) {
8905                 __io_uring_show_fdinfo(ctx, m);
8906                 percpu_ref_put(&ctx->refs);
8907         }
8908 }
8909 #endif
8910
8911 static const struct file_operations io_uring_fops = {
8912         .release        = io_uring_release,
8913         .flush          = io_uring_flush,
8914         .mmap           = io_uring_mmap,
8915 #ifndef CONFIG_MMU
8916         .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8917         .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8918 #endif
8919         .poll           = io_uring_poll,
8920         .fasync         = io_uring_fasync,
8921 #ifdef CONFIG_PROC_FS
8922         .show_fdinfo    = io_uring_show_fdinfo,
8923 #endif
8924 };
8925
8926 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8927                                   struct io_uring_params *p)
8928 {
8929         struct io_rings *rings;
8930         size_t size, sq_array_offset;
8931
8932         /* make sure these are sane, as we already accounted them */
8933         ctx->sq_entries = p->sq_entries;
8934         ctx->cq_entries = p->cq_entries;
8935
8936         size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8937         if (size == SIZE_MAX)
8938                 return -EOVERFLOW;
8939
8940         rings = io_mem_alloc(size);
8941         if (!rings)
8942                 return -ENOMEM;
8943
8944         ctx->rings = rings;
8945         ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8946         rings->sq_ring_mask = p->sq_entries - 1;
8947         rings->cq_ring_mask = p->cq_entries - 1;
8948         rings->sq_ring_entries = p->sq_entries;
8949         rings->cq_ring_entries = p->cq_entries;
8950         ctx->sq_mask = rings->sq_ring_mask;
8951         ctx->cq_mask = rings->cq_ring_mask;
8952
8953         size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8954         if (size == SIZE_MAX) {
8955                 io_mem_free(ctx->rings);
8956                 ctx->rings = NULL;
8957                 return -EOVERFLOW;
8958         }
8959
8960         ctx->sq_sqes = io_mem_alloc(size);
8961         if (!ctx->sq_sqes) {
8962                 io_mem_free(ctx->rings);
8963                 ctx->rings = NULL;
8964                 return -ENOMEM;
8965         }
8966
8967         return 0;
8968 }
8969
8970 /*
8971  * Allocate an anonymous fd, this is what constitutes the application
8972  * visible backing of an io_uring instance. The application mmaps this
8973  * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8974  * we have to tie this fd to a socket for file garbage collection purposes.
8975  */
8976 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8977 {
8978         struct file *file;
8979         int ret;
8980
8981 #if defined(CONFIG_UNIX)
8982         ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8983                                 &ctx->ring_sock);
8984         if (ret)
8985                 return ret;
8986 #endif
8987
8988         ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8989         if (ret < 0)
8990                 goto err;
8991
8992         file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8993                                         O_RDWR | O_CLOEXEC);
8994         if (IS_ERR(file)) {
8995 err_fd:
8996                 put_unused_fd(ret);
8997                 ret = PTR_ERR(file);
8998                 goto err;
8999         }
9000
9001 #if defined(CONFIG_UNIX)
9002         ctx->ring_sock->file = file;
9003 #endif
9004         if (unlikely(io_uring_add_task_file(file))) {
9005                 file = ERR_PTR(-ENOMEM);
9006                 goto err_fd;
9007         }
9008         fd_install(ret, file);
9009         return ret;
9010 err:
9011 #if defined(CONFIG_UNIX)
9012         sock_release(ctx->ring_sock);
9013         ctx->ring_sock = NULL;
9014 #endif
9015         return ret;
9016 }
9017
9018 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9019                            struct io_uring_params __user *params)
9020 {
9021         struct user_struct *user = NULL;
9022         struct io_ring_ctx *ctx;
9023         bool limit_mem;
9024         int ret;
9025
9026         if (!entries)
9027                 return -EINVAL;
9028         if (entries > IORING_MAX_ENTRIES) {
9029                 if (!(p->flags & IORING_SETUP_CLAMP))
9030                         return -EINVAL;
9031                 entries = IORING_MAX_ENTRIES;
9032         }
9033
9034         /*
9035          * Use twice as many entries for the CQ ring. It's possible for the
9036          * application to drive a higher depth than the size of the SQ ring,
9037          * since the sqes are only used at submission time. This allows for
9038          * some flexibility in overcommitting a bit. If the application has
9039          * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9040          * of CQ ring entries manually.
9041          */
9042         p->sq_entries = roundup_pow_of_two(entries);
9043         if (p->flags & IORING_SETUP_CQSIZE) {
9044                 /*
9045                  * If IORING_SETUP_CQSIZE is set, we do the same roundup
9046                  * to a power-of-two, if it isn't already. We do NOT impose
9047                  * any cq vs sq ring sizing.
9048                  */
9049                 if (p->cq_entries < p->sq_entries)
9050                         return -EINVAL;
9051                 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9052                         if (!(p->flags & IORING_SETUP_CLAMP))
9053                                 return -EINVAL;
9054                         p->cq_entries = IORING_MAX_CQ_ENTRIES;
9055                 }
9056                 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9057         } else {
9058                 p->cq_entries = 2 * p->sq_entries;
9059         }
9060
9061         user = get_uid(current_user());
9062         limit_mem = !capable(CAP_IPC_LOCK);
9063
9064         if (limit_mem) {
9065                 ret = __io_account_mem(user,
9066                                 ring_pages(p->sq_entries, p->cq_entries));
9067                 if (ret) {
9068                         free_uid(user);
9069                         return ret;
9070                 }
9071         }
9072
9073         ctx = io_ring_ctx_alloc(p);
9074         if (!ctx) {
9075                 if (limit_mem)
9076                         __io_unaccount_mem(user, ring_pages(p->sq_entries,
9077                                                                 p->cq_entries));
9078                 free_uid(user);
9079                 return -ENOMEM;
9080         }
9081         ctx->compat = in_compat_syscall();
9082         ctx->user = user;
9083         ctx->creds = get_current_cred();
9084
9085         ctx->sqo_task = get_task_struct(current);
9086
9087         /*
9088          * This is just grabbed for accounting purposes. When a process exits,
9089          * the mm is exited and dropped before the files, hence we need to hang
9090          * on to this mm purely for the purposes of being able to unaccount
9091          * memory (locked/pinned vm). It's not used for anything else.
9092          */
9093         mmgrab(current->mm);
9094         ctx->mm_account = current->mm;
9095
9096 #ifdef CONFIG_BLK_CGROUP
9097         /*
9098          * The sq thread will belong to the original cgroup it was inited in.
9099          * If the cgroup goes offline (e.g. disabling the io controller), then
9100          * issued bios will be associated with the closest cgroup later in the
9101          * block layer.
9102          */
9103         rcu_read_lock();
9104         ctx->sqo_blkcg_css = blkcg_css();
9105         ret = css_tryget_online(ctx->sqo_blkcg_css);
9106         rcu_read_unlock();
9107         if (!ret) {
9108                 /* don't init against a dying cgroup, have the user try again */
9109                 ctx->sqo_blkcg_css = NULL;
9110                 ret = -ENODEV;
9111                 goto err;
9112         }
9113 #endif
9114
9115         /*
9116          * Account memory _before_ installing the file descriptor. Once
9117          * the descriptor is installed, it can get closed at any time. Also
9118          * do this before hitting the general error path, as ring freeing
9119          * will un-account as well.
9120          */
9121         io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
9122                        ACCT_LOCKED);
9123         ctx->limit_mem = limit_mem;
9124
9125         ret = io_allocate_scq_urings(ctx, p);
9126         if (ret)
9127                 goto err;
9128
9129         ret = io_sq_offload_create(ctx, p);
9130         if (ret)
9131                 goto err;
9132
9133         if (!(p->flags & IORING_SETUP_R_DISABLED))
9134                 io_sq_offload_start(ctx);
9135
9136         memset(&p->sq_off, 0, sizeof(p->sq_off));
9137         p->sq_off.head = offsetof(struct io_rings, sq.head);
9138         p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9139         p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9140         p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9141         p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9142         p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9143         p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9144
9145         memset(&p->cq_off, 0, sizeof(p->cq_off));
9146         p->cq_off.head = offsetof(struct io_rings, cq.head);
9147         p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9148         p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9149         p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9150         p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9151         p->cq_off.cqes = offsetof(struct io_rings, cqes);
9152         p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9153
9154         p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9155                         IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9156                         IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9157                         IORING_FEAT_POLL_32BITS;
9158
9159         if (copy_to_user(params, p, sizeof(*p))) {
9160                 ret = -EFAULT;
9161                 goto err;
9162         }
9163
9164         /*
9165          * Install ring fd as the very last thing, so we don't risk someone
9166          * having closed it before we finish setup
9167          */
9168         ret = io_uring_get_fd(ctx);
9169         if (ret < 0)
9170                 goto err;
9171
9172         trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9173         return ret;
9174 err:
9175         io_ring_ctx_wait_and_kill(ctx);
9176         return ret;
9177 }
9178
9179 /*
9180  * Sets up an aio uring context, and returns the fd. Applications asks for a
9181  * ring size, we return the actual sq/cq ring sizes (among other things) in the
9182  * params structure passed in.
9183  */
9184 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9185 {
9186         struct io_uring_params p;
9187         int i;
9188
9189         if (copy_from_user(&p, params, sizeof(p)))
9190                 return -EFAULT;
9191         for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9192                 if (p.resv[i])
9193                         return -EINVAL;
9194         }
9195
9196         if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9197                         IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9198                         IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9199                         IORING_SETUP_R_DISABLED))
9200                 return -EINVAL;
9201
9202         return  io_uring_create(entries, &p, params);
9203 }
9204
9205 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9206                 struct io_uring_params __user *, params)
9207 {
9208         return io_uring_setup(entries, params);
9209 }
9210
9211 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9212 {
9213         struct io_uring_probe *p;
9214         size_t size;
9215         int i, ret;
9216
9217         size = struct_size(p, ops, nr_args);
9218         if (size == SIZE_MAX)
9219                 return -EOVERFLOW;
9220         p = kzalloc(size, GFP_KERNEL);
9221         if (!p)
9222                 return -ENOMEM;
9223
9224         ret = -EFAULT;
9225         if (copy_from_user(p, arg, size))
9226                 goto out;
9227         ret = -EINVAL;
9228         if (memchr_inv(p, 0, size))
9229                 goto out;
9230
9231         p->last_op = IORING_OP_LAST - 1;
9232         if (nr_args > IORING_OP_LAST)
9233                 nr_args = IORING_OP_LAST;
9234
9235         for (i = 0; i < nr_args; i++) {
9236                 p->ops[i].op = i;
9237                 if (!io_op_defs[i].not_supported)
9238                         p->ops[i].flags = IO_URING_OP_SUPPORTED;
9239         }
9240         p->ops_len = i;
9241
9242         ret = 0;
9243         if (copy_to_user(arg, p, size))
9244                 ret = -EFAULT;
9245 out:
9246         kfree(p);
9247         return ret;
9248 }
9249
9250 static int io_register_personality(struct io_ring_ctx *ctx)
9251 {
9252         const struct cred *creds = get_current_cred();
9253         int id;
9254
9255         id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9256                                 USHRT_MAX, GFP_KERNEL);
9257         if (id < 0)
9258                 put_cred(creds);
9259         return id;
9260 }
9261
9262 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9263 {
9264         const struct cred *old_creds;
9265
9266         old_creds = idr_remove(&ctx->personality_idr, id);
9267         if (old_creds) {
9268                 put_cred(old_creds);
9269                 return 0;
9270         }
9271
9272         return -EINVAL;
9273 }
9274
9275 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9276                                     unsigned int nr_args)
9277 {
9278         struct io_uring_restriction *res;
9279         size_t size;
9280         int i, ret;
9281
9282         /* Restrictions allowed only if rings started disabled */
9283         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9284                 return -EBADFD;
9285
9286         /* We allow only a single restrictions registration */
9287         if (ctx->restrictions.registered)
9288                 return -EBUSY;
9289
9290         if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9291                 return -EINVAL;
9292
9293         size = array_size(nr_args, sizeof(*res));
9294         if (size == SIZE_MAX)
9295                 return -EOVERFLOW;
9296
9297         res = memdup_user(arg, size);
9298         if (IS_ERR(res))
9299                 return PTR_ERR(res);
9300
9301         ret = 0;
9302
9303         for (i = 0; i < nr_args; i++) {
9304                 switch (res[i].opcode) {
9305                 case IORING_RESTRICTION_REGISTER_OP:
9306                         if (res[i].register_op >= IORING_REGISTER_LAST) {
9307                                 ret = -EINVAL;
9308                                 goto out;
9309                         }
9310
9311                         __set_bit(res[i].register_op,
9312                                   ctx->restrictions.register_op);
9313                         break;
9314                 case IORING_RESTRICTION_SQE_OP:
9315                         if (res[i].sqe_op >= IORING_OP_LAST) {
9316                                 ret = -EINVAL;
9317                                 goto out;
9318                         }
9319
9320                         __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9321                         break;
9322                 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9323                         ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9324                         break;
9325                 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9326                         ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9327                         break;
9328                 default:
9329                         ret = -EINVAL;
9330                         goto out;
9331                 }
9332         }
9333
9334 out:
9335         /* Reset all restrictions if an error happened */
9336         if (ret != 0)
9337                 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9338         else
9339                 ctx->restrictions.registered = true;
9340
9341         kfree(res);
9342         return ret;
9343 }
9344
9345 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9346 {
9347         if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9348                 return -EBADFD;
9349
9350         if (ctx->restrictions.registered)
9351                 ctx->restricted = 1;
9352
9353         ctx->flags &= ~IORING_SETUP_R_DISABLED;
9354
9355         io_sq_offload_start(ctx);
9356
9357         return 0;
9358 }
9359
9360 static bool io_register_op_must_quiesce(int op)
9361 {
9362         switch (op) {
9363         case IORING_UNREGISTER_FILES:
9364         case IORING_REGISTER_FILES_UPDATE:
9365         case IORING_REGISTER_PROBE:
9366         case IORING_REGISTER_PERSONALITY:
9367         case IORING_UNREGISTER_PERSONALITY:
9368                 return false;
9369         default:
9370                 return true;
9371         }
9372 }
9373
9374 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9375                                void __user *arg, unsigned nr_args)
9376         __releases(ctx->uring_lock)
9377         __acquires(ctx->uring_lock)
9378 {
9379         int ret;
9380
9381         /*
9382          * We're inside the ring mutex, if the ref is already dying, then
9383          * someone else killed the ctx or is already going through
9384          * io_uring_register().
9385          */
9386         if (percpu_ref_is_dying(&ctx->refs))
9387                 return -ENXIO;
9388
9389         if (io_register_op_must_quiesce(opcode)) {
9390                 percpu_ref_kill(&ctx->refs);
9391
9392                 /*
9393                  * Drop uring mutex before waiting for references to exit. If
9394                  * another thread is currently inside io_uring_enter() it might
9395                  * need to grab the uring_lock to make progress. If we hold it
9396                  * here across the drain wait, then we can deadlock. It's safe
9397                  * to drop the mutex here, since no new references will come in
9398                  * after we've killed the percpu ref.
9399                  */
9400                 mutex_unlock(&ctx->uring_lock);
9401                 do {
9402                         ret = wait_for_completion_interruptible(&ctx->ref_comp);
9403                         if (!ret)
9404                                 break;
9405                         ret = io_run_task_work_sig();
9406                         if (ret < 0)
9407                                 break;
9408                 } while (1);
9409
9410                 mutex_lock(&ctx->uring_lock);
9411
9412                 if (ret) {
9413                         percpu_ref_resurrect(&ctx->refs);
9414                         goto out_quiesce;
9415                 }
9416         }
9417
9418         if (ctx->restricted) {
9419                 if (opcode >= IORING_REGISTER_LAST) {
9420                         ret = -EINVAL;
9421                         goto out;
9422                 }
9423
9424                 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9425                         ret = -EACCES;
9426                         goto out;
9427                 }
9428         }
9429
9430         switch (opcode) {
9431         case IORING_REGISTER_BUFFERS:
9432                 ret = io_sqe_buffer_register(ctx, arg, nr_args);
9433                 break;
9434         case IORING_UNREGISTER_BUFFERS:
9435                 ret = -EINVAL;
9436                 if (arg || nr_args)
9437                         break;
9438                 ret = io_sqe_buffer_unregister(ctx);
9439                 break;
9440         case IORING_REGISTER_FILES:
9441                 ret = io_sqe_files_register(ctx, arg, nr_args);
9442                 break;
9443         case IORING_UNREGISTER_FILES:
9444                 ret = -EINVAL;
9445                 if (arg || nr_args)
9446                         break;
9447                 ret = io_sqe_files_unregister(ctx);
9448                 break;
9449         case IORING_REGISTER_FILES_UPDATE:
9450                 ret = io_sqe_files_update(ctx, arg, nr_args);
9451                 break;
9452         case IORING_REGISTER_EVENTFD:
9453         case IORING_REGISTER_EVENTFD_ASYNC:
9454                 ret = -EINVAL;
9455                 if (nr_args != 1)
9456                         break;
9457                 ret = io_eventfd_register(ctx, arg);
9458                 if (ret)
9459                         break;
9460                 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9461                         ctx->eventfd_async = 1;
9462                 else
9463                         ctx->eventfd_async = 0;
9464                 break;
9465         case IORING_UNREGISTER_EVENTFD:
9466                 ret = -EINVAL;
9467                 if (arg || nr_args)
9468                         break;
9469                 ret = io_eventfd_unregister(ctx);
9470                 break;
9471         case IORING_REGISTER_PROBE:
9472                 ret = -EINVAL;
9473                 if (!arg || nr_args > 256)
9474                         break;
9475                 ret = io_probe(ctx, arg, nr_args);
9476                 break;
9477         case IORING_REGISTER_PERSONALITY:
9478                 ret = -EINVAL;
9479                 if (arg || nr_args)
9480                         break;
9481                 ret = io_register_personality(ctx);
9482                 break;
9483         case IORING_UNREGISTER_PERSONALITY:
9484                 ret = -EINVAL;
9485                 if (arg)
9486                         break;
9487                 ret = io_unregister_personality(ctx, nr_args);
9488                 break;
9489         case IORING_REGISTER_ENABLE_RINGS:
9490                 ret = -EINVAL;
9491                 if (arg || nr_args)
9492                         break;
9493                 ret = io_register_enable_rings(ctx);
9494                 break;
9495         case IORING_REGISTER_RESTRICTIONS:
9496                 ret = io_register_restrictions(ctx, arg, nr_args);
9497                 break;
9498         default:
9499                 ret = -EINVAL;
9500                 break;
9501         }
9502
9503 out:
9504         if (io_register_op_must_quiesce(opcode)) {
9505                 /* bring the ctx back to life */
9506                 percpu_ref_reinit(&ctx->refs);
9507 out_quiesce:
9508                 reinit_completion(&ctx->ref_comp);
9509         }
9510         return ret;
9511 }
9512
9513 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9514                 void __user *, arg, unsigned int, nr_args)
9515 {
9516         struct io_ring_ctx *ctx;
9517         long ret = -EBADF;
9518         struct fd f;
9519
9520         f = fdget(fd);
9521         if (!f.file)
9522                 return -EBADF;
9523
9524         ret = -EOPNOTSUPP;
9525         if (f.file->f_op != &io_uring_fops)
9526                 goto out_fput;
9527
9528         ctx = f.file->private_data;
9529
9530         mutex_lock(&ctx->uring_lock);
9531         ret = __io_uring_register(ctx, opcode, arg, nr_args);
9532         mutex_unlock(&ctx->uring_lock);
9533         trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9534                                                         ctx->cq_ev_fd != NULL, ret);
9535 out_fput:
9536         fdput(f);
9537         return ret;
9538 }
9539
9540 static int __init io_uring_init(void)
9541 {
9542 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9543         BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9544         BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9545 } while (0)
9546
9547 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9548         __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9549         BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9550         BUILD_BUG_SQE_ELEM(0,  __u8,   opcode);
9551         BUILD_BUG_SQE_ELEM(1,  __u8,   flags);
9552         BUILD_BUG_SQE_ELEM(2,  __u16,  ioprio);
9553         BUILD_BUG_SQE_ELEM(4,  __s32,  fd);
9554         BUILD_BUG_SQE_ELEM(8,  __u64,  off);
9555         BUILD_BUG_SQE_ELEM(8,  __u64,  addr2);
9556         BUILD_BUG_SQE_ELEM(16, __u64,  addr);
9557         BUILD_BUG_SQE_ELEM(16, __u64,  splice_off_in);
9558         BUILD_BUG_SQE_ELEM(24, __u32,  len);
9559         BUILD_BUG_SQE_ELEM(28,     __kernel_rwf_t, rw_flags);
9560         BUILD_BUG_SQE_ELEM(28, /* compat */   int, rw_flags);
9561         BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9562         BUILD_BUG_SQE_ELEM(28, __u32,  fsync_flags);
9563         BUILD_BUG_SQE_ELEM(28, /* compat */ __u16,  poll_events);
9564         BUILD_BUG_SQE_ELEM(28, __u32,  poll32_events);
9565         BUILD_BUG_SQE_ELEM(28, __u32,  sync_range_flags);
9566         BUILD_BUG_SQE_ELEM(28, __u32,  msg_flags);
9567         BUILD_BUG_SQE_ELEM(28, __u32,  timeout_flags);
9568         BUILD_BUG_SQE_ELEM(28, __u32,  accept_flags);
9569         BUILD_BUG_SQE_ELEM(28, __u32,  cancel_flags);
9570         BUILD_BUG_SQE_ELEM(28, __u32,  open_flags);
9571         BUILD_BUG_SQE_ELEM(28, __u32,  statx_flags);
9572         BUILD_BUG_SQE_ELEM(28, __u32,  fadvise_advice);
9573         BUILD_BUG_SQE_ELEM(28, __u32,  splice_flags);
9574         BUILD_BUG_SQE_ELEM(32, __u64,  user_data);
9575         BUILD_BUG_SQE_ELEM(40, __u16,  buf_index);
9576         BUILD_BUG_SQE_ELEM(42, __u16,  personality);
9577         BUILD_BUG_SQE_ELEM(44, __s32,  splice_fd_in);
9578
9579         BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9580         BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9581         req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
9582         return 0;
9583 };
9584 __initcall(io_uring_init);