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