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