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