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