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