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