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