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