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