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