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