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