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