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