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