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